@krovacloud/cli 0.7.2 → 0.7.4

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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["errText","readline","osConstants","PRIVATE_NOTE","createServer"],"sources":["../src/lib/keychain.ts","../src/lib/base-url.ts","../src/lib/config.ts","../src/lib/output.ts","../src/lib/client.ts","../src/lib/output-format.ts","../src/lib/runtime.ts","../src/lib/persist.ts","../src/commands/auth.ts","../src/commands/backups.ts","../src/commands/catalog.ts","../src/lib/completion.ts","../src/commands/completion.ts","../src/commands/context.ts","../src/lib/create-prompt.ts","../src/lib/resolve.ts","../src/lib/safety.ts","../src/lib/spinner.ts","../src/lib/wait.ts","../src/commands/cubes.ts","../src/commands/domains.ts","../src/commands/login.ts","../src/commands/snapshots.ts","../src/lib/ssh.ts","../src/lib/tunnel.ts","../src/commands/dbclients.ts","../src/commands/exec.ts","../src/commands/ssh.ts","../src/commands/tunnel.ts","../src/commands/tcp.ts","../src/lib/semver.ts","../src/commands/version.ts","../src/commands/update.ts","../src/commands/webhooks.ts","../src/commands/whoami.ts","../src/lib/hints.ts","../src/index.ts"],"sourcesContent":["// OS keychain access for API keys. macOS goes through the `security` CLI and\n// Linux through `secret-tool` (libsecret). Both are called with argv arrays\n// (spawnSync, never a shell string). Anything else, or any failure, is reported\n// to the caller, which falls back to the 0600 config file.\n//\n// Why spawnSync: `load()` and `resolve()` in config.ts are synchronous and run\n// in every command, so the keychain backend is synchronous too. The keychain is\n// only touched when a stored key is actually needed (never when --api-key or\n// KROVA_API_KEY wins).\n\nimport { spawnSync } from \"node:child_process\";\n\nexport const KEYCHAIN_SERVICE = \"krova-cli\";\nexport const NO_KEYCHAIN_ENV = \"KROVA_NO_KEYCHAIN\";\n\nconst TIMEOUT_MS = 15_000;\n\nexport interface KeychainBackend {\n /** Human name for messages, e.g. \"macOS Keychain\". */\n readonly name: string;\n /** The stored secret, or undefined when there is no such item. Throws on any other failure. */\n get(account: string): string | undefined;\n /** Create or replace the item. Throws on failure. */\n set(account: string, secret: string): void;\n /** Remove the item; a missing item is not an error. Throws on any other failure. */\n delete(account: string): void;\n}\n\n/** Thrown when no keychain can be used at all (opted out, unsupported platform, tool missing). */\nexport class KeychainUnavailableError extends Error {\n constructor(\n message: string,\n readonly optOut = false,\n ) {\n super(message);\n this.name = \"KeychainUnavailableError\";\n }\n}\n\ninterface RunResult {\n status: number | null;\n stdout: string;\n stderr: string;\n}\n\nfunction run(cmd: string, args: string[], input?: string, detached = false): RunResult {\n // `detached` is honored by spawnSync (libuv UV_PROCESS_DETACHED, i.e. setsid) but is\n // missing from @types/node's SpawnSyncOptions, hence the cast.\n const r = spawnSync(cmd, args, {\n encoding: \"utf8\",\n input,\n timeout: TIMEOUT_MS,\n windowsHide: true,\n detached,\n } as Parameters<typeof spawnSync>[2] & { encoding: \"utf8\" });\n if (r.error) {\n const code = (r.error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") throw new KeychainUnavailableError(`\\`${cmd}\\` was not found`);\n if (code === \"ETIMEDOUT\") throw new Error(`\\`${cmd}\\` timed out after ${TIMEOUT_MS / 1000}s`);\n throw new Error(`\\`${cmd}\\` failed: ${r.error.message}`);\n }\n return { status: r.status, stdout: r.stdout ?? \"\", stderr: r.stderr ?? \"\" };\n}\n\nfunction assertSecret(secret: string): void {\n if (!secret || /[\\r\\n\\0]/.test(secret)) throw new Error(\"the API key is empty or contains a line break\");\n}\n\nfunction failure(cmd: string, r: RunResult): Error {\n const detail = r.stderr.trim().split(\"\\n\")[0] || `exit ${r.status}`;\n return new Error(`\\`${cmd}\\` failed: ${detail}`);\n}\n\n/** macOS: the `security` CLI (verified against `man security` on macOS and a live round trip).\n *\n * The password never goes in argv: `add-generic-password ... -w` with NO value after\n * the last option makes `security` prompt for it (\"Put at end of command to be\n * prompted (recommended)\"), and the prompt reads stdin only when the process has no\n * controlling terminal. A normal terminal run would read /dev/tty and ignore our pipe,\n * so the child is spawned detached (setsid, no controlling terminal) and gets\n * \"<secret>\\n<secret>\\n\" on stdin (prompt + retype). The write is verified by a read-back\n * in config.ts, so a platform where this misbehaves falls back to the file. */\nexport function macosBackend(service = KEYCHAIN_SERVICE): KeychainBackend {\n return {\n name: \"macOS Keychain\",\n get(account) {\n const r = run(\"security\", [\"find-generic-password\", \"-s\", service, \"-a\", account, \"-w\"]);\n if (r.status === 44) return undefined; // errSecItemNotFound\n if (r.status !== 0) throw failure(\"security\", r);\n return r.stdout.replace(/\\n$/, \"\");\n },\n set(account, secret) {\n assertSecret(secret);\n const r = run(\n \"security\",\n [\"add-generic-password\", \"-U\", \"-s\", service, \"-a\", account, \"-l\", `Krova CLI (${account})`, \"-w\"],\n `${secret}\\n${secret}\\n`,\n true,\n );\n if (r.status !== 0) throw failure(\"security\", r);\n },\n delete(account) {\n const r = run(\"security\", [\"delete-generic-password\", \"-s\", service, \"-a\", account]);\n if (r.status !== 0 && r.status !== 44) throw failure(\"security\", r);\n },\n };\n}\n\n/** Linux: `secret-tool` from libsecret. `store` reads the secret from stdin when it is not a\n * terminal (documented in secret-tool(1): \"Everything up to EOF becomes the password\"), so\n * nothing secret is in argv. Not run on this build machine (macOS); the argv shapes follow the\n * man page synopsis. */\nexport function secretToolBackend(service = KEYCHAIN_SERVICE): KeychainBackend {\n return {\n name: \"Secret Service (secret-tool)\",\n get(account) {\n const r = run(\"secret-tool\", [\"lookup\", \"service\", service, \"account\", account]);\n if (r.status === 0) return r.stdout.replace(/\\n$/, \"\");\n // Not found is exactly exit 1 with nothing on stdout or stderr; any other code is a failure.\n if (r.status === 1 && !r.stdout && !r.stderr.trim()) return undefined;\n throw failure(\"secret-tool\", r);\n },\n set(account, secret) {\n assertSecret(secret);\n const r = run(\n \"secret-tool\",\n [\"store\", `--label=Krova CLI (${account})`, \"service\", service, \"account\", account],\n secret,\n );\n if (r.status !== 0) throw failure(\"secret-tool\", r);\n },\n delete(account) {\n const r = run(\"secret-tool\", [\"clear\", \"service\", service, \"account\", account]);\n if (r.status === 0) return;\n // A failed clear is only \"nothing to delete\" if a lookup confirms the item is gone.\n if (this.get(account) === undefined) return;\n throw failure(\"secret-tool\", r);\n },\n };\n}\n\n/** Test seam: `undefined` uses the real platform backend, a backend replaces it,\n * `null` means \"no keychain available\". */\nlet override: KeychainBackend | null | undefined;\nexport function setKeychainBackendForTests(b: KeychainBackend | null | undefined): void {\n override = b;\n}\n\nexport function keychainOptedOut(): boolean {\n const v = (process.env[NO_KEYCHAIN_ENV] ?? \"\").trim().toLowerCase();\n return v === \"1\" || v === \"true\" || v === \"yes\";\n}\n\n/** The backend to use for reads (an existing keychain context must be readable even\n * under KROVA_NO_KEYCHAIN, which only governs where new keys are WRITTEN). */\nexport function readBackend(): KeychainBackend {\n if (override === null) throw new KeychainUnavailableError(\"no keychain is available\");\n if (override) return override;\n if (process.platform === \"darwin\") return macosBackend();\n if (process.platform === \"linux\") return secretToolBackend();\n throw new KeychainUnavailableError(`no keychain support on ${process.platform}`);\n}\n\n/** The backend to use for writes: like readBackend, but KROVA_NO_KEYCHAIN=1 forces the file. */\nexport function writeBackend(): KeychainBackend {\n if (keychainOptedOut()) throw new KeychainUnavailableError(`${NO_KEYCHAIN_ENV} is set`, true);\n return readBackend();\n}\n","const API_PATH = \"/api/v1\";\n\n/**\n * The API base URL the CLI talks to, by the same rule as the SDK's client: surrounding\n * whitespace and trailing slashes are removed, a bare origin (`https://krova.cloud`) gets\n * `/api/v1` appended, and any other path is kept as given. Call it only with a value that\n * is set; an empty or whitespace-only one means \"not set\" and is the caller's to skip.\n */\nexport function normalizeBaseUrl(raw: string): string {\n const trimmed = raw.trim().replace(/\\/+$/, \"\");\n let url: URL;\n try {\n url = new URL(trimmed);\n } catch {\n return trimmed;\n }\n if (url.pathname === \"/\" && !url.search && !url.hash) return `${trimmed}${API_PATH}`;\n return trimmed;\n}\n","// Reads/writes ~/.config/krova/config.json in the EXACT shape the Go CLI used,\n// so existing configs keep working. Multi-context, with legacy single-key\n// migration. The file is always tightened to 0600 on save. API keys live in the\n// OS keychain when one is available (see keychain.ts) and in this file otherwise.\n\nimport { randomBytes } from \"node:crypto\";\nimport { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { normalizeBaseUrl } from \"./base-url.js\";\nimport {\n KeychainUnavailableError,\n KEYCHAIN_SERVICE,\n readBackend,\n writeBackend,\n} from \"./keychain.js\";\n\nexport const DEFAULT_BASE_URL = \"https://krova.cloud/api/v1\";\nexport const DEFAULT_CONTEXT_NAME = \"default\";\n\nexport const ENV = {\n apiKey: \"KROVA_API_KEY\",\n spaceId: \"KROVA_SPACE_ID\",\n baseUrl: \"KROVA_BASE_URL\",\n context: \"KROVA_CONTEXT\",\n npmRegistry: \"KROVA_NPM_REGISTRY\",\n} as const;\n\n/** Where a context's API key lives. A context with no `keyStorage` is a file context. */\nexport type KeyStorage = \"keychain\" | \"file\";\n\nexport interface Context {\n name: string;\n apiKey?: string;\n keyStorage?: KeyStorage;\n spaceId?: string;\n spaceName?: string;\n baseUrl?: string;\n}\n\nexport interface Config {\n currentContext?: string;\n contexts?: Context[];\n // legacy (pre-context) fields — parsed then migrated into a \"default\" context\n apiKey?: string;\n spaceId?: string;\n baseUrl?: string;\n}\n\nexport function configDir(): string {\n const xdg = (process.env.XDG_CONFIG_HOME ?? \"\").trim();\n if (xdg) return join(xdg, \"krova\");\n return join(homedir(), \".config\", \"krova\");\n}\n\nexport function configPath(): string {\n return join(configDir(), \"config.json\");\n}\n\nexport function load(): Config {\n let cfg: Config = {};\n try {\n cfg = JSON.parse(readFileSync(configPath(), \"utf8\")) as Config;\n } catch {\n cfg = {};\n }\n return migrate(cfg);\n}\n\n// If only legacy fields are set, synthesize a \"default\" context from them.\nfunction migrate(cfg: Config): Config {\n if ((cfg.apiKey ?? \"\").trim() && (!cfg.contexts || cfg.contexts.length === 0)) {\n cfg.contexts = [\n {\n name: DEFAULT_CONTEXT_NAME,\n apiKey: cfg.apiKey,\n spaceId: cfg.spaceId,\n baseUrl: cfg.baseUrl,\n },\n ];\n cfg.currentContext = DEFAULT_CONTEXT_NAME;\n }\n cfg.apiKey = undefined;\n cfg.spaceId = undefined;\n cfg.baseUrl = undefined;\n return cfg;\n}\n\nexport function save(cfg: Config): void {\n const path = configPath();\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n // clear legacy fields; only serialize non-empty keys (matches Go omitempty)\n const clean: Config = {};\n if (cfg.currentContext) clean.currentContext = cfg.currentContext;\n if (cfg.contexts && cfg.contexts.length) {\n clean.contexts = cfg.contexts.map((c) => {\n const o: Context = { name: c.name };\n // A keychain context never writes its key to the file.\n if (c.apiKey && c.keyStorage !== \"keychain\") o.apiKey = c.apiKey;\n if (c.keyStorage) o.keyStorage = c.keyStorage;\n if (c.spaceId) o.spaceId = c.spaceId;\n if (c.spaceName) o.spaceName = c.spaceName;\n if (c.baseUrl) o.baseUrl = c.baseUrl;\n return o;\n });\n }\n // Atomic: write a 0600 temp file in the same directory, then rename over the config, so a\n // crash or full disk never leaves a half-written file (and the key is never briefly world-readable).\n const tmp = `${path}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`;\n try {\n writeFileSync(tmp, `${JSON.stringify(clean, null, 2)}\\n`, { mode: 0o600, flag: \"wx\" });\n renameSync(tmp, path);\n } catch (e) {\n try {\n unlinkSync(tmp);\n } catch {\n /* already gone */\n }\n throw e;\n }\n chmodSync(path, 0o600);\n}\n\nexport function find(cfg: Config, name: string): Context | undefined {\n return (cfg.contexts ?? []).find((c) => c.name === name);\n}\n\n/** The active context: `override` (e.g. --context) wins, else currentContext. */\nexport function current(cfg: Config, override?: string): Context | undefined {\n const name = (override ?? \"\").trim() || (cfg.currentContext ?? \"\").trim();\n if (!name) return undefined;\n return find(cfg, name);\n}\n\n/** Merge-in a context: only NON-EMPTY apiKey/spaceId/spaceName/baseUrl\n * overwrite an existing value. This keeps a transient per-command override\n * (e.g. a one-off `--base-url`) from being silently persisted over the\n * context's real base URL. First-ever context becomes current. Returns it. */\nexport function upsert(cfg: Config, incoming: Context): Context {\n cfg.contexts ??= [];\n let ctx = cfg.contexts.find((c) => c.name === incoming.name);\n if (!ctx) {\n ctx = { name: incoming.name };\n cfg.contexts.push(ctx);\n if (!cfg.currentContext) cfg.currentContext = ctx.name;\n }\n if ((incoming.apiKey ?? \"\").trim()) ctx.apiKey = incoming.apiKey;\n if ((incoming.spaceId ?? \"\").trim()) ctx.spaceId = incoming.spaceId;\n if ((incoming.spaceName ?? \"\").trim()) ctx.spaceName = incoming.spaceName;\n if ((incoming.baseUrl ?? \"\").trim()) ctx.baseUrl = incoming.baseUrl;\n return ctx;\n}\n\n/** Drop a context from `cfg` in memory only (the caller still calls `save`). Does not touch the\n * keychain: use `removeContext` to remove a context and its keychain item together. */\nexport function remove(cfg: Config, name: string): boolean {\n const before = (cfg.contexts ?? []).length;\n cfg.contexts = (cfg.contexts ?? []).filter((c) => c.name !== name);\n if (cfg.contexts.length === before) return false;\n if (cfg.currentContext === name) {\n cfg.currentContext = cfg.contexts[0]?.name ?? \"\";\n }\n return true;\n}\n\n/** Remove a context, save the config, and only then delete its keychain item, so a failed save\n * leaves both the context and its key intact. Returns false when there is no such context. */\nexport function removeContext(cfg: Config, name: string, persist: () => void = () => save(cfg)): boolean {\n const gone = find(cfg, name);\n if (!gone) return false;\n const snapshot = { contexts: [...(cfg.contexts ?? [])], currentContext: cfg.currentContext };\n remove(cfg, name);\n try {\n persist();\n } catch (e) {\n cfg.contexts = snapshot.contexts;\n cfg.currentContext = snapshot.currentContext;\n throw e;\n }\n deleteContextKey(gone);\n return true;\n}\n\nexport type Source = \"flag\" | \"env\" | \"context\" | \"\";\n\nexport interface Resolved {\n apiKey: string;\n spaceId: string;\n baseUrl: string;\n apiKeySource: Source;\n /** Where a context-sourced key is stored; \"\" when the key came from a flag or env var, or is missing. */\n apiKeyStorage: KeyStorage | \"\";\n spaceIdSource: Source;\n contextName: string;\n}\n\nexport interface GlobalFlags {\n apiKey?: string;\n space?: string;\n baseUrl?: string;\n context?: string;\n}\n\n/** Resolve credentials with precedence flag > env > active context. */\nexport function resolve(cfg: Config, flags: GlobalFlags): Resolved {\n const ctx = current(cfg, (flags.context ?? \"\").trim() || process.env[ENV.context]);\n const pick = (\n flag: string | undefined,\n env: string | undefined,\n ctxVal: string | undefined\n ): [string, Source] => {\n if ((flag ?? \"\").trim()) return [flag as string, \"flag\"];\n if ((env ?? \"\").trim()) return [env as string, \"env\"];\n if ((ctxVal ?? \"\").trim()) return [ctxVal as string, \"context\"];\n return [\"\", \"\"];\n };\n // --api-key and KROVA_API_KEY win without ever touching the keychain: the stored\n // key is only read (and the keychain only prompted) when nothing overrides it.\n const overridden = Boolean((flags.apiKey ?? \"\").trim() || (process.env[ENV.apiKey] ?? \"\").trim());\n const [apiKey, apiKeySource] = pick(\n flags.apiKey,\n process.env[ENV.apiKey],\n overridden || !ctx ? undefined : contextKey(ctx),\n );\n const [spaceId, spaceIdSource] = pick(flags.space, process.env[ENV.spaceId], ctx?.spaceId);\n const [baseUrlRaw] = pick(flags.baseUrl, process.env[ENV.baseUrl], ctx?.baseUrl);\n return {\n apiKey,\n spaceId,\n baseUrl: baseUrlRaw ? normalizeBaseUrl(baseUrlRaw) : DEFAULT_BASE_URL,\n apiKeySource,\n apiKeyStorage: apiKeySource === \"context\" && ctx ? storageOf(ctx) : \"\",\n spaceIdSource,\n contextName: ctx?.name ?? \"\",\n };\n}\n\n// --- API key storage (OS keychain with a 0600 file fallback) ---------------\n\nexport function storageOf(ctx: Context): KeyStorage {\n return ctx.keyStorage === \"keychain\" ? \"keychain\" : \"file\";\n}\n\nconst errText = (e: unknown): string => (e instanceof Error ? e.message : String(e));\n\n/** One short line on stderr (stdout stays clean for --json). */\nfunction warn(msg: string): void {\n process.stderr.write(`krova: ${msg}\\n`);\n}\n\n/** The context's API key: from the file, or from the OS keychain for a keychain context.\n * A keychain that cannot be read warns on stderr and returns \"\" (so the caller sees\n * \"no key\" and is told to log in again) instead of crashing every command. */\nexport function contextKey(ctx: Context): string {\n if (storageOf(ctx) !== \"keychain\") return ctx.apiKey ?? \"\";\n try {\n const key = readBackend().get(ctx.name);\n if (key) return key;\n warn(\n `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`,\n );\n } catch (e) {\n warn(\n `could not read the API key for context \"${ctx.name}\" from the OS keychain (${errText(e)}); run \\`krova login --context ${ctx.name}\\` to store it again`,\n );\n }\n return \"\";\n}\n\nexport interface StoreResult {\n storage: KeyStorage;\n /** Human name of the keychain used, when storage is \"keychain\". */\n backend?: string;\n}\n\n/** Write `key` to the keychain (verified by a read-back) and mark `ctx` as a keychain\n * context, else keep it in the 0600 file with a one-line stderr message. Mutates `ctx`;\n * the caller still calls `save`. Never throws. */\nexport function setContextKey(ctx: Context, key: string): StoreResult {\n try {\n const backend = writeBackend();\n backend.set(ctx.name, key);\n if (backend.get(ctx.name) !== key) {\n try {\n backend.delete(ctx.name);\n } catch {\n /* best effort */\n }\n throw new Error(\"the keychain did not return the stored key\");\n }\n ctx.keyStorage = \"keychain\";\n ctx.apiKey = undefined;\n return { storage: \"keychain\", backend: backend.name };\n } catch (e) {\n // An explicit KROVA_NO_KEYCHAIN opt-out is silent; every other reason is said once.\n if (!(e instanceof KeychainUnavailableError && e.optOut)) {\n warn(`OS keychain unavailable (${errText(e)}); storing the API key in ${configPath()} (mode 0600) instead`);\n }\n }\n // Leaving a keychain context for the file: drop the stale item.\n if (storageOf(ctx) === \"keychain\") deleteContextKey(ctx);\n ctx.keyStorage = \"file\";\n ctx.apiKey = key;\n return { storage: \"file\" };\n}\n\n/** Delete the context's keychain item, if it has one. Failure is a warning, not an error:\n * the context is being removed either way. */\nexport function deleteContextKey(ctx: Context): void {\n if (storageOf(ctx) !== \"keychain\") return;\n try {\n readBackend().delete(ctx.name);\n } catch (e) {\n warn(`could not delete the keychain item for context \"${ctx.name}\" (${errText(e)}); remove it by hand (service ${KEYCHAIN_SERVICE}, account ${ctx.name})`);\n }\n}\n\n/** Rename a context and save the config. A keychain key moves with it: the new item is written\n * and verified first, the config is saved, and only then is the old item deleted. A failure at\n * any step before that leaves the context (and its old item) as it was. */\nexport function renameContext(\n cfg: Config,\n oldName: string,\n newName: string,\n persist: () => void = () => save(cfg),\n): void {\n const c = find(cfg, oldName);\n if (!c) throw new Error(`no context named \"${oldName}\"`);\n assertContextName(newName);\n if (find(cfg, newName)) throw new Error(`a context named \"${newName}\" already exists`);\n const moved = storageOf(c) === \"keychain\";\n const backend = moved ? readBackend() : undefined;\n if (backend) {\n let key: string | undefined;\n try {\n key = backend.get(oldName);\n } catch (e) {\n throw new Error(`could not read the key for \"${oldName}\" from the OS keychain: ${errText(e)}`);\n }\n if (!key) throw new Error(`the API key for \"${oldName}\" is not in the OS keychain; run \\`krova login --context ${oldName}\\` first`);\n try {\n backend.set(newName, key);\n if (backend.get(newName) !== key) throw new Error(\"the keychain did not return the stored key\");\n } catch (e) {\n try {\n backend.delete(newName);\n } catch {\n /* best effort */\n }\n throw new Error(`could not move the key to \"${newName}\" in the OS keychain: ${errText(e)}`);\n }\n }\n const wasCurrent = cfg.currentContext === oldName;\n c.name = newName;\n if (wasCurrent) cfg.currentContext = newName;\n try {\n persist();\n } catch (e) {\n c.name = oldName;\n if (wasCurrent) cfg.currentContext = oldName;\n if (backend) {\n try {\n backend.delete(newName);\n } catch {\n /* best effort */\n }\n }\n throw e;\n }\n if (backend) {\n try {\n backend.delete(oldName);\n } catch (e) {\n warn(`renamed, but could not delete the old keychain item (${errText(e)}); remove it by hand (service ${KEYCHAIN_SERVICE}, account ${oldName})`);\n }\n }\n}\n\nexport interface MigrateEntry {\n context: string;\n result: \"migrated\" | \"skipped\" | \"failed\";\n detail?: string;\n}\n\n/** Move every file-stored key into the keychain. A key leaves the file only after the\n * keychain read-back matches; `save` runs after each context so a later failure never\n * loses an earlier move. Throws when no keychain can be used at all. */\nexport function migrateKeysToKeychain(cfg: Config): { backend: string; entries: MigrateEntry[] } {\n const backend = writeBackend(); // honors KROVA_NO_KEYCHAIN (throws KeychainUnavailableError)\n const entries: MigrateEntry[] = [];\n for (const ctx of cfg.contexts ?? []) {\n if (storageOf(ctx) === \"keychain\") {\n entries.push({ context: ctx.name, result: \"skipped\", detail: \"already in the keychain\" });\n continue;\n }\n const key = (ctx.apiKey ?? \"\").trim();\n if (!key) {\n entries.push({ context: ctx.name, result: \"skipped\", detail: \"no API key stored\" });\n continue;\n }\n try {\n backend.set(ctx.name, key);\n if (backend.get(ctx.name) !== key) {\n try {\n backend.delete(ctx.name);\n } catch {\n /* best effort */\n }\n throw new Error(\"the keychain did not return the stored key\");\n }\n } catch (e) {\n entries.push({ context: ctx.name, result: \"failed\", detail: errText(e) });\n continue;\n }\n ctx.keyStorage = \"keychain\";\n ctx.apiKey = undefined;\n save(cfg);\n entries.push({ context: ctx.name, result: \"migrated\" });\n }\n return { backend: backend.name, entries };\n}\n\n/** A context name becomes a keychain account passed to `security` and `secret-tool`, so one that\n * starts with `-` could be read as an option. */\nexport function assertContextName(name: string): void {\n if (name.trim().startsWith(\"-\")) throw new Error(`context names cannot start with \"-\" (got \"${name}\")`);\n}\n\nexport function sanitizeContextName(name: string): string {\n const clean = name.trim().toLowerCase().replace(/\\s+/g, \"-\");\n assertContextName(clean);\n return clean;\n}\n\nexport function maskKey(key: string): string {\n if (!key) return \"\";\n if (key.length <= 8) return \"****\";\n return `${key.slice(0, 6)}…${key.slice(-4)}`;\n}\n\n/** The key as it should be printed: masked unless `--show-secrets` was passed. */\nexport function displayKey(key: string, showSecrets: boolean): string {\n return showSecrets ? key : maskKey(key);\n}\n","/**\n * Stop quietly when the reader of stdout goes away (`krova cubes list | head -1`),\n * the way standard Unix tools do: an EPIPE ends the process with status 0 and no\n * stack trace. Every other write error is still reported, as `Error: ...` with\n * status 1; only the one expected case is silent.\n */\nexport function exitQuietlyOnBrokenPipe(\n stream: NodeJS.EventEmitter = process.stdout,\n exit: (code: number) => void = (code) => process.exit(code),\n warn: (text: string) => void = (text) => void process.stderr.write(text)\n): void {\n stream.on(\"error\", (err: NodeJS.ErrnoException) => {\n if (err?.code === \"EPIPE\") return exit(0);\n warn(`Error: ${err instanceof Error ? err.message : String(err)}\\n`);\n exit(1);\n });\n}\n\nexport function printJSON(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\n/**\n * Where to connect for a TCP mapping: `host:port`.\n *\n * `host` is the Cube's OWN stable hostname, which survives migration to\n * another server — not the server's hostname, which does not. Shared by\n * `tcp list` and `tcp add` so the two can never disagree about how a connect\n * target is spelled.\n *\n * Falls back to the bare port when the Cube has no host (no server assigned).\n * Printing a port alone is honest about what is known; inventing a host, or\n * printing `null:30000`, is not.\n */\nexport function mappingConnectTarget(mapping: {\n host?: string | null;\n hostPort: number;\n}): string {\n return mapping.host\n ? `${mapping.host}:${mapping.hostPort}`\n : String(mapping.hostPort);\n}\n\nexport function printTable(header: string[], rows: string[][]): void {\n const widths = header.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length))\n );\n const fmt = (cols: string[]) =>\n cols\n .map((c, i) => (c ?? \"\").padEnd(widths[i] ?? 0))\n .join(\" \")\n .replace(/\\s+$/, \"\");\n process.stdout.write(`${fmt(header)}\\n`);\n for (const r of rows) process.stdout.write(`${fmt(r)}\\n`);\n}\n\nexport function printKeyValue(pairs: Array<[string, string]>): void {\n const w = Math.max(0, ...pairs.map(([k]) => k.length));\n for (const [k, v] of pairs) {\n process.stdout.write(`${k.padEnd(w)} ${v}\\n`);\n }\n}\n","import { KrovaClient } from \"@krovacloud/sdk\";\n\nimport { normalizeBaseUrl } from \"./base-url.js\";\nimport type { Resolved } from \"./config.js\";\n\n/** Build the SDK client, or throw the same message the Go CLI used. */\nexport function makeClient(res: Resolved): KrovaClient {\n if (!res.apiKey) {\n throw new Error(\n \"no API key found: run `krova auth login`, set KROVA_API_KEY, or pass --api-key\"\n );\n }\n return new KrovaClient({ apiKey: res.apiKey, baseUrl: res.baseUrl });\n}\n\n/** Raw JSON request for endpoints the SDK doesn't cover:\n * GET /space, GET .../ssh, POST /auth/cli/start, POST /auth/cli/poll. */\nexport async function rawRequest<T>(opts: {\n method: string;\n baseUrl: string;\n path: string;\n apiKey?: string;\n body?: unknown;\n timeoutMs: number;\n}): Promise<{ status: number; data: T | undefined }> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), opts.timeoutMs);\n try {\n const headers: Record<string, string> = { Accept: \"application/json\" };\n if (opts.apiKey) headers[\"X-API-KEY\"] = opts.apiKey;\n if (opts.body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n const res = await fetch(`${normalizeBaseUrl(opts.baseUrl)}${opts.path}`, {\n method: opts.method,\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n redirect: \"manual\",\n signal: controller.signal,\n });\n let data: T | undefined;\n const text = await res.text();\n if (text) {\n try {\n data = JSON.parse(text) as T;\n } catch {\n data = undefined;\n }\n }\n return { status: res.status, data };\n } finally {\n clearTimeout(timer);\n }\n}\n","/** The values the global `-o, --output <format>` flag accepts. */\nexport const OUTPUT_FORMATS = [\"table\", \"json\"] as const;\nexport type OutputFormat = (typeof OUTPUT_FORMATS)[number];\n\n/** Values worth completing after a flag, keyed by the flag as typed. */\nexport const FLAG_VALUE_CHOICES: Record<string, readonly string[]> = {\n \"-o\": OUTPUT_FORMATS,\n \"--output\": OUTPUT_FORMATS,\n};\n\n/**\n * Validate the `--output` value. Unset means the default, `table`.\n * Throws a one-line error for anything else, so a typo never silently\n * falls back to a table in a script that expects JSON.\n */\nexport function parseOutputFormat(raw: unknown): OutputFormat {\n if (raw === undefined || raw === null || raw === \"\") return \"table\";\n const value = String(raw);\n if ((OUTPUT_FORMATS as readonly string[]).includes(value)) return value as OutputFormat;\n throw new Error(`--output must be \"json\" or \"table\" (got \"${value}\")`);\n}\n","import type { Command } from \"commander\";\n\nimport {\n type Config,\n type GlobalFlags,\n type Resolved,\n load,\n resolve,\n save,\n upsert,\n} from \"./config.js\";\nimport { makeClient, rawRequest } from \"./client.js\";\nimport { parseOutputFormat } from \"./output-format.js\";\n\n/** Parse a Go-style duration (\"30s\", \"500ms\", \"2m\", \"1h\") to ms. Non-positive\n * or unparseable floors to 30s (matches the Go requestTimeout behavior). */\nexport function parseDuration(input: string | undefined): number {\n const s = (input ?? \"\").trim();\n if (!s) return 30_000;\n let total = 0;\n const re = /(\\d+(?:\\.\\d+)?)(ms|s|m|h)/g;\n let m: RegExpExecArray | null = re.exec(s);\n let matched = false;\n while (m) {\n matched = true;\n const n = Number(m[1]);\n const unit = m[2];\n total += unit === \"ms\" ? n : unit === \"s\" ? n * 1000 : unit === \"m\" ? n * 60_000 : n * 3_600_000;\n m = re.exec(s);\n }\n if (!matched) {\n const n = Number(s);\n if (Number.isFinite(n)) total = n * 1000; // bare number = seconds\n }\n return total > 0 ? total : 30_000;\n}\n\nexport interface Runtime {\n flags: GlobalFlags;\n cfg: Config;\n res: Resolved;\n json: boolean;\n timeoutMs: number;\n}\n\n/** What the last `getRuntime` call resolved; the top-level error handler reads it\n * to name the base URL in a connection hint and to stay quiet in JSON mode. */\nlet active: { baseUrl: string; json: boolean } | undefined;\n\nexport function activeRuntime(): { baseUrl: string; json: boolean } | undefined {\n return active;\n}\n\nexport function getRuntime(cmd: Command): Runtime {\n const opts = cmd.optsWithGlobals() as Record<string, unknown>;\n const flags: GlobalFlags = {\n apiKey: opts.apiKey as string | undefined,\n space: opts.space as string | undefined,\n baseUrl: opts.baseUrl as string | undefined,\n context: opts.context as string | undefined,\n };\n const cfg = load();\n const res = resolve(cfg, flags);\n // `-o json` is `--json`; either one selects JSON. An invalid -o throws here.\n const json = Boolean(opts.json) || parseOutputFormat(opts.output) === \"json\";\n active = { baseUrl: res.baseUrl, json };\n return {\n flags,\n cfg,\n res,\n json,\n timeoutMs: parseDuration(opts.timeout as string | undefined),\n };\n}\n\nexport interface SpaceInfo {\n id: string;\n name?: string;\n slug?: string;\n /**\n * The key this request authenticated with: `expiresAt` is an ISO date-time,\n * or `null` for a key that never expires. `null` for an OAuth token, and\n * absent when the server is too old to send it, so treat absent as unknown.\n */\n apiKey?: { name: string; expiresAt: string | null } | null;\n}\n\n/**\n * The outcome of actually asking the server whether a key works.\n *\n * A stored key is NOT a working key: it can be revoked server-side at any\n * time, and the local config has no way to know. Every caller that wants to\n * report on credentials must distinguish \"rejected\" from \"couldn't reach the\n * server\" — collapsing either into a plain boolean is what made `auth status`\n * print \"Authenticated: yes\" for a key the API answers 401 to.\n */\nexport type AuthProbe =\n /** The server accepted the key and told us which space it belongs to. */\n | { state: \"valid\"; space: SpaceInfo }\n /** The key is absent locally — nothing to check. */\n | { state: \"missing\" }\n /** The server actively rejected the key (revoked, deleted, wrong env). */\n | { state: \"rejected\"; status: number }\n /** Endpoint absent (older server) — the key may still be fine. */\n | { state: \"unsupported\" }\n /** Network/DNS/timeout — says nothing about the key's validity. */\n | { state: \"unreachable\"; error: string };\n\n/** Ask the server whether `apiKey` is actually accepted. Never throws. */\nexport async function probeAuth(\n baseUrl: string,\n apiKey: string,\n timeoutMs: number\n): Promise<AuthProbe> {\n if (!apiKey) return { state: \"missing\" };\n try {\n const { status, data } = await rawRequest<SpaceInfo>({\n method: \"GET\",\n baseUrl,\n path: \"/space\",\n apiKey,\n timeoutMs,\n });\n if (status === 200 && data?.id) return { state: \"valid\", space: data };\n if (status === 401 || status === 403) return { state: \"rejected\", status };\n if (status === 404) return { state: \"unsupported\" };\n return { state: \"unreachable\", error: `HTTP ${status}` };\n } catch (err) {\n return {\n state: \"unreachable\",\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n/** Resolve the active space id: explicit value wins, else auto-detect via\n * GET /space (and cache it into the current context). */\nexport async function resolveSpace(rt: Runtime): Promise<string> {\n if (rt.res.spaceId) return rt.res.spaceId;\n const { status, data } = await rawRequest<SpaceInfo>({\n method: \"GET\",\n baseUrl: rt.res.baseUrl,\n path: \"/space\",\n apiKey: rt.res.apiKey,\n timeoutMs: rt.timeoutMs,\n });\n if (status === 200 && data?.id) {\n // Best-effort cache of the resolved space into the current named context.\n // Deliberately does NOT write baseUrl: rt.res.baseUrl already folds in a\n // one-off --base-url / KROVA_BASE_URL override, and persisting that here\n // would permanently rewrite the context's real base URL from a transient\n // flag. Only the space id/name are cached.\n if (rt.res.contextName) {\n upsert(rt.cfg, {\n name: rt.res.contextName,\n spaceId: data.id,\n spaceName: data.name,\n });\n try {\n save(rt.cfg);\n } catch {\n /* non-fatal */\n }\n }\n return data.id;\n }\n if (status === 404) {\n throw new Error(\n \"couldn't auto-detect your space (the server doesn't support it yet) — pass --space, set KROVA_SPACE_ID, or run `krova login`\"\n );\n }\n if (status === 401 || status === 403) {\n throw new Error(`auto-detect space failed: the API key was rejected (HTTP ${status})`);\n }\n throw new Error(`auto-detect space failed (HTTP ${status})`);\n}\n\nexport { makeClient };\n","import {\n DEFAULT_CONTEXT_NAME,\n configPath,\n type StoreResult,\n load,\n sanitizeContextName,\n save,\n setContextKey,\n upsert,\n} from \"./config.js\";\nimport { probeAuth } from \"./runtime.js\";\n\n/** Save + switch to a context after a login. Best-effort space lookup fills in\n * spaceId/spaceName and a nicer context name. Mirrors the Go persistLogin. */\nexport async function persistLogin(input: {\n apiKey: string;\n baseUrl: string;\n spaceId?: string;\n ctxName?: string;\n timeoutMs: number;\n}): Promise<{ ctxName: string; spaceName: string; stored: StoreResult }> {\n const cfg = load();\n let spaceId = input.spaceId ?? \"\";\n let spaceName = \"\";\n let derivedName = \"\";\n\n const probe = await probeAuth(input.baseUrl, input.apiKey, input.timeoutMs);\n const sp = probe.state === \"valid\" ? probe.space : null;\n if (sp) {\n // Prefer an explicitly-provided --space over the fetched id; only fall back\n // to the resolved space when the caller didn't pin one.\n if (!spaceId) spaceId = sp.id;\n spaceName = sp.name ?? \"\";\n derivedName = (sp.slug || sp.name || \"\").trim();\n }\n\n let name = (input.ctxName ?? \"\").trim();\n if (!name) name = derivedName || DEFAULT_CONTEXT_NAME;\n name = sanitizeContextName(name);\n\n const cur = upsert(cfg, {\n name,\n spaceId,\n spaceName,\n baseUrl: input.baseUrl,\n });\n // Keychain first, 0600 file as the fallback; the key is never written to the file when the keychain took it.\n const stored = setContextKey(cur, input.apiKey);\n cfg.currentContext = cur.name; // login always switches current\n save(cfg);\n return { ctxName: cur.name, spaceName: cur.spaceName ?? \"\", stored };\n}\n\n/** The line printed after a login: says where the key went. */\nexport function loginMessage(ctxName: string, stored: StoreResult): string {\n return stored.storage === \"keychain\"\n ? `Logged in. Saved context \"${ctxName}\" to ${configPath()} (API key in the ${stored.backend})`\n : `Logged in. Saved context \"${ctxName}\" to ${configPath()}`;\n}\n","import { Command } from \"commander\";\n\nimport { KeychainUnavailableError } from \"../lib/keychain.js\";\nimport {\n configPath,\n displayKey,\n find,\n load,\n migrateKeysToKeychain,\n removeContext,\n} from \"../lib/config.js\";\nimport { printJSON, printKeyValue } from \"../lib/output.js\";\nimport { loginMessage, persistLogin } from \"../lib/persist.js\";\nimport { getRuntime, probeAuth } from \"../lib/runtime.js\";\n\n/** Prompt for an API key. Hidden echo when stdin is a TTY. */\nfunction promptAPIKey(): Promise<string> {\n return new Promise((resolve, reject) => {\n process.stdout.write(\"Krova API key: \");\n const stdin = process.stdin;\n const tty = Boolean(stdin.isTTY);\n let buf = \"\";\n if (tty) stdin.setRawMode(true);\n stdin.resume();\n stdin.setEncoding(\"utf8\");\n const finish = (fn: () => void) => {\n if (tty) stdin.setRawMode(false);\n stdin.pause();\n stdin.removeListener(\"data\", onData);\n fn();\n };\n const onData = (ch: string) => {\n for (const c of ch) {\n const code = c.charCodeAt(0);\n if (code === 10 || code === 13) {\n finish(() => {\n process.stdout.write(\"\\n\");\n resolve(buf.trim());\n });\n return;\n }\n if (code === 3) {\n finish(() => reject(new Error(\"cancelled\")));\n return;\n }\n if (code === 127 || code === 8) {\n buf = buf.slice(0, -1);\n } else if (code >= 32) {\n buf += c;\n }\n }\n };\n stdin.on(\"data\", onData);\n });\n}\n\nexport function authCommand(): Command {\n const auth = new Command(\"auth\").description(\"manage Krova Cloud credentials\");\n\n auth\n .command(\"login\")\n .description(\"log in by pasting an API key\")\n .option(\"--api-key <key>\", \"API key (else you'll be prompted)\")\n .option(\"--space <id>\", \"Space ID to store with the key\")\n .option(\"--context <name>\", \"name for the saved context\")\n .action(async (opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n let key = (opts.apiKey as string) || rt.flags.apiKey || \"\";\n if (!key.trim()) key = await promptAPIKey();\n if (!key.trim()) throw new Error(\"no API key provided\");\n const { ctxName, spaceName, stored } = await persistLogin({\n apiKey: key.trim(),\n baseUrl: rt.res.baseUrl,\n spaceId: opts.space as string | undefined,\n // Not opts.context: the root's own --context takes the flag first, so the\n // local option never receives it. The merged flags always carry it.\n ctxName: rt.flags.context,\n timeoutMs: rt.timeoutMs,\n });\n process.stdout.write(`${loginMessage(ctxName, stored)}\\n`);\n if (spaceName) process.stdout.write(`Space: ${spaceName}\\n`);\n });\n\n auth\n .command(\"status\")\n .description(\"show the resolved credentials and verify them against the API\")\n .option(\"--offline\", \"skip the live check; only report what's stored locally\")\n .option(\"--show-secrets\", \"print the full API key instead of a masked one\")\n .action(async (opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const showSecrets = Boolean(opts.showSecrets);\n const offline = Boolean(opts.offline);\n\n // A STORED key is not a WORKING key — it can be revoked server-side at\n // any time. Reporting local presence as \"Authenticated: yes\" sends the\n // user hunting for a config problem that isn't there, so unless they ask\n // for --offline we go and ask the API.\n const probe = offline\n ? ({ state: \"missing\" } as const)\n : await probeAuth(rt.res.baseUrl, rt.res.apiKey, rt.timeoutMs);\n\n const hasKey = Boolean(rt.res.apiKey);\n const authenticated = offline ? hasKey : probe.state === \"valid\";\n\n const detail =\n offline || !hasKey\n ? \"\"\n : probe.state === \"rejected\"\n ? `the API rejected this key (HTTP ${probe.status}) — it is invalid, revoked or expired, or belongs to another environment; run \\`krova login\\``\n : probe.state === \"unreachable\"\n ? `could not reach ${rt.res.baseUrl} (${probe.error}) — the key was NOT verified`\n : probe.state === \"unsupported\"\n ? \"this server has no /space endpoint, so the key could not be verified\"\n : \"\";\n\n // Live space beats the cached copy: a stale spaceId in the config is\n // exactly the kind of drift this command exists to surface.\n const spaceId = probe.state === \"valid\" ? probe.space.id : rt.res.spaceId;\n\n if (rt.json) {\n return printJSON({\n authenticated,\n verified: probe.state === \"valid\",\n checkState: offline ? \"skipped\" : probe.state,\n detail: detail || undefined,\n context: rt.res.contextName,\n apiKeySource: rt.res.apiKeySource,\n apiKeyStorage: rt.res.apiKeyStorage || undefined,\n ...(showSecrets\n ? { apiKey: rt.res.apiKey }\n : { apiKeyMasked: displayKey(rt.res.apiKey, false) }),\n spaceId,\n spaceSource: rt.res.spaceIdSource,\n baseUrl: rt.res.baseUrl,\n configPath: configPath(),\n });\n }\n\n const label = !hasKey\n ? \"no (no API key found)\"\n : offline\n ? \"not checked (--offline; a key is stored)\"\n : probe.state === \"valid\"\n ? \"yes (verified against the API)\"\n : probe.state === \"rejected\"\n ? \"NO — key rejected by the API\"\n : \"unknown (could not verify)\";\n\n printKeyValue([\n [\"Authenticated\", label],\n [\"Context\", rt.res.contextName || \"—\"],\n [\n \"API key\",\n rt.res.apiKey\n ? `${displayKey(rt.res.apiKey, showSecrets)} (${rt.res.apiKeySource}${rt.res.apiKeyStorage ? `, ${rt.res.apiKeyStorage}` : \"\"})`\n : \"—\",\n ],\n [\"Space ID\", spaceId ? `${spaceId} (${rt.res.spaceIdSource})` : \"—\"],\n [\"Base URL\", rt.res.baseUrl],\n [\"Config\", configPath()],\n ]);\n if (detail) process.stdout.write(`\\n${detail}\\n`);\n\n // Exit non-zero only when the credentials are KNOWN to be unusable, so\n // scripts and CI can gate on `krova auth status` (matches\n // `gh auth status`). An unreachable or too-old API says nothing about\n // the key, so those stay 0 rather than failing a build over a blip.\n if (!hasKey || probe.state === \"rejected\") process.exitCode = 1;\n });\n\n auth\n .command(\"logout\")\n .description(\"remove a saved context and its API key from this machine\")\n .option(\"--context <name>\", \"the context to remove (default: the current one)\")\n .action((opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const cfg = load();\n // The global --context may be consumed before this command sees it, so read both.\n const name =\n ((opts.context as string | undefined) ?? rt.flags.context ?? \"\").trim() ||\n rt.res.contextName;\n if (!name) throw new Error(`not logged in: no saved context in ${configPath()}`);\n if (!find(cfg, name)) throw new Error(`no context named \"${name}\"`);\n const wasCurrent = cfg.currentContext === name;\n removeContext(cfg, name); // saves the config, then deletes the keychain item\n const current = cfg.currentContext || null;\n if (rt.json) return printJSON({ context: name, result: \"logged_out\", current });\n process.stdout.write(\n `Logged out of ${name}. The API key still works until you revoke it in the dashboard (Settings > API keys).\\n`,\n );\n if (wasCurrent && current) process.stdout.write(`Now using ${current}.\\n`);\n });\n\n auth\n .command(\"migrate-keychain\")\n .description(\"move API keys saved in the config file into the OS keychain\")\n .action((_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const cfg = load();\n let result: ReturnType<typeof migrateKeysToKeychain>;\n try {\n result = migrateKeysToKeychain(cfg);\n } catch (e) {\n if (e instanceof KeychainUnavailableError) {\n throw new Error(\n e.optOut\n ? `${e.message}; unset KROVA_NO_KEYCHAIN to move keys into the keychain`\n : `no OS keychain available (${e.message}); keys stay in ${configPath()}`,\n );\n }\n throw e;\n }\n const failed = result.entries.filter((x) => x.result === \"failed\");\n if (failed.length > 0) process.exitCode = 1;\n if (rt.json) return printJSON({ keychain: result.backend, results: result.entries });\n if (result.entries.length === 0) process.stdout.write(\"No contexts to migrate.\\n\");\n for (const x of result.entries) {\n const tail = x.detail ? ` (${x.detail})` : \"\";\n process.stdout.write(\n `${x.result === \"migrated\" ? \"Moved\" : x.result === \"failed\" ? \"FAILED\" : \"Skipped\"} ${x.context}${x.result === \"migrated\" ? ` to the ${result.backend}` : tail}\\n`,\n );\n if (x.result === \"failed\") process.stderr.write(` ${x.detail}\\n`);\n }\n });\n\n return auth;\n}\n","import type { Backup, BackupShare, KrovaClient } from \"@krovacloud/sdk\";\nimport { Command } from \"commander\";\n\nimport { printJSON, printKeyValue, printTable } from \"../lib/output.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\n\n/**\n * Resolve a backup name-or-id to an id, the same rule as `resolveCube`: an\n * exact id wins; else exactly one exact name match; else a clear error.\n */\nexport async function resolveBackup(\n client: KrovaClient,\n spaceId: string,\n ref: string\n): Promise<string> {\n const backups = await client.backups.list(spaceId);\n if (backups.some((b) => b.id === ref)) return ref;\n const byName = backups.filter((b) => b.name === ref);\n if (byName.length === 1) return byName[0]!.id;\n if (byName.length === 0) {\n throw new Error(\n `no backup named or with ID \"${ref}\" in this space (see \\`krova backups list\\`)`\n );\n }\n const ids = byName.map((b) => b.id).join(\", \");\n throw new Error(\n `backup name \"${ref}\" is ambiguous: it matches ${byName.length} backups (${ids}) — use the backup ID instead`\n );\n}\n\n/** One row of `krova backups shares`: which way it goes, and the other space. */\nexport function shareRows(list: { incoming: BackupShare[]; outgoing: BackupShare[] }): string[][] {\n const row = (direction: string, s: BackupShare) => [\n s.id,\n direction,\n s.backupName,\n s.counterpartySpaceName,\n s.status,\n s.expiresAt,\n ];\n return [\n ...list.incoming.map((s) => row(\"incoming\", s)),\n ...list.outgoing.map((s) => row(\"outgoing\", s)),\n ];\n}\n\nfunction backupPairs(b: Backup): Array<[string, string]> {\n return [\n [\"ID\", b.id],\n [\"Name\", b.name],\n [\"Status\", b.status],\n [\"From Cube\", `${b.originalCubeName} (${b.originalCubeId})`],\n [\"Size (bytes)\", b.sizeBytes == null ? \"\" : String(b.sizeBytes)],\n [\"Disk (GB)\", String(b.diskSizeGb)],\n [\"Shared from\", b.sharedFromBackupId ?? \"\"],\n [\"Created\", b.createdAt],\n ];\n}\n\n/**\n * `krova backups` — list, download and share backups, and answer shares.\n *\n * Every subcommand needs the Backups permissions on the API key's member:\n * View Backups to read, Manage Backups for everything else.\n */\nexport function backupsCommand(): Command {\n const cmd = new Command(\"backups\").description(\n \"list, download and share backups, and answer backup shares\"\n );\n\n cmd\n .command(\"list\")\n .description(\"list this space's backups, newest first\")\n .action(async (_opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const backups = await client.backups.list(space);\n if (rt.json) return printJSON(backups);\n printTable(\n [\"ID\", \"NAME\", \"STATUS\", \"SIZE (BYTES)\", \"SHARED FROM\", \"CREATED\"],\n backups.map((b) => [\n b.id,\n b.name,\n b.status,\n b.sizeBytes == null ? \"\" : String(b.sizeBytes),\n b.sharedFromBackupId ?? \"\",\n b.createdAt,\n ]),\n );\n });\n\n cmd\n .command(\"get\")\n .argument(\"<backup>\", \"backup name or ID\")\n .description(\"show one backup\")\n .action(async (ref: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const backup = await client.backups.get(space, await resolveBackup(client, space, ref));\n if (rt.json) return printJSON(backup);\n printKeyValue(backupPairs(backup));\n });\n\n cmd\n .command(\"download\")\n .argument(\"<backup>\", \"backup name or ID\")\n .description(\"print a link to download the backup's .cube archive (valid for 15 minutes)\")\n .action(async (ref: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const link = await client.backups.download(space, await resolveBackup(client, space, ref));\n if (rt.json) return printJSON(link);\n if (!link) throw new Error(\"the API returned no download link\");\n printKeyValue([\n [\"URL\", link.url ?? \"\"],\n [\"File\", link.filename ?? \"\"],\n [\"Size (bytes)\", link.sizeBytes == null ? \"\" : String(link.sizeBytes)],\n [\"Expires\", link.expiresAt ?? \"\"],\n ]);\n // The link needs no further authentication, and the archive is the whole disk.\n process.stderr.write(\n \"Anyone with this link can download the archive until it expires. Do not paste it anywhere shared.\\n\"\n );\n });\n\n cmd\n .command(\"share\")\n .argument(\"<backup>\", \"backup name or ID\")\n .argument(\"<destination-space-id>\", \"the space to offer a copy to\")\n .option(\"--idempotency-key <key>\", \"replaying the same key returns the original request\")\n .description(\n \"offer a copy of a backup to another space; it pays for its copy once it accepts (48 hours)\"\n )\n .action(async (ref: string, destinationSpaceId: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const share = await client.backups.share(\n space,\n await resolveBackup(client, space, ref),\n { destinationSpaceId },\n opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined\n );\n if (rt.json) return printJSON(share);\n process.stdout.write(\n `Share ${share.id} requested. ${share.counterpartySpaceName} has until ${share.expiresAt} to accept.\\n`\n );\n });\n\n cmd\n .command(\"shares\")\n .description(\"list pending backup shares into and out of this space\")\n .action(async (_opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const list = await client.backupShares.list(space);\n if (rt.json) return printJSON(list);\n printTable([\"ID\", \"DIRECTION\", \"BACKUP\", \"OTHER SPACE\", \"STATUS\", \"EXPIRES\"], shareRows(list));\n });\n\n cmd\n .command(\"accept\")\n .argument(\"<share-id>\", \"an incoming share (see `krova backups shares`)\")\n .description(\"accept a backup shared with this space; its storage is billed to this space\")\n .action(async (shareId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const accepted = await client.backupShares.accept(space, shareId);\n if (rt.json) return printJSON(accepted);\n process.stdout.write(\n `Accepted. The copy is backup ${accepted.backup.id} (\"${accepted.backup.name}\").\\n`\n );\n });\n\n cmd\n .command(\"decline\")\n .argument(\"<share-id>\", \"an incoming share (see `krova backups shares`)\")\n .description(\"decline a backup shared with this space\")\n .action(async (shareId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const share = await client.backupShares.decline(space, shareId);\n if (rt.json) return printJSON(share);\n process.stdout.write(`Declined share ${share.id}. Nothing was copied.\\n`);\n });\n\n cmd\n .command(\"cancel\")\n .argument(\"<share-id>\", \"an outgoing share (see `krova backups shares`)\")\n .description(\"withdraw a pending share this space offered\")\n .action(async (shareId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const share = await client.backupShares.cancel(space, shareId);\n if (rt.json) return printJSON(share);\n process.stdout.write(`Canceled share ${share.id}.\\n`);\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\n\nimport { printJSON, printKeyValue, printTable } from \"../lib/output.js\";\nimport { getRuntime, makeClient } from \"../lib/runtime.js\";\n\nfunction fmtVal(v: unknown): string {\n if (v === null || v === undefined) return \"\";\n if (typeof v === \"object\") return JSON.stringify(v);\n return String(v);\n}\n\n/** Flatten a top-level object field one level deep into `key.subkey` rows, so\n * nested objects (e.g. pricing's `rates`) render as readable key/value pairs\n * instead of a JSON blob. Exported for testing. */\nexport function flattenRows(entries: [string, unknown][]): [string, string][] {\n const rows: [string, string][] = [];\n for (const [k, v] of entries) {\n if (v && typeof v === \"object\" && !Array.isArray(v)) {\n for (const [sk, sv] of Object.entries(v as Record<string, unknown>)) {\n rows.push([`${k}.${sk}`, fmtVal(sv)]);\n }\n } else {\n rows.push([k, fmtVal(v)]);\n }\n }\n return rows;\n}\n\n/**\n * Render a catalog payload as text. If the payload has an array field, print any\n * scalar/object fields first (as key/value) and then the array as a table —\n * otherwise the non-array fields are silently dropped. This matters for\n * `pricing`, whose per-resource `rates` (the actual hourly prices), `currency`,\n * and `note` sit alongside the `tiers` array. `regions`/`images` have only the\n * array, so their output is unchanged.\n */\nfunction renderCatalog(obj: Record<string, unknown>): void {\n const arrKey = Object.keys(obj).find((k) => Array.isArray(obj[k]));\n if (!arrKey) {\n printKeyValue(flattenRows(Object.entries(obj)));\n return;\n }\n const rest = flattenRows(Object.entries(obj).filter(([k]) => k !== arrKey));\n if (rest.length) printKeyValue(rest);\n const arr = (obj[arrKey] as Record<string, unknown>[]) ?? [];\n const cols = [...new Set(arr.flatMap((o) => Object.keys(o)))];\n printTable(\n cols.map((c) => c.toUpperCase()),\n arr.map((o) => cols.map((c) => fmtVal(o[c])))\n );\n}\n\nfunction catalogCmd(\n name: string,\n desc: string,\n fetch: (c: ReturnType<typeof makeClient>) => Promise<Record<string, unknown>>\n): Command {\n return new Command(name)\n .description(desc)\n .action(async (_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const data = await fetch(client);\n if (rt.json) return printJSON(data);\n renderCatalog(data);\n });\n}\n\nexport function regionsCommand(): Command {\n return catalogCmd(\"regions\", \"list regions with available capacity\", (c) =>\n c.catalog.regions() as Promise<Record<string, unknown>>\n );\n}\nexport function imagesCommand(): Command {\n return catalogCmd(\"images\", \"list available OS images\", (c) =>\n c.catalog.images() as Promise<Record<string, unknown>>\n );\n}\nexport function pricingCommand(): Command {\n return catalogCmd(\"pricing\", \"show per-resource hourly pricing\", (c) =>\n c.catalog.pricing() as Promise<Record<string, unknown>>\n );\n}\n","import type { Command } from \"commander\";\n\nimport { FLAG_VALUE_CHOICES } from \"./output-format.js\";\n\nexport const COMPLETION_SHELLS = [\"bash\", \"zsh\", \"fish\"] as const;\nexport type CompletionShell = (typeof COMPLETION_SHELLS)[number];\n\ninterface OptionNode {\n long?: string;\n short?: string;\n description: string;\n takesValue: boolean;\n}\n\ninterface CommandNode {\n /** Canonical names from the root's first subcommand down; empty for the root. */\n path: string[];\n aliases: string[];\n description: string;\n options: OptionNode[];\n commands: CommandNode[];\n}\n\nconst oneLine = (s: string): string => s.split(\"\\n\")[0]!.replace(/\\s+/g, \" \").trim();\n\n/** Walk the commander tree (visible commands and options only). */\nexport function walkCommands(cmd: Command, path: string[] = []): CommandNode {\n const help = cmd.createHelp();\n return {\n path,\n aliases: cmd.aliases(),\n description: oneLine(cmd.description()),\n options: help.visibleOptions(cmd).map((o) => ({\n long: o.long,\n short: o.short,\n description: oneLine(o.description),\n takesValue: o.required || o.optional,\n })),\n commands: help.visibleCommands(cmd).map((c) => walkCommands(c, [...path, c.name()])),\n };\n}\n\n/** Shell single-quote: safe inside bash, zsh and fish single quotes. */\nconst sq = (s: string): string => `'${s.replace(/'/g, \"'\\\\''\")}'`;\nconst fishSq = (s: string): string => `'${s.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n\nconst flat = (node: CommandNode): CommandNode[] => [node, ...node.commands.flatMap(flat)];\nconst key = (path: string[]): string => path.join(\" \");\nconst optionWords = (n: CommandNode): string[] =>\n n.options.flatMap((o) => [o.long, o.short].filter((x): x is string => Boolean(x)));\nconst commandWords = (n: CommandNode): string[] => n.commands.flatMap((c) => [c.path.at(-1)!, ...c.aliases]);\n\n/** Every (parent path, typed word) -> child path transition, aliases included. */\nfunction transitions(root: CommandNode): Array<{ from: string; word: string; to: string }> {\n return flat(root).flatMap((parent) =>\n parent.commands.flatMap((c) =>\n [c.path.at(-1)!, ...c.aliases].map((word) => ({\n from: key(parent.path),\n word,\n to: key(c.path),\n }))\n )\n );\n}\n\ntype Choices = Record<string, readonly string[]>;\n\n/** Every flag in the tree that takes a value but has no fixed choices (paths, names, numbers). */\nfunction freeValueFlags(root: CommandNode, choices: Choices): string[] {\n const out = new Set<string>();\n for (const n of flat(root)) {\n for (const o of n.options) {\n if (!o.takesValue) continue;\n for (const f of [o.long, o.short]) if (f && !choices[f]) out.add(f);\n }\n }\n return [...out];\n}\n\nfunction bash(root: CommandNode, name: string, choices: Choices): string {\n const fn = `_${name}_complete`;\n const lines: string[] = [\n `# bash completion for ${name}, generated by \\`${name} completion bash\\``,\n `${fn}() {`,\n ` local cur prev cpath=\"\" w next i`,\n ` cur=\"\\${COMP_WORDS[COMP_CWORD]}\"`,\n ` prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"`,\n ` for ((i=1; i<COMP_CWORD; i++)); do`,\n ` w=\"\\${COMP_WORDS[i]}\"`,\n ` next=\"\"`,\n ` case \"$cpath/$w\" in`,\n ...transitions(root).map((t) => ` ${sq(`${t.from}/${t.word}`)}) next=${sq(t.to)};;`),\n ` esac`,\n ` [ -n \"$next\" ] && cpath=\"$next\"`,\n ` done`,\n ` case \"$prev\" in`,\n ...Object.entries(choices).map(\n ([flag, values]) => ` ${sq(flag)}) COMPREPLY=( $(compgen -W ${sq(values.join(\" \"))} -- \"$cur\") ); return;;`\n ),\n ...freeValueFlags(root, choices).map((f) => ` ${sq(f)}) COMPREPLY=(); return;;`),\n ` esac`,\n ` local cmds=\"\" opts=\"\"`,\n ` case \"$cpath\" in`,\n ...flat(root).map(\n (n) =>\n ` ${sq(key(n.path))}) cmds=${sq(commandWords(n).join(\" \"))}; opts=${sq(optionWords(n).join(\" \"))};;`\n ),\n ` esac`,\n ` if [[ \"$cur\" == -* ]]; then`,\n ` COMPREPLY=( $(compgen -W \"$opts\" -- \"$cur\") )`,\n ` else`,\n ` COMPREPLY=( $(compgen -W \"$cmds\" -- \"$cur\") )`,\n ` fi`,\n `}`,\n `complete -o default -F ${fn} ${name}`,\n ];\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction zsh(root: CommandNode, name: string, choices: Choices): string {\n const fn = `_${name}`;\n const item = (word: string, desc: string): string =>\n sq(`${word.replace(/:/g, \"\\\\:\")}${desc ? `:${desc}` : \"\"}`);\n const lines: string[] = [\n `#compdef ${name}`,\n `# zsh completion for ${name}, generated by \\`${name} completion zsh\\``,\n `${fn}() {`,\n ` local cpath=\"\" w next i`,\n ` local -a cmds opts`,\n ` for (( i=2; i<CURRENT; i++ )); do`,\n ` w=\"\\${words[i]}\"`,\n ` next=\"\"`,\n ` case \"$cpath/$w\" in`,\n ...transitions(root).map((t) => ` ${sq(`${t.from}/${t.word}`)}) next=${sq(t.to)};;`),\n ` esac`,\n ` [[ -n \"$next\" ]] && cpath=\"$next\"`,\n ` done`,\n ` case \"\\${words[CURRENT-1]}\" in`,\n ...Object.entries(choices).map(\n ([flag, values]) => ` ${sq(flag)}) compadd -- ${values.map(sq).join(\" \")}; return;;`\n ),\n ...freeValueFlags(root, choices).map((f) => ` ${sq(f)}) _files; return;;`),\n ` esac`,\n ` case \"$cpath\" in`,\n ...flat(root).flatMap((n) => {\n const cmdItems = n.commands.flatMap((c) =>\n [c.path.at(-1)!, ...c.aliases].map((w) => item(w, c.description))\n );\n const optItems = n.options.flatMap((o) =>\n [o.long, o.short].filter((x): x is string => Boolean(x)).map((w) => item(w, o.description))\n );\n return [` ${sq(key(n.path))})`, ` cmds=(${cmdItems.join(\" \")})`, ` opts=(${optItems.join(\" \")});;`];\n }),\n ` esac`,\n ` if [[ \"$PREFIX\" == -* ]]; then`,\n ` _describe -t options 'option' opts`,\n ` else`,\n ` _describe -t commands 'command' cmds`,\n ` (( \\${#cmds} )) || _files`,\n ` fi`,\n `}`,\n `if [ \"$funcstack[1]\" = \"${fn}\" ]; then`,\n ` ${fn} \"$@\"`,\n `else`,\n ` compdef ${fn} ${name}`,\n `fi`,\n ];\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction fish(root: CommandNode, name: string, choices: Choices): string {\n const fn = `__${name}_path`;\n const rootKey = \"root\";\n const k = (path: string[]): string => (path.length ? key(path) : rootKey);\n const lines: string[] = [\n `# fish completion for ${name}, generated by \\`${name} completion fish\\``,\n `function ${fn}`,\n ` set -l cpath ${rootKey}`,\n ` set -l tokens (commandline -opc)`,\n ` set -e tokens[1]`,\n ` for w in $tokens`,\n ` switch \"$cpath/$w\"`,\n ...transitions(root).flatMap((t) => [\n ` case ${fishSq(`${t.from || rootKey}/${t.word}`)}`,\n ` set cpath ${fishSq(t.to)}`,\n ]),\n ` end`,\n ` end`,\n ` echo $cpath`,\n `end`,\n ];\n for (const n of flat(root)) {\n const cond = `-n ${fishSq(`test (${fn}) = ${fishSq(k(n.path))}`)}`;\n // Where a command takes subcommands, offer only those. A command that takes\n // arguments keeps fish's file completion, as do options that take a value (-r).\n if (n.commands.length) lines.push(`complete -c ${name} ${cond} -f`);\n for (const c of n.commands) {\n for (const w of [c.path.at(-1)!, ...c.aliases]) {\n lines.push(`complete -c ${name} ${cond} -a ${fishSq(w)} -d ${fishSq(c.description)}`);\n }\n }\n for (const o of n.options) {\n const parts = [`complete -c ${name} ${cond}`];\n if (o.short) parts.push(`-s ${o.short.replace(/^-/, \"\")}`);\n if (o.long) parts.push(`-l ${o.long.replace(/^--/, \"\")}`);\n const values = [o.long, o.short].map((f) => (f ? choices[f] : undefined)).find(Boolean);\n if (values) parts.push(`-x -a ${fishSq(values.join(\" \"))}`);\n else if (o.takesValue) parts.push(\"-r\");\n parts.push(`-d ${fishSq(o.description)}`);\n lines.push(parts.join(\" \"));\n }\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/** Generate the completion script for `shell` from the live command tree under `root`. */\nexport function generateCompletion(\n shell: CompletionShell,\n root: Command,\n choices: Choices = FLAG_VALUE_CHOICES\n): string {\n const tree = walkCommands(root);\n const name = root.name();\n if (shell === \"bash\") return bash(tree, name, choices);\n if (shell === \"zsh\") return zsh(tree, name, choices);\n return fish(tree, name, choices);\n}\n\nexport const COMPLETION_INSTALL_HELP = `\nInstall (restart your shell afterward):\n\n bash mkdir -p ~/.local/share/bash-completion/completions\n krova completion bash > ~/.local/share/bash-completion/completions/krova\n (or add 'source <(krova completion bash)' to ~/.bashrc)\n zsh krova completion zsh > \"\\${fpath[1]}/_krova\"\n (needs 'autoload -U compinit && compinit' in ~/.zshrc; or add\n 'source <(krova completion zsh)' to ~/.zshrc after compinit)\n fish krova completion fish > ~/.config/fish/completions/krova.fish\n\nThe script is generated from the commands in your installed version, so\nre-run it after you upgrade the CLI.\n`;\n","import { Argument, Command } from \"commander\";\n\nimport {\n COMPLETION_INSTALL_HELP,\n COMPLETION_SHELLS,\n type CompletionShell,\n generateCompletion,\n} from \"../lib/completion.js\";\n\nexport function completionCommand(): Command {\n return new Command(\"completion\")\n .description(\"print a shell completion script (bash, zsh or fish)\")\n .addArgument(new Argument(\"<shell>\", \"target shell\").choices(COMPLETION_SHELLS))\n .addHelpText(\"after\", COMPLETION_INSTALL_HELP)\n .action((shell: CompletionShell, _opts, cmd: Command) => {\n let root = cmd;\n while (root.parent) root = root.parent;\n process.stdout.write(generateCompletion(shell, root));\n });\n}\n","import { Command } from \"commander\";\n\nimport { contextKey, displayKey, load, removeContext, renameContext, save, storageOf } from \"../lib/config.js\";\nimport { printJSON, printTable } from \"../lib/output.js\";\nimport { parseOutputFormat } from \"../lib/output-format.js\";\n\nexport function contextCommand(): Command {\n const ctx = new Command(\"context\")\n .aliases([\"ctx\", \"contexts\"])\n .description(\"manage named credential contexts (like kubectl/aws profiles)\");\n\n ctx\n .command(\"list\")\n .aliases([\"ls\"])\n .description(\"list all contexts\")\n .option(\"--show-secrets\", \"print full API keys instead of masked ones (JSON output only; the table has no key column)\")\n .action((opts, cmd: Command) => {\n // Not getRuntime: it resolves the active context, which would read its key from the keychain.\n const g = cmd.optsWithGlobals() as Record<string, unknown>;\n const json = Boolean(g.json) || parseOutputFormat(g.output) === \"json\";\n const cfg = load();\n if (json) {\n return printJSON({\n currentContext: cfg.currentContext ?? \"\",\n contexts: (cfg.contexts ?? []).map((c) => ({\n name: c.name,\n // A keychain key is only read (and the keychain only prompted) when the caller asks to see it.\n apiKey: opts.showSecrets || storageOf(c) === \"file\" ? displayKey(contextKey(c), Boolean(opts.showSecrets)) : \"****\",\n keyStorage: storageOf(c),\n spaceId: c.spaceId ?? \"\",\n spaceName: c.spaceName ?? \"\",\n baseUrl: c.baseUrl ?? \"\",\n })),\n });\n }\n printTable(\n [\"CURRENT\", \"NAME\", \"SPACE\", \"SPACE ID\", \"BASE URL\"],\n (cfg.contexts ?? []).map((c) => [\n c.name === cfg.currentContext ? \"*\" : \"\",\n c.name,\n c.spaceName ?? \"\",\n c.spaceId ?? \"\",\n c.baseUrl ?? \"\",\n ])\n );\n });\n\n ctx\n .command(\"current\")\n .description(\"print the current context name\")\n .action(() => {\n const cfg = load();\n if (!cfg.currentContext) throw new Error(\"no current context set\");\n process.stdout.write(`${cfg.currentContext}\\n`);\n });\n\n ctx\n .command(\"use\")\n .argument(\"<name>\", \"context name\")\n .description(\"switch the current context\")\n .action((name: string) => {\n const cfg = load();\n if (!(cfg.contexts ?? []).some((c) => c.name === name)) {\n throw new Error(`no context named \"${name}\"`);\n }\n cfg.currentContext = name;\n save(cfg);\n process.stdout.write(`Switched to context ${name}\\n`);\n });\n\n ctx\n .command(\"rename\")\n .argument(\"<old>\", \"current name\")\n .argument(\"<new>\", \"new name\")\n .description(\"rename a context\")\n .action((oldName: string, newName: string) => {\n const cfg = load();\n if (!newName.trim()) throw new Error(\"new name must not be empty\");\n // Moves the keychain item too, so the key follows the context name.\n renameContext(cfg, oldName, newName); // also saves the config, then deletes the old item\n process.stdout.write(`Renamed ${oldName} → ${newName}\\n`);\n });\n\n ctx\n .command(\"delete\")\n .aliases([\"rm\"])\n .argument(\"<name>\", \"context name\")\n .description(\"delete a context\")\n .action((name: string) => {\n const cfg = load();\n // Saves the config first, then deletes the keychain item.\n if (!removeContext(cfg, name)) throw new Error(`no context named \"${name}\"`);\n process.stdout.write(`Deleted context ${name}\\n`);\n });\n\n return ctx;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport * as readline from \"node:readline/promises\";\n\n/**\n * The interactive half of `krova cubes create`.\n *\n * Everything the prompt flow touches from the outside (the terminal, the\n * catalog, the key files) comes in through an interface, so tests drive it\n * with scripted answers and never need a TTY, a network or a real home dir.\n */\n\n/** Defaults for the resource flags. `cubes create` registers them on its options too. */\nexport const DEFAULT_RESOURCES = { vcpu: \"1\", ram: \"1\", disk: \"10\" } as const;\n\n/** One question-and-answer channel. */\nexport interface PromptIO {\n /** Show `question` and resolve with the typed line. Rejects with PromptAbortError when input ends. */\n ask(question: string): Promise<string>;\n /** Text for the person at the terminal (stdout). */\n write(text: string): void;\n /** A warning (stderr). */\n warn(text: string): void;\n close(): void;\n}\n\n/** Input ended (Ctrl+C, Ctrl+D, closed pipe) before the questions were answered. */\nexport class PromptAbortError extends Error {\n constructor() {\n super(\"input closed\");\n this.name = \"PromptAbortError\";\n }\n}\n\n/** Prompts run only on a real terminal, and never when the caller asked for JSON. */\nexport function isInteractive(opts: {\n json: boolean;\n stdin?: { isTTY?: boolean };\n stdout?: { isTTY?: boolean };\n}): boolean {\n if (opts.json) return false;\n const stdin = opts.stdin ?? process.stdin;\n const stdout = opts.stdout ?? process.stdout;\n return Boolean(stdin.isTTY && stdout.isTTY);\n}\n\n/** The real terminal, via node:readline/promises. */\nexport function createReadlineIO(): PromptIO {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const closed = new Promise<never>((_, reject) => {\n rl.once(\"close\", () => reject(new PromptAbortError()));\n });\n // The rejection is observed through `ask`; this keeps it from surfacing unhandled.\n closed.catch(() => undefined);\n rl.on(\"SIGINT\", () => rl.close());\n return {\n ask: (question) => Promise.race([rl.question(question), closed]),\n write: (text) => void process.stdout.write(text),\n warn: (text) => void process.stderr.write(text),\n close: () => rl.close(),\n };\n}\n\nexport interface CatalogImage {\n id: string;\n name: string;\n version: string;\n}\n\nexport interface CatalogRegion {\n slug: string;\n name: string;\n}\n\n/** The slice of `client.catalog` the prompts use. */\nexport interface CatalogSource {\n images(): Promise<{ images: CatalogImage[] }>;\n regions(): Promise<{ regions: CatalogRegion[] }>;\n}\n\n/** Where public keys are read from. Only `.pub` paths ever reach `readFile`. */\nexport interface KeyFiles {\n home: string;\n readFile(path: string): Promise<string>;\n}\n\nexport function defaultKeyFiles(): KeyFiles {\n return { home: homedir(), readFile: (path) => readFile(path, \"utf8\") };\n}\n\n/** Key files offered, in order. Public halves only; a private key is never opened. */\nexport const KEY_CANDIDATE_FILES = [\"id_ed25519.pub\", \"id_rsa.pub\"] as const;\n\n/** What the person typed on the command line; `undefined` means not given. */\nexport interface CreateGiven {\n name?: string;\n image?: string;\n sshKey?: string;\n region?: string;\n vcpu?: string;\n ram?: string;\n disk?: string;\n}\n\nexport interface CreateAnswers {\n name: string;\n image: string;\n sshKey: string;\n region?: string;\n vcpu: string;\n ram: string;\n disk: string;\n}\n\nexport interface PromptDeps {\n io: PromptIO;\n catalog: CatalogSource;\n keyFiles: KeyFiles;\n}\n\n// Mirrors the API's own checks (validateName and isValidSshPublicKey in krova-cloud).\nconst KEY_PREFIXES = [\n \"ssh-rsa\",\n \"ssh-ed25519\",\n \"ecdsa-sha2-nistp256\",\n \"ecdsa-sha2-nistp384\",\n \"ecdsa-sha2-nistp521\",\n \"ssh-dss\",\n \"sk-ssh-ed25519@openssh.com\",\n \"sk-ecdsa-sha2-nistp256@openssh.com\",\n];\n\n/** A cube name: 1 to 64 characters after trimming, no control characters. Returns the trimmed name or null. */\nexport function validCubeName(raw: string): string | null {\n const name = raw.trim();\n if (name.length === 0 || name.length > 64) return null;\n // biome-ignore lint/suspicious/noControlCharactersInRegex: detecting control characters is the point\n if (/[\\x00-\\x1F\\x7F]/.test(name)) return null;\n return name;\n}\n\nexport function validSshPublicKey(raw: string): boolean {\n const type = raw.trim().split(/\\s+/)[0] ?? \"\";\n return KEY_PREFIXES.some((prefix) => type.startsWith(prefix));\n}\n\nfunction positiveInt(raw: string): number | null {\n const n = Number(raw.trim());\n return Number.isInteger(n) && n > 0 ? n : null;\n}\n\n/** Read one public key file. Refuses anything that is not a `.pub` path. */\nasync function readPublicKey(keyFiles: KeyFiles, path: string): Promise<string | null> {\n if (!path.endsWith(\".pub\")) throw new Error(`refusing to read a non-public key file: ${path}`);\n try {\n const key = (await keyFiles.readFile(path)).trim();\n return validSshPublicKey(key) ? key : null;\n } catch {\n return null;\n }\n}\n\nexport interface KeyCandidate {\n /** Shown to the person, with `~` for the home directory. */\n label: string;\n key: string;\n}\n\nexport async function findKeyCandidates(keyFiles: KeyFiles): Promise<KeyCandidate[]> {\n const found: KeyCandidate[] = [];\n for (const file of KEY_CANDIDATE_FILES) {\n const key = await readPublicKey(keyFiles, join(keyFiles.home, \".ssh\", file));\n if (key) found.push({ label: `~/.ssh/${file}`, key });\n }\n return found;\n}\n\n/** \"ssh-ed25519 AAAA you@laptop\" -> \"ssh-ed25519 you@laptop\" (type and comment, never the key body). */\nfunction keyBlurb(key: string): string {\n const [type, , ...comment] = key.trim().split(/\\s+/);\n return [type, comment.join(\" \")].filter(Boolean).join(\" \");\n}\n\nfunction errText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nasync function askName(io: PromptIO): Promise<string> {\n for (;;) {\n const name = validCubeName(await io.ask(\"Name: \"));\n if (name) return name;\n io.write(\"A name is 1 to 64 characters with no control characters.\\n\");\n }\n}\n\nasync function askImage(io: PromptIO, catalog: CatalogSource): Promise<string> {\n let images: CatalogImage[] = [];\n try {\n images = (await catalog.images()).images;\n } catch (err) {\n io.warn(`Could not load the image list (${errText(err)}).\\n`);\n }\n if (images.length === 0) {\n for (;;) {\n const slug = (await io.ask(\"Image slug (see `krova images`): \")).trim();\n if (slug) return slug;\n }\n }\n io.write(\"Images:\\n\");\n images.forEach((img, i) => {\n io.write(` ${i + 1}) ${img.id} (${[img.name, img.version].filter(Boolean).join(\" \")})\\n`);\n });\n for (;;) {\n const answer = (await io.ask(\"Image (number or slug): \")).trim();\n const byNumber = /^\\d+$/.test(answer) ? images[Number(answer) - 1] : undefined;\n if (byNumber) return byNumber.id;\n const byId = images.find((img) => img.id === answer);\n if (byId) return byId.id;\n io.write(`Pick a number from 1 to ${images.length}, or one of the slugs above.\\n`);\n }\n}\n\n/** `undefined` means \"let Krova choose\". */\nasync function askRegion(io: PromptIO, catalog: CatalogSource): Promise<string | undefined> {\n let regions: CatalogRegion[] = [];\n try {\n regions = (await catalog.regions()).regions;\n } catch (err) {\n io.warn(`Could not load the region list (${errText(err)}).\\n`);\n }\n if (regions.length === 0) return undefined;\n io.write(\"Regions:\\n\");\n regions.forEach((r, i) => {\n io.write(` ${i + 1}) ${r.slug} (${r.name})\\n`);\n });\n for (;;) {\n const answer = (await io.ask(\"Region (number or slug, Enter to let Krova choose): \")).trim();\n if (!answer) return undefined;\n const byNumber = /^\\d+$/.test(answer) ? regions[Number(answer) - 1] : undefined;\n if (byNumber) return byNumber.slug;\n const bySlug = regions.find((r) => r.slug === answer);\n if (bySlug) return bySlug.slug;\n io.write(`Pick a number from 1 to ${regions.length}, a slug above, or press Enter.\\n`);\n }\n}\n\nasync function askSize(io: PromptIO, label: string, fallback: string): Promise<string> {\n for (;;) {\n const answer = (await io.ask(`${label} [${fallback}]: `)).trim();\n const n = positiveInt(answer === \"\" ? fallback : answer);\n if (n !== null) return String(n);\n io.write(`${label} must be a positive whole number.\\n`);\n }\n}\n\nasync function askSshKey(io: PromptIO, keyFiles: KeyFiles): Promise<string> {\n const candidates = await findKeyCandidates(keyFiles);\n if (candidates.length > 0) {\n io.write(\"SSH public keys found:\\n\");\n candidates.forEach((c, i) => {\n io.write(` ${i + 1}) ${c.label} (${keyBlurb(c.key)})\\n`);\n });\n }\n const prompt =\n candidates.length > 0\n ? \"SSH key (number, or paste a public key) [1]: \"\n : \"SSH public key (paste it, e.g. ssh-ed25519 AAAA...): \";\n for (;;) {\n const answer = (await io.ask(prompt)).trim();\n if (candidates.length > 0 && answer === \"\") return (candidates[0] as KeyCandidate).key;\n const picked = /^\\d+$/.test(answer) ? candidates[Number(answer) - 1] : undefined;\n if (picked) return picked.key;\n if (validSshPublicKey(answer)) return answer;\n io.write(\"That is not a public key. It starts with ssh-ed25519, ssh-rsa, ecdsa-sha2-... or sk-...\\n\");\n }\n}\n\n/**\n * Ask for every value not already given on the command line. Questions come in\n * the order name, image, region, size, SSH key; a value given as a flag is\n * never asked again.\n */\nexport async function promptCreate(given: CreateGiven, deps: PromptDeps): Promise<CreateAnswers> {\n const { io, catalog, keyFiles } = deps;\n const name = given.name ?? (await askName(io));\n const image = given.image ?? (await askImage(io, catalog));\n const region = given.region ?? (await askRegion(io, catalog));\n const vcpu = given.vcpu ?? (await askSize(io, \"vCPUs\", DEFAULT_RESOURCES.vcpu));\n const ram = given.ram ?? (await askSize(io, \"RAM in GB\", DEFAULT_RESOURCES.ram));\n const disk = given.disk ?? (await askSize(io, \"Disk in GB\", DEFAULT_RESOURCES.disk));\n const sshKey = given.sshKey ?? (await askSshKey(io, keyFiles));\n return { name, image, sshKey, ...(region ? { region } : {}), vcpu, ram, disk };\n}\n\n/** One line that says what is about to be created. */\nexport function summarize(\n a: Pick<CreateAnswers, \"name\" | \"image\" | \"region\" | \"vcpu\" | \"ram\" | \"disk\">,\n): string {\n const parts = [\n a.image,\n a.region ? `region ${a.region}` : \"region chosen by Krova\",\n `${a.vcpu} vCPU`,\n `${a.ram} GB RAM`,\n `${a.disk} GB disk`,\n ];\n return `Create cube \"${a.name}\" (${parts.join(\", \")})`;\n}\n\n/** `[Y/n]`: Enter or y/yes is yes, n/no is no, anything else asks again. */\nexport async function confirmCreate(io: PromptIO, summary: string): Promise<boolean> {\n for (;;) {\n const answer = (await io.ask(`${summary}? [Y/n] `)).trim().toLowerCase();\n if (answer === \"\" || answer === \"y\" || answer === \"yes\") return true;\n if (answer === \"n\" || answer === \"no\") return false;\n }\n}\n","import type { KrovaClient } from \"@krovacloud/sdk\";\n\n/** Resolve a cube name-or-id to an id (parity with the Go resolveCube):\n * exact id wins; else exactly one exact name match; else a clear error. */\nexport async function resolveCube(\n client: KrovaClient,\n spaceId: string,\n ref: string\n): Promise<string> {\n const { cubes } = await client.cubes.list(spaceId);\n if (cubes.some((c) => c.id === ref)) return ref;\n const byName = cubes.filter((c) => c.name === ref);\n if (byName.length === 1) return byName[0]!.id;\n if (byName.length === 0) {\n throw new Error(\n `no cube named or with ID \"${ref}\" in this space (see \\`krova cubes list\\`)`\n );\n }\n const ids = byName.map((c) => c.id).join(\", \");\n throw new Error(\n `cube name \"${ref}\" is ambiguous: it matches ${byName.length} cubes (${ids}) — use the cube ID instead`\n );\n}\n","import * as readline from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\n\nexport interface TTYState {\n stdin: boolean;\n stdout: boolean;\n}\n\n/** The real terminal state of this process. */\nexport function currentTTY(): TTYState {\n return { stdin: Boolean(process.stdin.isTTY), stdout: Boolean(process.stdout.isTTY) };\n}\n\n/**\n * Whether a destructive or risky command should stop and ask first.\n *\n * Only a person at a terminal is asked: when stdin or stdout is piped (a script,\n * CI, an agent), the command proceeds exactly as it always did, so adding a\n * prompt never turns a working script into a hung one. `--yes` always skips it.\n */\nexport function shouldConfirm(opts: { yes?: boolean }, tty: TTYState = currentTTY()): boolean {\n if (opts.yes) return false;\n return tty.stdin && tty.stdout;\n}\n\n/** Dotted-quad IPv4 to a 32-bit number, or null when it is not one. */\nfunction ipv4ToNumber(addr: string): number | null {\n const parts = addr.split(\".\");\n if (parts.length !== 4) return null;\n let n = 0;\n for (const part of parts) {\n if (!/^\\d{1,3}$/.test(part) || Number(part) > 255) return null;\n n = n * 256 + Number(part);\n }\n return n;\n}\n\n/**\n * Whether a whitelist leaves the port open to every address.\n *\n * Open means: no entries at all; any entry whose prefix length is numerically 0\n * (`0.0.0.0/0`, `::/0`, and spellings such as `0.0.0.0/00` or `1.2.3.4/0`); or\n * the two IPv4 halves `0.0.0.0/1` and `128.0.0.0/1` together, which cover the\n * whole IPv4 space.\n */\nexport function isOpenWhitelist(whitelist: readonly string[]): boolean {\n const entries = whitelist.map((w) => w.trim()).filter(Boolean);\n if (entries.length === 0) return true;\n const halves = new Set<number>();\n for (const entry of entries) {\n const slash = entry.lastIndexOf(\"/\");\n if (slash < 0) continue;\n const prefix = entry.slice(slash + 1).trim();\n if (!/^\\d+$/.test(prefix)) continue;\n const length = Number(prefix);\n if (length === 0) return true;\n if (length === 1) {\n const n = ipv4ToNumber(entry.slice(0, slash).trim());\n if (n !== null) halves.add(n >= 2 ** 31 ? 1 : 0);\n }\n }\n return halves.size === 2;\n}\n\nexport function publicExposureWarning(cube: string, cubePort: number): string {\n 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}.`;\n}\n\n/**\n * Read a y/N answer. The prompt goes to stderr so `--json` stdout stays pure\n * JSON. Anything but y or yes counts as no. If the input ends before an answer\n * (Ctrl+D), the answer is no and the exit code is set to 1: nobody chose to\n * abort, so a script wrapping a terminal session must not read it as success.\n * The streams are injectable for tests.\n */\nexport function confirm(\n question: string,\n io: { input: Readable; output: Writable } = { input: process.stdin, output: process.stderr },\n): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = readline.createInterface({ input: io.input, output: io.output });\n let answered = false;\n rl.on(\"close\", () => {\n if (answered) return;\n process.exitCode = 1;\n resolve(false);\n });\n rl.question(question, (answer) => {\n answered = true;\n rl.close();\n resolve(/^y(es)?$/i.test(answer.trim()));\n });\n });\n}\n\n/** Print the abort notice: stdout for people, stderr under `--json`. */\nexport function printAborted(json: boolean): void {\n (json ? process.stderr : process.stdout).write(\"Aborted.\\n\");\n}\n","const FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nconst CLEAR_LINE = \"\\r\\x1b[K\";\n\nexport interface Spinner {\n /** Stop the spinner and clear its line. Safe to call more than once. */\n stop(): void;\n}\n\nconst NOOP: Spinner = { stop() {} };\n\n/**\n * Whether a spinner may be drawn: only on an interactive stderr, and never\n * when the command prints JSON (the caller passes `json`).\n */\nexport function spinnerEnabled(json: boolean, stream: NodeJS.WriteStream = process.stderr): boolean {\n return Boolean(stream.isTTY) && !json;\n}\n\n/**\n * Start a tiny stderr spinner with `label`. Returns a no-op when stderr is not\n * a TTY or `json` is set, so piped and scripted output never changes.\n * The line is cleared by `stop()` and, as a backstop, when the process exits.\n */\nexport function startSpinner(\n label: string,\n opts: { json?: boolean; stream?: NodeJS.WriteStream } = {}\n): Spinner {\n const stream = opts.stream ?? process.stderr;\n if (!spinnerEnabled(Boolean(opts.json), stream)) return NOOP;\n\n let i = 0;\n let active = true;\n const draw = () => stream.write(`${CLEAR_LINE}${FRAMES[i++ % FRAMES.length]} ${label}`);\n const clear = () => stream.write(CLEAR_LINE);\n const onExit = () => {\n if (active) clear();\n };\n draw();\n const timer = setInterval(draw, 80);\n timer.unref();\n process.once(\"exit\", onExit);\n return {\n stop() {\n if (!active) return;\n active = false;\n clearInterval(timer);\n process.removeListener(\"exit\", onExit);\n clear();\n },\n };\n}\n\n/** Run `fn` with a spinner that is cleared on success and on failure. */\nexport async function withSpinner<T>(\n label: string,\n opts: { json?: boolean; stream?: NodeJS.WriteStream },\n fn: () => Promise<T>\n): Promise<T> {\n const spinner = startSpinner(label, opts);\n try {\n return await fn();\n } finally {\n spinner.stop();\n }\n}\n","import { KrovaError } from \"@krovacloud/sdk\";\nimport type { Command } from \"commander\";\n\nimport { spinnerEnabled } from \"./spinner.js\";\n\n/** Every state the API reports for a Cube. */\nexport const CUBE_STATES = [\n \"pending\",\n \"booting\",\n \"running\",\n \"stopped\",\n \"stopping\",\n \"resizing\",\n \"error\",\n \"deleted\",\n] as const;\n\nexport type CubeState = (typeof CUBE_STATES)[number];\n\nexport const DEFAULT_WAIT_TIMEOUT_S = 300;\n/** Product behavior: how often the CLI asks the API while it waits. */\nexport const WAIT_POLL_MS = 2000;\n\n/** States a Cube does not come back from, so waiting on another state is over. */\nconst DEAD_ENDS: ReadonlySet<string> = new Set([\"error\", \"deleted\"]);\n\n/** Consecutive failed polls (a dropped connection, a 5xx) before the wait gives up. */\nconst MAX_POLL_FAILURES = 3;\n\n/** A whole number of seconds, 1 or more. `undefined` gives the default. */\nexport function parseWaitSeconds(raw: string | undefined, flag: string): number {\n if (raw === undefined) return DEFAULT_WAIT_TIMEOUT_S;\n const s = String(raw).trim();\n const n = Number(s);\n if (!/^\\d+$/.test(s) || !Number.isInteger(n) || n < 1) {\n throw new Error(`${flag} must be a whole number of seconds, 1 or more (got \"${raw}\").`);\n }\n return n;\n}\n\nexport function parseWaitState(raw: string | undefined): CubeState {\n const s = (raw ?? \"running\").trim().toLowerCase();\n if (!(CUBE_STATES as readonly string[]).includes(s)) {\n throw new Error(`--state must be one of ${CUBE_STATES.join(\", \")} (got \"${raw}\").`);\n }\n return s as CubeState;\n}\n\n/**\n * A flag's value only when it was typed on the command line, looking through\n * the parents too. The root command defines `--timeout` as well (the per-request\n * timeout), and commander hands a flag to the outermost command that knows it,\n * so a subcommand's own `--timeout` never sees the value.\n */\nexport function optionFromCli(cmd: Command, key: string): string | undefined {\n for (let c: Command | null = cmd; c; c = c.parent) {\n if (c.getOptionValueSource(key) === \"cli\") return String(c.getOptionValue(key));\n }\n return undefined;\n}\n\nexport interface WaitOptions<T extends { state: string }> {\n /** What the user typed, for messages. */\n cubeRef: string;\n target: string;\n timeoutS: number;\n /** One look at the Cube. */\n get: () => Promise<T>;\n intervalMs?: number;\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n /** Called after every look, with the state and the seconds waited so far. */\n onPoll?: (state: string, elapsedS: number) => void;\n}\n\nconst realSleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n\nfunction transient(err: unknown): boolean {\n return !(err instanceof KrovaError) || err.status >= 500;\n}\n\n/**\n * Poll a Cube until it reaches `target`. Resolves with the Cube as last seen.\n * Rejects with a one-line message on a timeout, or when the Cube lands in\n * `error` or `deleted` (unless that is the state asked for).\n */\nexport async function waitForCubeState<T extends { state: string }>(\n o: WaitOptions<T>\n): Promise<T> {\n const interval = o.intervalMs ?? WAIT_POLL_MS;\n const sleep = o.sleep ?? realSleep;\n const now = o.now ?? Date.now;\n const start = now();\n const deadline = start + o.timeoutS * 1000;\n let last = \"unknown\";\n let failures = 0;\n for (;;) {\n let cube: T | undefined;\n try {\n cube = await o.get();\n failures = 0;\n } catch (err) {\n if (!transient(err) || ++failures >= MAX_POLL_FAILURES) throw err;\n }\n if (cube) {\n last = cube.state;\n o.onPoll?.(last, Math.floor((now() - start) / 1000));\n if (last === o.target) return cube;\n if (DEAD_ENDS.has(last)) {\n throw new Error(\n `cube ${o.cubeRef} is in the \"${last}\" state, so it will not become ${o.target}`\n );\n }\n }\n const left = deadline - now();\n if (left <= 0) {\n throw new Error(\n `timed out after ${o.timeoutS}s waiting for cube ${o.cubeRef} to be ${o.target} (last state: ${last})`\n );\n }\n await sleep(Math.min(interval, left));\n }\n}\n\n/** The one-line progress readout on stderr: a TTY only, never with JSON. */\nexport function startWaitProgress(\n cubeRef: string,\n target: string,\n json: boolean,\n stream: NodeJS.WriteStream = process.stderr\n): { update: (state: string, elapsedS: number) => void; stop: () => void } {\n if (!spinnerEnabled(json, stream)) return { update() {}, stop() {} };\n const CLEAR = \"\\r\\x1b[K\";\n let drawn = false;\n const clear = () => {\n if (drawn) stream.write(CLEAR);\n drawn = false;\n };\n process.once(\"exit\", clear);\n return {\n update(state, elapsedS) {\n drawn = true;\n stream.write(`${CLEAR}Waiting for cube ${cubeRef} to be ${target}: ${state}, ${elapsedS}s`);\n },\n stop() {\n clear();\n process.removeListener(\"exit\", clear);\n },\n };\n}\n","import { KrovaError } from \"@krovacloud/sdk\";\nimport { Command } from \"commander\";\n\nimport {\n type CatalogSource,\n type KeyFiles,\n type PromptIO,\n DEFAULT_RESOURCES,\n PromptAbortError,\n confirmCreate,\n createReadlineIO,\n defaultKeyFiles,\n isInteractive,\n promptCreate,\n summarize,\n} from \"../lib/create-prompt.js\";\nimport { printJSON, printKeyValue, printTable } from \"../lib/output.js\";\nimport { resolveCube } from \"../lib/resolve.js\";\nimport { confirm, printAborted, shouldConfirm } from \"../lib/safety.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\nimport { withSpinner } from \"../lib/spinner.js\";\nimport {\n DEFAULT_WAIT_TIMEOUT_S,\n optionFromCli,\n parseWaitSeconds,\n parseWaitState,\n startWaitProgress,\n waitForCubeState,\n} from \"../lib/wait.js\";\n\nfunction listCmd(): Command {\n return new Command(\"list\")\n .aliases([\"ls\"])\n .description(\"list Cubes in the space\")\n .action(async (_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const { cubes } = await client.cubes.list(space);\n if (rt.json) return printJSON(cubes);\n printTable(\n [\"ID\", \"NAME\", \"STATE\", \"VCPU\", \"RAM(GB)\", \"DISK(GB)\", \"IMAGE\", \"IPV4\", \"PROTECTED\"],\n cubes.map((c) => [\n c.id,\n c.name,\n c.state,\n String(c.resources.vcpu),\n String(c.resources.ramGb),\n String(c.resources.diskGb),\n c.image,\n c.publicIpv4 ?? \"—\",\n // The ✓ is the only character readable in a terminal at 80-column\n // width; spelling out \"yes\"/\"no\" pushes the column past the screen\n // edge on the smallest supported layout. Empty cell when the flag is\n // off — the header column is the cue.\n c.terminationProtection ? \"✓\" : \"\",\n ])\n );\n });\n}\n\n/** Block until a Cube reaches `target`, with a progress line on a terminal. */\nasync function waitForCube(\n rt: ReturnType<typeof getRuntime>,\n client: ReturnType<typeof makeClient>,\n space: string,\n id: string,\n cubeRef: string,\n target: string,\n timeoutS: number\n) {\n const progress = startWaitProgress(cubeRef, target, rt.json);\n try {\n return await waitForCubeState({\n cubeRef,\n target,\n timeoutS,\n get: () => client.cubes.get(space, id),\n onPoll: progress.update,\n });\n } finally {\n progress.stop();\n }\n}\n\nfunction waitCmd(): Command {\n return new Command(\"wait\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"wait until a Cube reaches a state (running by default); exits 1 on a timeout or an error state\")\n .option(\"--state <state>\", \"state to wait for: pending, booting, running, stopped, stopping, resizing, error or deleted (default running)\")\n .option(\"--timeout <seconds>\", `give up after this many seconds (default ${DEFAULT_WAIT_TIMEOUT_S})`)\n .action(async (cubeRef: string, opts, cmd: Command) => {\n const target = parseWaitState(opts.state as string | undefined);\n const timeoutS = parseWaitSeconds(optionFromCli(cmd, \"timeout\"), \"--timeout\");\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cube = await waitForCube(rt, client, space, id, cubeRef, target, timeoutS);\n if (rt.json) return printJSON(cube);\n process.stdout.write(`Cube ${cube.id} is ${cube.state}\\n`);\n });\n}\n\nfunction getCmd(): Command {\n return new Command(\"get\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"show a single Cube\")\n .action(async (cubeRef: string, _opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cube = await client.cubes.get(space, id);\n if (rt.json) return printJSON(cube);\n printKeyValue([\n [\"ID\", cube.id],\n [\"Name\", cube.name],\n [\"State\", cube.state],\n [\"Image\", cube.image],\n [\"vCPU\", String(cube.resources.vcpu)],\n [\"RAM (GB)\", String(cube.resources.ramGb)],\n [\"Disk (GB)\", String(cube.resources.diskGb)],\n [\"Public IPv4\", cube.publicIpv4 ?? \"—\"],\n [\"Cost/hour\", `$${cube.costPerHour}`],\n [\"Idle timeout\", describeIdleTimeout(cube.idleTimeoutMinutes)],\n [\"Last active\", cube.lastActiveAt ?? \"-\"],\n ]);\n });\n}\n\n/** The values `cubes create` turns into a request body. All strings, as typed. */\nexport interface CreateBodyInput {\n name: string;\n image: string;\n sshKey: string;\n vcpu: string;\n ram: string;\n disk: string;\n region?: string;\n userData?: string;\n terminationProtection?: boolean;\n /** Minutes (10 to 10080) or `null` for off; leave out to send nothing. */\n idleTimeoutMinutes?: number | null;\n}\n\n/**\n * Build the POST /cubes body. Validates resources client-side so bad input\n * fails with a clear message rather than being coerced to NaN, then JSON null,\n * then a generic server 400.\n */\nexport function buildCreateBody(input: CreateBodyInput): Record<string, unknown> {\n const posInt = (flag: string, raw: string): number => {\n const n = Number(raw);\n if (!Number.isInteger(n) || n <= 0) {\n throw new Error(`--${flag} must be a positive integer (got \"${raw}\").`);\n }\n return n;\n };\n const body: Record<string, unknown> = {\n name: input.name,\n image: input.image,\n sshPublicKey: input.sshKey,\n resources: {\n vcpu: posInt(\"vcpu\", input.vcpu),\n ramGb: posInt(\"ram\", input.ram),\n diskGb: posInt(\"disk\", input.disk),\n },\n };\n if (input.region) body.region = input.region;\n if (input.userData) body.userData = input.userData;\n // Only send the flag when explicitly turned on; the server defaults it\n // to `false`, and an explicit `false` would just be noise on the wire.\n if (input.terminationProtection) body.terminationProtection = true;\n // `null` (--idle-timeout off) is sent on purpose; only `undefined` means \"not given\".\n if (input.idleTimeoutMinutes !== undefined) body.idleTimeoutMinutes = input.idleTimeoutMinutes;\n return body;\n}\n\n/** What `cubes create` needs from the outside world; tests swap these. */\nexport interface CreateDeps {\n /** Whether prompting is allowed (a real terminal, and not --json). */\n interactive: (json: boolean) => boolean;\n makeIO: () => PromptIO;\n keyFiles: () => KeyFiles;\n /** Catalog to list images and regions from; defaults to the API client's. */\n catalog?: (client: ReturnType<typeof makeClient>) => CatalogSource;\n /** Where human messages go; defaults to stdout. */\n stdout?: (text: string) => void;\n}\n\nconst defaultCreateDeps: CreateDeps = {\n interactive: (json) => isInteractive({ json }),\n makeIO: createReadlineIO,\n keyFiles: defaultKeyFiles,\n};\n\n// Required on the command line unless the terminal can ask. Order is the order\n// commander reports a missing one in.\nconst REQUIRED_CREATE_FLAGS = [\n [\"--name\", \"name\"],\n [\"--image\", \"image\"],\n [\"--ssh-key\", \"sshKey\"],\n] as const;\n\nexport function createCmd(deps: CreateDeps = defaultCreateDeps): Command {\n return new Command(\"create\")\n .description(\"provision a new Cube (in a terminal, asks for anything you leave out)\")\n .option(\"--name <name>\", \"cube name\")\n .option(\"--image <slug>\", \"OS image slug (see `krova images`)\")\n .option(\"--ssh-key <key>\", \"SSH public key written to authorized_keys\")\n .option(\"--vcpu <n>\", \"number of vCPUs\", DEFAULT_RESOURCES.vcpu)\n .option(\"--ram <gb>\", \"RAM in GB\", DEFAULT_RESOURCES.ram)\n .option(\"--disk <gb>\", \"disk size in GB\", DEFAULT_RESOURCES.disk)\n .option(\"--region <slug>\", \"region slug (see `krova regions`)\")\n .option(\"--user-data <script>\", \"cloud-init script\")\n .option(\"--idempotency-key <key>\", \"idempotency key (24h dedupe)\")\n .option(\n \"--termination-protection\",\n \"turn on termination protection (the cube cannot be deleted until turned off)\",\n false\n )\n .option(\"--idle-timeout <minutes>\", IDLE_TIMEOUT_HELP)\n .option(\"--wait\", \"wait until the Cube is running before returning\")\n .option(\"--wait-timeout <seconds>\", `with --wait, give up after this many seconds (default ${DEFAULT_WAIT_TIMEOUT_S})`)\n .option(\"-y, --yes\", \"skip the confirmation after the prompts\")\n .action(async (opts, cmd: Command) => {\n // Checked first so a bad value fails before any prompt or request.\n const waitTimeoutS = parseWaitSeconds(opts.waitTimeout as string | undefined, \"--wait-timeout\");\n const idleTimeoutMinutes =\n opts.idleTimeout === undefined ? undefined : parseIdleTimeout(opts.idleTimeout);\n // --name, --image and --ssh-key were requiredOption; without a terminal\n // they still are, with commander's own message and exit code.\n const missing = REQUIRED_CREATE_FLAGS.filter(([, key]) => opts[key] === undefined);\n const globals = cmd.optsWithGlobals() as { json?: unknown; output?: unknown };\n const wantsJson = Boolean(globals.json) || globals.output === \"json\";\n const prompting = missing.length > 0 && deps.interactive(wantsJson);\n if (missing.length > 0 && !prompting) {\n const flags = cmd.options.find((o) => o.long === missing[0]?.[0])?.flags;\n cmd.error(`error: required option '${flags}' not specified`, {\n code: \"commander.missingMandatoryOptionValue\",\n });\n }\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const out = deps.stdout ?? ((text: string) => void process.stdout.write(text));\n const build = (v: {\n name: string;\n image: string;\n sshKey: string;\n vcpu: string;\n ram: string;\n disk: string;\n region?: string;\n }) =>\n buildCreateBody({\n ...v,\n userData: opts.userData,\n terminationProtection: opts.terminationProtection,\n idleTimeoutMinutes,\n });\n let body: Record<string, unknown>;\n if (prompting) {\n const io = deps.makeIO();\n try {\n // A resource flag counts as given only when it came from the command line.\n const given = (key: \"vcpu\" | \"ram\" | \"disk\") =>\n cmd.getOptionValueSource(key) === \"default\" ? undefined : (opts[key] as string);\n const answers = await promptCreate(\n {\n name: opts.name,\n image: opts.image,\n sshKey: opts.sshKey,\n region: opts.region,\n vcpu: given(\"vcpu\"),\n ram: given(\"ram\"),\n disk: given(\"disk\"),\n },\n {\n io,\n catalog: deps.catalog ? deps.catalog(client) : client.catalog,\n keyFiles: deps.keyFiles(),\n }\n );\n // Build first so a bad flag value fails before the confirmation, not after it.\n body = build(answers);\n if (!opts.yes && !(await confirmCreate(io, summarize(answers)))) {\n out(\"Aborted.\\n\");\n return;\n }\n } catch (err) {\n if (!(err instanceof PromptAbortError)) throw err;\n out(\"\\nAborted.\\n\");\n process.exitCode = 1;\n return;\n } finally {\n io.close();\n }\n } else {\n body = build({\n name: opts.name,\n image: opts.image,\n sshKey: opts.sshKey,\n vcpu: opts.vcpu,\n ram: opts.ram,\n disk: opts.disk,\n region: opts.region,\n });\n }\n const cube = await withSpinner(\"Creating cube\", { json: rt.json }, () =>\n client.cubes.create(\n space,\n body as never,\n opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined\n )\n );\n if (idleTimeoutMinutes !== undefined && !idleTimeoutApplied(cube.idleTimeoutMinutes, idleTimeoutMinutes)) {\n // An older server ignores the field it does not know and still answers 201.\n process.stderr.write(IDLE_UNSUPPORTED_WARNING);\n }\n if (!opts.wait) {\n if (rt.json) return printJSON(cube);\n out(`Created cube ${cube.id} (${cube.state})\\n`);\n return;\n }\n if (!rt.json) out(`Created cube ${cube.id} (${cube.state})\\n`);\n const ready = await waitForCube(rt, client, space, cube.id, cube.id, \"running\", waitTimeoutS);\n if (rt.json) return printJSON(ready);\n out(`Cube ${ready.id} is running\\n`);\n });\n}\n\nfunction actionCmd(\n name: string,\n past: string,\n fn: (c: ReturnType<typeof makeClient>[\"cubes\"], space: string, id: string) => Promise<unknown>\n): Command {\n return new Command(name)\n .argument(\"<cube>\", \"cube name or ID\")\n .description(`${name} a Cube`)\n .action(async (cubeRef: string, _opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n await fn(client.cubes, space, id);\n if (rt.json) return printJSON({ id, result: past });\n process.stdout.write(`${past} cube ${id}\\n`);\n });\n}\n\nfunction deleteCmd(): Command {\n return new Command(\"delete\")\n .argument(\"<cube>\", \"cube name or ID\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .description(\"delete a Cube (permanent)\")\n .action(async (cubeRef: string, opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n if (shouldConfirm(opts)) {\n const ok = await confirm(\n `Delete cube ${cubeRef}${cubeRef === id ? \"\" : ` (${id})`}? This is permanent and cannot be undone. [y/N] `,\n );\n if (!ok) return printAborted(rt.json);\n }\n await client.cubes.delete(space, id);\n if (rt.json) return printJSON({ id, result: \"Deleting\" });\n process.stdout.write(`Deleting cube ${id}\\n`);\n });\n}\n\nfunction restartCmd(): Command {\n return new Command(\"restart\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"restart a Cube (cold restart — picks up a refreshed kernel)\")\n .action(async (cubeRef: string, _opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n await client.cubes.restart(space, id);\n if (rt.json) return printJSON({ id, result: \"Restarting\" });\n // Say COLD explicitly. A `reboot` from inside the Cube looks equivalent\n // but cannot change the kernel — Firecracker treats a guest reboot as a\n // shutdown and the kernel comes from the host.\n process.stdout.write(\n `Restarting cube ${id} (cold restart — disk state is preserved)\\n`,\n );\n });\n}\n\nfunction sshPortCmd(): Command {\n return new Command(\"ssh-port\")\n .argument(\"<cube>\", \"cube name or ID\")\n .requiredOption(\n \"--port <n>\",\n \"the port INSIDE the Cube that sshd listens on (default 22)\",\n )\n .description(\"change the in-Cube port that SSH is forwarded to (not the host port)\")\n .action(async (cubeRef: string, opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cubePort = Number(opts.port);\n if (!Number.isInteger(cubePort) || cubePort < 1 || cubePort > 65535) {\n throw new Error(\"--port must be an integer between 1 and 65535\");\n }\n await client.cubes.update(space, id, { cubePort } as never);\n if (rt.json) return printJSON({ id, cubePort });\n // Be explicit about WHICH side changed. The host port is assigned by\n // Krova and is not affected by this call, so pointing this at a port\n // nothing is listening on inside the Cube silently breaks SSH access.\n process.stdout.write(\n `Cube ${id}: SSH now forwarded to in-Cube port ${cubePort}.\\n` +\n (cubePort === 22\n ? \"\"\n : `Warning: sshd inside the Cube must be listening on ${cubePort}, ` +\n \"or SSH will stop working. The default is 22.\\n\"),\n );\n });\n}\n\nfunction renameCmd(): Command {\n return new Command(\"rename\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<new-name>\", \"the new name (1 to 64 printable characters)\")\n .description(\"rename a Cube (names do not have to be unique; a running Cube's hostname changes on its next cold restart)\")\n .action(async (cubeRef: string, rawName: string, _opts, cmd: Command) => {\n const newName = parseCubeName(rawName);\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cube = await client.cubes.rename(space, id, newName);\n if (rt.json) return printJSON(cube);\n process.stdout.write(`Renamed cube ${id} to ${cube.name}\\n`);\n });\n}\n\nconst IDLE_TIMEOUT_HELP =\n 'power the Cube off after this many minutes without activity (10 to 10080), or \"off\" (needs a server with the idle-timeout feature)';\n\nconst IDLE_UNSUPPORTED_WARNING =\n \"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\";\n\n/**\n * Parse `--idle-timeout`: whole minutes from 10 to 10080 (7 days), or `off`\n * (sent as `null`). Plain decimal digits only, so 1e2, 0x10 and \" 20\" fail.\n */\nexport function parseIdleTimeout(raw: string): number | null {\n if (raw === \"off\") return null;\n const n = Number(raw);\n if (!/^\\d+$/.test(raw) || !Number.isSafeInteger(n) || n < 10 || n > 10080) {\n throw new Error('--idle-timeout must be a whole number of minutes from 10 to 10080, or \"off\"');\n }\n return n;\n}\n\n/**\n * Did the server apply the requested timeout? A present field must equal the request. An absent field means\n * the server omitted it (an older server, or a null it left out): that only counts as applied for `off`.\n */\nexport function idleTimeoutApplied(\n returned: number | null | undefined,\n requested: number | null,\n): boolean {\n return returned === undefined ? requested === null : returned === requested;\n}\n\n/** `off` for a Cube with no timeout, `N min` for one with a timeout, `-` when the server does not say. */\nexport function describeIdleTimeout(minutes: number | null | undefined): string {\n if (minutes === undefined) return \"-\";\n return minutes === null ? \"off\" : `${minutes} min`;\n}\n\nfunction updateCmd(): Command {\n return new Command(\"update\")\n .argument(\"<cube>\", \"cube name or ID\")\n .option(\"--idle-timeout <minutes>\", IDLE_TIMEOUT_HELP)\n .description(\"change a Cube's settings (idle auto-stop; `rename`, `resize` and `protect` cover the rest)\")\n .action(async (cubeRef: string, opts, cmd: Command) => {\n if (opts.idleTimeout === undefined) {\n throw new Error(\"nothing to update: pass --idle-timeout <minutes|off>\");\n }\n const minutes = parseIdleTimeout(opts.idleTimeout);\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cube = await client.cubes.setIdleTimeout(space, id, minutes);\n // A 200 that does not carry the new value means the server ignored the field; never report a change that did not happen.\n if (!idleTimeoutApplied(cube.idleTimeoutMinutes, minutes)) {\n throw new Error(\n cube.idleTimeoutMinutes === undefined\n ? \"the server did not apply --idle-timeout (it needs a server with the idle-timeout feature)\"\n : `the server kept the idle timeout at ${describeIdleTimeout(cube.idleTimeoutMinutes)}`\n );\n }\n if (rt.json) return printJSON(cube);\n process.stdout.write(\n minutes === null\n ? `Turned off idle auto-stop for cube ${id}\\n`\n : `Set idle auto-stop for cube ${id} to ${minutes} min\\n`\n );\n });\n}\n\n/** Parse a `--vcpu`/`--ram`/`--disk` value. `integer` rejects fractions (RAM may be fractional). */\nexport function parseSize(flag: string, raw: string, integer: boolean): number {\n // Plain decimal digits only: Number() would also take 0x10, 1e1 and \" 5 \".\n const n = Number(raw);\n if (!(integer ? /^\\d+$/ : /^\\d+(\\.\\d+)?$/).test(raw) || !Number.isFinite(n) || n <= 0) {\n throw new Error(`${flag} must be a positive ${integer ? \"whole number\" : \"number\"}`);\n }\n return n;\n}\n\n/** Trim a new Cube name and check it locally: 1 to 64 characters, no control, line-separator or bidi characters. */\nexport function parseCubeName(raw: string): string {\n const name = raw.trim();\n const length = [...name].length;\n if (length < 1 || length > 64 || /[\\p{Cc}\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u2069]/u.test(name)) {\n throw new Error(\"the new name must be 1 to 64 printable characters\");\n }\n return name;\n}\n\nconst RESIZE_DIMENSIONS = [\n { key: \"vcpu\", label: \"vCPU\", unit: \"\" },\n { key: \"ramGb\", label: \"RAM\", unit: \" GB\" },\n { key: \"diskGb\", label: \"Disk\", unit: \" GB\" },\n] as const;\n\nfunction describeSize(size: { vcpu: number; ramGb: number; diskGb: number }): string {\n return `${size.vcpu} vCPU, ${size.ramGb} GB RAM, ${size.diskGb} GB disk`;\n}\n\nfunction resizeCmd(): Command {\n return new Command(\"resize\")\n .argument(\"<cube>\", \"cube name or ID\")\n .option(\"--vcpu <n>\", \"new vCPU count\")\n .option(\"--ram <gb>\", \"new RAM in GB (fractions allowed)\")\n .option(\"--disk <gb>\", \"new disk in GB (disk can only grow)\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .description(\n \"change a Cube's vCPU, RAM and/or disk; the API says whether it is applied live or restarts the Cube\",\n )\n .action(async (cubeRef: string, opts, cmd: Command) => {\n const resources: { vcpu?: number; ramGb?: number; diskGb?: number } = {};\n if (opts.vcpu !== undefined) resources.vcpu = parseSize(\"--vcpu\", opts.vcpu, true);\n if (opts.ram !== undefined) resources.ramGb = parseSize(\"--ram\", opts.ram, false);\n if (opts.disk !== undefined) resources.diskGb = parseSize(\"--disk\", opts.disk, true);\n if (Object.keys(resources).length === 0) {\n throw new Error(\"give at least one of --vcpu, --ram or --disk\");\n }\n\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n\n // The API only says whether a resize is live or restarts the Cube AFTER it\n // queues the job, so the question cannot name the outcome: it states the\n // change and that some changes restart. Only a person at a terminal is\n // asked; scripts and pipes proceed, and -y skips it.\n if (shouldConfirm(opts)) {\n const current = (await client.cubes.get(space, id)).resources;\n const target = { ...current, ...resources };\n const ok = await confirm(\n `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] `,\n );\n if (!ok) return printAborted(rt.json);\n }\n\n let result: Awaited<ReturnType<typeof client.cubes.resize>>;\n try {\n result = await client.cubes.resize(space, id, resources);\n } catch (err) {\n // The host, not the request, is out of room: retrying the same size\n // will not help, so say what will.\n if (\n err instanceof KrovaError &&\n err.status === 400 &&\n (err.body as { code?: unknown } | undefined)?.code === \"insufficient_host_capacity\"\n ) {\n Object.assign(err, {\n hint: \"The server this Cube runs on has no room for that size. Try a smaller size, or contact support.\",\n });\n }\n throw err;\n }\n\n if (rt.json) return printJSON({ id, ...result });\n process.stdout.write(`Resize queued for cube ${id} (job ${result.jobId})\\n`);\n for (const { key, label, unit } of RESIZE_DIMENSIONS) {\n const from = result.previous[key];\n const to = result.requested[key];\n process.stdout.write(\n ` ${label}: ${from === to ? `${to}${unit} (unchanged)` : `${from}${unit} -> ${to}${unit}`}\\n`,\n );\n }\n process.stdout.write(\n result.requiresRestart\n ? \"The Cube restarts to apply this change.\\n\"\n : \"Applied live: the Cube does not restart.\\n\",\n );\n process.stdout.write(`The Cube keeps its current size until the change is applied. Check with: krova cubes get ${id}\\n`);\n });\n}\n\n/**\n * Toggle a Cube's termination-protection flag. Shared by `protect` and\n * `unprotect`; only the boolean `enabled` differs.\n */\nfunction setProtectionCmd(name: string, enabled: boolean, past: string): Command {\n return new Command(name)\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\n enabled\n ? \"turn on termination protection (idempotent — no-op if already on; the cube cannot be deleted until turned off)\"\n : \"turn off termination protection (idempotent — no-op if already off)\",\n )\n .action(async (cubeRef: string, _opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n // The SDK call is idempotent: re-protecting a protected cube or\n // unprotecting an unprotected one is a no-op on the server. The CLI\n // surfaces the latest audit fields in `--json` for callers that want to\n // see who last changed the flag.\n const cube = await client.cubes.setTerminationProtection(space, id, enabled);\n if (rt.json) return printJSON(cube);\n process.stdout.write(`${past} cube ${id}\\n`);\n });\n}\n\nexport function cubesCommand(): Command {\n const cubes = new Command(\"cubes\").description(\"manage Cubes (Firecracker microVMs)\");\n cubes.addCommand(listCmd());\n cubes.addCommand(getCmd());\n cubes.addCommand(waitCmd());\n cubes.addCommand(createCmd());\n cubes.addCommand(\n actionCmd(\"power-off\", \"Powering off\", (c, s, id) => c.powerOff(s, id)),\n );\n cubes.addCommand(actionCmd(\"wake\", \"Starting\", (c, s, id) => c.wake(s, id)));\n cubes.addCommand(deleteCmd());\n cubes.addCommand(restartCmd());\n cubes.addCommand(sshPortCmd());\n cubes.addCommand(updateCmd());\n cubes.addCommand(renameCmd());\n cubes.addCommand(resizeCmd());\n cubes.addCommand(setProtectionCmd(\"protect\", true, \"Protected\"));\n cubes.addCommand(setProtectionCmd(\"unprotect\", false, \"Unprotected\"));\n return cubes;\n}\n\n// `list` and `get` are also mounted at the root (parity with the Go CLI).\nexport const rootListCommand = listCmd;\nexport const rootGetCommand = getCmd;\n","import { Command } from \"commander\";\n\nimport { printJSON, printTable } from \"../lib/output.js\";\nimport { resolveCube } from \"../lib/resolve.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\n\n/**\n * Narrow a `--origin-scheme` / positional scheme to the two the API accepts.\n * Returns undefined when the flag was omitted, so callers can leave the field\n * off the request entirely rather than sending an explicit default.\n */\nexport function parseOriginScheme(value: unknown): \"http\" | \"https\" | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (value === \"http\" || value === \"https\") return value;\n throw new Error(`--origin-scheme must be \"http\" or \"https\" (got \"${String(value)}\").`);\n}\n\n/**\n * Narrow a `--proxy-protocol` / positional version to what the API accepts:\n * \"v1\" or \"v2\", or \"off\" for none (sent as `null`). Returns undefined when the\n * flag was omitted, so `add` leaves the field off the request entirely.\n */\nexport function parseProxyProtocol(value: unknown): \"v1\" | \"v2\" | null | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (value === \"v1\" || value === \"v2\") return value;\n if (value === \"off\") return null;\n throw new Error(`--proxy-protocol must be \"v1\", \"v2\" or \"off\" (got \"${String(value)}\").`);\n}\n\ntype PrintableRecord = {\n type: string;\n host: string;\n value: string;\n note?: string | null;\n mustBeGrey?: boolean;\n state?: string;\n detail?: string;\n};\n\n/** How each live state reads on a terminal. */\nconst STATE_LABEL: Record<string, string> = {\n found: \"found\",\n // ⛔ NOT \"failed\". Before you publish a record, absent is the expected state.\n missing: \"not added yet\",\n mismatch: \"needs a change\",\n // ⛔ OUR lookup failed. Never phrased as the user's mistake.\n unknown: \"couldn't check\",\n};\n\n/**\n * Print the DNS records a domain needs.\n *\n * Both the host AND the value, because a record cannot be created from the\n * value alone — which is what made the old guidance impossible to act on.\n */\nfunction printRecords(records: PrintableRecord[], withState = false): void {\n if (records.length === 0) return;\n process.stdout.write(\"\\nDNS records to publish:\\n\");\n for (const r of records) {\n const state = withState && r.state ? ` [${STATE_LABEL[r.state] ?? r.state}]` : \"\";\n process.stdout.write(`\\n ${r.type.padEnd(5)} ${r.host}${state}\\n`);\n process.stdout.write(` -> ${r.value}\\n`);\n if (r.mustBeGrey) {\n // The single most common wildcard failure: proxied, so the CA sees\n // Cloudflare's addresses instead of the record.\n process.stdout.write(\" On Cloudflare: DNS only (grey cloud)\\n\");\n }\n if (withState && r.detail && r.state !== \"found\") {\n process.stdout.write(` ${r.detail}\\n`);\n }\n }\n}\n\n/** `krova domains` — manage a Cube's custom domains. */\nexport function domainsCommand(): Command {\n const cmd = new Command(\"domains\").description(\"manage a Cube's custom domains\");\n\n cmd\n .command(\"list\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"list the custom domains attached to a Cube\")\n .action(async (cubeRef: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const domains = await client.domains.list(space, id);\n if (rt.json) return printJSON(domains);\n printTable(\n [\"ID\", \"DOMAIN\", \"PORT\", \"STATUS\"],\n domains.map((d) => [d.id, d.domain, String(d.port ?? \"\"), d.status]),\n );\n });\n\n cmd\n .command(\"add\")\n .argument(\"<cube>\", \"cube name or ID\")\n .requiredOption(\"--domain <domain>\", \"the domain name to attach\")\n .requiredOption(\"--port <n>\", \"the in-Cube port to route to\")\n .option(\"--origin-scheme <scheme>\", \"transport the edge uses to reach the Cube: http (default) or https when the Cube terminates TLS itself\")\n .option(\"--proxy-protocol <version>\", \"send a PROXY protocol header (v1 or v2) naming the visitor on each connection to the Cube; your app must accept it on this port. Off by default\")\n .option(\"--confirm-mixed-proxy-protocol\", \"attach even though other domains on the same Cube port use a different PROXY protocol setting\")\n .description(\"attach a custom domain to a Cube\")\n .action(async (cubeRef: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const port = Number(opts.port);\n if (!Number.isInteger(port) || port <= 0 || port > 65535) {\n throw new Error(`--port must be a valid port (got \"${opts.port}\").`);\n }\n const originScheme = parseOriginScheme(opts.originScheme);\n const proxyProtocol = parseProxyProtocol(opts.proxyProtocol);\n const { domain, records } = await client.domains.create(space, id, {\n domain: opts.domain,\n port,\n ...(originScheme ? { originScheme } : {}),\n ...(proxyProtocol ? { proxyProtocol } : {}),\n ...(opts.confirmMixedProxyProtocol ? { confirmMixedProxyProtocol: true } : {}),\n });\n if (rt.json) return printJSON({ domain, records });\n process.stdout.write(`Attached ${domain.domain} (${domain.id}) — status ${domain.status}\\n`);\n // ⛔ Print the records. Attaching a domain does nothing until they exist,\n // and before this the CLI sent people away to find out what to publish —\n // for a wildcard, two of the three records were not discoverable from\n // anything the CLI printed.\n printRecords(records);\n process.stdout.write(\n `\\nAfter publishing them: krova domains records ${cubeRef} ${domain.id}\\n`,\n );\n });\n\n cmd\n .command(\"records\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<domain-id>\", \"the domain mapping ID (see `krova domains list`)\")\n .description(\"show the DNS records a domain needs, and whether they resolve yet\")\n .action(async (cubeRef: string, mappingId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const out = await client.domains.records(space, id, mappingId);\n if (rt.json) return printJSON(out);\n process.stdout.write(\n `${out.domain} — ${out.summary.found} of ${out.summary.total} records found\\n`,\n );\n printRecords(out.records, true);\n if (!out.summary.complete) {\n process.stdout.write(\"\\nDNS changes can take a few minutes to spread.\\n\");\n }\n });\n\n cmd\n .command(\"set-origin\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<domain-id>\", \"the domain mapping ID (see `krova domains list`)\")\n .argument(\"<scheme>\", \"http or https\")\n .description(\"set the transport the edge uses to reach the Cube\")\n .action(async (cubeRef: string, mappingId: string, scheme: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const originScheme = parseOriginScheme(scheme);\n if (!originScheme) {\n throw new Error(`scheme must be \"http\" or \"https\" (got \"${scheme}\").`);\n }\n const domain = await client.domains.update(space, id, mappingId, { originScheme });\n if (rt.json) return printJSON(domain);\n process.stdout.write(`${domain.domain} now reached over ${originScheme}\\n`);\n });\n\n cmd\n .command(\"set-proxy-protocol\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<domain-id>\", \"the domain mapping ID (see `krova domains list`)\")\n .argument(\"<version>\", \"v1, v2 or off\")\n .option(\"--confirm-mixed-proxy-protocol\", \"save even though other domains on the same Cube port use a different setting\")\n .description(\"send a PROXY protocol header naming the visitor on each connection to the Cube, or stop\")\n .action(async (cubeRef: string, mappingId: string, version: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const proxyProtocol = parseProxyProtocol(version);\n if (proxyProtocol === undefined) {\n throw new Error(`version must be \"v1\", \"v2\" or \"off\" (got \"${version}\").`);\n }\n const domain = await client.domains.update(space, id, mappingId, {\n proxyProtocol,\n ...(opts.confirmMixedProxyProtocol ? { confirmMixedProxyProtocol: true } : {}),\n });\n if (rt.json) return printJSON(domain);\n process.stdout.write(\n proxyProtocol\n ? `${domain.domain} now sends a PROXY protocol ${proxyProtocol} header to the Cube\\n`\n : `${domain.domain} no longer sends a PROXY protocol header\\n`,\n );\n });\n\n cmd\n .command(\"rm\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<domain-id>\", \"the domain mapping ID (see `krova domains list`)\")\n .description(\"detach a custom domain from a Cube\")\n .action(async (cubeRef: string, mappingId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n await client.domains.delete(space, id, mappingId);\n if (rt.json) return printJSON({ id: mappingId, result: \"detached\" });\n process.stdout.write(`Detached domain ${mappingId}\\n`);\n });\n\n return cmd;\n}\n","import { spawn } from \"node:child_process\";\n\nimport { Command } from \"commander\";\n\nimport { rawRequest } from \"../lib/client.js\";\nimport { loginMessage, persistLogin } from \"../lib/persist.js\";\nimport { getRuntime } from \"../lib/runtime.js\";\nimport { spinnerEnabled, withSpinner } from \"../lib/spinner.js\";\n\ninterface StartResponse {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string;\n interval: number;\n expiresIn: number;\n}\ninterface PollResponse {\n apiKey: string;\n spaceId: string;\n}\n\nconst BROWSER_UNAVAILABLE =\n \"Browser login isn't enabled on this server yet — run `krova auth login` to paste an API key from https://krova.cloud\";\n\n/** Characters that never appear in a device-login URL and that cmd.exe treats as operators. */\nconst SHELL_METACHARS = /[&|^<>\"]/;\n\n/**\n * Only open https URLs, or http to a loopback host, and return the normalized href.\n * The device-login URL is `<base>/cli?code=<ALNUM-ALNUM>`: it never needs `& | ^ < > \"`, so a URL\n * carrying one is refused on every platform. `%` is refused on Windows only, where it expands\n * environment variables in some launchers; the real URL never contains it (the code is alphanumeric).\n * A refused URL is not opened: the caller prints it for the user to open by hand.\n */\nexport function safeBrowserURL(\n raw: string,\n platform: NodeJS.Platform = process.platform\n): string | null {\n let u: URL;\n try {\n u = new URL(raw);\n } catch {\n return null;\n }\n const loopbackHttp =\n u.protocol === \"http:\" &&\n (u.hostname === \"localhost\" || u.hostname === \"127.0.0.1\" || u.hostname === \"[::1]\");\n if (!((u.protocol === \"https:\" && u.hostname) || loopbackHttp)) return null;\n const href = u.href;\n if (SHELL_METACHARS.test(href)) return null;\n if (platform === \"win32\" && href.includes(\"%\")) return null;\n return href;\n}\n\n/** Removes C0, DEL and C1 control characters (ESC included) so a server string cannot drive the terminal. */\nexport function stripControlChars(s: string): string {\n return s.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \"\");\n}\n\n/** The URL as it is shown to the user: the normalized href when it parses, else the raw string, with control characters stripped. */\nexport function displayURL(raw: string): string {\n try {\n return stripControlChars(new URL(raw).href);\n } catch {\n return stripControlChars(raw);\n }\n}\n\nexport interface BrowserSpawnPlan {\n command: string;\n args: string[];\n options: { stdio: \"ignore\"; detached: true; windowsHide?: true };\n}\n\n/**\n * How to open `href` in the default browser. Never uses a shell: on Windows `rundll32` is a real\n * executable, so cmd.exe never parses the URL.\n */\nexport function browserSpawnPlan(\n href: string,\n platform: NodeJS.Platform = process.platform\n): BrowserSpawnPlan {\n if (platform === \"win32\") {\n return {\n command: \"rundll32\",\n args: [\"url.dll,FileProtocolHandler\", href],\n options: { stdio: \"ignore\", detached: true, windowsHide: true },\n };\n }\n return {\n command: platform === \"darwin\" ? \"open\" : \"xdg-open\",\n args: [href],\n options: { stdio: \"ignore\", detached: true },\n };\n}\n\nfunction openBrowser(href: string): void {\n const plan = browserSpawnPlan(href);\n const child = spawn(plan.command, plan.args, plan.options);\n child.on(\"error\", () => {\n /* fall through — the URL was already printed */\n });\n child.unref();\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport function loginCommand(): Command {\n return new Command(\"login\")\n .description(\"log in through your browser (device authorization)\")\n .option(\"--no-browser\", \"don't open a browser; just print the URL\")\n .option(\"--context <name>\", \"name for the saved context\")\n .action(async (opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const baseUrl = rt.res.baseUrl;\n\n const start = await rawRequest<StartResponse>({\n method: \"POST\",\n baseUrl,\n path: \"/auth/cli/start\",\n timeoutMs: rt.timeoutMs,\n });\n if (start.status === 404) throw new Error(BROWSER_UNAVAILABLE);\n if (start.status !== 200 || !start.data?.deviceCode) {\n throw new Error(`device login failed to start (HTTP ${start.status})`);\n }\n const s = start.data;\n process.stdout.write(`Your verification code is: ${stripControlChars(String(s.userCode ?? \"\"))}\\n`);\n\n const target = s.verificationUriComplete || s.verificationUri;\n const safe = safeBrowserURL(target);\n if (safe && opts.browser !== false) {\n process.stdout.write(`Opening ${safe} …\\n`);\n openBrowser(safe);\n } else {\n process.stdout.write(`Open this URL to approve the login:\\n ${displayURL(target)}\\n`);\n if (!safe) {\n process.stdout.write(\n \"It was not opened automatically because it contains characters that are unsafe to pass to the system opener.\\n\"\n );\n }\n }\n\n const intervalMs = Math.max((s.interval || 5) * 1000, 5000);\n const deadline = Date.now() + Math.max(s.expiresIn || 600, 1) * 1000;\n // On an interactive terminal the spinner says it; otherwise keep the plain line.\n if (!spinnerEnabled(rt.json)) process.stdout.write(\"Waiting for approval…\\n\");\n\n // Poll loop. withSpinner clears the spinner line on success and on failure.\n const approved = await withSpinner(\"Waiting for approval\", { json: rt.json }, async () => {\n for (;;) {\n if (Date.now() >= deadline) {\n throw new Error(\n \"login timed out: the verification code expired before it was approved\"\n );\n }\n await sleep(intervalMs);\n const poll = await rawRequest<PollResponse>({\n method: \"POST\",\n baseUrl,\n path: \"/auth/cli/poll\",\n body: { deviceCode: s.deviceCode },\n timeoutMs: rt.timeoutMs,\n });\n if (poll.status === 200) {\n if (!poll.data?.apiKey) throw new Error(\"login succeeded but no API key was returned\");\n return poll.data;\n }\n if (poll.status === 202 || poll.status === 425 || poll.status === 428) continue;\n if (poll.status === 410) {\n throw new Error(\"login expired: request a new code with `krova login`\");\n }\n if (poll.status === 404) throw new Error(BROWSER_UNAVAILABLE);\n throw new Error(`login failed while polling (HTTP ${poll.status})`);\n }\n });\n const { ctxName, spaceName, stored } = await persistLogin({\n apiKey: approved.apiKey,\n baseUrl,\n spaceId: approved.spaceId,\n // Not opts.context: the root's own --context takes the flag first, so the\n // local option never receives it. The merged flags always carry it.\n ctxName: rt.flags.context,\n timeoutMs: rt.timeoutMs,\n });\n process.stdout.write(`${loginMessage(ctxName, stored)}\\n`);\n if (spaceName) process.stdout.write(`Space: ${spaceName}\\n`);\n });\n}\n","import { Command } from \"commander\";\n\nimport { printJSON, printTable } from \"../lib/output.js\";\nimport { resolveCube } from \"../lib/resolve.js\";\nimport { confirm, printAborted, shouldConfirm } from \"../lib/safety.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\n\n/** `krova snapshots` — snapshot and restore a Cube's disk. */\nexport function snapshotsCommand(): Command {\n const cmd = new Command(\"snapshots\").description(\"snapshot and restore a Cube's disk\");\n\n cmd\n .command(\"list\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"list a Cube's snapshots\")\n .action(async (cubeRef: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const snaps = await client.snapshots.list(space, id);\n if (rt.json) return printJSON(snaps);\n printTable(\n [\"ID\", \"NAME\", \"STATUS\", \"KIND\", \"SIZE (BYTES)\", \"CREATED\"],\n snaps.map((s) => [\n s.id,\n s.name,\n s.status,\n s.kind,\n s.sizeBytes == null ? \"\" : String(s.sizeBytes),\n s.createdAt,\n ]),\n );\n });\n\n cmd\n .command(\"create\")\n .argument(\"<cube>\", \"cube name or ID\")\n .option(\"--name <name>\", \"a name for the snapshot\")\n .description(\"create a snapshot of a Cube's disk\")\n .action(async (cubeRef: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const snap = await client.snapshots.create(space, id, opts.name ? { name: opts.name } : {});\n if (rt.json) return printJSON(snap);\n process.stdout.write(`Created snapshot ${snap.id} (${snap.status})\\n`);\n });\n\n cmd\n .command(\"rm\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<snapshot-id>\", \"the snapshot ID (see `krova snapshots list`)\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .description(\"delete a snapshot (permanent)\")\n .action(async (cubeRef: string, snapshotId: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n if (shouldConfirm(opts)) {\n // Show the snapshot's name when we can find it; the ID alone is hard to recognize.\n const name = (await client.snapshots.list(space, id).catch(() => [])).find(\n (s) => s.id === snapshotId,\n )?.name;\n const ok = await confirm(\n `Delete snapshot ${name ? `\"${name}\" (${snapshotId})` : snapshotId} of cube ${cubeRef}? This is permanent and cannot be undone. [y/N] `,\n );\n if (!ok) return printAborted(rt.json);\n }\n await client.snapshots.delete(space, id, snapshotId);\n if (rt.json) return printJSON({ id: snapshotId, result: \"deleted\" });\n process.stdout.write(`Deleted snapshot ${snapshotId}\\n`);\n });\n\n cmd\n .command(\"restore\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<snapshot-id>\", \"the snapshot to restore the Cube's disk from\")\n .description(\"restore a Cube's disk from one of its snapshots (replaces the disk)\")\n .action(async (cubeRef: string, snapshotId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n await client.cubes.restore(space, id, snapshotId);\n if (rt.json) return printJSON({ id, snapshotId, result: \"restore enqueued\" });\n process.stdout.write(`Restore of cube ${id} from ${snapshotId} enqueued\\n`);\n });\n\n return cmd;\n}\n","// SSH: fetch connection info, pin host keys, build a hardened `ssh` argv, exec.\n// Ports the Go CLI's option-injection guards and known_hosts pinning verbatim.\n\nimport { spawn } from \"node:child_process\";\nimport { appendFileSync, chmodSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { isIP } from \"node:net\";\nimport { dirname } from \"node:path\";\n\nimport { constants as osConstants } from \"node:os\";\n\nimport type { Command } from \"commander\";\n\nimport { rawRequest } from \"./client.js\";\nimport { configDir } from \"./config.js\";\nimport { join } from \"node:path\";\nimport { resolveCube } from \"./resolve.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"./runtime.js\";\n\nexport interface SshHostKey {\n type: string;\n key: string;\n}\nexport interface SshInfo {\n host: string;\n port: number;\n user: string;\n hostKeys: SshHostKey[];\n}\n\nexport interface SshOptions {\n /** Extra ssh flags placed before everything else (for example `-N`, `-T`). */\n preArgs?: string[];\n identity?: string;\n localFwd?: string[];\n remoteFwd?: string[];\n knownHosts?: string;\n remoteCmd?: string[];\n}\n\n// Characters an ssh host must never contain (option/metacharacter injection).\nconst HOST_BANNED = new Set(\n \"@/\\\\'\\\"`$;&|<>(){}*?!#=,\".split(\"\")\n);\n// User is slightly looser — it may contain '=' (host may not).\nconst USER_BANNED = new Set(\n \"@/\\\\'\\\"`$;&|<>(){}*?!#,:[]\".split(\"\")\n);\n\n// One DNS label: letters, digits and inner hyphens, at most 63 characters.\nconst DNS_NAME =\n /^(?=.{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])?)*$/;\n\nexport function validateSSHHost(host: string): void {\n const h = host.trim();\n if (!h) throw new Error(\"empty host\");\n if (h.startsWith(\"-\")) throw new Error(\"host must not start with '-'\");\n for (const r of h) {\n const code = r.codePointAt(0) ?? 0;\n if (code <= 0x20 || code === 0x7f) {\n throw new Error(\"host contains whitespace or control characters\");\n }\n if (HOST_BANNED.has(r)) {\n throw new Error(`host contains a disallowed character ${JSON.stringify(r)}`);\n }\n }\n if (isIP(h) === 0 && !DNS_NAME.test(h)) {\n throw new Error(\"host must be an IP address or a DNS hostname\");\n }\n}\n\nexport function validateSSHUser(user: string): void {\n const u = user.trim();\n if (!u) return; // empty user is allowed\n if (u.startsWith(\"-\")) throw new Error(\"user must not start with '-'\");\n for (const r of u) {\n const code = r.codePointAt(0) ?? 0;\n if (code <= 0x20 || code === 0x7f) {\n throw new Error(\"user contains whitespace or control characters\");\n }\n if (USER_BANNED.has(r)) {\n throw new Error(`user contains a disallowed character ${JSON.stringify(r)}`);\n }\n }\n}\n\n/** known_hosts host field: \"[host]:port\" when the port isn't the default 22. */\nexport function knownHostsHost(host: string, port: number): string {\n if (port > 0 && port !== 22) return `[${host}]:${port}`;\n return host;\n}\n\nexport function knownHostsPath(): string {\n return join(configDir(), \"known_hosts\");\n}\n\n/** True for a DNS hostname (e.g. the Cube's stable SSH hostname), false for a\n * bare IPv4/IPv6 address. */\nexport function isHostname(host: string): boolean {\n return isIP(host) === 0;\n}\n\n/** True when `host:port` has no existing known_hosts pin yet — used to print a\n * one-time note the first time we pin a Cube's hostname rather than its IP. */\nexport function isUnpinned(host: string, port: number): boolean {\n const field = knownHostsHost(host, port);\n let existing = \"\";\n try {\n existing = readFileSync(knownHostsPath(), \"utf8\");\n } catch {\n existing = \"\";\n }\n return !existing.split(\"\\n\").some((line) => line.split(/\\s+/)[0] === field);\n}\n\n/** Pin the cube's host keys to ~/.config/krova/known_hosts (0600), pruning any\n * stale line for the same host:port (rebuilt cubes can reuse an IP+DNAT port). */\nexport function writeKnownHosts(info: SshInfo): string {\n const path = knownHostsPath();\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const field = knownHostsHost(info.host, info.port);\n\n let existing = \"\";\n try {\n existing = readFileSync(path, \"utf8\");\n } catch {\n existing = \"\";\n }\n const kept = existing\n .split(\"\\n\")\n .filter((line) => line.trim() && line.split(/\\s+/)[0] !== field);\n writeFileSync(path, kept.length ? `${kept.join(\"\\n\")}\\n` : \"\", { mode: 0o600 });\n chmodSync(path, 0o600);\n\n for (const k of info.hostKeys) {\n appendFileSync(path, `${field} ${k.type} ${k.key}\\n`);\n }\n return path;\n}\n\n/** Build the ssh argv. `--` is placed immediately before the destination —\n * the primary option-injection guard (with the validators above). */\nexport function buildSSHArgs(info: SshInfo, o: SshOptions): string[] {\n const args: string[] = [...(o.preArgs ?? [])];\n if (o.knownHosts) {\n args.push(\"-o\", `UserKnownHostsFile=${o.knownHosts}`, \"-o\", \"StrictHostKeyChecking=yes\");\n }\n if ((o.identity ?? \"\").trim()) args.push(\"-i\", o.identity as string);\n if (info.port > 0) args.push(\"-p\", String(info.port));\n for (const l of o.localFwd ?? []) if (l.trim()) args.push(\"-L\", l);\n for (const r of o.remoteFwd ?? []) if (r.trim()) args.push(\"-R\", r);\n const user = info.user.trim();\n const target = user ? `${user}@${info.host}` : info.host;\n args.push(\"--\", target);\n args.push(...(o.remoteCmd ?? []));\n return args;\n}\n\n/** Exec system ssh, inheriting stdio (interactive unless a remote cmd is given). */\nexport function execSSH(args: string[]): Promise<number> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"ssh\", args, { stdio: \"inherit\" });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => resolve(code ?? 0));\n });\n}\n\n/** Map a child's (code, signal) to a shell-style exit code. */\nexport function exitCodeFor(code: number | null, signal: NodeJS.Signals | null): number {\n if (code !== null) return code;\n if (signal) return 128 + (osConstants.signals[signal] ?? 0);\n return 1;\n}\n\n/** Exec a binary with inherited stdio and resolve to its exit code. A signal\n * death maps to 128 + the signal number; a missing binary names itself. */\nexport function execInherit(bin: string, args: string[]): Promise<number> {\n return new Promise((resolve, reject) => {\n const child = spawn(bin, args, { stdio: \"inherit\" });\n // Ctrl+C already reaches the child through the terminal; a signal sent only\n // to this process (kill, a supervisor) is passed on, and we keep running\n // until the child has exited so its exit code is not lost.\n const forward = (sig: NodeJS.Signals) => {\n child.kill(sig);\n };\n const signals: NodeJS.Signals[] = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"];\n for (const sig of signals) process.on(sig, forward);\n const done = () => {\n for (const sig of signals) process.off(sig, forward);\n };\n child.on(\"error\", (err: NodeJS.ErrnoException) => {\n done();\n if (err.code === \"ENOENT\") reject(new Error(`\\`${bin}\\` was not found on your PATH`));\n else reject(err);\n });\n child.on(\"exit\", (code, signal) => {\n done();\n resolve(exitCodeFor(code, signal));\n });\n });\n}\n\nexport interface SshTarget {\n cubeId: string;\n info: SshInfo;\n /** Path of the pinned known_hosts file, or \"\" when the server sent no host keys. */\n knownHosts: string;\n}\n\n/** Resolve a Cube (name or ID) to its validated SSH endpoint and pin its host\n * keys. Shared by `ssh`, `tunnel`, `connect`, `psql`, `redis`, `mysql`, `exec`\n * and `cp`, so every one of them keeps the same strict host-key checking. */\nexport async function resolveSshTarget(\n cmd: Command,\n cubeRef: string,\n o: { requireHostKeys?: boolean } = {}\n): Promise<SshTarget> {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n\n const { status, data } = await rawRequest<SshInfo>({\n method: \"GET\",\n baseUrl: rt.res.baseUrl,\n path: `/spaces/${space}/cubes/${id}/ssh`,\n apiKey: rt.res.apiKey,\n timeoutMs: rt.timeoutMs,\n });\n if (status === 404) {\n throw new Error(\n `SSH info isn't available on this server yet — try \\`krova cubes get ${cubeRef}\\` for the Cube's IP and ssh manually`\n );\n }\n if (status === 401 || status === 403) {\n throw new Error(`SSH info request was rejected (HTTP ${status})`);\n }\n if (status !== 200 || !data?.host) {\n throw new Error(`couldn't fetch SSH info (HTTP ${status})`);\n }\n\n const info: SshInfo = {\n host: data.host,\n port: data.port ?? 0,\n user: data.user ?? \"\",\n hostKeys: data.hostKeys ?? [],\n };\n validateSSHHost(info.host);\n validateSSHUser(info.user);\n if (info.port < 0 || info.port > 65535) throw new Error(\"invalid ssh port\");\n\n if (o.requireHostKeys && !info.hostKeys.length) {\n // Fail closed: without a recorded key there is nothing to pin, and these\n // commands never fall back to trusting whatever key the host presents.\n throw new Error(\n \"Krova has no recorded host key for this Cube yet; use `krova ssh` to connect interactively\"\n );\n }\n\n let knownHosts = \"\";\n if (info.hostKeys.length) {\n if (isHostname(info.host) && isUnpinned(info.host, info.port)) {\n process.stderr.write(\n \"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\"\n );\n }\n knownHosts = writeKnownHosts(info);\n } else {\n process.stderr.write(\n \"note: this server didn't provide host keys — using ssh trust-on-first-use (host-key checking stays on).\\n\"\n );\n }\n return { cubeId: id, info, knownHosts };\n}\n\n// ── scp ────────────────────────────────────────────────────────────────────\n\nexport interface CpOperands {\n /** Cube name or ID of the one remote side. */\n cube: string;\n direction: \"upload\" | \"download\";\n /** Path on the Cube (may be empty: the login directory). */\n remotePath: string;\n /** Path on this machine, made safe to hand to scp as a local operand. */\n localPath: string;\n}\n\n/** Split `<cube>:<path>`. A prefix with a slash in it (`./a:b`, `/tmp/x:y`) is\n * a local path, and on Windows a one-letter prefix is a drive letter. */\nfunction splitRemote(arg: string): { cube: string; path: string } | undefined {\n const i = arg.indexOf(\":\");\n if (i <= 0) return undefined;\n const cube = arg.slice(0, i);\n if (cube.includes(\"/\") || cube.includes(\"\\\\\")) return undefined;\n if (process.platform === \"win32\" && cube.length === 1) return undefined;\n return { cube, path: arg.slice(i + 1) };\n}\n\n/** scp reads `a:b` as host `a`; a local path with a colon before its first\n * slash gets a `./` so it stays local. */\nfunction safeLocalPath(p: string): string {\n const colon = p.indexOf(\":\");\n // A Windows drive letter (`C:\\\\x`) is not a host.\n if (process.platform === \"win32\" && colon === 1) return p;\n const slash = p.indexOf(\"/\");\n if (colon !== -1 && (slash === -1 || colon < slash)) return `./${p}`;\n return p;\n}\n\n/** Decide which side of `krova cp` is the Cube. Exactly one must be. */\nexport function parseCpOperands(src: string, dst: string): CpOperands {\n if (!src || !dst) throw new Error(\"cp needs a source and a destination\");\n const s = splitRemote(src);\n const d = splitRemote(dst);\n if (s && d) {\n throw new Error(\"cp copies between this machine and a Cube: only one side can be <cube>:<path>\");\n }\n if (!s && !d) {\n throw new Error(\"one side must be a Cube path like <cube>:<path> (both sides are local)\");\n }\n const remote = (s ?? d) as { cube: string; path: string };\n if (remote.path.startsWith(\"-\")) {\n throw new Error(\"a remote path must not start with '-'\");\n }\n if (/[\\0\\r\\n]/.test(remote.path)) {\n throw new Error(\"a remote path must not contain control characters\");\n }\n return s\n ? { cube: s.cube, direction: \"download\", remotePath: s.path, localPath: safeLocalPath(dst) }\n : { cube: remote.cube, direction: \"upload\", remotePath: remote.path, localPath: safeLocalPath(src) };\n}\n\n/** Build the scp argv: strict host keys, `-P` port, and `--` before the operands. */\nexport function buildSCPArgs(\n info: SshInfo,\n o: { knownHosts?: string; identity?: string; recursive?: boolean; operands: CpOperands }\n): string[] {\n // scp splits `user@host:path` on colons, so neither part may carry one.\n const user = info.user.trim();\n if (/[:\\[\\]]/.test(user)) throw new Error(\"user contains a disallowed character\");\n if (info.host.includes(\":\") && isIP(info.host) !== 6) {\n throw new Error(\"host contains a disallowed character\");\n }\n const args: string[] = [];\n if (o.knownHosts) {\n args.push(\"-o\", `UserKnownHostsFile=${o.knownHosts}`, \"-o\", \"StrictHostKeyChecking=yes\");\n }\n if ((o.identity ?? \"\").trim()) args.push(\"-i\", o.identity as string);\n if (info.port > 0) args.push(\"-P\", String(info.port));\n if (o.recursive) args.push(\"-r\");\n const host = isIP(info.host) === 6 ? `[${info.host}]` : info.host;\n const remote = `${user ? `${user}@` : \"\"}${host}:${o.operands.remotePath}`;\n const { direction, localPath } = o.operands;\n args.push(\"--\", ...(direction === \"upload\" ? [localPath, remote] : [remote, localPath]));\n return args;\n}\n","// Private tunnels: `ssh -N -L 127.0.0.1:<local>:localhost:<cube port>` over the\n// same strict host-key path as `krova ssh`, plus the helpers the database\n// client commands use (free loopback port, readiness wait, client on PATH).\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { accessSync, constants, statSync } from \"node:fs\";\nimport { createServer, connect } from \"node:net\";\nimport { delimiter, join } from \"node:path\";\n\nimport { type SshInfo, buildSSHArgs, exitCodeFor } from \"./ssh.js\";\n\n/** The only address a tunnel ever binds. Never 0.0.0.0. */\nexport const LOOPBACK = \"127.0.0.1\";\n\n/** Parse a TCP port: digits only, 1 to 65535. */\nexport function parsePort(value: string, label: string): number {\n const s = String(value ?? \"\").trim();\n const n = Number(s);\n if (!/^\\d{1,5}$/.test(s) || !Number.isInteger(n) || n < 1 || n > 65535) {\n throw new Error(`${label} must be a whole number from 1 to 65535`);\n }\n return n;\n}\n\n/** Parse `[localPort:]cubePort`. The local port defaults to the Cube port. */\nexport function parseTunnelSpec(spec: string): { localPort: number; cubePort: number } {\n const m = /^(\\d+)(?::(\\d+))?$/.exec(String(spec ?? \"\").trim());\n if (!m) {\n throw new Error(`invalid port spec \"${spec}\": use <cubePort> or <localPort>:<cubePort>`);\n }\n if (m[2] === undefined) {\n const cubePort = parsePort(m[1] as string, \"cube port\");\n return { localPort: cubePort, cubePort };\n }\n return {\n localPort: parsePort(m[1] as string, \"local port\"),\n cubePort: parsePort(m[2], \"cube port\"),\n };\n}\n\n/** Build the tunnel argv: loopback-only bind, no remote command, and ssh exits\n * if the forward cannot be set up. Host keys stay strictly checked. */\nexport function buildTunnelArgs(\n info: SshInfo,\n o: { identity?: string; knownHosts?: string; localPort: number; cubePort: number }\n): string[] {\n return buildSSHArgs(info, {\n preArgs: [\"-N\", \"-o\", \"ExitOnForwardFailure=yes\"],\n identity: o.identity,\n knownHosts: o.knownHosts,\n localFwd: [`${LOOPBACK}:${o.localPort}:localhost:${o.cubePort}`],\n });\n}\n\n/** Ask the OS for a free loopback port (bind to port 0, read it, release it). */\nexport function freeLoopbackPort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const srv = createServer();\n srv.once(\"error\", reject);\n srv.listen(0, LOOPBACK, () => {\n const addr = srv.address();\n if (addr && typeof addr === \"object\") {\n const { port } = addr;\n srv.close(() => resolve(port));\n } else {\n srv.close(() => reject(new Error(\"couldn't find a free local port\")));\n }\n });\n });\n}\n\nfunction canConnect(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const sock = connect({ host: LOOPBACK, port });\n sock.once(\"connect\", () => {\n sock.destroy();\n resolve(true);\n });\n sock.once(\"error\", () => {\n sock.destroy();\n resolve(false);\n });\n });\n}\n\nconst READY_GRACE_MS = 150;\n\n/** Wait until the local forward accepts a connection. ssh opens the listener\n * once it has authenticated, so a refused connect means \"not yet\": retry with a\n * short growing delay and stop at once if ssh exits or attempts run out. */\nexport async function waitForPort(\n port: number,\n ssh: { exited: Promise<number> },\n maxAttempts = 480\n): Promise<\"ready\" | \"ssh-exited\" | \"timeout\"> {\n let sshDone = false;\n const markDone = () => {\n sshDone = true;\n };\n void ssh.exited.then(markDone, markDone);\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n if (sshDone) return \"ssh-exited\";\n if (await canConnect(port)) {\n // Something answered. If another process holds the port, ssh fails to bind\n // (ExitOnForwardFailure) and exits right after: give it a short bounded\n // moment to do so, and only call the tunnel ready if ssh is still running.\n await Promise.race([\n ssh.exited.then(markDone, markDone),\n new Promise((r) => setTimeout(r, READY_GRACE_MS)),\n ]);\n return sshDone ? \"ssh-exited\" : \"ready\";\n }\n await new Promise((r) => setTimeout(r, Math.min(20 * 2 ** Math.min(attempt, 4), 250)));\n }\n return \"timeout\";\n}\n\n/** True when `name` is an executable file in one of the PATH directories. */\nexport function findOnPath(name: string, env: NodeJS.ProcessEnv = process.env): boolean {\n const exts =\n process.platform === \"win32\"\n ? [\"\", ...(env.PATHEXT ?? \".EXE;.CMD;.BAT\").split(\";\").filter(Boolean)]\n : [\"\"];\n for (const dir of (env.PATH ?? \"\").split(delimiter)) {\n if (!dir) continue;\n for (const ext of exts) {\n const file = join(dir, name + ext);\n try {\n if (!statSync(file).isFile()) continue;\n accessSync(file, constants.X_OK);\n return true;\n } catch {\n // not here\n }\n }\n }\n return false;\n}\n\nexport interface Spawned {\n child: ChildProcess;\n /** Resolves with a shell-style exit code when the process ends. */\n exited: Promise<number>;\n}\n\n/** Start the tunnel's ssh. stdin and stdout are not used (ssh prompts for a\n * passphrase on the terminal itself); stderr stays visible.\n *\n * `ignoreSigint` keeps a terminal Ctrl+C (sent to the whole foreground process\n * group) from killing the tunnel while a database client is using it: ssh is\n * started through `sh` with SIGINT ignored, which survives the exec. It is NOT\n * `detached: true`, because that calls setsid(), so ssh would lose the\n * controlling terminal and could no longer ask for a key passphrase. */\nexport function spawnTunnel(args: string[], o: { ignoreSigint?: boolean } = {}): Spawned {\n const stdio: [\"ignore\", \"ignore\", \"inherit\"] = [\"ignore\", \"ignore\", \"inherit\"];\n const child =\n o.ignoreSigint && process.platform !== \"win32\"\n ? spawn(\"/bin/sh\", [\"-c\", 'trap \"\" INT; exec ssh \"$@\"', \"sh\", ...args], { stdio })\n : spawn(\"ssh\", args, { stdio });\n const exited = new Promise<number>((resolve, reject) => {\n child.once(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") reject(new Error(\"`ssh` was not found on your PATH\"));\n else reject(err);\n });\n child.once(\"exit\", (code, signal) => resolve(exitCodeFor(code, signal)));\n });\n return { child, exited };\n}\n\nconst STOP_SIGNALS: NodeJS.Signals[] = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"];\n\n/** Hold a tunnel open until it ends. Ctrl+C (or SIGTERM) stops it cleanly and\n * exits 0; otherwise the exit code is ssh's own. `onReady` runs once the local\n * port accepts connections, when a `readyPort` is given. */\nexport async function holdTunnel(\n args: string[],\n opts: { readyPort?: number; onReady?: () => void } = {}\n): Promise<number> {\n const ssh = spawnTunnel(args);\n let stopped = false;\n const stop = (sig: NodeJS.Signals) => {\n stopped = true;\n ssh.child.kill(sig);\n };\n for (const sig of STOP_SIGNALS) process.on(sig, stop);\n try {\n if (opts.readyPort !== undefined) {\n const state = await waitForPort(opts.readyPort, ssh);\n if (state === \"ready\") {\n opts.onReady?.();\n } else if (state === \"timeout\") {\n ssh.child.kill(\"SIGTERM\");\n await ssh.exited;\n throw new Error(\"the tunnel didn't come up in time\");\n }\n }\n const code = await ssh.exited;\n return stopped ? 0 : code;\n } finally {\n for (const sig of STOP_SIGNALS) process.off(sig, stop);\n }\n}\n\n/** Open a tunnel, run `client` against the local port with stdio inherited,\n * then close the tunnel. Exits with the client's code. */\nexport async function runClientThroughTunnel(o: {\n sshArgs: string[];\n localPort: number;\n client: string;\n clientArgs: string[];\n}): Promise<number> {\n const ssh = spawnTunnel(o.sshArgs, { ignoreSigint: true });\n let client: ChildProcess | undefined;\n const onSignal = (sig: NodeJS.Signals) => {\n if (sig === \"SIGINT\") {\n // Once the client runs, Ctrl+C belongs to it (psql cancels the query) and\n // the tunnel ignores it. Before that, it is how the user gives up waiting.\n if (!client) ssh.child.kill(\"SIGTERM\");\n return;\n }\n client?.kill(sig);\n ssh.child.kill(sig);\n };\n // Never leave the tunnel behind, whatever way this process ends.\n const killTunnel = () => {\n if (ssh.child.exitCode === null && ssh.child.signalCode === null) ssh.child.kill(\"SIGTERM\");\n };\n process.on(\"exit\", killTunnel);\n for (const sig of STOP_SIGNALS) process.on(sig, onSignal);\n try {\n const state = await waitForPort(o.localPort, ssh);\n if (state === \"ssh-exited\") {\n const code = await ssh.exited;\n throw new Error(`ssh exited (code ${code}) before the tunnel was ready`);\n }\n if (state === \"timeout\") {\n ssh.child.kill(\"SIGTERM\");\n await ssh.exited;\n throw new Error(\"the tunnel didn't come up in time\");\n }\n const running = spawn(o.client, o.clientArgs, { stdio: \"inherit\" });\n client = running;\n return await new Promise<number>((resolve, reject) => {\n running.once(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") reject(new Error(`\\`${o.client}\\` was not found on your PATH`));\n else reject(err);\n });\n running.once(\"exit\", (code, signal) => resolve(exitCodeFor(code, signal)));\n });\n } finally {\n killTunnel();\n await ssh.exited.catch(() => 0);\n for (const sig of STOP_SIGNALS) process.off(sig, onSignal);\n process.off(\"exit\", killTunnel);\n }\n}\n","import { Command } from \"commander\";\n\nimport { resolveSshTarget } from \"../lib/ssh.js\";\nimport {\n LOOPBACK,\n buildTunnelArgs,\n findOnPath,\n freeLoopbackPort,\n parsePort,\n runClientThroughTunnel,\n} from \"../lib/tunnel.js\";\n\nconst PRIVATE_NOTE =\n \"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.\";\n\n/** A user or database name: no leading `-`, nothing a client could read as a\n * connection string (`=`, `:`, `/`, spaces). */\nconst IDENT = /^[A-Za-z0-9_][A-Za-z0-9_.$-]{0,62}$/;\n\nexport function validateIdent(value: string, label: string): string {\n if (!IDENT.test(value)) {\n throw new Error(\n `${label} may only use letters, digits, '_', '.', '$' and '-', and must not start with '-'`\n );\n }\n return value;\n}\n\nexport interface DbClientSpec {\n command: string;\n client: string;\n defaultPort: number;\n description: string;\n userDefault?: string;\n dbDefault?: string;\n clientArgs(o: { port: number; user?: string; db?: string }): string[];\n}\n\nexport const DB_CLIENTS: DbClientSpec[] = [\n {\n command: \"psql\",\n client: \"psql\",\n defaultPort: 5432,\n userDefault: \"postgres\",\n dbDefault: \"postgres\",\n description: \"open psql against a PostgreSQL server in a Cube\",\n clientArgs: ({ port, user, db }) => [\n \"-h\",\n LOOPBACK,\n \"-p\",\n String(port),\n \"-U\",\n user as string,\n \"-d\",\n db as string,\n ],\n },\n {\n command: \"redis\",\n client: \"redis-cli\",\n defaultPort: 6379,\n description: \"open redis-cli against a Redis server in a Cube\",\n clientArgs: ({ port }) => [\"-h\", LOOPBACK, \"-p\", String(port)],\n },\n {\n command: \"mysql\",\n client: \"mysql\",\n defaultPort: 3306,\n userDefault: \"root\",\n description: \"open mysql against a MySQL or MariaDB server in a Cube\",\n clientArgs: ({ port, user, db }) => [\n \"-h\",\n LOOPBACK,\n \"-P\",\n String(port),\n \"--protocol=tcp\",\n \"-u\",\n user as string,\n ...(db ? [`--database=${db}`] : []),\n ],\n },\n];\n\nfunction dbClientCommand(spec: DbClientSpec): Command {\n const c = new Command(spec.command)\n .argument(\"<cube>\", \"cube name or ID\")\n .description(`${spec.description}. ${PRIVATE_NOTE}`)\n .option(\"--port <cubePort>\", `port inside the Cube (default ${spec.defaultPort})`)\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to ssh -i\");\n if (spec.userDefault) {\n // Commander appends `(default: \"<value>\")` itself when a default is passed.\n c.option(\"--user <user>\", \"database user\", spec.userDefault);\n }\n if (spec.command === \"psql\") c.option(\"--db <name>\", \"database name\", \"postgres\");\n if (spec.command === \"mysql\") c.option(\"--db <name>\", \"database to use\");\n return c.action(async (cubeRef: string, opts, cmd: Command) => {\n // Check everything that needs no network first, so a typo or a missing\n // client fails before any tunnel is opened.\n const cubePort =\n opts.port !== undefined ? parsePort(opts.port as string, \"--port\") : spec.defaultPort;\n const user = spec.userDefault ? validateIdent(opts.user as string, \"--user\") : undefined;\n const db = opts.db ? validateIdent(opts.db as string, \"--db\") : undefined;\n if (!findOnPath(spec.client)) {\n throw new Error(`\\`${spec.client}\\` was not found on your PATH — install it and try again`);\n }\n\n const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });\n const localPort = await freeLoopbackPort();\n const sshArgs = buildTunnelArgs(info, {\n identity: opts.identity as string | undefined,\n knownHosts,\n localPort,\n cubePort,\n });\n process.exitCode = await runClientThroughTunnel({\n sshArgs,\n localPort,\n client: spec.client,\n clientArgs: spec.clientArgs({ port: localPort, user, db }),\n });\n });\n}\n\nexport const psqlCommand = () => dbClientCommand(DB_CLIENTS[0] as DbClientSpec);\nexport const redisCommand = () => dbClientCommand(DB_CLIENTS[1] as DbClientSpec);\nexport const mysqlCommand = () => dbClientCommand(DB_CLIENTS[2] as DbClientSpec);\n","import { Command } from \"commander\";\n\nimport {\n buildSCPArgs,\n buildSSHArgs,\n execInherit,\n parseCpOperands,\n resolveSshTarget,\n} from \"../lib/ssh.js\";\n\nexport function execCommand(): Command {\n return new Command(\"exec\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<command...>\", \"command to run (after --)\")\n .description(\n \"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.\"\n )\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to ssh -i\")\n .action(async (cubeRef: string, command: string[], opts, cmd: Command) => {\n if (!command.some((w) => w.trim())) {\n throw new Error(\"exec needs a command to run, e.g. krova exec <cube> -- uname -a\");\n }\n const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });\n const args = buildSSHArgs(info, {\n preArgs: [\"-T\"],\n identity: opts.identity as string | undefined,\n knownHosts,\n remoteCmd: command,\n });\n process.exitCode = await execInherit(\"ssh\", args);\n });\n}\n\nexport function cpCommand(): Command {\n return new Command(\"cp\")\n .argument(\"<src>\", \"source: a local path or <cube>:<path>\")\n .argument(\"<dst>\", \"destination: a local path or <cube>:<path>\")\n .description(\n \"copy files between this machine and a Cube over scp. Exactly one side is <cube>:<path> (cube by name or ID).\"\n )\n .option(\"-r, --recursive\", \"copy directories recursively\")\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to scp -i\")\n .action(async (src: string, dst: string, opts, cmd: Command) => {\n const operands = parseCpOperands(src, dst);\n const { info, knownHosts } = await resolveSshTarget(cmd, operands.cube, { requireHostKeys: true });\n const args = buildSCPArgs(info, {\n knownHosts,\n identity: opts.identity as string | undefined,\n recursive: Boolean(opts.recursive),\n operands,\n });\n process.exitCode = await execInherit(\"scp\", args);\n });\n}\n","import { Command } from \"commander\";\n\nimport { buildSSHArgs, execSSH, resolveSshTarget } from \"../lib/ssh.js\";\n\nconst collect = (v: string, acc: string[]) => {\n acc.push(v);\n return acc;\n};\n\nexport function sshCommand(): Command {\n return new Command(\"ssh\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"[command...]\", \"command to run non-interactively (after --)\")\n .description(\"open an SSH session to a Cube (by name or ID)\")\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to ssh -i\")\n .option(\"-L, --local-forward <spec>\", \"local port forward, passed to ssh -L (repeatable)\", collect, [])\n .option(\"-R, --remote-forward <spec>\", \"remote port forward, passed to ssh -R (repeatable)\", collect, [])\n .action(async (cubeRef: string, command: string[], opts, cmd: Command) => {\n const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef);\n const args = buildSSHArgs(info, {\n identity: opts.identity as string | undefined,\n localFwd: opts.localForward as string[],\n remoteFwd: opts.remoteForward as string[],\n knownHosts,\n remoteCmd: command,\n });\n process.exitCode = await execSSH(args);\n });\n}\n","import { Command } from \"commander\";\n\nimport { printJSON } from \"../lib/output.js\";\nimport { resolveSshTarget } from \"../lib/ssh.js\";\nimport {\n LOOPBACK,\n buildTunnelArgs,\n freeLoopbackPort,\n holdTunnel,\n parsePort,\n parseTunnelSpec,\n} from \"../lib/tunnel.js\";\n\nconst PRIVATE_NOTE =\n \"The port is reachable only from this machine, over your SSH key. Prefer it to a public `krova tcp add` mapping for databases.\";\n\nfunction announceForwarding(localPort: number, cubeRef: string, cubePort: number): void {\n process.stderr.write(\n `Forwarding localhost:${localPort} -> ${cubeRef}:${cubePort}. Press Ctrl+C to stop.\\n`\n );\n}\n\nexport function tunnelCommand(): Command {\n return new Command(\"tunnel\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<ports>\", \"[localPort:]cubePort (the local port defaults to the Cube port)\")\n .description(\n `forward a local port to a port inside a Cube over SSH. ${PRIVATE_NOTE}`\n )\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to ssh -i\")\n .action(async (cubeRef: string, spec: string, opts, cmd: Command) => {\n const { localPort, cubePort } = parseTunnelSpec(spec);\n const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });\n const args = buildTunnelArgs(info, {\n identity: opts.identity as string | undefined,\n knownHosts,\n localPort,\n cubePort,\n });\n // Say \"Forwarding\" only once the local port is listening, so the line is\n // never printed for a tunnel that failed to come up.\n process.exitCode = await holdTunnel(args, {\n readyPort: localPort,\n onReady: () => announceForwarding(localPort, cubeRef, cubePort),\n });\n });\n}\n\nexport function connectCommand(): Command {\n return new Command(\"connect\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\n `open a private tunnel to a Cube port on a free local port and print the local endpoint. ${PRIVATE_NOTE}`\n )\n .requiredOption(\"--port <cubePort>\", \"port inside the Cube to reach\")\n .option(\"--local-port <port>\", \"local port to listen on (default: a free one)\")\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to ssh -i\")\n .action(async (cubeRef: string, opts, cmd: Command) => {\n const cubePort = parsePort(opts.port as string, \"--port\");\n const localPort =\n opts.localPort !== undefined\n ? parsePort(opts.localPort as string, \"--local-port\")\n : await freeLoopbackPort();\n const json = Boolean(cmd.optsWithGlobals().json);\n const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });\n const args = buildTunnelArgs(info, {\n identity: opts.identity as string | undefined,\n knownHosts,\n localPort,\n cubePort,\n });\n process.exitCode = await holdTunnel(args, {\n readyPort: localPort,\n onReady: () => {\n if (json) {\n printJSON({ host: LOOPBACK, port: localPort, cube: cubeRef, cubePort });\n } else {\n process.stdout.write(`localhost:${localPort}\\n`);\n }\n announceForwarding(localPort, cubeRef, cubePort);\n },\n });\n });\n}\n","import { Command } from \"commander\";\n\nimport { mappingConnectTarget, printJSON, printTable } from \"../lib/output.js\";\nimport { resolveCube } from \"../lib/resolve.js\";\nimport {\n confirm,\n isOpenWhitelist,\n printAborted,\n publicExposureWarning,\n shouldConfirm,\n} from \"../lib/safety.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\n\n/** `krova tcp` — manage a Cube's TCP port mappings. */\nexport function tcpCommand(): Command {\n const cmd = new Command(\"tcp\").description(\"manage a Cube's TCP port mappings\");\n\n cmd\n .command(\"list\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"list a Cube's TCP port mappings\")\n .action(async (cubeRef: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const maps = await client.tcpMappings.list(space, id);\n if (rt.json) return printJSON(maps);\n // CONNECT is what a reader actually needs: the table used to print a\n // host port with no host, so building a connect string meant a second\n // command and knowing to combine the two. `host` is the Cube's own\n // stable name (it survives migration), so this string keeps working\n // after the Cube moves — unlike the server's hostname.\n printTable(\n [\n \"ID\",\n \"CUBE PORT\",\n \"CONNECT\",\n \"LABEL\",\n \"STATUS\",\n \"SSH\",\n \"UDP\",\n ],\n maps.map((m) => [\n m.id,\n String(m.cubePort),\n mappingConnectTarget(m),\n m.label ?? \"\",\n m.status,\n m.isSsh ? \"yes\" : \"no\",\n m.udpEnabled ? \"yes\" : \"no\",\n ]),\n );\n });\n\n cmd\n .command(\"add\")\n .argument(\"<cube>\", \"cube name or ID\")\n .requiredOption(\"--port <n>\", \"the in-Cube port to expose\")\n .option(\n \"--whitelist <cidr>\",\n \"restrict access to this IP/CIDR (repeatable)\",\n (val: string, acc: string[]) => {\n acc.push(val);\n return acc;\n },\n [] as string[],\n )\n .option(\"-y, --yes\", \"skip the confirmation prompt when the port would be open to the whole internet\")\n .option(\"--no-udp\", \"don't forward UDP on this port (UDP is forwarded by default alongside TCP)\")\n .description(\"expose a Cube TCP port on the host, optionally IP-restricted\")\n .action(async (cubeRef: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cubePort = Number(opts.port);\n if (!Number.isInteger(cubePort) || cubePort <= 0 || cubePort > 65535) {\n throw new Error(`--port must be a valid port (got \"${opts.port}\").`);\n }\n const whitelist = opts.whitelist as string[];\n // A port with no whitelist (or 0.0.0.0/0, ::/0) is open to everyone. Warn on\n // stderr every time; only a person at a terminal is asked to confirm, so a\n // script keeps working unchanged.\n if (isOpenWhitelist(whitelist)) {\n process.stderr.write(`${publicExposureWarning(cubeRef, cubePort)}\\n`);\n if (shouldConfirm(opts)) {\n const ok = await confirm(\"Open this port to the whole internet? [y/N] \");\n if (!ok) return printAborted(rt.json);\n }\n }\n // ⛔ `whitelistedIps` — NOT `whitelistIps`. The published spec named the\n // field `whitelistIps` while the server has always read\n // `whitelistedIps`, so every `--whitelist` mapping this CLI created was\n // silently published WORLD-OPEN, with a 201 and no error. Reproduced on\n // production 2026-09-02: a mapping added with `--whitelist\n // 203.0.113.0/24` served content to an off-list address.\n //\n // The server now accepts both names, so an older CLI keeps working; this\n // sends the canonical one.\n //\n // ⛔ `udpEnabled` — omit it unless `--no-udp` was passed. The server\n // defaults `udpEnabled` to `true` when the field is absent, so this must\n // NOT send `udpEnabled: opts.udp` (commander defaults `opts.udp` to\n // `true`, but sending that explicitly is fine — sending `false` on mere\n // silence would not be). Only `--no-udp` sets `opts.udp` to `false`, and\n // only then do we send the field at all.\n const mapping = await client.tcpMappings.create(space, id, {\n cubePort,\n ...(whitelist.length ? { whitelistedIps: whitelist } : {}),\n ...(opts.udp === false ? { udpEnabled: false } : {}),\n });\n if (rt.json) return printJSON(mapping);\n // Say where to reach it, not just which port was picked — the point of\n // adding a mapping is to connect to it. Falls back to the bare port if\n // the Cube has no host yet (no server assigned).\n process.stdout.write(\n `Mapped cube port ${mapping.cubePort} → ${mappingConnectTarget(mapping)} (${mapping.id})\\n`,\n );\n });\n\n cmd\n .command(\"rm\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<mapping-id>\", \"the mapping ID (see `krova tcp list`)\")\n .description(\"remove a TCP port mapping\")\n .action(async (cubeRef: string, mappingId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n await client.tcpMappings.delete(space, id, mappingId);\n if (rt.json) return printJSON({ id: mappingId, result: \"removed\" });\n process.stdout.write(`Removed TCP mapping ${mappingId}\\n`);\n });\n\n return cmd;\n}\n","/** A MAJOR.MINOR.PATCH version, plus its pre-release part when it has one. */\ninterface ParsedVersion {\n core: [number, number, number];\n pre: string[];\n}\n\nexport function parseVersion(input: string): ParsedVersion | undefined {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/.exec(\n input.trim()\n );\n if (!m) return undefined;\n const [major, minor, patch] = [m[1], m[2], m[3]];\n if (major === undefined || minor === undefined || patch === undefined) return undefined;\n const pre = m[4];\n return {\n core: [Number(major), Number(minor), Number(patch)],\n pre: pre ? pre.split(\".\") : [],\n };\n}\n\n/** Semver ordering of two pre-release parts: numeric identifiers below\n * alphanumeric ones, numbers compared as numbers, everything else as text. */\nfunction comparePre(a: string[], b: string[]): number {\n // No pre-release outranks any pre-release of the same release.\n if (a.length === 0 || b.length === 0) return b.length - a.length;\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n const x = a[i] ?? \"\";\n const y = b[i] ?? \"\";\n const xNum = /^\\d+$/.test(x);\n const yNum = /^\\d+$/.test(y);\n if (xNum && yNum) {\n const diff = Number(x) - Number(y);\n if (diff !== 0) return diff;\n continue;\n }\n if (xNum !== yNum) return xNum ? -1 : 1;\n if (x !== y) return x < y ? -1 : 1;\n }\n return a.length - b.length;\n}\n\n/** Negative when `a` is older than `b`, zero when equal, positive when newer.\n * A pre-release sorts below the release it leads to (1.0.0-rc.1 < 1.0.0).\n * Throws on input that is not MAJOR.MINOR.PATCH[-pre][+build]. */\nexport function compareVersions(a: string, b: string): number {\n const va = parseVersion(a);\n const vb = parseVersion(b);\n if (!va) throw new Error(`not a version: ${a}`);\n if (!vb) throw new Error(`not a version: ${b}`);\n for (let i = 0; i < 3; i++) {\n const diff = (va.core[i] ?? 0) - (vb.core[i] ?? 0);\n if (diff !== 0) return diff;\n }\n return comparePre(va.pre, vb.pre);\n}\n","import { createRequire } from \"node:module\";\n\nimport { Command } from \"commander\";\n\nimport { printJSON } from \"../lib/output.js\";\nimport { getRuntime } from \"../lib/runtime.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\") as { version: string };\n\nexport const CLI_VERSION = pkg.version;\n\nexport function versionCommand(): Command {\n return new Command(\"version\")\n .description(\"print the krova CLI version\")\n .action((_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const info = {\n version: CLI_VERSION,\n node: process.version,\n platform: `${process.platform}/${process.arch}`,\n };\n if (rt.json) return printJSON(info);\n process.stdout.write(`krova ${info.version} (node ${info.node}, ${info.platform})\\n`);\n });\n}\n","import { Command } from \"commander\";\n\nimport { ENV } from \"../lib/config.js\";\nimport { printJSON } from \"../lib/output.js\";\nimport { getRuntime } from \"../lib/runtime.js\";\nimport { compareVersions, parseVersion } from \"../lib/semver.js\";\nimport { CLI_VERSION } from \"./version.js\";\n\nconst DEFAULT_REGISTRY = \"https://registry.npmjs.org\";\nconst UPDATE_COMMAND = \"npm install -g @krovacloud/cli@latest\";\n/** Checking npm is a quick metadata lookup, so never wait longer than this,\n * even when the global --timeout is larger. */\nconst CHECK_TIMEOUT_CAP_MS = 10_000;\n\n/** One reason line, plus a hint when the failure looks like the network —\n * the top-level handler names the API base URL for any connection failure,\n * which would be wrong here: this check talks to npm, not to Krova. */\nfunction failureFor(err: unknown, timeoutMs: number): { reason: string; hint?: string } {\n const mirrorHint = `Check your connection or set ${ENV.npmRegistry} to use an npm mirror.`;\n if (!(err instanceof Error)) return { reason: String(err) };\n const code = (err as Error & { code?: unknown }).code;\n if (err.name === \"TimeoutError\" || err.name === \"AbortError\" || code === \"ABORT_ERR\") {\n return { reason: `timed out after ${timeoutMs / 1000}s`, hint: mirrorHint };\n }\n const cause = (err as Error & { cause?: unknown }).cause;\n if (\n cause &&\n typeof cause === \"object\" &&\n typeof (cause as { message?: unknown }).message === \"string\"\n ) {\n return { reason: (cause as { message: string }).message, hint: mirrorHint };\n }\n return { reason: err.message, hint: err.message === \"fetch failed\" ? mirrorHint : undefined };\n}\n\nfunction registryError(reason: string, hint?: string): Error {\n const err = new Error(`could not check the npm registry: ${reason}`);\n return hint ? Object.assign(err, { hint }) : err;\n}\n\n/** The canonical MAJOR.MINOR.PATCH[-prerelease] form: no leading v, no +build metadata. */\nfunction formatVersion(parsed: { core: [number, number, number]; pre: string[] }): string {\n const [major, minor, patch] = parsed.core;\n const pre = parsed.pre.length > 0 ? `-${parsed.pre.join(\".\")}` : \"\";\n return `${major}.${minor}.${patch}${pre}`;\n}\n\n/** The registry's latest published version, normalized, e.g. \"0.7.0\". */\nasync function fetchLatestVersion(baseUrl: string, timeoutMs: number): Promise<string> {\n const base = (baseUrl || DEFAULT_REGISTRY).replace(/\\/+$/, \"\");\n let res: Response;\n try {\n res = await fetch(`${base}/@krovacloud%2fcli/latest`, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (err) {\n const failure = failureFor(err, timeoutMs);\n throw registryError(failure.reason, failure.hint);\n }\n if (!res.ok) throw registryError(`the registry answered HTTP ${res.status}`);\n let body: unknown;\n try {\n body = await res.json();\n } catch (err) {\n // The timeout can fire while the body streams in; that is a timeout, not bad JSON.\n if (err instanceof Error && (err.name === \"TimeoutError\" || err.name === \"AbortError\")) {\n const failure = failureFor(err, timeoutMs);\n throw registryError(failure.reason, failure.hint);\n }\n throw registryError(\"the response was not valid JSON\");\n }\n const version = (body as { version?: unknown } | null)?.version;\n const parsed = typeof version === \"string\" ? parseVersion(version) : undefined;\n if (!parsed) {\n throw registryError(\"the response did not name a version\");\n }\n return formatVersion(parsed);\n}\n\nexport function updateCommand(): Command {\n return new Command(\"update\")\n .description(\"check the npm registry for a newer krova CLI (never installs)\")\n .action(async (_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const latest = await fetchLatestVersion(\n process.env[ENV.npmRegistry] ?? \"\",\n Math.min(rt.timeoutMs, CHECK_TIMEOUT_CAP_MS)\n );\n const current = CLI_VERSION;\n const updateAvailable = compareVersions(latest, current) > 0;\n\n if (rt.json) {\n return printJSON({ current, latest, updateAvailable, command: UPDATE_COMMAND });\n }\n process.stdout.write(\n updateAvailable\n ? `krova ${latest} is available (you have ${current}). Update with: ${UPDATE_COMMAND}\\n`\n : `krova ${latest} is the latest version.\\n`\n );\n });\n}\n","import { createServer } from \"node:http\";\nimport * as readline from \"node:readline\";\n\nimport type { components } from \"@krovacloud/sdk\";\nimport { krovaErrorFrom } from \"@krovacloud/sdk\";\nimport { verifyKrovaWebhookOrThrow } from \"@krovacloud/webhook\";\nimport { Command } from \"commander\";\n\nimport { printJSON, printKeyValue, printTable } from \"../lib/output.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\n\nconst DEFAULT_LISTEN_HOST = \"127.0.0.1\";\nconst DEFAULT_LISTEN_PORT = 4666;\n\n/**\n * Parse a `--addr` value into `{ host, port }`. Handles `host:port`, a bare host\n * (e.g. `localhost`), a bare port, bracketed IPv6 (`[::1]:4666`), and bare IPv6\n * (`::1`). Exported for testing.\n */\nexport function parseListenAddr(addr: string): { host: string; port: number } {\n const s = (addr ?? \"\").trim();\n // Bracketed IPv6: [::1] or [::1]:4666\n const bracket = s.match(/^\\[([^\\]]+)\\](?::(\\d+))?$/);\n if (bracket) {\n return { host: bracket[1] as string, port: bracket[2] ? Number(bracket[2]) : DEFAULT_LISTEN_PORT };\n }\n // Two or more colons and no brackets ⇒ a bare IPv6 address with no port.\n if ((s.match(/:/g)?.length ?? 0) >= 2) {\n return { host: s, port: DEFAULT_LISTEN_PORT };\n }\n // Single colon ⇒ host:port.\n const i = s.lastIndexOf(\":\");\n if (i > 0) {\n const port = Number(s.slice(i + 1));\n return {\n host: s.slice(0, i),\n port: Number.isInteger(port) && port > 0 && port <= 65535 ? port : DEFAULT_LISTEN_PORT,\n };\n }\n // No colon ⇒ a bare port (all digits) or a bare host.\n if (/^\\d+$/.test(s)) {\n const port = Number(s);\n return { host: DEFAULT_LISTEN_HOST, port: port > 0 && port <= 65535 ? port : DEFAULT_LISTEN_PORT };\n }\n return { host: s || DEFAULT_LISTEN_HOST, port: DEFAULT_LISTEN_PORT };\n}\n\nexport function webhooksCommand(): Command {\n const wh = new Command(\"webhooks\").description(\"developer tools for Krova Cloud webhooks\");\n\n // A webhook endpoint as the API returns it. The list endpoint omits\n // `description`; POST and GET /:id include it. Keep it optional so a single\n // type covers both shapes without inventing fields the server didn't send.\n type Webhook = components[\"schemas\"][\"Webhook\"] & { description?: string | null };\n type WebhookWithSecret = Webhook & { secret: string };\n type WebhookDelivery = components[\"schemas\"][\"WebhookDelivery\"];\n\n /** Read a y/N line from stdin. Empty / non-y answers count as \"no\". */\n function confirm(question: string): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n rl.question(question, (answer) => {\n rl.close();\n resolve(/^y(es)?$/i.test(answer.trim()));\n });\n });\n }\n\n wh\n .command(\"list\")\n .description(\"list webhook endpoints in the active space\")\n .action(async (_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const { data, error, response } = await client.raw.GET(\n \"/spaces/{spaceId}/webhooks\",\n { params: { path: { spaceId: space } } },\n );\n if (!response.ok) throw krovaErrorFrom(response, error);\n const { webhooks } = data as unknown as { webhooks: Webhook[] };\n if (rt.json) return printJSON(webhooks);\n printTable(\n [\"ID\", \"URL\", \"DESCRIPTION\", \"EVENTS\", \"ENABLED\", \"CREATED AT\"],\n webhooks.map((w) => [\n w.id,\n w.url,\n w.description ?? \"—\",\n w.events.join(\",\"),\n String(w.enabled),\n w.createdAt,\n ]),\n );\n });\n\n wh\n .command(\"add\")\n .description(\"create a webhook endpoint (signing secret shown once)\")\n .requiredOption(\"--url <url>\", \"the URL Krova should POST events to\")\n .requiredOption(\n \"--events <list>\",\n \"comma-separated event names (e.g. cube.running,cube.stopped)\",\n )\n .option(\"--description <text>\", \"human-readable description for this endpoint\")\n .action(async (opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const events = String(opts.events)\n .split(\",\")\n .map((e) => e.trim())\n .filter(Boolean);\n if (events.length === 0) {\n throw new Error(\"--events must list at least one event (e.g. cube.running).\");\n }\n const body: { url: string; events: string[]; description?: string } = {\n url: String(opts.url),\n events,\n };\n if (opts.description) body.description = String(opts.description);\n const { data, error, response } = await client.raw.POST(\n \"/spaces/{spaceId}/webhooks\",\n { params: { path: { spaceId: space } }, body: body as never },\n );\n if (!response.ok) throw krovaErrorFrom(response, error);\n const created = (data as unknown as { webhook: WebhookWithSecret }).webhook;\n if (rt.json) {\n // Emit the full { webhook, secret } shape so callers don't have to\n // guess which field carries the secret. After this point, the CLI\n // must NOT echo the secret again.\n return printJSON({ webhook: created, secret: created.secret });\n }\n process.stdout.write(`\\nCreated webhook ${created.id} for ${created.url}\\n`);\n process.stdout.write(\"\\n=== SIGNING SECRET (save now, shown once) ===\\n\");\n process.stdout.write(`${created.secret}\\n`);\n process.stdout.write(\"=== END SIGNING SECRET ===\\n\\n\");\n process.stdout.write(\"Save this now — it is the only time the secret will be shown.\\n\");\n });\n\n wh\n .command(\"get\")\n .argument(\"<endpoint-id>\", \"the webhook endpoint ID\")\n .description(\"show a single webhook endpoint\")\n .action(async (endpointId: string, _opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const { data, error, response } = await client.raw.GET(\n \"/spaces/{spaceId}/webhooks/{endpointId}\",\n { params: { path: { spaceId: space, endpointId } } },\n );\n if (!response.ok) throw krovaErrorFrom(response, error);\n const { webhook } = data as unknown as { webhook: Webhook };\n if (rt.json) return printJSON(webhook);\n const rows: Array<[string, string]> = [\n [\"ID\", webhook.id],\n [\"URL\", webhook.url],\n ];\n if (webhook.description != null) rows.push([\"Description\", webhook.description]);\n rows.push(\n [\"Events\", webhook.events.join(\",\")],\n [\"Enabled\", String(webhook.enabled)],\n [\"Created At\", webhook.createdAt],\n [\"Updated At\", webhook.updatedAt],\n );\n printKeyValue(rows);\n });\n\n wh\n .command(\"rm\")\n .argument(\"<endpoint-id>\", \"the webhook endpoint ID\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .description(\"delete a webhook endpoint (and its delivery history)\")\n .action(async (endpointId: string, opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n if (!opts.yes) {\n const ok = await confirm(\n `Delete webhook ${endpointId}? This also drops its delivery history. [y/N] `,\n );\n if (!ok) {\n process.stdout.write(\"Aborted.\\n\");\n return;\n }\n }\n const { error, response } = await client.raw.DELETE(\n \"/spaces/{spaceId}/webhooks/{endpointId}\",\n { params: { path: { spaceId: space, endpointId } } },\n );\n if (!response.ok) throw krovaErrorFrom(response, error);\n if (rt.json) return printJSON({ id: endpointId, result: \"deleted\" });\n process.stdout.write(`Deleted webhook ${endpointId}\\n`);\n });\n\n wh\n .command(\"deliveries\")\n .argument(\"<endpoint-id>\", \"the webhook endpoint ID\")\n .option(\"--limit <n>\", \"max deliveries to return (1-100)\", \"50\")\n .description(\"list recent delivery attempts for a webhook endpoint\")\n .action(async (endpointId: string, opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const limit = Number(opts.limit);\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n throw new Error(\"--limit must be an integer between 1 and 100.\");\n }\n const { data, error, response } = await client.raw.GET(\n \"/spaces/{spaceId}/webhooks/{endpointId}/deliveries\",\n { params: { path: { spaceId: space, endpointId }, query: { limit } } },\n );\n if (!response.ok) throw krovaErrorFrom(response, error);\n const { deliveries } = data as unknown as { deliveries: WebhookDelivery[] };\n if (rt.json) return printJSON(deliveries);\n printTable(\n [\"ID\", \"EVENT\", \"STATUS\", \"ATTEMPTS\", \"LAST ATTEMPT\", \"RESPONSE\", \"CREATED AT\"],\n deliveries.map((d) => [\n d.id,\n d.event,\n d.status,\n String(d.attempts),\n d.lastAttemptAt ?? \"—\",\n d.responseStatus != null ? String(d.responseStatus) : \"—\",\n d.createdAt,\n ]),\n );\n });\n\n wh.command(\"listen\")\n .description(\"run a local server that verifies + prints incoming webhook deliveries\")\n .option(\"--addr <host:port>\", \"address to listen on\", \"127.0.0.1:4666\")\n .option(\"--path <path>\", \"path to accept POSTs on\", \"/\")\n .option(\"--secret <secret>\", \"signing secret (or the KROVA_WEBHOOK_SECRET env var)\")\n .action((opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const secret = (opts.secret as string) || process.env.KROVA_WEBHOOK_SECRET || \"\";\n if (!secret) {\n throw new Error(\n \"a signing secret is required: pass --secret or set KROVA_WEBHOOK_SECRET\"\n );\n }\n const { host, port } = parseListenAddr(String(opts.addr));\n const wantPath = String(opts.path);\n\n const server = createServer((req, res) => {\n const reqPath = (req.url ?? \"/\").split(\"?\")[0];\n if (req.method !== \"POST\" || reqPath !== wantPath) {\n res.writeHead(405);\n res.end(\"method not allowed\");\n return;\n }\n const chunks: Buffer[] = [];\n let size = 0;\n req.on(\"data\", (c: Buffer) => {\n size += c.length;\n if (size <= 1_048_576) chunks.push(c);\n });\n req.on(\"end\", () => {\n const body = Buffer.concat(chunks).toString(\"utf8\");\n const sig = (req.headers[\"x-krova-signature\"] as string) || \"\";\n try {\n verifyKrovaWebhookOrThrow({ payload: body, signature: sig, secret });\n } catch (e) {\n process.stderr.write(`✗ rejected delivery: ${(e as Error).message}\\n`);\n res.writeHead(400);\n res.end(\"invalid signature\");\n return;\n }\n try {\n const event = JSON.parse(body);\n if (rt.json) process.stdout.write(`${JSON.stringify(event)}\\n`);\n else printJSON(event);\n } catch {\n process.stdout.write(`${body}\\n`);\n }\n res.writeHead(200);\n res.end(\"ok\");\n });\n });\n\n server.listen(port, host, () => {\n process.stderr.write(`Listening for webhooks on http://${host}:${port}${wantPath}\\n`);\n });\n const stop = () => server.close(() => process.exit(0));\n process.on(\"SIGINT\", stop);\n process.on(\"SIGTERM\", stop);\n });\n\n return wh;\n}\n","import { Command } from \"commander\";\n\nimport { displayKey, find } from \"../lib/config.js\";\nimport { printJSON, printKeyValue } from \"../lib/output.js\";\nimport { getRuntime, probeAuth } from \"../lib/runtime.js\";\n\n/** \"never\", or the ISO date with how far away it is, e.g. `2026-12-16T12:00:00.000Z (in 30 days)`. */\nexport function describeExpiry(expiresAt: string | null, now: number = Date.now()): string {\n if (expiresAt === null) return \"never\";\n const at = Date.parse(expiresAt);\n if (Number.isNaN(at)) return expiresAt;\n const days = Math.floor((at - now) / 86_400_000);\n if (days < 0) return `${expiresAt} (expired)`;\n if (days === 0) return `${expiresAt} (within a day)`;\n return `${expiresAt} (in ${days} ${days === 1 ? \"day\" : \"days\"})`;\n}\n\nexport function whoamiCommand(): Command {\n return new Command(\"whoami\")\n .description(\"show the current context, space, and base URL\")\n .option(\"--show-secrets\", \"print the full API key instead of a masked one\")\n .action(async (opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const showSecrets = Boolean(opts.showSecrets);\n const ctx = find(rt.cfg, rt.res.contextName);\n let spaceId = rt.res.spaceId;\n let spaceName = ctx?.spaceName ?? \"\";\n\n const probe = await probeAuth(rt.res.baseUrl, rt.res.apiKey, rt.timeoutMs);\n if (probe.state === \"valid\") {\n spaceId = probe.space.id;\n spaceName = probe.space.name ?? spaceName;\n }\n const spaceLive = probe.state === \"valid\";\n // `undefined` when unknown: the key was not checked, the key came from an\n // OAuth token (the API sends `apiKey: null`), or an older server omits it.\n const keyInfo = probe.state === \"valid\" ? probe.space.apiKey : undefined;\n const expiresAt = keyInfo ? keyInfo.expiresAt : undefined;\n\n // A rejected key used to render as a bare \"Space —\", which reads like a\n // missing setting rather than dead credentials. Say so out loud.\n const warning =\n probe.state === \"rejected\"\n ? `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.`\n : probe.state === \"unreachable\"\n ? `could not reach ${rt.res.baseUrl} (${probe.error}) — showing locally cached values.`\n : \"\";\n\n if (rt.json) {\n return printJSON({\n context: rt.res.contextName,\n spaceId,\n spaceName,\n ...(showSecrets\n ? { apiKey: rt.res.apiKey }\n : { apiKeyMasked: displayKey(rt.res.apiKey, false) }),\n ...(expiresAt !== undefined ? { apiKeyExpiresAt: expiresAt } : {}),\n apiKeySource: rt.res.apiKeySource,\n apiKeyStorage: rt.res.apiKeyStorage || undefined,\n baseUrl: rt.res.baseUrl,\n spaceLive,\n checkState: probe.state,\n warning: warning || undefined,\n });\n }\n printKeyValue([\n [\"Context\", rt.res.contextName || \"—\"],\n [\"Space\", spaceName || \"—\"],\n [\"Space ID\", spaceId || \"—\"],\n [\n \"API key\",\n rt.res.apiKey\n ? `${displayKey(rt.res.apiKey, showSecrets)} (${rt.res.apiKeySource}${rt.res.apiKeyStorage ? `, ${rt.res.apiKeyStorage}` : \"\"})`\n : \"—\",\n ],\n ...(expiresAt !== undefined\n ? [[\"Key expires\", describeExpiry(expiresAt)] as [string, string]]\n : []),\n [\"Base URL\", rt.res.baseUrl],\n ]);\n if (warning) process.stdout.write(`\\n${warning}\\n`);\n if (probe.state === \"rejected\") process.exitCode = 1;\n });\n}\n","import { KrovaError, TerminationProtectedError } from \"@krovacloud/sdk\";\n\nimport { ENV } from \"./config.js\";\n\nconst NETWORK_CODES = new Set([\n \"ECONNREFUSED\",\n \"ENOTFOUND\",\n \"ETIMEDOUT\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n]);\n\n/** Hint for an API status, or undefined when a generic hint would not help (e.g. 400, 422). */\nexport function hintForStatus(status: number): string | undefined {\n if (status === 401) return \"Your API key was rejected. Run krova login, or check krova whoami.\";\n if (status === 403) {\n return \"Your key's member lacks the permission for this action. Ask a space owner to grant it.\";\n }\n if (status === 404) return \"Not found. Check the name or ID with the matching list command.\";\n if (status === 409) return \"The resource is busy or in a conflicting state. Try again in a moment.\";\n if (status === 429) return \"Rate limited. Wait a moment and try again.\";\n if (status >= 500 && status <= 599) {\n return \"Krova had a server error. Try again; if it keeps happening, contact support.\";\n }\n return undefined;\n}\n\n/** True when `err` (or anything in its cause chain) is a connection failure. */\nexport function isNetworkError(err: unknown): boolean {\n const seen = new Set<unknown>();\n const walk = (e: unknown, depth: number): boolean => {\n if (!e || typeof e !== \"object\" || depth > 5 || seen.has(e)) return false;\n seen.add(e);\n const { code, message, cause, errors } = e as {\n code?: unknown;\n message?: unknown;\n cause?: unknown;\n errors?: unknown;\n };\n if (typeof code === \"string\" && NETWORK_CODES.has(code)) return true;\n if (typeof message === \"string\") {\n if (message === \"fetch failed\") return true;\n for (const c of NETWORK_CODES) if (message.includes(c)) return true;\n }\n if (walk(cause, depth + 1)) return true;\n return Array.isArray(errors) && errors.some((x) => walk(x, depth + 1));\n };\n return walk(err, 0);\n}\n\n/**\n * The one extra line the top-level error handler prints under `Error: ...`.\n *\n * - An error that carries its own `hint` string wins: it is returned as-is, so\n * a command that already explains itself is never given a second, generic one.\n * - A `KrovaError` (the API answered) gets a hint by status. A termination\n * protection refusal gets none: retrying cannot help and its message is exact.\n * - A connection failure gets a hint naming the base URL being used.\n * - Anything else (validation, local errors) gets none.\n */\nexport function errorHint(err: unknown, baseUrl: string): string | undefined {\n const own = (err as { hint?: unknown } | null)?.hint;\n if (typeof own === \"string\" && own) return own;\n if (err instanceof TerminationProtectedError) return undefined;\n if (err instanceof KrovaError) return hintForStatus(err.status);\n if (isNetworkError(err)) {\n return `Could not reach ${baseUrl}. Check your connection or ${ENV.baseUrl}.`;\n }\n return undefined;\n}\n","import { Command } from \"commander\";\n\nimport { authCommand } from \"./commands/auth.js\";\nimport { backupsCommand } from \"./commands/backups.js\";\nimport { imagesCommand, pricingCommand, regionsCommand } from \"./commands/catalog.js\";\nimport { completionCommand } from \"./commands/completion.js\";\nimport { contextCommand } from \"./commands/context.js\";\nimport { cubesCommand, rootGetCommand, rootListCommand } from \"./commands/cubes.js\";\nimport { domainsCommand } from \"./commands/domains.js\";\nimport { loginCommand } from \"./commands/login.js\";\nimport { snapshotsCommand } from \"./commands/snapshots.js\";\nimport { mysqlCommand, psqlCommand, redisCommand } from \"./commands/dbclients.js\";\nimport { cpCommand, execCommand } from \"./commands/exec.js\";\nimport { sshCommand } from \"./commands/ssh.js\";\nimport { connectCommand, tunnelCommand } from \"./commands/tunnel.js\";\nimport { tcpCommand } from \"./commands/tcp.js\";\nimport { updateCommand } from \"./commands/update.js\";\nimport { CLI_VERSION, versionCommand } from \"./commands/version.js\";\nimport { webhooksCommand } from \"./commands/webhooks.js\";\nimport { whoamiCommand } from \"./commands/whoami.js\";\nimport { DEFAULT_BASE_URL, ENV, load, resolve } from \"./lib/config.js\";\nimport { errorHint } from \"./lib/hints.js\";\nimport { parseOutputFormat } from \"./lib/output-format.js\";\nimport { exitQuietlyOnBrokenPipe } from \"./lib/output.js\";\nimport { activeRuntime } from \"./lib/runtime.js\";\n\nexitQuietlyOnBrokenPipe();\n\nconst program = new Command();\nprogram\n .name(\"krova\")\n .description(\n \"krova is the command-line interface for Krova Cloud — manage Cubes (Firecracker microVMs), browse the catalog, and receive webhooks.\"\n )\n .version(CLI_VERSION, \"-v, --version\", \"print the krova CLI version\")\n .showHelpAfterError();\n\nprogram.addCommand(loginCommand());\nprogram.addCommand(authCommand());\nprogram.addCommand(contextCommand());\nprogram.addCommand(whoamiCommand());\nprogram.addCommand(cubesCommand());\nprogram.addCommand(domainsCommand());\nprogram.addCommand(snapshotsCommand());\nprogram.addCommand(backupsCommand());\nprogram.addCommand(tcpCommand());\nprogram.addCommand(sshCommand());\nprogram.addCommand(tunnelCommand());\nprogram.addCommand(connectCommand());\nprogram.addCommand(psqlCommand());\nprogram.addCommand(redisCommand());\nprogram.addCommand(mysqlCommand());\nprogram.addCommand(execCommand());\nprogram.addCommand(cpCommand());\nprogram.addCommand(rootListCommand()); // `krova list` (alias `ls`)\nprogram.addCommand(rootGetCommand()); // `krova get`\nprogram.addCommand(regionsCommand());\nprogram.addCommand(imagesCommand());\nprogram.addCommand(pricingCommand());\nprogram.addCommand(webhooksCommand());\nprogram.addCommand(versionCommand());\nprogram.addCommand(updateCommand());\nprogram.addCommand(completionCommand());\n\n// cobra-style persistent flags: usable on any command, before or after it.\n// Skips a flag a command already defines locally (e.g. login's own --context).\nconst applyGlobals = (cmd: Command): void => {\n const have = new Set(cmd.options.map((o) => o.long));\n const add = (flags: string, desc: string, def?: string) => {\n const long = flags.split(/[ ,<[]/).find((f) => f.startsWith(\"--\"));\n if (long && !have.has(long)) cmd.option(flags, desc, def);\n };\n add(\"--api-key <key>\", \"Krova Cloud API key (overrides env and context)\");\n add(\"--space <id>\", \"Space ID (overrides KROVA_SPACE_ID and context)\");\n add(\"--base-url <url>\", \"override the API base URL\");\n add(\"--context <name>\", \"use a named context (overrides KROVA_CONTEXT)\");\n add(\"--json\", \"output machine-readable JSON instead of a table\");\n add(\"-o, --output <format>\", \"output format: table (default) or json; -o json is the same as --json\");\n add(\"--timeout <duration>\", \"per-request timeout\", \"30s\");\n for (const c of cmd.commands) applyGlobals(c);\n};\napplyGlobals(program);\n\n// Reject a bad `-o` before any command runs, with a one-line error.\nprogram.hook(\"preAction\", (_root, actionCmd) => {\n parseOutputFormat((actionCmd.optsWithGlobals() as { output?: unknown }).output);\n});\n\n/** The base URL for a connection hint: the one the failing command resolved,\n * else what the environment and saved context would give. */\nfunction hintBaseUrl(): string {\n const active = activeRuntime();\n if (active) return active.baseUrl;\n try {\n return resolve(load(), {}).baseUrl;\n } catch {\n return process.env[ENV.baseUrl] || DEFAULT_BASE_URL;\n }\n}\n\nasync function main(): Promise<void> {\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`Error: ${msg}\\n`);\n // One actionable line under the error. Not in JSON mode: errors there stay\n // exactly as they were (plain text on stderr), so a script's parsing is unchanged.\n if (!activeRuntime()?.json) {\n const hint = errorHint(err, hintBaseUrl());\n if (hint) process.stderr.write(`${hint}\\n`);\n }\n process.exitCode = 1;\n }\n}\n\nvoid main();\n"],"mappings":";;;;;;;;;;;;;;;;AAYA,MAAa,mBAAmB;AAChC,MAAa,kBAAkB;AAE/B,MAAM,aAAa;;AAcnB,IAAa,2BAAb,cAA8C,MAAM;CAGvC;CAFX,YACE,SACA,SAAkB,OAClB;EACA,MAAM,OAAO;EAFJ,KAAA,SAAA;EAGT,KAAK,OAAO;CACd;AACF;AAQA,SAAS,IAAI,KAAa,MAAgB,OAAgB,WAAW,OAAkB;CAGrF,MAAM,IAAI,UAAU,KAAK,MAAM;EAC7B,UAAU;EACV;EACA,SAAS;EACT,aAAa;EACb;CACF,CAA2D;CAC3D,IAAI,EAAE,OAAO;EACX,MAAM,OAAQ,EAAE,MAAgC;EAChD,IAAI,SAAS,UAAU,MAAM,IAAI,yBAAyB,KAAK,IAAI,iBAAiB;EACpF,IAAI,SAAS,aAAa,MAAM,IAAI,MAAM,KAAK,IAAI,qBAAqB,aAAa,IAAK,EAAE;EAC5F,MAAM,IAAI,MAAM,KAAK,IAAI,aAAa,EAAE,MAAM,SAAS;CACzD;CACA,OAAO;EAAE,QAAQ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AA0B,MAAM;AAChF,CAAC;;;AAID,SAAS,cAAsB;CAC7B,MAAM,SAAS,cAAc;CAC7B,IAAI,QAAQ,OAAO,OAAO;CAC1B,IAAI;EACF,OAAO,QAAQ,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC;CAC7B,QAAQ;EACN,OAAO,QAAQ,IAAI,IAAI,YAAA;CACzB;AACF;AAEA,eAAe,OAAsB;CACnC,IAAI;EACF,MAAM,QAAQ,WAAW,QAAQ,IAAI;CACvC,SAAS,KAAK;EACZ,MAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EAC3D,QAAQ,OAAO,MAAM,UAAU,IAAI,GAAG;EAGtC,IAAI,CAAC,cAAc,CAAC,EAAE,MAAM;GAC1B,MAAM,OAAO,UAAU,KAAK,YAAY,CAAC;GACzC,IAAI,MAAM,QAAQ,OAAO,MAAM,GAAG,KAAK,GAAG;EAC5C;EACA,QAAQ,WAAW;CACrB;AACF;AAEK,KAAK"}
1
+ {"version":3,"file":"index.js","names":["errText","readline","osConstants","PRIVATE_NOTE","createServer"],"sources":["../src/lib/keychain.ts","../src/lib/base-url.ts","../src/lib/config.ts","../src/lib/output.ts","../src/lib/client.ts","../src/lib/output-format.ts","../src/lib/runtime.ts","../src/lib/persist.ts","../src/commands/auth.ts","../src/commands/backups.ts","../src/commands/catalog.ts","../src/lib/completion.ts","../src/commands/completion.ts","../src/commands/context.ts","../src/lib/create-prompt.ts","../src/lib/resolve.ts","../src/lib/safety.ts","../src/lib/spinner.ts","../src/lib/wait.ts","../src/commands/cubes.ts","../src/commands/domains.ts","../src/commands/login.ts","../src/commands/snapshots.ts","../src/lib/ssh.ts","../src/lib/tunnel.ts","../src/commands/dbclients.ts","../src/commands/exec.ts","../src/commands/ssh.ts","../src/commands/tunnel.ts","../src/commands/tcp.ts","../src/lib/semver.ts","../src/commands/version.ts","../src/commands/update.ts","../src/commands/webhooks.ts","../src/commands/whoami.ts","../src/lib/hints.ts","../src/index.ts"],"sourcesContent":["// OS keychain access for API keys. macOS goes through the `security` CLI and\n// Linux through `secret-tool` (libsecret). Both are called with argv arrays\n// (spawnSync, never a shell string). Anything else, or any failure, is reported\n// to the caller, which falls back to the 0600 config file.\n//\n// Why spawnSync: `load()` and `resolve()` in config.ts are synchronous and run\n// in every command, so the keychain backend is synchronous too. The keychain is\n// only touched when a stored key is actually needed (never when --api-key or\n// KROVA_API_KEY wins).\n\nimport { spawnSync } from \"node:child_process\";\n\nexport const KEYCHAIN_SERVICE = \"krova-cli\";\nexport const NO_KEYCHAIN_ENV = \"KROVA_NO_KEYCHAIN\";\n\nconst TIMEOUT_MS = 15_000;\n\nexport interface KeychainBackend {\n /** Human name for messages, e.g. \"macOS Keychain\". */\n readonly name: string;\n /** The stored secret, or undefined when there is no such item. Throws on any other failure. */\n get(account: string): string | undefined;\n /** Create or replace the item. Throws on failure. */\n set(account: string, secret: string): void;\n /** Remove the item; a missing item is not an error. Throws on any other failure. */\n delete(account: string): void;\n}\n\n/** Thrown when no keychain can be used at all (opted out, unsupported platform, tool missing). */\nexport class KeychainUnavailableError extends Error {\n constructor(\n message: string,\n readonly optOut = false,\n ) {\n super(message);\n this.name = \"KeychainUnavailableError\";\n }\n}\n\ninterface RunResult {\n status: number | null;\n stdout: string;\n stderr: string;\n}\n\nfunction run(cmd: string, args: string[], input?: string, detached = false): RunResult {\n // `detached` is honored by spawnSync (libuv UV_PROCESS_DETACHED, i.e. setsid) but is\n // missing from @types/node's SpawnSyncOptions, hence the cast.\n const r = spawnSync(cmd, args, {\n encoding: \"utf8\",\n input,\n timeout: TIMEOUT_MS,\n windowsHide: true,\n detached,\n } as Parameters<typeof spawnSync>[2] & { encoding: \"utf8\" });\n if (r.error) {\n const code = (r.error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") throw new KeychainUnavailableError(`\\`${cmd}\\` was not found`);\n if (code === \"ETIMEDOUT\") throw new Error(`\\`${cmd}\\` timed out after ${TIMEOUT_MS / 1000}s`);\n throw new Error(`\\`${cmd}\\` failed: ${r.error.message}`);\n }\n return { status: r.status, stdout: r.stdout ?? \"\", stderr: r.stderr ?? \"\" };\n}\n\nfunction assertSecret(secret: string): void {\n if (!secret || /[\\r\\n\\0]/.test(secret)) throw new Error(\"the API key is empty or contains a line break\");\n}\n\nfunction failure(cmd: string, r: RunResult): Error {\n const detail = r.stderr.trim().split(\"\\n\")[0] || `exit ${r.status}`;\n return new Error(`\\`${cmd}\\` failed: ${detail}`);\n}\n\n/** macOS: the `security` CLI (verified against `man security` on macOS and a live round trip).\n *\n * The password never goes in argv: `add-generic-password ... -w` with NO value after\n * the last option makes `security` prompt for it (\"Put at end of command to be\n * prompted (recommended)\"), and the prompt reads stdin only when the process has no\n * controlling terminal. A normal terminal run would read /dev/tty and ignore our pipe,\n * so the child is spawned detached (setsid, no controlling terminal) and gets\n * \"<secret>\\n<secret>\\n\" on stdin (prompt + retype). The write is verified by a read-back\n * in config.ts, so a platform where this misbehaves falls back to the file. */\nexport function macosBackend(service = KEYCHAIN_SERVICE): KeychainBackend {\n return {\n name: \"macOS Keychain\",\n get(account) {\n const r = run(\"security\", [\"find-generic-password\", \"-s\", service, \"-a\", account, \"-w\"]);\n if (r.status === 44) return undefined; // errSecItemNotFound\n if (r.status !== 0) throw failure(\"security\", r);\n return r.stdout.replace(/\\n$/, \"\");\n },\n set(account, secret) {\n assertSecret(secret);\n const r = run(\n \"security\",\n [\"add-generic-password\", \"-U\", \"-s\", service, \"-a\", account, \"-l\", `Krova CLI (${account})`, \"-w\"],\n `${secret}\\n${secret}\\n`,\n true,\n );\n if (r.status !== 0) throw failure(\"security\", r);\n },\n delete(account) {\n const r = run(\"security\", [\"delete-generic-password\", \"-s\", service, \"-a\", account]);\n if (r.status !== 0 && r.status !== 44) throw failure(\"security\", r);\n },\n };\n}\n\n/** Linux: `secret-tool` from libsecret. `store` reads the secret from stdin when it is not a\n * terminal (documented in secret-tool(1): \"Everything up to EOF becomes the password\"), so\n * nothing secret is in argv. Not run on this build machine (macOS); the argv shapes follow the\n * man page synopsis. */\nexport function secretToolBackend(service = KEYCHAIN_SERVICE): KeychainBackend {\n return {\n name: \"Secret Service (secret-tool)\",\n get(account) {\n const r = run(\"secret-tool\", [\"lookup\", \"service\", service, \"account\", account]);\n if (r.status === 0) return r.stdout.replace(/\\n$/, \"\");\n // Not found is exactly exit 1 with nothing on stdout or stderr; any other code is a failure.\n if (r.status === 1 && !r.stdout && !r.stderr.trim()) return undefined;\n throw failure(\"secret-tool\", r);\n },\n set(account, secret) {\n assertSecret(secret);\n const r = run(\n \"secret-tool\",\n [\"store\", `--label=Krova CLI (${account})`, \"service\", service, \"account\", account],\n secret,\n );\n if (r.status !== 0) throw failure(\"secret-tool\", r);\n },\n delete(account) {\n const r = run(\"secret-tool\", [\"clear\", \"service\", service, \"account\", account]);\n if (r.status === 0) return;\n // A failed clear is only \"nothing to delete\" if a lookup confirms the item is gone.\n if (this.get(account) === undefined) return;\n throw failure(\"secret-tool\", r);\n },\n };\n}\n\n/** Test seam: `undefined` uses the real platform backend, a backend replaces it,\n * `null` means \"no keychain available\". */\nlet override: KeychainBackend | null | undefined;\nexport function setKeychainBackendForTests(b: KeychainBackend | null | undefined): void {\n override = b;\n}\n\nexport function keychainOptedOut(): boolean {\n const v = (process.env[NO_KEYCHAIN_ENV] ?? \"\").trim().toLowerCase();\n return v === \"1\" || v === \"true\" || v === \"yes\";\n}\n\n/** The backend to use for reads (an existing keychain context must be readable even\n * under KROVA_NO_KEYCHAIN, which only governs where new keys are WRITTEN). */\nexport function readBackend(): KeychainBackend {\n if (override === null) throw new KeychainUnavailableError(\"no keychain is available\");\n if (override) return override;\n if (process.platform === \"darwin\") return macosBackend();\n if (process.platform === \"linux\") return secretToolBackend();\n throw new KeychainUnavailableError(`no keychain support on ${process.platform}`);\n}\n\n/** The backend to use for writes: like readBackend, but KROVA_NO_KEYCHAIN=1 forces the file. */\nexport function writeBackend(): KeychainBackend {\n if (keychainOptedOut()) throw new KeychainUnavailableError(`${NO_KEYCHAIN_ENV} is set`, true);\n return readBackend();\n}\n","const API_PATH = \"/api/v1\";\n\n/**\n * The API base URL the CLI talks to, by the same rule as the SDK's client: surrounding\n * whitespace and trailing slashes are removed, a bare origin (`https://krova.cloud`) gets\n * `/api/v1` appended, and any other path is kept as given. Call it only with a value that\n * is set; an empty or whitespace-only one means \"not set\" and is the caller's to skip.\n */\nexport function normalizeBaseUrl(raw: string): string {\n const trimmed = raw.trim().replace(/\\/+$/, \"\");\n let url: URL;\n try {\n url = new URL(trimmed);\n } catch {\n return trimmed;\n }\n if (url.pathname === \"/\" && !url.search && !url.hash) return `${trimmed}${API_PATH}`;\n return trimmed;\n}\n","// Reads/writes ~/.config/krova/config.json in the EXACT shape the Go CLI used,\n// so existing configs keep working. Multi-context, with legacy single-key\n// migration. The file is always tightened to 0600 on save. API keys live in the\n// OS keychain when one is available (see keychain.ts) and in this file otherwise.\n\nimport { randomBytes } from \"node:crypto\";\nimport { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { normalizeBaseUrl } from \"./base-url.js\";\nimport {\n KeychainUnavailableError,\n KEYCHAIN_SERVICE,\n readBackend,\n writeBackend,\n} from \"./keychain.js\";\n\nexport const DEFAULT_BASE_URL = \"https://krova.cloud/api/v1\";\nexport const DEFAULT_CONTEXT_NAME = \"default\";\n\nexport const ENV = {\n apiKey: \"KROVA_API_KEY\",\n spaceId: \"KROVA_SPACE_ID\",\n baseUrl: \"KROVA_BASE_URL\",\n context: \"KROVA_CONTEXT\",\n npmRegistry: \"KROVA_NPM_REGISTRY\",\n} as const;\n\n/** Where a context's API key lives. A context with no `keyStorage` is a file context. */\nexport type KeyStorage = \"keychain\" | \"file\";\n\nexport interface Context {\n name: string;\n apiKey?: string;\n keyStorage?: KeyStorage;\n spaceId?: string;\n spaceName?: string;\n baseUrl?: string;\n}\n\nexport interface Config {\n currentContext?: string;\n contexts?: Context[];\n // legacy (pre-context) fields — parsed then migrated into a \"default\" context\n apiKey?: string;\n spaceId?: string;\n baseUrl?: string;\n}\n\nexport function configDir(): string {\n const xdg = (process.env.XDG_CONFIG_HOME ?? \"\").trim();\n if (xdg) return join(xdg, \"krova\");\n return join(homedir(), \".config\", \"krova\");\n}\n\nexport function configPath(): string {\n return join(configDir(), \"config.json\");\n}\n\nexport function load(): Config {\n let cfg: Config = {};\n try {\n cfg = JSON.parse(readFileSync(configPath(), \"utf8\")) as Config;\n } catch {\n cfg = {};\n }\n return migrate(cfg);\n}\n\n// If only legacy fields are set, synthesize a \"default\" context from them.\nfunction migrate(cfg: Config): Config {\n if ((cfg.apiKey ?? \"\").trim() && (!cfg.contexts || cfg.contexts.length === 0)) {\n cfg.contexts = [\n {\n name: DEFAULT_CONTEXT_NAME,\n apiKey: cfg.apiKey,\n spaceId: cfg.spaceId,\n baseUrl: cfg.baseUrl,\n },\n ];\n cfg.currentContext = DEFAULT_CONTEXT_NAME;\n }\n cfg.apiKey = undefined;\n cfg.spaceId = undefined;\n cfg.baseUrl = undefined;\n return cfg;\n}\n\nexport function save(cfg: Config): void {\n const path = configPath();\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n // clear legacy fields; only serialize non-empty keys (matches Go omitempty)\n const clean: Config = {};\n if (cfg.currentContext) clean.currentContext = cfg.currentContext;\n if (cfg.contexts && cfg.contexts.length) {\n clean.contexts = cfg.contexts.map((c) => {\n const o: Context = { name: c.name };\n // A keychain context never writes its key to the file.\n if (c.apiKey && c.keyStorage !== \"keychain\") o.apiKey = c.apiKey;\n if (c.keyStorage) o.keyStorage = c.keyStorage;\n if (c.spaceId) o.spaceId = c.spaceId;\n if (c.spaceName) o.spaceName = c.spaceName;\n if (c.baseUrl) o.baseUrl = c.baseUrl;\n return o;\n });\n }\n // Atomic: write a 0600 temp file in the same directory, then rename over the config, so a\n // crash or full disk never leaves a half-written file (and the key is never briefly world-readable).\n const tmp = `${path}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`;\n try {\n writeFileSync(tmp, `${JSON.stringify(clean, null, 2)}\\n`, { mode: 0o600, flag: \"wx\" });\n renameSync(tmp, path);\n } catch (e) {\n try {\n unlinkSync(tmp);\n } catch {\n /* already gone */\n }\n throw e;\n }\n chmodSync(path, 0o600);\n}\n\nexport function find(cfg: Config, name: string): Context | undefined {\n return (cfg.contexts ?? []).find((c) => c.name === name);\n}\n\n/** The active context: `override` (e.g. --context) wins, else currentContext. */\nexport function current(cfg: Config, override?: string): Context | undefined {\n const name = (override ?? \"\").trim() || (cfg.currentContext ?? \"\").trim();\n if (!name) return undefined;\n return find(cfg, name);\n}\n\n/** Merge-in a context: only NON-EMPTY apiKey/spaceId/spaceName/baseUrl\n * overwrite an existing value. This keeps a transient per-command override\n * (e.g. a one-off `--base-url`) from being silently persisted over the\n * context's real base URL. First-ever context becomes current. Returns it. */\nexport function upsert(cfg: Config, incoming: Context): Context {\n cfg.contexts ??= [];\n let ctx = cfg.contexts.find((c) => c.name === incoming.name);\n if (!ctx) {\n ctx = { name: incoming.name };\n cfg.contexts.push(ctx);\n if (!cfg.currentContext) cfg.currentContext = ctx.name;\n }\n if ((incoming.apiKey ?? \"\").trim()) ctx.apiKey = incoming.apiKey;\n if ((incoming.spaceId ?? \"\").trim()) ctx.spaceId = incoming.spaceId;\n if ((incoming.spaceName ?? \"\").trim()) ctx.spaceName = incoming.spaceName;\n if ((incoming.baseUrl ?? \"\").trim()) ctx.baseUrl = incoming.baseUrl;\n return ctx;\n}\n\n/** Drop a context from `cfg` in memory only (the caller still calls `save`). Does not touch the\n * keychain: use `removeContext` to remove a context and its keychain item together. */\nexport function remove(cfg: Config, name: string): boolean {\n const before = (cfg.contexts ?? []).length;\n cfg.contexts = (cfg.contexts ?? []).filter((c) => c.name !== name);\n if (cfg.contexts.length === before) return false;\n if (cfg.currentContext === name) {\n cfg.currentContext = cfg.contexts[0]?.name ?? \"\";\n }\n return true;\n}\n\n/** Remove a context, save the config, and only then delete its keychain item, so a failed save\n * leaves both the context and its key intact. Returns false when there is no such context. */\nexport function removeContext(cfg: Config, name: string, persist: () => void = () => save(cfg)): boolean {\n const gone = find(cfg, name);\n if (!gone) return false;\n const snapshot = { contexts: [...(cfg.contexts ?? [])], currentContext: cfg.currentContext };\n remove(cfg, name);\n try {\n persist();\n } catch (e) {\n cfg.contexts = snapshot.contexts;\n cfg.currentContext = snapshot.currentContext;\n throw e;\n }\n deleteContextKey(gone);\n return true;\n}\n\nexport type Source = \"flag\" | \"env\" | \"context\" | \"\";\n\nexport interface Resolved {\n apiKey: string;\n spaceId: string;\n baseUrl: string;\n apiKeySource: Source;\n /** Where a context-sourced key is stored; \"\" when the key came from a flag or env var, or is missing. */\n apiKeyStorage: KeyStorage | \"\";\n spaceIdSource: Source;\n contextName: string;\n}\n\nexport interface GlobalFlags {\n apiKey?: string;\n space?: string;\n baseUrl?: string;\n context?: string;\n}\n\n/** Resolve credentials with precedence flag > env > active context. */\nexport function resolve(cfg: Config, flags: GlobalFlags): Resolved {\n const ctx = current(cfg, (flags.context ?? \"\").trim() || process.env[ENV.context]);\n const pick = (\n flag: string | undefined,\n env: string | undefined,\n ctxVal: string | undefined\n ): [string, Source] => {\n if ((flag ?? \"\").trim()) return [flag as string, \"flag\"];\n if ((env ?? \"\").trim()) return [env as string, \"env\"];\n if ((ctxVal ?? \"\").trim()) return [ctxVal as string, \"context\"];\n return [\"\", \"\"];\n };\n // --api-key and KROVA_API_KEY win without ever touching the keychain: the stored\n // key is only read (and the keychain only prompted) when nothing overrides it.\n const overridden = Boolean((flags.apiKey ?? \"\").trim() || (process.env[ENV.apiKey] ?? \"\").trim());\n const [apiKey, apiKeySource] = pick(\n flags.apiKey,\n process.env[ENV.apiKey],\n overridden || !ctx ? undefined : contextKey(ctx),\n );\n const [spaceId, spaceIdSource] = pick(flags.space, process.env[ENV.spaceId], ctx?.spaceId);\n const [baseUrlRaw] = pick(flags.baseUrl, process.env[ENV.baseUrl], ctx?.baseUrl);\n return {\n apiKey,\n spaceId,\n baseUrl: baseUrlRaw ? normalizeBaseUrl(baseUrlRaw) : DEFAULT_BASE_URL,\n apiKeySource,\n apiKeyStorage: apiKeySource === \"context\" && ctx ? storageOf(ctx) : \"\",\n spaceIdSource,\n contextName: ctx?.name ?? \"\",\n };\n}\n\n// --- API key storage (OS keychain with a 0600 file fallback) ---------------\n\nexport function storageOf(ctx: Context): KeyStorage {\n return ctx.keyStorage === \"keychain\" ? \"keychain\" : \"file\";\n}\n\nconst errText = (e: unknown): string => (e instanceof Error ? e.message : String(e));\n\n/** One short line on stderr (stdout stays clean for --json). */\nfunction warn(msg: string): void {\n process.stderr.write(`krova: ${msg}\\n`);\n}\n\n/** The context's API key: from the file, or from the OS keychain for a keychain context.\n * A keychain that cannot be read warns on stderr and returns \"\" (so the caller sees\n * \"no key\" and is told to log in again) instead of crashing every command. */\nexport function contextKey(ctx: Context): string {\n if (storageOf(ctx) !== \"keychain\") return ctx.apiKey ?? \"\";\n try {\n const key = readBackend().get(ctx.name);\n if (key) return key;\n warn(\n `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`,\n );\n } catch (e) {\n warn(\n `could not read the API key for context \"${ctx.name}\" from the OS keychain (${errText(e)}); run \\`krova login --context ${ctx.name}\\` to store it again`,\n );\n }\n return \"\";\n}\n\nexport interface StoreResult {\n storage: KeyStorage;\n /** Human name of the keychain used, when storage is \"keychain\". */\n backend?: string;\n}\n\n/** Write `key` to the keychain (verified by a read-back) and mark `ctx` as a keychain\n * context, else keep it in the 0600 file with a one-line stderr message. Mutates `ctx`;\n * the caller still calls `save`. Never throws. */\nexport function setContextKey(ctx: Context, key: string): StoreResult {\n try {\n const backend = writeBackend();\n backend.set(ctx.name, key);\n if (backend.get(ctx.name) !== key) {\n try {\n backend.delete(ctx.name);\n } catch {\n /* best effort */\n }\n throw new Error(\"the keychain did not return the stored key\");\n }\n ctx.keyStorage = \"keychain\";\n ctx.apiKey = undefined;\n return { storage: \"keychain\", backend: backend.name };\n } catch (e) {\n // An explicit KROVA_NO_KEYCHAIN opt-out is silent; every other reason is said once.\n if (!(e instanceof KeychainUnavailableError && e.optOut)) {\n warn(`OS keychain unavailable (${errText(e)}); storing the API key in ${configPath()} (mode 0600) instead`);\n }\n }\n // Leaving a keychain context for the file: drop the stale item.\n if (storageOf(ctx) === \"keychain\") deleteContextKey(ctx);\n ctx.keyStorage = \"file\";\n ctx.apiKey = key;\n return { storage: \"file\" };\n}\n\n/** Delete the context's keychain item, if it has one. Failure is a warning, not an error:\n * the context is being removed either way. */\nexport function deleteContextKey(ctx: Context): void {\n if (storageOf(ctx) !== \"keychain\") return;\n try {\n readBackend().delete(ctx.name);\n } catch (e) {\n warn(`could not delete the keychain item for context \"${ctx.name}\" (${errText(e)}); remove it by hand (service ${KEYCHAIN_SERVICE}, account ${ctx.name})`);\n }\n}\n\n/** Rename a context and save the config. A keychain key moves with it: the new item is written\n * and verified first, the config is saved, and only then is the old item deleted. A failure at\n * any step before that leaves the context (and its old item) as it was. */\nexport function renameContext(\n cfg: Config,\n oldName: string,\n newName: string,\n persist: () => void = () => save(cfg),\n): void {\n const c = find(cfg, oldName);\n if (!c) throw new Error(`no context named \"${oldName}\"`);\n assertContextName(newName);\n if (find(cfg, newName)) throw new Error(`a context named \"${newName}\" already exists`);\n const moved = storageOf(c) === \"keychain\";\n const backend = moved ? readBackend() : undefined;\n if (backend) {\n let key: string | undefined;\n try {\n key = backend.get(oldName);\n } catch (e) {\n throw new Error(`could not read the key for \"${oldName}\" from the OS keychain: ${errText(e)}`);\n }\n if (!key) throw new Error(`the API key for \"${oldName}\" is not in the OS keychain; run \\`krova login --context ${oldName}\\` first`);\n try {\n backend.set(newName, key);\n if (backend.get(newName) !== key) throw new Error(\"the keychain did not return the stored key\");\n } catch (e) {\n try {\n backend.delete(newName);\n } catch {\n /* best effort */\n }\n throw new Error(`could not move the key to \"${newName}\" in the OS keychain: ${errText(e)}`);\n }\n }\n const wasCurrent = cfg.currentContext === oldName;\n c.name = newName;\n if (wasCurrent) cfg.currentContext = newName;\n try {\n persist();\n } catch (e) {\n c.name = oldName;\n if (wasCurrent) cfg.currentContext = oldName;\n if (backend) {\n try {\n backend.delete(newName);\n } catch {\n /* best effort */\n }\n }\n throw e;\n }\n if (backend) {\n try {\n backend.delete(oldName);\n } catch (e) {\n warn(`renamed, but could not delete the old keychain item (${errText(e)}); remove it by hand (service ${KEYCHAIN_SERVICE}, account ${oldName})`);\n }\n }\n}\n\nexport interface MigrateEntry {\n context: string;\n result: \"migrated\" | \"skipped\" | \"failed\";\n detail?: string;\n}\n\n/** Move every file-stored key into the keychain. A key leaves the file only after the\n * keychain read-back matches; `save` runs after each context so a later failure never\n * loses an earlier move. Throws when no keychain can be used at all. */\nexport function migrateKeysToKeychain(cfg: Config): { backend: string; entries: MigrateEntry[] } {\n const backend = writeBackend(); // honors KROVA_NO_KEYCHAIN (throws KeychainUnavailableError)\n const entries: MigrateEntry[] = [];\n for (const ctx of cfg.contexts ?? []) {\n if (storageOf(ctx) === \"keychain\") {\n entries.push({ context: ctx.name, result: \"skipped\", detail: \"already in the keychain\" });\n continue;\n }\n const key = (ctx.apiKey ?? \"\").trim();\n if (!key) {\n entries.push({ context: ctx.name, result: \"skipped\", detail: \"no API key stored\" });\n continue;\n }\n try {\n backend.set(ctx.name, key);\n if (backend.get(ctx.name) !== key) {\n try {\n backend.delete(ctx.name);\n } catch {\n /* best effort */\n }\n throw new Error(\"the keychain did not return the stored key\");\n }\n } catch (e) {\n entries.push({ context: ctx.name, result: \"failed\", detail: errText(e) });\n continue;\n }\n ctx.keyStorage = \"keychain\";\n ctx.apiKey = undefined;\n save(cfg);\n entries.push({ context: ctx.name, result: \"migrated\" });\n }\n return { backend: backend.name, entries };\n}\n\n/** A context name becomes a keychain account passed to `security` and `secret-tool`, so one that\n * starts with `-` could be read as an option. */\nexport function assertContextName(name: string): void {\n if (name.trim().startsWith(\"-\")) throw new Error(`context names cannot start with \"-\" (got \"${name}\")`);\n}\n\nexport function sanitizeContextName(name: string): string {\n const clean = name.trim().toLowerCase().replace(/\\s+/g, \"-\");\n assertContextName(clean);\n return clean;\n}\n\nexport function maskKey(key: string): string {\n if (!key) return \"\";\n if (key.length <= 8) return \"****\";\n return `${key.slice(0, 6)}…${key.slice(-4)}`;\n}\n\n/** The key as it should be printed: masked unless `--show-secrets` was passed. */\nexport function displayKey(key: string, showSecrets: boolean): string {\n return showSecrets ? key : maskKey(key);\n}\n","/**\n * Stop quietly when the reader of stdout goes away (`krova cubes list | head -1`),\n * the way standard Unix tools do: an EPIPE ends the process with status 0 and no\n * stack trace. Every other write error is still reported, as `Error: ...` with\n * status 1; only the one expected case is silent.\n */\nexport function exitQuietlyOnBrokenPipe(\n stream: NodeJS.EventEmitter = process.stdout,\n exit: (code: number) => void = (code) => process.exit(code),\n warn: (text: string) => void = (text) => void process.stderr.write(text)\n): void {\n stream.on(\"error\", (err: NodeJS.ErrnoException) => {\n if (err?.code === \"EPIPE\") return exit(0);\n warn(`Error: ${err instanceof Error ? err.message : String(err)}\\n`);\n exit(1);\n });\n}\n\nexport function printJSON(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\n/**\n * Where to connect for a TCP mapping: `host:port`.\n *\n * `host` is the Cube's OWN stable hostname, which survives migration to\n * another server — not the server's hostname, which does not. Shared by\n * `tcp list` and `tcp add` so the two can never disagree about how a connect\n * target is spelled.\n *\n * Falls back to the bare port when the Cube has no host (no server assigned).\n * Printing a port alone is honest about what is known; inventing a host, or\n * printing `null:30000`, is not.\n */\nexport function mappingConnectTarget(mapping: {\n host?: string | null;\n hostPort: number;\n}): string {\n return mapping.host\n ? `${mapping.host}:${mapping.hostPort}`\n : String(mapping.hostPort);\n}\n\nexport function printTable(header: string[], rows: string[][]): void {\n const widths = header.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length))\n );\n const fmt = (cols: string[]) =>\n cols\n .map((c, i) => (c ?? \"\").padEnd(widths[i] ?? 0))\n .join(\" \")\n .replace(/\\s+$/, \"\");\n process.stdout.write(`${fmt(header)}\\n`);\n for (const r of rows) process.stdout.write(`${fmt(r)}\\n`);\n}\n\nexport function printKeyValue(pairs: Array<[string, string]>): void {\n const w = Math.max(0, ...pairs.map(([k]) => k.length));\n for (const [k, v] of pairs) {\n process.stdout.write(`${k.padEnd(w)} ${v}\\n`);\n }\n}\n","import { KrovaClient } from \"@krovacloud/sdk\";\n\nimport { normalizeBaseUrl } from \"./base-url.js\";\nimport type { Resolved } from \"./config.js\";\n\n/** Build the SDK client, or throw the same message the Go CLI used. */\nexport function makeClient(res: Resolved): KrovaClient {\n if (!res.apiKey) {\n throw new Error(\n \"no API key found: run `krova auth login`, set KROVA_API_KEY, or pass --api-key\"\n );\n }\n return new KrovaClient({ apiKey: res.apiKey, baseUrl: res.baseUrl });\n}\n\n/** Raw JSON request for endpoints the SDK doesn't cover:\n * GET /space, GET .../ssh, POST /auth/cli/start, POST /auth/cli/poll. */\nexport async function rawRequest<T>(opts: {\n method: string;\n baseUrl: string;\n path: string;\n apiKey?: string;\n body?: unknown;\n timeoutMs: number;\n}): Promise<{ status: number; data: T | undefined }> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), opts.timeoutMs);\n try {\n const headers: Record<string, string> = { Accept: \"application/json\" };\n if (opts.apiKey) headers[\"X-API-KEY\"] = opts.apiKey;\n if (opts.body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n const res = await fetch(`${normalizeBaseUrl(opts.baseUrl)}${opts.path}`, {\n method: opts.method,\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n redirect: \"manual\",\n signal: controller.signal,\n });\n let data: T | undefined;\n const text = await res.text();\n if (text) {\n try {\n data = JSON.parse(text) as T;\n } catch {\n data = undefined;\n }\n }\n return { status: res.status, data };\n } finally {\n clearTimeout(timer);\n }\n}\n","/** The values the global `-o, --output <format>` flag accepts. */\nexport const OUTPUT_FORMATS = [\"table\", \"json\"] as const;\nexport type OutputFormat = (typeof OUTPUT_FORMATS)[number];\n\n/** Values worth completing after a flag, keyed by the flag as typed. */\nexport const FLAG_VALUE_CHOICES: Record<string, readonly string[]> = {\n \"-o\": OUTPUT_FORMATS,\n \"--output\": OUTPUT_FORMATS,\n};\n\n/**\n * Validate the `--output` value. Unset means the default, `table`.\n * Throws a one-line error for anything else, so a typo never silently\n * falls back to a table in a script that expects JSON.\n */\nexport function parseOutputFormat(raw: unknown): OutputFormat {\n if (raw === undefined || raw === null || raw === \"\") return \"table\";\n const value = String(raw);\n if ((OUTPUT_FORMATS as readonly string[]).includes(value)) return value as OutputFormat;\n throw new Error(`--output must be \"json\" or \"table\" (got \"${value}\")`);\n}\n","import type { Command } from \"commander\";\n\nimport {\n type Config,\n type GlobalFlags,\n type Resolved,\n load,\n resolve,\n save,\n upsert,\n} from \"./config.js\";\nimport { makeClient, rawRequest } from \"./client.js\";\nimport { parseOutputFormat } from \"./output-format.js\";\n\n/** Parse a Go-style duration (\"30s\", \"500ms\", \"2m\", \"1h\") to ms. Non-positive\n * or unparseable floors to 30s (matches the Go requestTimeout behavior). */\nexport function parseDuration(input: string | undefined): number {\n const s = (input ?? \"\").trim();\n if (!s) return 30_000;\n let total = 0;\n const re = /(\\d+(?:\\.\\d+)?)(ms|s|m|h)/g;\n let m: RegExpExecArray | null = re.exec(s);\n let matched = false;\n while (m) {\n matched = true;\n const n = Number(m[1]);\n const unit = m[2];\n total += unit === \"ms\" ? n : unit === \"s\" ? n * 1000 : unit === \"m\" ? n * 60_000 : n * 3_600_000;\n m = re.exec(s);\n }\n if (!matched) {\n const n = Number(s);\n if (Number.isFinite(n)) total = n * 1000; // bare number = seconds\n }\n return total > 0 ? total : 30_000;\n}\n\nexport interface Runtime {\n flags: GlobalFlags;\n cfg: Config;\n res: Resolved;\n json: boolean;\n timeoutMs: number;\n}\n\n/** What the last `getRuntime` call resolved; the top-level error handler reads it\n * to name the base URL in a connection hint and to stay quiet in JSON mode. */\nlet active: { baseUrl: string; json: boolean } | undefined;\n\nexport function activeRuntime(): { baseUrl: string; json: boolean } | undefined {\n return active;\n}\n\nexport function getRuntime(cmd: Command): Runtime {\n const opts = cmd.optsWithGlobals() as Record<string, unknown>;\n const flags: GlobalFlags = {\n apiKey: opts.apiKey as string | undefined,\n space: opts.space as string | undefined,\n baseUrl: opts.baseUrl as string | undefined,\n context: opts.context as string | undefined,\n };\n const cfg = load();\n const res = resolve(cfg, flags);\n // `-o json` is `--json`; either one selects JSON. An invalid -o throws here.\n const json = Boolean(opts.json) || parseOutputFormat(opts.output) === \"json\";\n active = { baseUrl: res.baseUrl, json };\n return {\n flags,\n cfg,\n res,\n json,\n timeoutMs: parseDuration(opts.timeout as string | undefined),\n };\n}\n\nexport interface SpaceInfo {\n id: string;\n name?: string;\n slug?: string;\n /**\n * The key this request authenticated with: `expiresAt` is an ISO date-time,\n * or `null` for a key that never expires. `null` for an OAuth token, and\n * absent when the server is too old to send it, so treat absent as unknown.\n */\n apiKey?: { name: string; expiresAt: string | null } | null;\n}\n\n/**\n * The outcome of actually asking the server whether a key works.\n *\n * A stored key is NOT a working key: it can be revoked server-side at any\n * time, and the local config has no way to know. Every caller that wants to\n * report on credentials must distinguish \"rejected\" from \"couldn't reach the\n * server\" — collapsing either into a plain boolean is what made `auth status`\n * print \"Authenticated: yes\" for a key the API answers 401 to.\n */\nexport type AuthProbe =\n /** The server accepted the key and told us which space it belongs to. */\n | { state: \"valid\"; space: SpaceInfo }\n /** The key is absent locally — nothing to check. */\n | { state: \"missing\" }\n /** The server actively rejected the key (revoked, deleted, wrong env). */\n | { state: \"rejected\"; status: number }\n /** Endpoint absent (older server) — the key may still be fine. */\n | { state: \"unsupported\" }\n /** Network/DNS/timeout — says nothing about the key's validity. */\n | { state: \"unreachable\"; error: string };\n\n/** Ask the server whether `apiKey` is actually accepted. Never throws. */\nexport async function probeAuth(\n baseUrl: string,\n apiKey: string,\n timeoutMs: number\n): Promise<AuthProbe> {\n if (!apiKey) return { state: \"missing\" };\n try {\n const { status, data } = await rawRequest<SpaceInfo>({\n method: \"GET\",\n baseUrl,\n path: \"/space\",\n apiKey,\n timeoutMs,\n });\n if (status === 200 && data?.id) return { state: \"valid\", space: data };\n if (status === 401 || status === 403) return { state: \"rejected\", status };\n if (status === 404) return { state: \"unsupported\" };\n return { state: \"unreachable\", error: `HTTP ${status}` };\n } catch (err) {\n return {\n state: \"unreachable\",\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n/** Resolve the active space id: explicit value wins, else auto-detect via\n * GET /space (and cache it into the current context). */\nexport async function resolveSpace(rt: Runtime): Promise<string> {\n if (rt.res.spaceId) return rt.res.spaceId;\n const { status, data } = await rawRequest<SpaceInfo>({\n method: \"GET\",\n baseUrl: rt.res.baseUrl,\n path: \"/space\",\n apiKey: rt.res.apiKey,\n timeoutMs: rt.timeoutMs,\n });\n if (status === 200 && data?.id) {\n // Best-effort cache of the resolved space into the current named context.\n // Deliberately does NOT write baseUrl: rt.res.baseUrl already folds in a\n // one-off --base-url / KROVA_BASE_URL override, and persisting that here\n // would permanently rewrite the context's real base URL from a transient\n // flag. Only the space id/name are cached.\n if (rt.res.contextName) {\n upsert(rt.cfg, {\n name: rt.res.contextName,\n spaceId: data.id,\n spaceName: data.name,\n });\n try {\n save(rt.cfg);\n } catch {\n /* non-fatal */\n }\n }\n return data.id;\n }\n if (status === 404) {\n throw new Error(\n \"couldn't auto-detect your space (the server doesn't support it yet) — pass --space, set KROVA_SPACE_ID, or run `krova login`\"\n );\n }\n if (status === 401 || status === 403) {\n throw new Error(`auto-detect space failed: the API key was rejected (HTTP ${status})`);\n }\n throw new Error(`auto-detect space failed (HTTP ${status})`);\n}\n\nexport { makeClient };\n","import {\n DEFAULT_CONTEXT_NAME,\n configPath,\n type StoreResult,\n load,\n sanitizeContextName,\n save,\n setContextKey,\n upsert,\n} from \"./config.js\";\nimport { probeAuth } from \"./runtime.js\";\n\n/** Save + switch to a context after a login. Best-effort space lookup fills in\n * spaceId/spaceName and a nicer context name. Mirrors the Go persistLogin. */\nexport async function persistLogin(input: {\n apiKey: string;\n baseUrl: string;\n spaceId?: string;\n ctxName?: string;\n timeoutMs: number;\n}): Promise<{ ctxName: string; spaceName: string; stored: StoreResult }> {\n const cfg = load();\n let spaceId = input.spaceId ?? \"\";\n let spaceName = \"\";\n let derivedName = \"\";\n\n const probe = await probeAuth(input.baseUrl, input.apiKey, input.timeoutMs);\n const sp = probe.state === \"valid\" ? probe.space : null;\n if (sp) {\n // Prefer an explicitly-provided --space over the fetched id; only fall back\n // to the resolved space when the caller didn't pin one.\n if (!spaceId) spaceId = sp.id;\n spaceName = sp.name ?? \"\";\n derivedName = (sp.slug || sp.name || \"\").trim();\n }\n\n let name = (input.ctxName ?? \"\").trim();\n if (!name) name = derivedName || DEFAULT_CONTEXT_NAME;\n name = sanitizeContextName(name);\n\n const cur = upsert(cfg, {\n name,\n spaceId,\n spaceName,\n baseUrl: input.baseUrl,\n });\n // Keychain first, 0600 file as the fallback; the key is never written to the file when the keychain took it.\n const stored = setContextKey(cur, input.apiKey);\n cfg.currentContext = cur.name; // login always switches current\n save(cfg);\n return { ctxName: cur.name, spaceName: cur.spaceName ?? \"\", stored };\n}\n\n/** The line printed after a login: says where the key went. */\nexport function loginMessage(ctxName: string, stored: StoreResult): string {\n return stored.storage === \"keychain\"\n ? `Logged in. Saved context \"${ctxName}\" to ${configPath()} (API key in the ${stored.backend})`\n : `Logged in. Saved context \"${ctxName}\" to ${configPath()}`;\n}\n","import { Command } from \"commander\";\n\nimport { KeychainUnavailableError } from \"../lib/keychain.js\";\nimport {\n configPath,\n displayKey,\n find,\n load,\n migrateKeysToKeychain,\n removeContext,\n} from \"../lib/config.js\";\nimport { printJSON, printKeyValue } from \"../lib/output.js\";\nimport { loginMessage, persistLogin } from \"../lib/persist.js\";\nimport { getRuntime, probeAuth } from \"../lib/runtime.js\";\n\n/** Prompt for an API key. Hidden echo when stdin is a TTY. */\nfunction promptAPIKey(): Promise<string> {\n return new Promise((resolve, reject) => {\n process.stdout.write(\"Krova API key: \");\n const stdin = process.stdin;\n const tty = Boolean(stdin.isTTY);\n let buf = \"\";\n if (tty) stdin.setRawMode(true);\n stdin.resume();\n stdin.setEncoding(\"utf8\");\n const finish = (fn: () => void) => {\n if (tty) stdin.setRawMode(false);\n stdin.pause();\n stdin.removeListener(\"data\", onData);\n fn();\n };\n const onData = (ch: string) => {\n for (const c of ch) {\n const code = c.charCodeAt(0);\n if (code === 10 || code === 13) {\n finish(() => {\n process.stdout.write(\"\\n\");\n resolve(buf.trim());\n });\n return;\n }\n if (code === 3) {\n finish(() => reject(new Error(\"cancelled\")));\n return;\n }\n if (code === 127 || code === 8) {\n buf = buf.slice(0, -1);\n } else if (code >= 32) {\n buf += c;\n }\n }\n };\n stdin.on(\"data\", onData);\n });\n}\n\nexport function authCommand(): Command {\n const auth = new Command(\"auth\").description(\"manage Krova Cloud credentials\");\n\n auth\n .command(\"login\")\n .description(\"log in by pasting an API key\")\n .option(\"--api-key <key>\", \"API key (else you'll be prompted)\")\n .option(\"--space <id>\", \"Space ID to store with the key\")\n .option(\"--context <name>\", \"name for the saved context\")\n .action(async (opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n let key = (opts.apiKey as string) || rt.flags.apiKey || \"\";\n if (!key.trim()) key = await promptAPIKey();\n if (!key.trim()) throw new Error(\"no API key provided\");\n const { ctxName, spaceName, stored } = await persistLogin({\n apiKey: key.trim(),\n baseUrl: rt.res.baseUrl,\n spaceId: opts.space as string | undefined,\n // Not opts.context: the root's own --context takes the flag first, so the\n // local option never receives it. The merged flags always carry it.\n ctxName: rt.flags.context,\n timeoutMs: rt.timeoutMs,\n });\n process.stdout.write(`${loginMessage(ctxName, stored)}\\n`);\n if (spaceName) process.stdout.write(`Space: ${spaceName}\\n`);\n });\n\n auth\n .command(\"status\")\n .description(\"show the resolved credentials and verify them against the API\")\n .option(\"--offline\", \"skip the live check; only report what's stored locally\")\n .option(\"--show-secrets\", \"print the full API key instead of a masked one\")\n .action(async (opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const showSecrets = Boolean(opts.showSecrets);\n const offline = Boolean(opts.offline);\n\n // A STORED key is not a WORKING key — it can be revoked server-side at\n // any time. Reporting local presence as \"Authenticated: yes\" sends the\n // user hunting for a config problem that isn't there, so unless they ask\n // for --offline we go and ask the API.\n const probe = offline\n ? ({ state: \"missing\" } as const)\n : await probeAuth(rt.res.baseUrl, rt.res.apiKey, rt.timeoutMs);\n\n const hasKey = Boolean(rt.res.apiKey);\n const authenticated = offline ? hasKey : probe.state === \"valid\";\n\n const detail =\n offline || !hasKey\n ? \"\"\n : probe.state === \"rejected\"\n ? `the API rejected this key (HTTP ${probe.status}) — it is invalid, revoked or expired, or belongs to another environment; run \\`krova login\\``\n : probe.state === \"unreachable\"\n ? `could not reach ${rt.res.baseUrl} (${probe.error}) — the key was NOT verified`\n : probe.state === \"unsupported\"\n ? \"this server has no /space endpoint, so the key could not be verified\"\n : \"\";\n\n // Live space beats the cached copy: a stale spaceId in the config is\n // exactly the kind of drift this command exists to surface.\n const spaceId = probe.state === \"valid\" ? probe.space.id : rt.res.spaceId;\n\n if (rt.json) {\n return printJSON({\n authenticated,\n verified: probe.state === \"valid\",\n checkState: offline ? \"skipped\" : probe.state,\n detail: detail || undefined,\n context: rt.res.contextName,\n apiKeySource: rt.res.apiKeySource,\n apiKeyStorage: rt.res.apiKeyStorage || undefined,\n ...(showSecrets\n ? { apiKey: rt.res.apiKey }\n : { apiKeyMasked: displayKey(rt.res.apiKey, false) }),\n spaceId,\n spaceSource: rt.res.spaceIdSource,\n baseUrl: rt.res.baseUrl,\n configPath: configPath(),\n });\n }\n\n const label = !hasKey\n ? \"no (no API key found)\"\n : offline\n ? \"not checked (--offline; a key is stored)\"\n : probe.state === \"valid\"\n ? \"yes (verified against the API)\"\n : probe.state === \"rejected\"\n ? \"NO — key rejected by the API\"\n : \"unknown (could not verify)\";\n\n printKeyValue([\n [\"Authenticated\", label],\n [\"Context\", rt.res.contextName || \"—\"],\n [\n \"API key\",\n rt.res.apiKey\n ? `${displayKey(rt.res.apiKey, showSecrets)} (${rt.res.apiKeySource}${rt.res.apiKeyStorage ? `, ${rt.res.apiKeyStorage}` : \"\"})`\n : \"—\",\n ],\n [\"Space ID\", spaceId ? `${spaceId} (${rt.res.spaceIdSource})` : \"—\"],\n [\"Base URL\", rt.res.baseUrl],\n [\"Config\", configPath()],\n ]);\n if (detail) process.stdout.write(`\\n${detail}\\n`);\n\n // Exit non-zero only when the credentials are KNOWN to be unusable, so\n // scripts and CI can gate on `krova auth status` (matches\n // `gh auth status`). An unreachable or too-old API says nothing about\n // the key, so those stay 0 rather than failing a build over a blip.\n if (!hasKey || probe.state === \"rejected\") process.exitCode = 1;\n });\n\n auth\n .command(\"logout\")\n .description(\"remove a saved context and its API key from this machine\")\n .option(\"--context <name>\", \"the context to remove (default: the current one)\")\n .action((opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const cfg = load();\n // The global --context may be consumed before this command sees it, so read both.\n const name =\n ((opts.context as string | undefined) ?? rt.flags.context ?? \"\").trim() ||\n rt.res.contextName;\n if (!name) throw new Error(`not logged in: no saved context in ${configPath()}`);\n if (!find(cfg, name)) throw new Error(`no context named \"${name}\"`);\n const wasCurrent = cfg.currentContext === name;\n removeContext(cfg, name); // saves the config, then deletes the keychain item\n const current = cfg.currentContext || null;\n if (rt.json) return printJSON({ context: name, result: \"logged_out\", current });\n process.stdout.write(\n `Logged out of ${name}. The API key still works until you revoke it in the dashboard (Settings > API keys).\\n`,\n );\n if (wasCurrent && current) process.stdout.write(`Now using ${current}.\\n`);\n });\n\n auth\n .command(\"migrate-keychain\")\n .description(\"move API keys saved in the config file into the OS keychain\")\n .action((_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const cfg = load();\n let result: ReturnType<typeof migrateKeysToKeychain>;\n try {\n result = migrateKeysToKeychain(cfg);\n } catch (e) {\n if (e instanceof KeychainUnavailableError) {\n throw new Error(\n e.optOut\n ? `${e.message}; unset KROVA_NO_KEYCHAIN to move keys into the keychain`\n : `no OS keychain available (${e.message}); keys stay in ${configPath()}`,\n );\n }\n throw e;\n }\n const failed = result.entries.filter((x) => x.result === \"failed\");\n if (failed.length > 0) process.exitCode = 1;\n if (rt.json) return printJSON({ keychain: result.backend, results: result.entries });\n if (result.entries.length === 0) process.stdout.write(\"No contexts to migrate.\\n\");\n for (const x of result.entries) {\n const tail = x.detail ? ` (${x.detail})` : \"\";\n process.stdout.write(\n `${x.result === \"migrated\" ? \"Moved\" : x.result === \"failed\" ? \"FAILED\" : \"Skipped\"} ${x.context}${x.result === \"migrated\" ? ` to the ${result.backend}` : tail}\\n`,\n );\n if (x.result === \"failed\") process.stderr.write(` ${x.detail}\\n`);\n }\n });\n\n return auth;\n}\n","import type { Backup, BackupShare, KrovaClient } from \"@krovacloud/sdk\";\nimport { Command } from \"commander\";\n\nimport { printJSON, printKeyValue, printTable } from \"../lib/output.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\n\n/**\n * Resolve a backup name-or-id to an id, the same rule as `resolveCube`: an\n * exact id wins; else exactly one exact name match; else a clear error.\n */\nexport async function resolveBackup(\n client: KrovaClient,\n spaceId: string,\n ref: string\n): Promise<string> {\n const backups = await client.backups.list(spaceId);\n if (backups.some((b) => b.id === ref)) return ref;\n const byName = backups.filter((b) => b.name === ref);\n if (byName.length === 1) return byName[0]!.id;\n if (byName.length === 0) {\n throw new Error(\n `no backup named or with ID \"${ref}\" in this space (see \\`krova backups list\\`)`\n );\n }\n const ids = byName.map((b) => b.id).join(\", \");\n throw new Error(\n `backup name \"${ref}\" is ambiguous: it matches ${byName.length} backups (${ids}) — use the backup ID instead`\n );\n}\n\n/** One row of `krova backups shares`: which way it goes, and the other space. */\nexport function shareRows(list: { incoming: BackupShare[]; outgoing: BackupShare[] }): string[][] {\n const row = (direction: string, s: BackupShare) => [\n s.id,\n direction,\n s.backupName,\n s.counterpartySpaceName,\n s.status,\n s.expiresAt,\n ];\n return [\n ...list.incoming.map((s) => row(\"incoming\", s)),\n ...list.outgoing.map((s) => row(\"outgoing\", s)),\n ];\n}\n\nfunction backupPairs(b: Backup): Array<[string, string]> {\n return [\n [\"ID\", b.id],\n [\"Name\", b.name],\n [\"Status\", b.status],\n [\"From Cube\", `${b.originalCubeName} (${b.originalCubeId})`],\n [\"Size (bytes)\", b.sizeBytes == null ? \"\" : String(b.sizeBytes)],\n [\"Disk (GB)\", String(b.diskSizeGb)],\n [\"Shared from\", b.sharedFromBackupId ?? \"\"],\n [\"Created\", b.createdAt],\n ];\n}\n\n/**\n * `krova backups` — list, download and share backups, and answer shares.\n *\n * Every subcommand needs the Backups permissions on the API key's member:\n * View Backups to read, Manage Backups for everything else.\n */\nexport function backupsCommand(): Command {\n const cmd = new Command(\"backups\").description(\n \"list, download and share backups, and answer backup shares\"\n );\n\n cmd\n .command(\"list\")\n .description(\"list this space's backups, newest first\")\n .action(async (_opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const backups = await client.backups.list(space);\n if (rt.json) return printJSON(backups);\n printTable(\n [\"ID\", \"NAME\", \"STATUS\", \"SIZE (BYTES)\", \"SHARED FROM\", \"CREATED\"],\n backups.map((b) => [\n b.id,\n b.name,\n b.status,\n b.sizeBytes == null ? \"\" : String(b.sizeBytes),\n b.sharedFromBackupId ?? \"\",\n b.createdAt,\n ]),\n );\n });\n\n cmd\n .command(\"get\")\n .argument(\"<backup>\", \"backup name or ID\")\n .description(\"show one backup\")\n .action(async (ref: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const backup = await client.backups.get(space, await resolveBackup(client, space, ref));\n if (rt.json) return printJSON(backup);\n printKeyValue(backupPairs(backup));\n });\n\n cmd\n .command(\"download\")\n .argument(\"<backup>\", \"backup name or ID\")\n .description(\"print a link to download the backup's .cube archive (valid for 15 minutes)\")\n .action(async (ref: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const link = await client.backups.download(space, await resolveBackup(client, space, ref));\n if (rt.json) return printJSON(link);\n if (!link) throw new Error(\"the API returned no download link\");\n printKeyValue([\n [\"URL\", link.url ?? \"\"],\n [\"File\", link.filename ?? \"\"],\n [\"Size (bytes)\", link.sizeBytes == null ? \"\" : String(link.sizeBytes)],\n [\"Expires\", link.expiresAt ?? \"\"],\n ]);\n // The link needs no further authentication, and the archive is the whole disk.\n process.stderr.write(\n \"Anyone with this link can download the archive until it expires. Do not paste it anywhere shared.\\n\"\n );\n });\n\n cmd\n .command(\"share\")\n .argument(\"<backup>\", \"backup name or ID\")\n .argument(\"<destination-space-id>\", \"the space to offer a copy to\")\n .option(\"--idempotency-key <key>\", \"replaying the same key returns the original request\")\n .description(\n \"offer a copy of a backup to another space; it pays for its copy once it accepts (48 hours)\"\n )\n .action(async (ref: string, destinationSpaceId: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const share = await client.backups.share(\n space,\n await resolveBackup(client, space, ref),\n { destinationSpaceId },\n opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined\n );\n if (rt.json) return printJSON(share);\n process.stdout.write(\n `Share ${share.id} requested. ${share.counterpartySpaceName} has until ${share.expiresAt} to accept.\\n`\n );\n });\n\n cmd\n .command(\"shares\")\n .description(\"list pending backup shares into and out of this space\")\n .action(async (_opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const list = await client.backupShares.list(space);\n if (rt.json) return printJSON(list);\n printTable([\"ID\", \"DIRECTION\", \"BACKUP\", \"OTHER SPACE\", \"STATUS\", \"EXPIRES\"], shareRows(list));\n });\n\n cmd\n .command(\"accept\")\n .argument(\"<share-id>\", \"an incoming share (see `krova backups shares`)\")\n .description(\"accept a backup shared with this space; its storage is billed to this space\")\n .action(async (shareId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const accepted = await client.backupShares.accept(space, shareId);\n if (rt.json) return printJSON(accepted);\n process.stdout.write(\n `Accepted. The copy is backup ${accepted.backup.id} (\"${accepted.backup.name}\").\\n`\n );\n });\n\n cmd\n .command(\"decline\")\n .argument(\"<share-id>\", \"an incoming share (see `krova backups shares`)\")\n .description(\"decline a backup shared with this space\")\n .action(async (shareId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const share = await client.backupShares.decline(space, shareId);\n if (rt.json) return printJSON(share);\n process.stdout.write(`Declined share ${share.id}. Nothing was copied.\\n`);\n });\n\n cmd\n .command(\"cancel\")\n .argument(\"<share-id>\", \"an outgoing share (see `krova backups shares`)\")\n .description(\"withdraw a pending share this space offered\")\n .action(async (shareId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const share = await client.backupShares.cancel(space, shareId);\n if (rt.json) return printJSON(share);\n process.stdout.write(`Canceled share ${share.id}.\\n`);\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\n\nimport { printJSON, printKeyValue, printTable } from \"../lib/output.js\";\nimport { getRuntime, makeClient } from \"../lib/runtime.js\";\n\nfunction fmtVal(v: unknown): string {\n if (v === null || v === undefined) return \"\";\n if (typeof v === \"object\") return JSON.stringify(v);\n return String(v);\n}\n\n/** Flatten a top-level object field one level deep into `key.subkey` rows, so\n * nested objects (e.g. pricing's `rates`) render as readable key/value pairs\n * instead of a JSON blob. Exported for testing. */\nexport function flattenRows(entries: [string, unknown][]): [string, string][] {\n const rows: [string, string][] = [];\n for (const [k, v] of entries) {\n if (v && typeof v === \"object\" && !Array.isArray(v)) {\n for (const [sk, sv] of Object.entries(v as Record<string, unknown>)) {\n rows.push([`${k}.${sk}`, fmtVal(sv)]);\n }\n } else {\n rows.push([k, fmtVal(v)]);\n }\n }\n return rows;\n}\n\n/**\n * Render a catalog payload as text. If the payload has an array field, print any\n * scalar/object fields first (as key/value) and then the array as a table —\n * otherwise the non-array fields are silently dropped. This matters for\n * `pricing`, whose per-resource `rates` (the actual hourly prices), `currency`,\n * and `note` sit alongside the `tiers` array. `regions`/`images` have only the\n * array, so their output is unchanged.\n */\nfunction renderCatalog(obj: Record<string, unknown>): void {\n const arrKey = Object.keys(obj).find((k) => Array.isArray(obj[k]));\n if (!arrKey) {\n printKeyValue(flattenRows(Object.entries(obj)));\n return;\n }\n const rest = flattenRows(Object.entries(obj).filter(([k]) => k !== arrKey));\n if (rest.length) printKeyValue(rest);\n const arr = (obj[arrKey] as Record<string, unknown>[]) ?? [];\n const cols = [...new Set(arr.flatMap((o) => Object.keys(o)))];\n printTable(\n cols.map((c) => c.toUpperCase()),\n arr.map((o) => cols.map((c) => fmtVal(o[c])))\n );\n}\n\nfunction catalogCmd(\n name: string,\n desc: string,\n fetch: (c: ReturnType<typeof makeClient>) => Promise<Record<string, unknown>>\n): Command {\n return new Command(name)\n .description(desc)\n .action(async (_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const data = await fetch(client);\n if (rt.json) return printJSON(data);\n renderCatalog(data);\n });\n}\n\nexport function regionsCommand(): Command {\n return catalogCmd(\"regions\", \"list regions with available capacity\", (c) =>\n c.catalog.regions() as Promise<Record<string, unknown>>\n );\n}\nexport function imagesCommand(): Command {\n return catalogCmd(\"images\", \"list available OS images\", (c) =>\n c.catalog.images() as Promise<Record<string, unknown>>\n );\n}\nexport function pricingCommand(): Command {\n return catalogCmd(\"pricing\", \"show per-resource hourly pricing\", (c) =>\n c.catalog.pricing() as Promise<Record<string, unknown>>\n );\n}\n","import type { Command } from \"commander\";\n\nimport { FLAG_VALUE_CHOICES } from \"./output-format.js\";\n\nexport const COMPLETION_SHELLS = [\"bash\", \"zsh\", \"fish\"] as const;\nexport type CompletionShell = (typeof COMPLETION_SHELLS)[number];\n\ninterface OptionNode {\n long?: string;\n short?: string;\n description: string;\n takesValue: boolean;\n}\n\ninterface CommandNode {\n /** Canonical names from the root's first subcommand down; empty for the root. */\n path: string[];\n aliases: string[];\n description: string;\n options: OptionNode[];\n commands: CommandNode[];\n}\n\nconst oneLine = (s: string): string => s.split(\"\\n\")[0]!.replace(/\\s+/g, \" \").trim();\n\n/** Walk the commander tree (visible commands and options only). */\nexport function walkCommands(cmd: Command, path: string[] = []): CommandNode {\n const help = cmd.createHelp();\n return {\n path,\n aliases: cmd.aliases(),\n description: oneLine(cmd.description()),\n options: help.visibleOptions(cmd).map((o) => ({\n long: o.long,\n short: o.short,\n description: oneLine(o.description),\n takesValue: o.required || o.optional,\n })),\n commands: help.visibleCommands(cmd).map((c) => walkCommands(c, [...path, c.name()])),\n };\n}\n\n/** Shell single-quote: safe inside bash, zsh and fish single quotes. */\nconst sq = (s: string): string => `'${s.replace(/'/g, \"'\\\\''\")}'`;\nconst fishSq = (s: string): string => `'${s.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n\nconst flat = (node: CommandNode): CommandNode[] => [node, ...node.commands.flatMap(flat)];\nconst key = (path: string[]): string => path.join(\" \");\nconst optionWords = (n: CommandNode): string[] =>\n n.options.flatMap((o) => [o.long, o.short].filter((x): x is string => Boolean(x)));\nconst commandWords = (n: CommandNode): string[] => n.commands.flatMap((c) => [c.path.at(-1)!, ...c.aliases]);\n\n/** Every (parent path, typed word) -> child path transition, aliases included. */\nfunction transitions(root: CommandNode): Array<{ from: string; word: string; to: string }> {\n return flat(root).flatMap((parent) =>\n parent.commands.flatMap((c) =>\n [c.path.at(-1)!, ...c.aliases].map((word) => ({\n from: key(parent.path),\n word,\n to: key(c.path),\n }))\n )\n );\n}\n\ntype Choices = Record<string, readonly string[]>;\n\n/** Every flag in the tree that takes a value but has no fixed choices (paths, names, numbers). */\nfunction freeValueFlags(root: CommandNode, choices: Choices): string[] {\n const out = new Set<string>();\n for (const n of flat(root)) {\n for (const o of n.options) {\n if (!o.takesValue) continue;\n for (const f of [o.long, o.short]) if (f && !choices[f]) out.add(f);\n }\n }\n return [...out];\n}\n\nfunction bash(root: CommandNode, name: string, choices: Choices): string {\n const fn = `_${name}_complete`;\n const lines: string[] = [\n `# bash completion for ${name}, generated by \\`${name} completion bash\\``,\n `${fn}() {`,\n ` local cur prev cpath=\"\" w next i`,\n ` cur=\"\\${COMP_WORDS[COMP_CWORD]}\"`,\n ` prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"`,\n ` for ((i=1; i<COMP_CWORD; i++)); do`,\n ` w=\"\\${COMP_WORDS[i]}\"`,\n ` next=\"\"`,\n ` case \"$cpath/$w\" in`,\n ...transitions(root).map((t) => ` ${sq(`${t.from}/${t.word}`)}) next=${sq(t.to)};;`),\n ` esac`,\n ` [ -n \"$next\" ] && cpath=\"$next\"`,\n ` done`,\n ` case \"$prev\" in`,\n ...Object.entries(choices).map(\n ([flag, values]) => ` ${sq(flag)}) COMPREPLY=( $(compgen -W ${sq(values.join(\" \"))} -- \"$cur\") ); return;;`\n ),\n ...freeValueFlags(root, choices).map((f) => ` ${sq(f)}) COMPREPLY=(); return;;`),\n ` esac`,\n ` local cmds=\"\" opts=\"\"`,\n ` case \"$cpath\" in`,\n ...flat(root).map(\n (n) =>\n ` ${sq(key(n.path))}) cmds=${sq(commandWords(n).join(\" \"))}; opts=${sq(optionWords(n).join(\" \"))};;`\n ),\n ` esac`,\n ` if [[ \"$cur\" == -* ]]; then`,\n ` COMPREPLY=( $(compgen -W \"$opts\" -- \"$cur\") )`,\n ` else`,\n ` COMPREPLY=( $(compgen -W \"$cmds\" -- \"$cur\") )`,\n ` fi`,\n `}`,\n `complete -o default -F ${fn} ${name}`,\n ];\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction zsh(root: CommandNode, name: string, choices: Choices): string {\n const fn = `_${name}`;\n const item = (word: string, desc: string): string =>\n sq(`${word.replace(/:/g, \"\\\\:\")}${desc ? `:${desc}` : \"\"}`);\n const lines: string[] = [\n `#compdef ${name}`,\n `# zsh completion for ${name}, generated by \\`${name} completion zsh\\``,\n `${fn}() {`,\n ` local cpath=\"\" w next i`,\n ` local -a cmds opts`,\n ` for (( i=2; i<CURRENT; i++ )); do`,\n ` w=\"\\${words[i]}\"`,\n ` next=\"\"`,\n ` case \"$cpath/$w\" in`,\n ...transitions(root).map((t) => ` ${sq(`${t.from}/${t.word}`)}) next=${sq(t.to)};;`),\n ` esac`,\n ` [[ -n \"$next\" ]] && cpath=\"$next\"`,\n ` done`,\n ` case \"\\${words[CURRENT-1]}\" in`,\n ...Object.entries(choices).map(\n ([flag, values]) => ` ${sq(flag)}) compadd -- ${values.map(sq).join(\" \")}; return;;`\n ),\n ...freeValueFlags(root, choices).map((f) => ` ${sq(f)}) _files; return;;`),\n ` esac`,\n ` case \"$cpath\" in`,\n ...flat(root).flatMap((n) => {\n const cmdItems = n.commands.flatMap((c) =>\n [c.path.at(-1)!, ...c.aliases].map((w) => item(w, c.description))\n );\n const optItems = n.options.flatMap((o) =>\n [o.long, o.short].filter((x): x is string => Boolean(x)).map((w) => item(w, o.description))\n );\n return [` ${sq(key(n.path))})`, ` cmds=(${cmdItems.join(\" \")})`, ` opts=(${optItems.join(\" \")});;`];\n }),\n ` esac`,\n ` if [[ \"$PREFIX\" == -* ]]; then`,\n ` _describe -t options 'option' opts`,\n ` else`,\n ` _describe -t commands 'command' cmds`,\n ` (( \\${#cmds} )) || _files`,\n ` fi`,\n `}`,\n `if [ \"$funcstack[1]\" = \"${fn}\" ]; then`,\n ` ${fn} \"$@\"`,\n `else`,\n ` compdef ${fn} ${name}`,\n `fi`,\n ];\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction fish(root: CommandNode, name: string, choices: Choices): string {\n const fn = `__${name}_path`;\n const rootKey = \"root\";\n const k = (path: string[]): string => (path.length ? key(path) : rootKey);\n const lines: string[] = [\n `# fish completion for ${name}, generated by \\`${name} completion fish\\``,\n `function ${fn}`,\n ` set -l cpath ${rootKey}`,\n ` set -l tokens (commandline -opc)`,\n ` set -e tokens[1]`,\n ` for w in $tokens`,\n ` switch \"$cpath/$w\"`,\n ...transitions(root).flatMap((t) => [\n ` case ${fishSq(`${t.from || rootKey}/${t.word}`)}`,\n ` set cpath ${fishSq(t.to)}`,\n ]),\n ` end`,\n ` end`,\n ` echo $cpath`,\n `end`,\n ];\n for (const n of flat(root)) {\n const cond = `-n ${fishSq(`test (${fn}) = ${fishSq(k(n.path))}`)}`;\n // Where a command takes subcommands, offer only those. A command that takes\n // arguments keeps fish's file completion, as do options that take a value (-r).\n if (n.commands.length) lines.push(`complete -c ${name} ${cond} -f`);\n for (const c of n.commands) {\n for (const w of [c.path.at(-1)!, ...c.aliases]) {\n lines.push(`complete -c ${name} ${cond} -a ${fishSq(w)} -d ${fishSq(c.description)}`);\n }\n }\n for (const o of n.options) {\n const parts = [`complete -c ${name} ${cond}`];\n if (o.short) parts.push(`-s ${o.short.replace(/^-/, \"\")}`);\n if (o.long) parts.push(`-l ${o.long.replace(/^--/, \"\")}`);\n const values = [o.long, o.short].map((f) => (f ? choices[f] : undefined)).find(Boolean);\n if (values) parts.push(`-x -a ${fishSq(values.join(\" \"))}`);\n else if (o.takesValue) parts.push(\"-r\");\n parts.push(`-d ${fishSq(o.description)}`);\n lines.push(parts.join(\" \"));\n }\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/** Generate the completion script for `shell` from the live command tree under `root`. */\nexport function generateCompletion(\n shell: CompletionShell,\n root: Command,\n choices: Choices = FLAG_VALUE_CHOICES\n): string {\n const tree = walkCommands(root);\n const name = root.name();\n if (shell === \"bash\") return bash(tree, name, choices);\n if (shell === \"zsh\") return zsh(tree, name, choices);\n return fish(tree, name, choices);\n}\n\nexport const COMPLETION_INSTALL_HELP = `\nInstall (restart your shell afterward):\n\n bash mkdir -p ~/.local/share/bash-completion/completions\n krova completion bash > ~/.local/share/bash-completion/completions/krova\n (or add 'source <(krova completion bash)' to ~/.bashrc)\n zsh krova completion zsh > \"\\${fpath[1]}/_krova\"\n (needs 'autoload -U compinit && compinit' in ~/.zshrc; or add\n 'source <(krova completion zsh)' to ~/.zshrc after compinit)\n fish krova completion fish > ~/.config/fish/completions/krova.fish\n\nThe script is generated from the commands in your installed version, so\nre-run it after you upgrade the CLI.\n`;\n","import { Argument, Command } from \"commander\";\n\nimport {\n COMPLETION_INSTALL_HELP,\n COMPLETION_SHELLS,\n type CompletionShell,\n generateCompletion,\n} from \"../lib/completion.js\";\n\nexport function completionCommand(): Command {\n return new Command(\"completion\")\n .description(\"print a shell completion script (bash, zsh or fish)\")\n .addArgument(new Argument(\"<shell>\", \"target shell\").choices(COMPLETION_SHELLS))\n .addHelpText(\"after\", COMPLETION_INSTALL_HELP)\n .action((shell: CompletionShell, _opts, cmd: Command) => {\n let root = cmd;\n while (root.parent) root = root.parent;\n process.stdout.write(generateCompletion(shell, root));\n });\n}\n","import { Command } from \"commander\";\n\nimport { contextKey, displayKey, load, removeContext, renameContext, save, storageOf } from \"../lib/config.js\";\nimport { printJSON, printTable } from \"../lib/output.js\";\nimport { parseOutputFormat } from \"../lib/output-format.js\";\n\nexport function contextCommand(): Command {\n const ctx = new Command(\"context\")\n .aliases([\"ctx\", \"contexts\"])\n .description(\"manage named credential contexts (like kubectl/aws profiles)\");\n\n ctx\n .command(\"list\")\n .aliases([\"ls\"])\n .description(\"list all contexts\")\n .option(\"--show-secrets\", \"print full API keys instead of masked ones (JSON output only; the table has no key column)\")\n .action((opts, cmd: Command) => {\n // Not getRuntime: it resolves the active context, which would read its key from the keychain.\n const g = cmd.optsWithGlobals() as Record<string, unknown>;\n const json = Boolean(g.json) || parseOutputFormat(g.output) === \"json\";\n const cfg = load();\n if (json) {\n return printJSON({\n currentContext: cfg.currentContext ?? \"\",\n contexts: (cfg.contexts ?? []).map((c) => ({\n name: c.name,\n // A keychain key is only read (and the keychain only prompted) when the caller asks to see it.\n apiKey: opts.showSecrets || storageOf(c) === \"file\" ? displayKey(contextKey(c), Boolean(opts.showSecrets)) : \"****\",\n keyStorage: storageOf(c),\n spaceId: c.spaceId ?? \"\",\n spaceName: c.spaceName ?? \"\",\n baseUrl: c.baseUrl ?? \"\",\n })),\n });\n }\n printTable(\n [\"CURRENT\", \"NAME\", \"SPACE\", \"SPACE ID\", \"BASE URL\"],\n (cfg.contexts ?? []).map((c) => [\n c.name === cfg.currentContext ? \"*\" : \"\",\n c.name,\n c.spaceName ?? \"\",\n c.spaceId ?? \"\",\n c.baseUrl ?? \"\",\n ])\n );\n });\n\n ctx\n .command(\"current\")\n .description(\"print the current context name\")\n .action(() => {\n const cfg = load();\n if (!cfg.currentContext) throw new Error(\"no current context set\");\n process.stdout.write(`${cfg.currentContext}\\n`);\n });\n\n ctx\n .command(\"use\")\n .argument(\"<name>\", \"context name\")\n .description(\"switch the current context\")\n .action((name: string) => {\n const cfg = load();\n if (!(cfg.contexts ?? []).some((c) => c.name === name)) {\n throw new Error(`no context named \"${name}\"`);\n }\n cfg.currentContext = name;\n save(cfg);\n process.stdout.write(`Switched to context ${name}\\n`);\n });\n\n ctx\n .command(\"rename\")\n .argument(\"<old>\", \"current name\")\n .argument(\"<new>\", \"new name\")\n .description(\"rename a context\")\n .action((oldName: string, newName: string) => {\n const cfg = load();\n if (!newName.trim()) throw new Error(\"new name must not be empty\");\n // Moves the keychain item too, so the key follows the context name.\n renameContext(cfg, oldName, newName); // also saves the config, then deletes the old item\n process.stdout.write(`Renamed ${oldName} → ${newName}\\n`);\n });\n\n ctx\n .command(\"delete\")\n .aliases([\"rm\"])\n .argument(\"<name>\", \"context name\")\n .description(\"delete a context\")\n .action((name: string) => {\n const cfg = load();\n // Saves the config first, then deletes the keychain item.\n if (!removeContext(cfg, name)) throw new Error(`no context named \"${name}\"`);\n process.stdout.write(`Deleted context ${name}\\n`);\n });\n\n return ctx;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport * as readline from \"node:readline/promises\";\n\n/**\n * The interactive half of `krova cubes create`.\n *\n * Everything the prompt flow touches from the outside (the terminal, the\n * catalog, the key files) comes in through an interface, so tests drive it\n * with scripted answers and never need a TTY, a network or a real home dir.\n */\n\n/** Defaults for the resource flags. `cubes create` registers them on its options too. */\nexport const DEFAULT_RESOURCES = { vcpu: \"1\", ram: \"1\", disk: \"10\" } as const;\n\n/** One question-and-answer channel. */\nexport interface PromptIO {\n /** Show `question` and resolve with the typed line. Rejects with PromptAbortError when input ends. */\n ask(question: string): Promise<string>;\n /** Text for the person at the terminal (stdout). */\n write(text: string): void;\n /** A warning (stderr). */\n warn(text: string): void;\n close(): void;\n}\n\n/** Input ended (Ctrl+C, Ctrl+D, closed pipe) before the questions were answered. */\nexport class PromptAbortError extends Error {\n constructor() {\n super(\"input closed\");\n this.name = \"PromptAbortError\";\n }\n}\n\n/** Prompts run only on a real terminal, and never when the caller asked for JSON. */\nexport function isInteractive(opts: {\n json: boolean;\n stdin?: { isTTY?: boolean };\n stdout?: { isTTY?: boolean };\n}): boolean {\n if (opts.json) return false;\n const stdin = opts.stdin ?? process.stdin;\n const stdout = opts.stdout ?? process.stdout;\n return Boolean(stdin.isTTY && stdout.isTTY);\n}\n\n/** The real terminal, via node:readline/promises. */\nexport function createReadlineIO(): PromptIO {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const closed = new Promise<never>((_, reject) => {\n rl.once(\"close\", () => reject(new PromptAbortError()));\n });\n // The rejection is observed through `ask`; this keeps it from surfacing unhandled.\n closed.catch(() => undefined);\n rl.on(\"SIGINT\", () => rl.close());\n return {\n ask: (question) => Promise.race([rl.question(question), closed]),\n write: (text) => void process.stdout.write(text),\n warn: (text) => void process.stderr.write(text),\n close: () => rl.close(),\n };\n}\n\nexport interface CatalogImage {\n id: string;\n name: string;\n version: string;\n}\n\nexport interface CatalogRegion {\n slug: string;\n name: string;\n}\n\n/** The slice of `client.catalog` the prompts use. */\nexport interface CatalogSource {\n images(): Promise<{ images: CatalogImage[] }>;\n regions(): Promise<{ regions: CatalogRegion[] }>;\n}\n\n/** Where public keys are read from. Only `.pub` paths ever reach `readFile`. */\nexport interface KeyFiles {\n home: string;\n readFile(path: string): Promise<string>;\n}\n\nexport function defaultKeyFiles(): KeyFiles {\n return { home: homedir(), readFile: (path) => readFile(path, \"utf8\") };\n}\n\n/** Key files offered, in order. Public halves only; a private key is never opened. */\nexport const KEY_CANDIDATE_FILES = [\"id_ed25519.pub\", \"id_rsa.pub\"] as const;\n\n/** What the person typed on the command line; `undefined` means not given. */\nexport interface CreateGiven {\n name?: string;\n image?: string;\n sshKey?: string;\n region?: string;\n vcpu?: string;\n ram?: string;\n disk?: string;\n}\n\nexport interface CreateAnswers {\n name: string;\n image: string;\n sshKey: string;\n region?: string;\n vcpu: string;\n ram: string;\n disk: string;\n}\n\nexport interface PromptDeps {\n io: PromptIO;\n catalog: CatalogSource;\n keyFiles: KeyFiles;\n}\n\n// Mirrors the API's own checks (validateName and isValidSshPublicKey in krova-cloud).\nconst KEY_PREFIXES = [\n \"ssh-rsa\",\n \"ssh-ed25519\",\n \"ecdsa-sha2-nistp256\",\n \"ecdsa-sha2-nistp384\",\n \"ecdsa-sha2-nistp521\",\n \"ssh-dss\",\n \"sk-ssh-ed25519@openssh.com\",\n \"sk-ecdsa-sha2-nistp256@openssh.com\",\n];\n\n/** A cube name: 1 to 64 characters after trimming, no control characters. Returns the trimmed name or null. */\nexport function validCubeName(raw: string): string | null {\n const name = raw.trim();\n if (name.length === 0 || name.length > 64) return null;\n // biome-ignore lint/suspicious/noControlCharactersInRegex: detecting control characters is the point\n if (/[\\x00-\\x1F\\x7F]/.test(name)) return null;\n return name;\n}\n\nexport function validSshPublicKey(raw: string): boolean {\n const type = raw.trim().split(/\\s+/)[0] ?? \"\";\n return KEY_PREFIXES.some((prefix) => type.startsWith(prefix));\n}\n\nfunction positiveInt(raw: string): number | null {\n const n = Number(raw.trim());\n return Number.isInteger(n) && n > 0 ? n : null;\n}\n\n/** Read one public key file. Refuses anything that is not a `.pub` path. */\nasync function readPublicKey(keyFiles: KeyFiles, path: string): Promise<string | null> {\n if (!path.endsWith(\".pub\")) throw new Error(`refusing to read a non-public key file: ${path}`);\n try {\n const key = (await keyFiles.readFile(path)).trim();\n return validSshPublicKey(key) ? key : null;\n } catch {\n return null;\n }\n}\n\nexport interface KeyCandidate {\n /** Shown to the person, with `~` for the home directory. */\n label: string;\n key: string;\n}\n\nexport async function findKeyCandidates(keyFiles: KeyFiles): Promise<KeyCandidate[]> {\n const found: KeyCandidate[] = [];\n for (const file of KEY_CANDIDATE_FILES) {\n const key = await readPublicKey(keyFiles, join(keyFiles.home, \".ssh\", file));\n if (key) found.push({ label: `~/.ssh/${file}`, key });\n }\n return found;\n}\n\n/** \"ssh-ed25519 AAAA you@laptop\" -> \"ssh-ed25519 you@laptop\" (type and comment, never the key body). */\nfunction keyBlurb(key: string): string {\n const [type, , ...comment] = key.trim().split(/\\s+/);\n return [type, comment.join(\" \")].filter(Boolean).join(\" \");\n}\n\nfunction errText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nasync function askName(io: PromptIO): Promise<string> {\n for (;;) {\n const name = validCubeName(await io.ask(\"Name: \"));\n if (name) return name;\n io.write(\"A name is 1 to 64 characters with no control characters.\\n\");\n }\n}\n\nasync function askImage(io: PromptIO, catalog: CatalogSource): Promise<string> {\n let images: CatalogImage[] = [];\n try {\n images = (await catalog.images()).images;\n } catch (err) {\n io.warn(`Could not load the image list (${errText(err)}).\\n`);\n }\n if (images.length === 0) {\n for (;;) {\n const slug = (await io.ask(\"Image slug (see `krova images`): \")).trim();\n if (slug) return slug;\n }\n }\n io.write(\"Images:\\n\");\n images.forEach((img, i) => {\n io.write(` ${i + 1}) ${img.id} (${[img.name, img.version].filter(Boolean).join(\" \")})\\n`);\n });\n for (;;) {\n const answer = (await io.ask(\"Image (number or slug): \")).trim();\n const byNumber = /^\\d+$/.test(answer) ? images[Number(answer) - 1] : undefined;\n if (byNumber) return byNumber.id;\n const byId = images.find((img) => img.id === answer);\n if (byId) return byId.id;\n io.write(`Pick a number from 1 to ${images.length}, or one of the slugs above.\\n`);\n }\n}\n\n/** `undefined` means \"let Krova choose\". */\nasync function askRegion(io: PromptIO, catalog: CatalogSource): Promise<string | undefined> {\n let regions: CatalogRegion[] = [];\n try {\n regions = (await catalog.regions()).regions;\n } catch (err) {\n io.warn(`Could not load the region list (${errText(err)}).\\n`);\n }\n if (regions.length === 0) return undefined;\n io.write(\"Regions:\\n\");\n regions.forEach((r, i) => {\n io.write(` ${i + 1}) ${r.slug} (${r.name})\\n`);\n });\n for (;;) {\n const answer = (await io.ask(\"Region (number or slug, Enter to let Krova choose): \")).trim();\n if (!answer) return undefined;\n const byNumber = /^\\d+$/.test(answer) ? regions[Number(answer) - 1] : undefined;\n if (byNumber) return byNumber.slug;\n const bySlug = regions.find((r) => r.slug === answer);\n if (bySlug) return bySlug.slug;\n io.write(`Pick a number from 1 to ${regions.length}, a slug above, or press Enter.\\n`);\n }\n}\n\nasync function askSize(io: PromptIO, label: string, fallback: string): Promise<string> {\n for (;;) {\n const answer = (await io.ask(`${label} [${fallback}]: `)).trim();\n const n = positiveInt(answer === \"\" ? fallback : answer);\n if (n !== null) return String(n);\n io.write(`${label} must be a positive whole number.\\n`);\n }\n}\n\nasync function askSshKey(io: PromptIO, keyFiles: KeyFiles): Promise<string> {\n const candidates = await findKeyCandidates(keyFiles);\n if (candidates.length > 0) {\n io.write(\"SSH public keys found:\\n\");\n candidates.forEach((c, i) => {\n io.write(` ${i + 1}) ${c.label} (${keyBlurb(c.key)})\\n`);\n });\n }\n const prompt =\n candidates.length > 0\n ? \"SSH key (number, or paste a public key) [1]: \"\n : \"SSH public key (paste it, e.g. ssh-ed25519 AAAA...): \";\n for (;;) {\n const answer = (await io.ask(prompt)).trim();\n if (candidates.length > 0 && answer === \"\") return (candidates[0] as KeyCandidate).key;\n const picked = /^\\d+$/.test(answer) ? candidates[Number(answer) - 1] : undefined;\n if (picked) return picked.key;\n if (validSshPublicKey(answer)) return answer;\n io.write(\"That is not a public key. It starts with ssh-ed25519, ssh-rsa, ecdsa-sha2-... or sk-...\\n\");\n }\n}\n\n/**\n * Ask for every value not already given on the command line. Questions come in\n * the order name, image, region, size, SSH key; a value given as a flag is\n * never asked again.\n */\nexport async function promptCreate(given: CreateGiven, deps: PromptDeps): Promise<CreateAnswers> {\n const { io, catalog, keyFiles } = deps;\n const name = given.name ?? (await askName(io));\n const image = given.image ?? (await askImage(io, catalog));\n const region = given.region ?? (await askRegion(io, catalog));\n const vcpu = given.vcpu ?? (await askSize(io, \"vCPUs\", DEFAULT_RESOURCES.vcpu));\n const ram = given.ram ?? (await askSize(io, \"RAM in GB\", DEFAULT_RESOURCES.ram));\n const disk = given.disk ?? (await askSize(io, \"Disk in GB\", DEFAULT_RESOURCES.disk));\n const sshKey = given.sshKey ?? (await askSshKey(io, keyFiles));\n return { name, image, sshKey, ...(region ? { region } : {}), vcpu, ram, disk };\n}\n\n/** One line that says what is about to be created. */\nexport function summarize(\n a: Pick<CreateAnswers, \"name\" | \"image\" | \"region\" | \"vcpu\" | \"ram\" | \"disk\">,\n): string {\n const parts = [\n a.image,\n a.region ? `region ${a.region}` : \"region chosen by Krova\",\n `${a.vcpu} vCPU`,\n `${a.ram} GB RAM`,\n `${a.disk} GB disk`,\n ];\n return `Create cube \"${a.name}\" (${parts.join(\", \")})`;\n}\n\n/** `[Y/n]`: Enter or y/yes is yes, n/no is no, anything else asks again. */\nexport async function confirmCreate(io: PromptIO, summary: string): Promise<boolean> {\n for (;;) {\n const answer = (await io.ask(`${summary}? [Y/n] `)).trim().toLowerCase();\n if (answer === \"\" || answer === \"y\" || answer === \"yes\") return true;\n if (answer === \"n\" || answer === \"no\") return false;\n }\n}\n","import type { KrovaClient } from \"@krovacloud/sdk\";\n\n/** Resolve a cube name-or-id to an id (parity with the Go resolveCube):\n * exact id wins; else exactly one exact name match; else a clear error. */\nexport async function resolveCube(\n client: KrovaClient,\n spaceId: string,\n ref: string\n): Promise<string> {\n const { cubes } = await client.cubes.list(spaceId);\n if (cubes.some((c) => c.id === ref)) return ref;\n const byName = cubes.filter((c) => c.name === ref);\n if (byName.length === 1) return byName[0]!.id;\n if (byName.length === 0) {\n throw new Error(\n `no cube named or with ID \"${ref}\" in this space (see \\`krova cubes list\\`)`\n );\n }\n const ids = byName.map((c) => c.id).join(\", \");\n throw new Error(\n `cube name \"${ref}\" is ambiguous: it matches ${byName.length} cubes (${ids}) — use the cube ID instead`\n );\n}\n","import * as readline from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\n\nexport interface TTYState {\n stdin: boolean;\n stdout: boolean;\n}\n\n/** The real terminal state of this process. */\nexport function currentTTY(): TTYState {\n return { stdin: Boolean(process.stdin.isTTY), stdout: Boolean(process.stdout.isTTY) };\n}\n\n/**\n * Whether a destructive or risky command should stop and ask first.\n *\n * Only a person at a terminal is asked: when stdin or stdout is piped (a script,\n * CI, an agent), the command proceeds exactly as it always did, so adding a\n * prompt never turns a working script into a hung one. `--yes` always skips it.\n */\nexport function shouldConfirm(opts: { yes?: boolean }, tty: TTYState = currentTTY()): boolean {\n if (opts.yes) return false;\n return tty.stdin && tty.stdout;\n}\n\n/** Dotted-quad IPv4 to a 32-bit number, or null when it is not one. */\nfunction ipv4ToNumber(addr: string): number | null {\n const parts = addr.split(\".\");\n if (parts.length !== 4) return null;\n let n = 0;\n for (const part of parts) {\n if (!/^\\d{1,3}$/.test(part) || Number(part) > 255) return null;\n n = n * 256 + Number(part);\n }\n return n;\n}\n\n/**\n * Whether a whitelist leaves the port open to every address.\n *\n * Open means: no entries at all; any entry whose prefix length is numerically 0\n * (`0.0.0.0/0`, `::/0`, and spellings such as `0.0.0.0/00` or `1.2.3.4/0`); or\n * the two IPv4 halves `0.0.0.0/1` and `128.0.0.0/1` together, which cover the\n * whole IPv4 space.\n */\nexport function isOpenWhitelist(whitelist: readonly string[]): boolean {\n const entries = whitelist.map((w) => w.trim()).filter(Boolean);\n if (entries.length === 0) return true;\n const halves = new Set<number>();\n for (const entry of entries) {\n const slash = entry.lastIndexOf(\"/\");\n if (slash < 0) continue;\n const prefix = entry.slice(slash + 1).trim();\n if (!/^\\d+$/.test(prefix)) continue;\n const length = Number(prefix);\n if (length === 0) return true;\n if (length === 1) {\n const n = ipv4ToNumber(entry.slice(0, slash).trim());\n if (n !== null) halves.add(n >= 2 ** 31 ? 1 : 0);\n }\n }\n return halves.size === 2;\n}\n\nexport function publicExposureWarning(cube: string, cubePort: number): string {\n 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}.`;\n}\n\n/**\n * Read a y/N answer. The prompt goes to stderr so `--json` stdout stays pure\n * JSON. Anything but y or yes counts as no. If the input ends before an answer\n * (Ctrl+D), the answer is no and the exit code is set to 1: nobody chose to\n * abort, so a script wrapping a terminal session must not read it as success.\n * The streams are injectable for tests.\n */\nexport function confirm(\n question: string,\n io: { input: Readable; output: Writable } = { input: process.stdin, output: process.stderr },\n): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = readline.createInterface({ input: io.input, output: io.output });\n let answered = false;\n rl.on(\"close\", () => {\n if (answered) return;\n process.exitCode = 1;\n resolve(false);\n });\n rl.question(question, (answer) => {\n answered = true;\n rl.close();\n resolve(/^y(es)?$/i.test(answer.trim()));\n });\n });\n}\n\n/** Print the abort notice: stdout for people, stderr under `--json`. */\nexport function printAborted(json: boolean): void {\n (json ? process.stderr : process.stdout).write(\"Aborted.\\n\");\n}\n","const FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nconst CLEAR_LINE = \"\\r\\x1b[K\";\n\nexport interface Spinner {\n /** Stop the spinner and clear its line. Safe to call more than once. */\n stop(): void;\n}\n\nconst NOOP: Spinner = { stop() {} };\n\n/**\n * Whether a spinner may be drawn: only on an interactive stderr, and never\n * when the command prints JSON (the caller passes `json`).\n */\nexport function spinnerEnabled(json: boolean, stream: NodeJS.WriteStream = process.stderr): boolean {\n return Boolean(stream.isTTY) && !json;\n}\n\n/**\n * Start a tiny stderr spinner with `label`. Returns a no-op when stderr is not\n * a TTY or `json` is set, so piped and scripted output never changes.\n * The line is cleared by `stop()` and, as a backstop, when the process exits.\n */\nexport function startSpinner(\n label: string,\n opts: { json?: boolean; stream?: NodeJS.WriteStream } = {}\n): Spinner {\n const stream = opts.stream ?? process.stderr;\n if (!spinnerEnabled(Boolean(opts.json), stream)) return NOOP;\n\n let i = 0;\n let active = true;\n const draw = () => stream.write(`${CLEAR_LINE}${FRAMES[i++ % FRAMES.length]} ${label}`);\n const clear = () => stream.write(CLEAR_LINE);\n const onExit = () => {\n if (active) clear();\n };\n draw();\n const timer = setInterval(draw, 80);\n timer.unref();\n process.once(\"exit\", onExit);\n return {\n stop() {\n if (!active) return;\n active = false;\n clearInterval(timer);\n process.removeListener(\"exit\", onExit);\n clear();\n },\n };\n}\n\n/** Run `fn` with a spinner that is cleared on success and on failure. */\nexport async function withSpinner<T>(\n label: string,\n opts: { json?: boolean; stream?: NodeJS.WriteStream },\n fn: () => Promise<T>\n): Promise<T> {\n const spinner = startSpinner(label, opts);\n try {\n return await fn();\n } finally {\n spinner.stop();\n }\n}\n","import { KrovaError } from \"@krovacloud/sdk\";\nimport type { Command } from \"commander\";\n\nimport { spinnerEnabled } from \"./spinner.js\";\n\n/** Every state the API reports for a Cube. */\nexport const CUBE_STATES = [\n \"pending\",\n \"booting\",\n \"running\",\n \"stopped\",\n \"stopping\",\n \"resizing\",\n \"error\",\n \"deleted\",\n] as const;\n\nexport type CubeState = (typeof CUBE_STATES)[number];\n\nexport const DEFAULT_WAIT_TIMEOUT_S = 300;\n/** Product behavior: how often the CLI asks the API while it waits. */\nexport const WAIT_POLL_MS = 2000;\n\n/** States a Cube does not come back from, so waiting on another state is over. */\nconst DEAD_ENDS: ReadonlySet<string> = new Set([\"error\", \"deleted\"]);\n\n/** Consecutive failed polls (a dropped connection, a 5xx) before the wait gives up. */\nconst MAX_POLL_FAILURES = 3;\n\n/** A whole number of seconds, 1 or more. `undefined` gives the default. */\nexport function parseWaitSeconds(raw: string | undefined, flag: string): number {\n if (raw === undefined) return DEFAULT_WAIT_TIMEOUT_S;\n const s = String(raw).trim();\n const n = Number(s);\n if (!/^\\d+$/.test(s) || !Number.isInteger(n) || n < 1) {\n throw new Error(`${flag} must be a whole number of seconds, 1 or more (got \"${raw}\").`);\n }\n return n;\n}\n\nexport function parseWaitState(raw: string | undefined): CubeState {\n const s = (raw ?? \"running\").trim().toLowerCase();\n if (!(CUBE_STATES as readonly string[]).includes(s)) {\n throw new Error(`--state must be one of ${CUBE_STATES.join(\", \")} (got \"${raw}\").`);\n }\n return s as CubeState;\n}\n\n/**\n * A flag's value only when it was typed on the command line, looking through\n * the parents too. The root command defines `--timeout` as well (the per-request\n * timeout), and commander hands a flag to the outermost command that knows it,\n * so a subcommand's own `--timeout` never sees the value.\n */\nexport function optionFromCli(cmd: Command, key: string): string | undefined {\n for (let c: Command | null = cmd; c; c = c.parent) {\n if (c.getOptionValueSource(key) === \"cli\") return String(c.getOptionValue(key));\n }\n return undefined;\n}\n\nexport interface WaitOptions<T extends { state: string }> {\n /** What the user typed, for messages. */\n cubeRef: string;\n target: string;\n timeoutS: number;\n /** One look at the Cube. */\n get: () => Promise<T>;\n intervalMs?: number;\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n /** Called after every look, with the state and the seconds waited so far. */\n onPoll?: (state: string, elapsedS: number) => void;\n}\n\nconst realSleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n\nfunction transient(err: unknown): boolean {\n return !(err instanceof KrovaError) || err.status >= 500;\n}\n\n/**\n * Poll a Cube until it reaches `target`. Resolves with the Cube as last seen.\n * Rejects with a one-line message on a timeout, or when the Cube lands in\n * `error` or `deleted` (unless that is the state asked for).\n */\nexport async function waitForCubeState<T extends { state: string }>(\n o: WaitOptions<T>\n): Promise<T> {\n const interval = o.intervalMs ?? WAIT_POLL_MS;\n const sleep = o.sleep ?? realSleep;\n const now = o.now ?? Date.now;\n const start = now();\n const deadline = start + o.timeoutS * 1000;\n let last = \"unknown\";\n let failures = 0;\n for (;;) {\n let cube: T | undefined;\n try {\n cube = await o.get();\n failures = 0;\n } catch (err) {\n if (!transient(err) || ++failures >= MAX_POLL_FAILURES) throw err;\n }\n if (cube) {\n last = cube.state;\n o.onPoll?.(last, Math.floor((now() - start) / 1000));\n if (last === o.target) return cube;\n if (DEAD_ENDS.has(last)) {\n throw new Error(\n `cube ${o.cubeRef} is in the \"${last}\" state, so it will not become ${o.target}`\n );\n }\n }\n const left = deadline - now();\n if (left <= 0) {\n throw new Error(\n `timed out after ${o.timeoutS}s waiting for cube ${o.cubeRef} to be ${o.target} (last state: ${last})`\n );\n }\n await sleep(Math.min(interval, left));\n }\n}\n\n/** The one-line progress readout on stderr: a TTY only, never with JSON. */\nexport function startWaitProgress(\n cubeRef: string,\n target: string,\n json: boolean,\n stream: NodeJS.WriteStream = process.stderr\n): { update: (state: string, elapsedS: number) => void; stop: () => void } {\n if (!spinnerEnabled(json, stream)) return { update() {}, stop() {} };\n const CLEAR = \"\\r\\x1b[K\";\n let drawn = false;\n const clear = () => {\n if (drawn) stream.write(CLEAR);\n drawn = false;\n };\n process.once(\"exit\", clear);\n return {\n update(state, elapsedS) {\n drawn = true;\n stream.write(`${CLEAR}Waiting for cube ${cubeRef} to be ${target}: ${state}, ${elapsedS}s`);\n },\n stop() {\n clear();\n process.removeListener(\"exit\", clear);\n },\n };\n}\n","import { KrovaError } from \"@krovacloud/sdk\";\nimport { Command } from \"commander\";\n\nimport {\n type CatalogSource,\n type KeyFiles,\n type PromptIO,\n DEFAULT_RESOURCES,\n PromptAbortError,\n confirmCreate,\n createReadlineIO,\n defaultKeyFiles,\n isInteractive,\n promptCreate,\n summarize,\n} from \"../lib/create-prompt.js\";\nimport { printJSON, printKeyValue, printTable } from \"../lib/output.js\";\nimport { resolveCube } from \"../lib/resolve.js\";\nimport { confirm, printAborted, shouldConfirm } from \"../lib/safety.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\nimport { withSpinner } from \"../lib/spinner.js\";\nimport {\n DEFAULT_WAIT_TIMEOUT_S,\n optionFromCli,\n parseWaitSeconds,\n parseWaitState,\n startWaitProgress,\n waitForCubeState,\n} from \"../lib/wait.js\";\n\nfunction listCmd(): Command {\n return new Command(\"list\")\n .aliases([\"ls\"])\n .description(\"list Cubes in the space\")\n .action(async (_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const { cubes } = await client.cubes.list(space);\n if (rt.json) return printJSON(cubes);\n printTable(\n [\"ID\", \"NAME\", \"STATE\", \"VCPU\", \"RAM(GB)\", \"DISK(GB)\", \"IMAGE\", \"IPV4\", \"PROTECTED\"],\n cubes.map((c) => [\n c.id,\n c.name,\n c.state,\n String(c.resources.vcpu),\n String(c.resources.ramGb),\n String(c.resources.diskGb),\n c.image,\n c.publicIpv4 ?? \"—\",\n // The ✓ is the only character readable in a terminal at 80-column\n // width; spelling out \"yes\"/\"no\" pushes the column past the screen\n // edge on the smallest supported layout. Empty cell when the flag is\n // off — the header column is the cue.\n c.terminationProtection ? \"✓\" : \"\",\n ])\n );\n });\n}\n\n/** Block until a Cube reaches `target`, with a progress line on a terminal. */\nasync function waitForCube(\n rt: ReturnType<typeof getRuntime>,\n client: ReturnType<typeof makeClient>,\n space: string,\n id: string,\n cubeRef: string,\n target: string,\n timeoutS: number\n) {\n const progress = startWaitProgress(cubeRef, target, rt.json);\n try {\n return await waitForCubeState({\n cubeRef,\n target,\n timeoutS,\n get: () => client.cubes.get(space, id),\n onPoll: progress.update,\n });\n } finally {\n progress.stop();\n }\n}\n\nfunction waitCmd(): Command {\n return new Command(\"wait\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"wait until a Cube reaches a state (running by default); exits 1 on a timeout or an error state\")\n .option(\"--state <state>\", \"state to wait for: pending, booting, running, stopped, stopping, resizing, error or deleted (default running)\")\n .option(\"--timeout <seconds>\", `give up after this many seconds (default ${DEFAULT_WAIT_TIMEOUT_S})`)\n .action(async (cubeRef: string, opts, cmd: Command) => {\n const target = parseWaitState(opts.state as string | undefined);\n const timeoutS = parseWaitSeconds(optionFromCli(cmd, \"timeout\"), \"--timeout\");\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cube = await waitForCube(rt, client, space, id, cubeRef, target, timeoutS);\n if (rt.json) return printJSON(cube);\n process.stdout.write(`Cube ${cube.id} is ${cube.state}\\n`);\n });\n}\n\nfunction getCmd(): Command {\n return new Command(\"get\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"show a single Cube\")\n .action(async (cubeRef: string, _opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cube = await client.cubes.get(space, id);\n if (rt.json) return printJSON(cube);\n printKeyValue([\n [\"ID\", cube.id],\n [\"Name\", cube.name],\n [\"State\", cube.state],\n [\"Image\", cube.image],\n [\"vCPU\", String(cube.resources.vcpu)],\n [\"RAM (GB)\", String(cube.resources.ramGb)],\n [\"Disk (GB)\", String(cube.resources.diskGb)],\n [\"Public IPv4\", cube.publicIpv4 ?? \"—\"],\n [\"Cost/hour\", `$${cube.costPerHour}`],\n [\"Idle timeout\", describeIdleTimeout(cube.idleTimeoutMinutes)],\n [\"Last active\", cube.lastActiveAt ?? \"-\"],\n ]);\n });\n}\n\n/** The values `cubes create` turns into a request body. All strings, as typed. */\nexport interface CreateBodyInput {\n name: string;\n image: string;\n sshKey: string;\n vcpu: string;\n ram: string;\n disk: string;\n region?: string;\n userData?: string;\n terminationProtection?: boolean;\n /** Minutes (10 to 10080) or `null` for off; leave out to send nothing. */\n idleTimeoutMinutes?: number | null;\n}\n\n/**\n * Build the POST /cubes body. Validates resources client-side so bad input\n * fails with a clear message rather than being coerced to NaN, then JSON null,\n * then a generic server 400.\n */\nexport function buildCreateBody(input: CreateBodyInput): Record<string, unknown> {\n const posInt = (flag: string, raw: string): number => {\n const n = Number(raw);\n if (!Number.isInteger(n) || n <= 0) {\n throw new Error(`--${flag} must be a positive integer (got \"${raw}\").`);\n }\n return n;\n };\n const body: Record<string, unknown> = {\n name: input.name,\n image: input.image,\n sshPublicKey: input.sshKey,\n resources: {\n vcpu: posInt(\"vcpu\", input.vcpu),\n ramGb: posInt(\"ram\", input.ram),\n diskGb: posInt(\"disk\", input.disk),\n },\n };\n if (input.region) body.region = input.region;\n if (input.userData) body.userData = input.userData;\n // Only send the flag when explicitly turned on; the server defaults it\n // to `false`, and an explicit `false` would just be noise on the wire.\n if (input.terminationProtection) body.terminationProtection = true;\n // `null` (--idle-timeout off) is sent on purpose; only `undefined` means \"not given\".\n if (input.idleTimeoutMinutes !== undefined) body.idleTimeoutMinutes = input.idleTimeoutMinutes;\n return body;\n}\n\n/** What `cubes create` needs from the outside world; tests swap these. */\nexport interface CreateDeps {\n /** Whether prompting is allowed (a real terminal, and not --json). */\n interactive: (json: boolean) => boolean;\n makeIO: () => PromptIO;\n keyFiles: () => KeyFiles;\n /** Catalog to list images and regions from; defaults to the API client's. */\n catalog?: (client: ReturnType<typeof makeClient>) => CatalogSource;\n /** Where human messages go; defaults to stdout. */\n stdout?: (text: string) => void;\n}\n\nconst defaultCreateDeps: CreateDeps = {\n interactive: (json) => isInteractive({ json }),\n makeIO: createReadlineIO,\n keyFiles: defaultKeyFiles,\n};\n\n// Required on the command line unless the terminal can ask. Order is the order\n// commander reports a missing one in.\nconst REQUIRED_CREATE_FLAGS = [\n [\"--name\", \"name\"],\n [\"--image\", \"image\"],\n [\"--ssh-key\", \"sshKey\"],\n] as const;\n\nexport function createCmd(deps: CreateDeps = defaultCreateDeps): Command {\n return new Command(\"create\")\n .description(\"provision a new Cube (in a terminal, asks for anything you leave out)\")\n .option(\"--name <name>\", \"cube name\")\n .option(\"--image <slug>\", \"OS image slug (see `krova images`)\")\n .option(\"--ssh-key <key>\", \"SSH public key written to authorized_keys\")\n .option(\"--vcpu <n>\", \"number of vCPUs\", DEFAULT_RESOURCES.vcpu)\n .option(\"--ram <gb>\", \"RAM in GB\", DEFAULT_RESOURCES.ram)\n .option(\"--disk <gb>\", \"disk size in GB\", DEFAULT_RESOURCES.disk)\n .option(\"--region <slug>\", \"region slug (see `krova regions`)\")\n .option(\"--user-data <script>\", \"cloud-init script\")\n .option(\"--idempotency-key <key>\", \"idempotency key (24h dedupe)\")\n .option(\n \"--termination-protection\",\n \"turn on termination protection (the cube cannot be deleted until turned off)\",\n false\n )\n .option(\"--idle-timeout <minutes>\", IDLE_TIMEOUT_HELP)\n .option(\"--wait\", \"wait until the Cube is running before returning\")\n .option(\"--wait-timeout <seconds>\", `with --wait, give up after this many seconds (default ${DEFAULT_WAIT_TIMEOUT_S})`)\n .option(\"-y, --yes\", \"skip the confirmation after the prompts\")\n .action(async (opts, cmd: Command) => {\n // Checked first so a bad value fails before any prompt or request.\n const waitTimeoutS = parseWaitSeconds(opts.waitTimeout as string | undefined, \"--wait-timeout\");\n const idleTimeoutMinutes =\n opts.idleTimeout === undefined ? undefined : parseIdleTimeout(opts.idleTimeout);\n // --name, --image and --ssh-key were requiredOption; without a terminal\n // they still are, with commander's own message and exit code.\n const missing = REQUIRED_CREATE_FLAGS.filter(([, key]) => opts[key] === undefined);\n const globals = cmd.optsWithGlobals() as { json?: unknown; output?: unknown };\n const wantsJson = Boolean(globals.json) || globals.output === \"json\";\n const prompting = missing.length > 0 && deps.interactive(wantsJson);\n if (missing.length > 0 && !prompting) {\n const flags = cmd.options.find((o) => o.long === missing[0]?.[0])?.flags;\n cmd.error(`error: required option '${flags}' not specified`, {\n code: \"commander.missingMandatoryOptionValue\",\n });\n }\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const out = deps.stdout ?? ((text: string) => void process.stdout.write(text));\n const build = (v: {\n name: string;\n image: string;\n sshKey: string;\n vcpu: string;\n ram: string;\n disk: string;\n region?: string;\n }) =>\n buildCreateBody({\n ...v,\n userData: opts.userData,\n terminationProtection: opts.terminationProtection,\n idleTimeoutMinutes,\n });\n let body: Record<string, unknown>;\n if (prompting) {\n const io = deps.makeIO();\n try {\n // A resource flag counts as given only when it came from the command line.\n const given = (key: \"vcpu\" | \"ram\" | \"disk\") =>\n cmd.getOptionValueSource(key) === \"default\" ? undefined : (opts[key] as string);\n const answers = await promptCreate(\n {\n name: opts.name,\n image: opts.image,\n sshKey: opts.sshKey,\n region: opts.region,\n vcpu: given(\"vcpu\"),\n ram: given(\"ram\"),\n disk: given(\"disk\"),\n },\n {\n io,\n catalog: deps.catalog ? deps.catalog(client) : client.catalog,\n keyFiles: deps.keyFiles(),\n }\n );\n // Build first so a bad flag value fails before the confirmation, not after it.\n body = build(answers);\n if (!opts.yes && !(await confirmCreate(io, summarize(answers)))) {\n out(\"Aborted.\\n\");\n return;\n }\n } catch (err) {\n if (!(err instanceof PromptAbortError)) throw err;\n out(\"\\nAborted.\\n\");\n process.exitCode = 1;\n return;\n } finally {\n io.close();\n }\n } else {\n body = build({\n name: opts.name,\n image: opts.image,\n sshKey: opts.sshKey,\n vcpu: opts.vcpu,\n ram: opts.ram,\n disk: opts.disk,\n region: opts.region,\n });\n }\n const cube = await withSpinner(\"Creating cube\", { json: rt.json }, () =>\n client.cubes.create(\n space,\n body as never,\n opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined\n )\n );\n if (idleTimeoutMinutes !== undefined && !idleTimeoutApplied(cube.idleTimeoutMinutes, idleTimeoutMinutes)) {\n // An older server ignores the field it does not know and still answers 201.\n process.stderr.write(IDLE_UNSUPPORTED_WARNING);\n }\n if (!opts.wait) {\n if (rt.json) return printJSON(cube);\n out(`Created cube ${cube.id} (${cube.state})\\n`);\n return;\n }\n if (!rt.json) out(`Created cube ${cube.id} (${cube.state})\\n`);\n const ready = await waitForCube(rt, client, space, cube.id, cube.id, \"running\", waitTimeoutS);\n if (rt.json) return printJSON(ready);\n out(`Cube ${ready.id} is running\\n`);\n });\n}\n\nfunction actionCmd(\n name: string,\n past: string,\n fn: (c: ReturnType<typeof makeClient>[\"cubes\"], space: string, id: string) => Promise<unknown>\n): Command {\n return new Command(name)\n .argument(\"<cube>\", \"cube name or ID\")\n .description(`${name} a Cube`)\n .action(async (cubeRef: string, _opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n await fn(client.cubes, space, id);\n if (rt.json) return printJSON({ id, result: past });\n process.stdout.write(`${past} cube ${id}\\n`);\n });\n}\n\nfunction deleteCmd(): Command {\n return new Command(\"delete\")\n .argument(\"<cube>\", \"cube name or ID\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .description(\"delete a Cube (permanent)\")\n .action(async (cubeRef: string, opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n if (shouldConfirm(opts)) {\n const ok = await confirm(\n `Delete cube ${cubeRef}${cubeRef === id ? \"\" : ` (${id})`}? This is permanent and cannot be undone. [y/N] `,\n );\n if (!ok) return printAborted(rt.json);\n }\n await client.cubes.delete(space, id);\n if (rt.json) return printJSON({ id, result: \"Deleting\" });\n process.stdout.write(`Deleting cube ${id}\\n`);\n });\n}\n\nfunction restartCmd(): Command {\n return new Command(\"restart\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"restart a Cube (cold restart — picks up a refreshed kernel)\")\n .action(async (cubeRef: string, _opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n await client.cubes.restart(space, id);\n if (rt.json) return printJSON({ id, result: \"Restarting\" });\n // Say COLD explicitly. A `reboot` from inside the Cube looks equivalent\n // but cannot change the kernel — Firecracker treats a guest reboot as a\n // shutdown and the kernel comes from the host.\n process.stdout.write(\n `Restarting cube ${id} (cold restart — disk state is preserved)\\n`,\n );\n });\n}\n\nfunction sshPortCmd(): Command {\n return new Command(\"ssh-port\")\n .argument(\"<cube>\", \"cube name or ID\")\n .requiredOption(\n \"--port <n>\",\n \"the port INSIDE the Cube that sshd listens on (default 22)\",\n )\n .description(\"change the in-Cube port that SSH is forwarded to (not the host port)\")\n .action(async (cubeRef: string, opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cubePort = Number(opts.port);\n if (!Number.isInteger(cubePort) || cubePort < 1 || cubePort > 65535) {\n throw new Error(\"--port must be an integer between 1 and 65535\");\n }\n await client.cubes.update(space, id, { cubePort } as never);\n if (rt.json) return printJSON({ id, cubePort });\n // Be explicit about WHICH side changed. The host port is assigned by\n // Krova and is not affected by this call, so pointing this at a port\n // nothing is listening on inside the Cube silently breaks SSH access.\n process.stdout.write(\n `Cube ${id}: SSH now forwarded to in-Cube port ${cubePort}.\\n` +\n (cubePort === 22\n ? \"\"\n : `Warning: sshd inside the Cube must be listening on ${cubePort}, ` +\n \"or SSH will stop working. The default is 22.\\n\"),\n );\n });\n}\n\nfunction renameCmd(): Command {\n return new Command(\"rename\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<new-name>\", \"the new name (1 to 64 printable characters)\")\n .description(\"rename a Cube (names do not have to be unique; a running Cube's hostname changes on its next cold restart)\")\n .action(async (cubeRef: string, rawName: string, _opts, cmd: Command) => {\n const newName = parseCubeName(rawName);\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cube = await client.cubes.rename(space, id, newName);\n if (rt.json) return printJSON(cube);\n process.stdout.write(`Renamed cube ${id} to ${cube.name}\\n`);\n });\n}\n\nconst IDLE_TIMEOUT_HELP =\n 'power the Cube off after this many minutes without activity (10 to 10080), or \"off\" (needs a server with the idle-timeout feature)';\n\nconst IDLE_UNSUPPORTED_WARNING =\n \"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\";\n\n/**\n * Parse `--idle-timeout`: whole minutes from 10 to 10080 (7 days), or `off`\n * (sent as `null`). Plain decimal digits only, so 1e2, 0x10 and \" 20\" fail.\n */\nexport function parseIdleTimeout(raw: string): number | null {\n if (raw === \"off\") return null;\n const n = Number(raw);\n if (!/^\\d+$/.test(raw) || !Number.isSafeInteger(n) || n < 10 || n > 10080) {\n throw new Error('--idle-timeout must be a whole number of minutes from 10 to 10080, or \"off\"');\n }\n return n;\n}\n\n/**\n * Did the server apply the requested timeout? A present field must equal the request. An absent field means\n * the server omitted it (an older server, or a null it left out): that only counts as applied for `off`.\n */\nexport function idleTimeoutApplied(\n returned: number | null | undefined,\n requested: number | null,\n): boolean {\n return returned === undefined ? requested === null : returned === requested;\n}\n\n/** `off` for a Cube with no timeout, `N min` for one with a timeout, `-` when the server does not say. */\nexport function describeIdleTimeout(minutes: number | null | undefined): string {\n if (minutes === undefined) return \"-\";\n return minutes === null ? \"off\" : `${minutes} min`;\n}\n\nfunction updateCmd(): Command {\n return new Command(\"update\")\n .argument(\"<cube>\", \"cube name or ID\")\n .option(\"--idle-timeout <minutes>\", IDLE_TIMEOUT_HELP)\n .description(\"change a Cube's settings (idle auto-stop; `rename`, `resize` and `protect` cover the rest)\")\n .action(async (cubeRef: string, opts, cmd: Command) => {\n if (opts.idleTimeout === undefined) {\n throw new Error(\"nothing to update: pass --idle-timeout <minutes|off>\");\n }\n const minutes = parseIdleTimeout(opts.idleTimeout);\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cube = await client.cubes.setIdleTimeout(space, id, minutes);\n // A 200 that does not carry the new value means the server ignored the field; never report a change that did not happen.\n if (!idleTimeoutApplied(cube.idleTimeoutMinutes, minutes)) {\n throw new Error(\n cube.idleTimeoutMinutes === undefined\n ? \"the server did not apply --idle-timeout (it needs a server with the idle-timeout feature)\"\n : `the server kept the idle timeout at ${describeIdleTimeout(cube.idleTimeoutMinutes)}`\n );\n }\n if (rt.json) return printJSON(cube);\n process.stdout.write(\n minutes === null\n ? `Turned off idle auto-stop for cube ${id}\\n`\n : `Set idle auto-stop for cube ${id} to ${minutes} min\\n`\n );\n });\n}\n\n/** Parse a `--vcpu`/`--ram`/`--disk` value. `integer` rejects fractions. RAM is parsed as a number here but the server only accepts whole GB, so a fraction is refused by the API. */\nexport function parseSize(flag: string, raw: string, integer: boolean): number {\n // Plain decimal digits only: Number() would also take 0x10, 1e1 and \" 5 \".\n const n = Number(raw);\n if (!(integer ? /^\\d+$/ : /^\\d+(\\.\\d+)?$/).test(raw) || !Number.isFinite(n) || n <= 0) {\n throw new Error(`${flag} must be a positive ${integer ? \"whole number\" : \"number\"}`);\n }\n return n;\n}\n\n/** Trim a new Cube name and check it locally: 1 to 64 characters, no control, line-separator or bidi characters. */\nexport function parseCubeName(raw: string): string {\n const name = raw.trim();\n const length = [...name].length;\n if (length < 1 || length > 64 || /[\\p{Cc}\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u2069]/u.test(name)) {\n throw new Error(\"the new name must be 1 to 64 printable characters\");\n }\n return name;\n}\n\nconst RESIZE_DIMENSIONS = [\n { key: \"vcpu\", label: \"vCPU\", unit: \"\" },\n { key: \"ramGb\", label: \"RAM\", unit: \" GB\" },\n { key: \"diskGb\", label: \"Disk\", unit: \" GB\" },\n] as const;\n\nfunction describeSize(size: { vcpu: number; ramGb: number; diskGb: number }): string {\n return `${size.vcpu} vCPU, ${size.ramGb} GB RAM, ${size.diskGb} GB disk`;\n}\n\nfunction resizeCmd(): Command {\n return new Command(\"resize\")\n .argument(\"<cube>\", \"cube name or ID\")\n .option(\"--vcpu <n>\", \"new vCPU count\")\n .option(\"--ram <gb>\", \"new RAM in whole GB (1 GB steps)\")\n .option(\"--disk <gb>\", \"new disk in GB (disk can only grow)\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .description(\n \"change a Cube's vCPU, RAM and/or disk; the API says whether it is applied live or restarts the Cube\",\n )\n .action(async (cubeRef: string, opts, cmd: Command) => {\n const resources: { vcpu?: number; ramGb?: number; diskGb?: number } = {};\n if (opts.vcpu !== undefined) resources.vcpu = parseSize(\"--vcpu\", opts.vcpu, true);\n if (opts.ram !== undefined) resources.ramGb = parseSize(\"--ram\", opts.ram, false);\n if (opts.disk !== undefined) resources.diskGb = parseSize(\"--disk\", opts.disk, true);\n if (Object.keys(resources).length === 0) {\n throw new Error(\"give at least one of --vcpu, --ram or --disk\");\n }\n\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n\n // The API only says whether a resize is live or restarts the Cube AFTER it\n // queues the job, so the question cannot name the outcome: it states the\n // change and that some changes restart. Only a person at a terminal is\n // asked; scripts and pipes proceed, and -y skips it.\n if (shouldConfirm(opts)) {\n const current = (await client.cubes.get(space, id)).resources;\n const target = { ...current, ...resources };\n const ok = await confirm(\n `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] `,\n );\n if (!ok) return printAborted(rt.json);\n }\n\n let result: Awaited<ReturnType<typeof client.cubes.resize>>;\n try {\n result = await client.cubes.resize(space, id, resources);\n } catch (err) {\n // The host, not the request, is out of room: retrying the same size\n // will not help, so say what will.\n if (\n err instanceof KrovaError &&\n err.status === 400 &&\n (err.body as { code?: unknown } | undefined)?.code === \"insufficient_host_capacity\"\n ) {\n Object.assign(err, {\n hint: \"The server this Cube runs on has no room for that size. Try a smaller size, or contact support.\",\n });\n }\n throw err;\n }\n\n if (rt.json) return printJSON({ id, ...result });\n process.stdout.write(`Resize queued for cube ${id} (job ${result.jobId})\\n`);\n for (const { key, label, unit } of RESIZE_DIMENSIONS) {\n const from = result.previous[key];\n const to = result.requested[key];\n process.stdout.write(\n ` ${label}: ${from === to ? `${to}${unit} (unchanged)` : `${from}${unit} -> ${to}${unit}`}\\n`,\n );\n }\n process.stdout.write(\n result.requiresRestart\n ? \"The Cube restarts to apply this change.\\n\"\n : \"Applied live: the Cube does not restart.\\n\",\n );\n process.stdout.write(`The Cube keeps its current size until the change is applied. Check with: krova cubes get ${id}\\n`);\n });\n}\n\n/**\n * Toggle a Cube's termination-protection flag. Shared by `protect` and\n * `unprotect`; only the boolean `enabled` differs.\n */\nfunction setProtectionCmd(name: string, enabled: boolean, past: string): Command {\n return new Command(name)\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\n enabled\n ? \"turn on termination protection (idempotent — no-op if already on; the cube cannot be deleted until turned off)\"\n : \"turn off termination protection (idempotent — no-op if already off)\",\n )\n .action(async (cubeRef: string, _opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n // The SDK call is idempotent: re-protecting a protected cube or\n // unprotecting an unprotected one is a no-op on the server. The CLI\n // surfaces the latest audit fields in `--json` for callers that want to\n // see who last changed the flag.\n const cube = await client.cubes.setTerminationProtection(space, id, enabled);\n if (rt.json) return printJSON(cube);\n process.stdout.write(`${past} cube ${id}\\n`);\n });\n}\n\nexport function cubesCommand(): Command {\n const cubes = new Command(\"cubes\").description(\"manage Cubes (Firecracker microVMs)\");\n cubes.addCommand(listCmd());\n cubes.addCommand(getCmd());\n cubes.addCommand(waitCmd());\n cubes.addCommand(createCmd());\n cubes.addCommand(\n actionCmd(\"power-off\", \"Powering off\", (c, s, id) => c.powerOff(s, id)),\n );\n cubes.addCommand(actionCmd(\"wake\", \"Starting\", (c, s, id) => c.wake(s, id)));\n cubes.addCommand(deleteCmd());\n cubes.addCommand(restartCmd());\n cubes.addCommand(sshPortCmd());\n cubes.addCommand(updateCmd());\n cubes.addCommand(renameCmd());\n cubes.addCommand(resizeCmd());\n cubes.addCommand(setProtectionCmd(\"protect\", true, \"Protected\"));\n cubes.addCommand(setProtectionCmd(\"unprotect\", false, \"Unprotected\"));\n return cubes;\n}\n\n// `list` and `get` are also mounted at the root (parity with the Go CLI).\nexport const rootListCommand = listCmd;\nexport const rootGetCommand = getCmd;\n","import { Command } from \"commander\";\n\nimport { printJSON, printTable } from \"../lib/output.js\";\nimport { resolveCube } from \"../lib/resolve.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\n\n/**\n * Narrow a `--origin-scheme` / positional scheme to the two the API accepts.\n * Returns undefined when the flag was omitted, so callers can leave the field\n * off the request entirely rather than sending an explicit default.\n */\nexport function parseOriginScheme(value: unknown): \"http\" | \"https\" | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (value === \"http\" || value === \"https\") return value;\n throw new Error(`--origin-scheme must be \"http\" or \"https\" (got \"${String(value)}\").`);\n}\n\n/**\n * Narrow a `--proxy-protocol` / positional version to what the API accepts:\n * \"v1\" or \"v2\", or \"off\" for none (sent as `null`). Returns undefined when the\n * flag was omitted, so `add` leaves the field off the request entirely.\n */\nexport function parseProxyProtocol(value: unknown): \"v1\" | \"v2\" | null | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n if (value === \"v1\" || value === \"v2\") return value;\n if (value === \"off\") return null;\n throw new Error(`--proxy-protocol must be \"v1\", \"v2\" or \"off\" (got \"${String(value)}\").`);\n}\n\ntype PrintableRecord = {\n type: string;\n host: string;\n value: string;\n note?: string | null;\n mustBeGrey?: boolean;\n state?: string;\n detail?: string;\n};\n\n/** How each live state reads on a terminal. */\nconst STATE_LABEL: Record<string, string> = {\n found: \"found\",\n // ⛔ NOT \"failed\". Before you publish a record, absent is the expected state.\n missing: \"not added yet\",\n mismatch: \"needs a change\",\n // ⛔ OUR lookup failed. Never phrased as the user's mistake.\n unknown: \"couldn't check\",\n};\n\n/**\n * Print the DNS records a domain needs.\n *\n * Both the host AND the value, because a record cannot be created from the\n * value alone — which is what made the old guidance impossible to act on.\n */\nfunction printRecords(records: PrintableRecord[], withState = false): void {\n if (records.length === 0) return;\n process.stdout.write(\"\\nDNS records to publish:\\n\");\n for (const r of records) {\n const state = withState && r.state ? ` [${STATE_LABEL[r.state] ?? r.state}]` : \"\";\n process.stdout.write(`\\n ${r.type.padEnd(5)} ${r.host}${state}\\n`);\n process.stdout.write(` -> ${r.value}\\n`);\n if (r.mustBeGrey) {\n // The single most common wildcard failure: proxied, so the CA sees\n // Cloudflare's addresses instead of the record.\n process.stdout.write(\" On Cloudflare: DNS only (grey cloud)\\n\");\n }\n if (withState && r.detail && r.state !== \"found\") {\n process.stdout.write(` ${r.detail}\\n`);\n }\n }\n}\n\n/** `krova domains` — manage a Cube's custom domains. */\nexport function domainsCommand(): Command {\n const cmd = new Command(\"domains\").description(\"manage a Cube's custom domains\");\n\n cmd\n .command(\"list\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"list the custom domains attached to a Cube\")\n .action(async (cubeRef: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const domains = await client.domains.list(space, id);\n if (rt.json) return printJSON(domains);\n printTable(\n [\"ID\", \"DOMAIN\", \"PORT\", \"STATUS\"],\n domains.map((d) => [d.id, d.domain, String(d.port ?? \"\"), d.status]),\n );\n });\n\n cmd\n .command(\"add\")\n .argument(\"<cube>\", \"cube name or ID\")\n .requiredOption(\"--domain <domain>\", \"the domain name to attach\")\n .requiredOption(\"--port <n>\", \"the in-Cube port to route to\")\n .option(\"--origin-scheme <scheme>\", \"transport the edge uses to reach the Cube: http (default) or https when the Cube terminates TLS itself\")\n .option(\"--proxy-protocol <version>\", \"send a PROXY protocol header (v1 or v2) naming the visitor on each connection to the Cube; your app must accept it on this port. Off by default\")\n .option(\"--confirm-mixed-proxy-protocol\", \"attach even though other domains on the same Cube port use a different PROXY protocol setting\")\n .description(\"attach a custom domain to a Cube\")\n .action(async (cubeRef: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const port = Number(opts.port);\n if (!Number.isInteger(port) || port <= 0 || port > 65535) {\n throw new Error(`--port must be a valid port (got \"${opts.port}\").`);\n }\n const originScheme = parseOriginScheme(opts.originScheme);\n const proxyProtocol = parseProxyProtocol(opts.proxyProtocol);\n const { domain, records } = await client.domains.create(space, id, {\n domain: opts.domain,\n port,\n ...(originScheme ? { originScheme } : {}),\n ...(proxyProtocol ? { proxyProtocol } : {}),\n ...(opts.confirmMixedProxyProtocol ? { confirmMixedProxyProtocol: true } : {}),\n });\n if (rt.json) return printJSON({ domain, records });\n process.stdout.write(`Attached ${domain.domain} (${domain.id}) — status ${domain.status}\\n`);\n // ⛔ Print the records. Attaching a domain does nothing until they exist,\n // and before this the CLI sent people away to find out what to publish —\n // for a wildcard, two of the three records were not discoverable from\n // anything the CLI printed.\n printRecords(records);\n process.stdout.write(\n `\\nAfter publishing them: krova domains records ${cubeRef} ${domain.id}\\n`,\n );\n });\n\n cmd\n .command(\"records\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<domain-id>\", \"the domain mapping ID (see `krova domains list`)\")\n .description(\"show the DNS records a domain needs, and whether they resolve yet\")\n .action(async (cubeRef: string, mappingId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const out = await client.domains.records(space, id, mappingId);\n if (rt.json) return printJSON(out);\n process.stdout.write(\n `${out.domain} — ${out.summary.found} of ${out.summary.total} records found\\n`,\n );\n printRecords(out.records, true);\n if (!out.summary.complete) {\n process.stdout.write(\"\\nDNS changes can take a few minutes to spread.\\n\");\n }\n });\n\n cmd\n .command(\"set-origin\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<domain-id>\", \"the domain mapping ID (see `krova domains list`)\")\n .argument(\"<scheme>\", \"http or https\")\n .description(\"set the transport the edge uses to reach the Cube\")\n .action(async (cubeRef: string, mappingId: string, scheme: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const originScheme = parseOriginScheme(scheme);\n if (!originScheme) {\n throw new Error(`scheme must be \"http\" or \"https\" (got \"${scheme}\").`);\n }\n const domain = await client.domains.update(space, id, mappingId, { originScheme });\n if (rt.json) return printJSON(domain);\n process.stdout.write(`${domain.domain} now reached over ${originScheme}\\n`);\n });\n\n cmd\n .command(\"set-proxy-protocol\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<domain-id>\", \"the domain mapping ID (see `krova domains list`)\")\n .argument(\"<version>\", \"v1, v2 or off\")\n .option(\"--confirm-mixed-proxy-protocol\", \"save even though other domains on the same Cube port use a different setting\")\n .description(\"send a PROXY protocol header naming the visitor on each connection to the Cube, or stop\")\n .action(async (cubeRef: string, mappingId: string, version: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const proxyProtocol = parseProxyProtocol(version);\n if (proxyProtocol === undefined) {\n throw new Error(`version must be \"v1\", \"v2\" or \"off\" (got \"${version}\").`);\n }\n const domain = await client.domains.update(space, id, mappingId, {\n proxyProtocol,\n ...(opts.confirmMixedProxyProtocol ? { confirmMixedProxyProtocol: true } : {}),\n });\n if (rt.json) return printJSON(domain);\n process.stdout.write(\n proxyProtocol\n ? `${domain.domain} now sends a PROXY protocol ${proxyProtocol} header to the Cube\\n`\n : `${domain.domain} no longer sends a PROXY protocol header\\n`,\n );\n });\n\n cmd\n .command(\"rm\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<domain-id>\", \"the domain mapping ID (see `krova domains list`)\")\n .description(\"detach a custom domain from a Cube\")\n .action(async (cubeRef: string, mappingId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n await client.domains.delete(space, id, mappingId);\n if (rt.json) return printJSON({ id: mappingId, result: \"detached\" });\n process.stdout.write(`Detached domain ${mappingId}\\n`);\n });\n\n return cmd;\n}\n","import { spawn } from \"node:child_process\";\n\nimport { Command } from \"commander\";\n\nimport { rawRequest } from \"../lib/client.js\";\nimport { loginMessage, persistLogin } from \"../lib/persist.js\";\nimport { getRuntime } from \"../lib/runtime.js\";\nimport { spinnerEnabled, withSpinner } from \"../lib/spinner.js\";\n\ninterface StartResponse {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string;\n interval: number;\n expiresIn: number;\n}\ninterface PollResponse {\n apiKey: string;\n spaceId: string;\n}\n\nconst BROWSER_UNAVAILABLE =\n \"Browser login isn't enabled on this server yet — run `krova auth login` to paste an API key from https://krova.cloud\";\n\n/** Characters that never appear in a device-login URL and that cmd.exe treats as operators. */\nconst SHELL_METACHARS = /[&|^<>\"]/;\n\n/**\n * Only open https URLs, or http to a loopback host, and return the normalized href.\n * The device-login URL is `<base>/cli?code=<ALNUM-ALNUM>`: it never needs `& | ^ < > \"`, so a URL\n * carrying one is refused on every platform. `%` is refused on Windows only, where it expands\n * environment variables in some launchers; the real URL never contains it (the code is alphanumeric).\n * A refused URL is not opened: the caller prints it for the user to open by hand.\n */\nexport function safeBrowserURL(\n raw: string,\n platform: NodeJS.Platform = process.platform\n): string | null {\n let u: URL;\n try {\n u = new URL(raw);\n } catch {\n return null;\n }\n const loopbackHttp =\n u.protocol === \"http:\" &&\n (u.hostname === \"localhost\" || u.hostname === \"127.0.0.1\" || u.hostname === \"[::1]\");\n if (!((u.protocol === \"https:\" && u.hostname) || loopbackHttp)) return null;\n const href = u.href;\n if (SHELL_METACHARS.test(href)) return null;\n if (platform === \"win32\" && href.includes(\"%\")) return null;\n return href;\n}\n\n/** Removes C0, DEL and C1 control characters (ESC included) so a server string cannot drive the terminal. */\nexport function stripControlChars(s: string): string {\n return s.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \"\");\n}\n\n/** The URL as it is shown to the user: the normalized href when it parses, else the raw string, with control characters stripped. */\nexport function displayURL(raw: string): string {\n try {\n return stripControlChars(new URL(raw).href);\n } catch {\n return stripControlChars(raw);\n }\n}\n\nexport interface BrowserSpawnPlan {\n command: string;\n args: string[];\n options: { stdio: \"ignore\"; detached: true; windowsHide?: true };\n}\n\n/**\n * How to open `href` in the default browser. Never uses a shell: on Windows `rundll32` is a real\n * executable, so cmd.exe never parses the URL.\n */\nexport function browserSpawnPlan(\n href: string,\n platform: NodeJS.Platform = process.platform\n): BrowserSpawnPlan {\n if (platform === \"win32\") {\n return {\n command: \"rundll32\",\n args: [\"url.dll,FileProtocolHandler\", href],\n options: { stdio: \"ignore\", detached: true, windowsHide: true },\n };\n }\n return {\n command: platform === \"darwin\" ? \"open\" : \"xdg-open\",\n args: [href],\n options: { stdio: \"ignore\", detached: true },\n };\n}\n\nfunction openBrowser(href: string): void {\n const plan = browserSpawnPlan(href);\n const child = spawn(plan.command, plan.args, plan.options);\n child.on(\"error\", () => {\n /* fall through — the URL was already printed */\n });\n child.unref();\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport function loginCommand(): Command {\n return new Command(\"login\")\n .description(\"log in through your browser (device authorization)\")\n .option(\"--no-browser\", \"don't open a browser; just print the URL\")\n .option(\"--context <name>\", \"name for the saved context\")\n .action(async (opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const baseUrl = rt.res.baseUrl;\n\n const start = await rawRequest<StartResponse>({\n method: \"POST\",\n baseUrl,\n path: \"/auth/cli/start\",\n timeoutMs: rt.timeoutMs,\n });\n if (start.status === 404) throw new Error(BROWSER_UNAVAILABLE);\n if (start.status !== 200 || !start.data?.deviceCode) {\n throw new Error(`device login failed to start (HTTP ${start.status})`);\n }\n const s = start.data;\n process.stdout.write(`Your verification code is: ${stripControlChars(String(s.userCode ?? \"\"))}\\n`);\n\n const target = s.verificationUriComplete || s.verificationUri;\n const safe = safeBrowserURL(target);\n if (safe && opts.browser !== false) {\n process.stdout.write(`Opening ${safe} …\\n`);\n openBrowser(safe);\n } else {\n process.stdout.write(`Open this URL to approve the login:\\n ${displayURL(target)}\\n`);\n if (!safe) {\n process.stdout.write(\n \"It was not opened automatically because it contains characters that are unsafe to pass to the system opener.\\n\"\n );\n }\n }\n\n const intervalMs = Math.max((s.interval || 5) * 1000, 5000);\n const deadline = Date.now() + Math.max(s.expiresIn || 600, 1) * 1000;\n // On an interactive terminal the spinner says it; otherwise keep the plain line.\n if (!spinnerEnabled(rt.json)) process.stdout.write(\"Waiting for approval…\\n\");\n\n // Poll loop. withSpinner clears the spinner line on success and on failure.\n const approved = await withSpinner(\"Waiting for approval\", { json: rt.json }, async () => {\n for (;;) {\n if (Date.now() >= deadline) {\n throw new Error(\n \"login timed out: the verification code expired before it was approved\"\n );\n }\n await sleep(intervalMs);\n const poll = await rawRequest<PollResponse>({\n method: \"POST\",\n baseUrl,\n path: \"/auth/cli/poll\",\n body: { deviceCode: s.deviceCode },\n timeoutMs: rt.timeoutMs,\n });\n if (poll.status === 200) {\n if (!poll.data?.apiKey) throw new Error(\"login succeeded but no API key was returned\");\n return poll.data;\n }\n if (poll.status === 202 || poll.status === 425 || poll.status === 428) continue;\n if (poll.status === 410) {\n throw new Error(\"login expired: request a new code with `krova login`\");\n }\n if (poll.status === 404) throw new Error(BROWSER_UNAVAILABLE);\n throw new Error(`login failed while polling (HTTP ${poll.status})`);\n }\n });\n const { ctxName, spaceName, stored } = await persistLogin({\n apiKey: approved.apiKey,\n baseUrl,\n spaceId: approved.spaceId,\n // Not opts.context: the root's own --context takes the flag first, so the\n // local option never receives it. The merged flags always carry it.\n ctxName: rt.flags.context,\n timeoutMs: rt.timeoutMs,\n });\n process.stdout.write(`${loginMessage(ctxName, stored)}\\n`);\n if (spaceName) process.stdout.write(`Space: ${spaceName}\\n`);\n });\n}\n","import { Command } from \"commander\";\n\nimport { printJSON, printTable } from \"../lib/output.js\";\nimport { resolveCube } from \"../lib/resolve.js\";\nimport { confirm, printAborted, shouldConfirm } from \"../lib/safety.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\n\n/** `krova snapshots` — snapshot and restore a Cube's disk. */\nexport function snapshotsCommand(): Command {\n const cmd = new Command(\"snapshots\").description(\"snapshot and restore a Cube's disk\");\n\n cmd\n .command(\"list\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"list a Cube's snapshots\")\n .action(async (cubeRef: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const snaps = await client.snapshots.list(space, id);\n if (rt.json) return printJSON(snaps);\n printTable(\n [\"ID\", \"NAME\", \"STATUS\", \"KIND\", \"SIZE (BYTES)\", \"CREATED\"],\n snaps.map((s) => [\n s.id,\n s.name,\n s.status,\n s.kind,\n s.sizeBytes == null ? \"\" : String(s.sizeBytes),\n s.createdAt,\n ]),\n );\n });\n\n cmd\n .command(\"create\")\n .argument(\"<cube>\", \"cube name or ID\")\n .option(\"--name <name>\", \"a name for the snapshot\")\n .description(\"create a snapshot of a Cube's disk\")\n .action(async (cubeRef: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const snap = await client.snapshots.create(space, id, opts.name ? { name: opts.name } : {});\n if (rt.json) return printJSON(snap);\n process.stdout.write(`Created snapshot ${snap.id} (${snap.status})\\n`);\n });\n\n cmd\n .command(\"rm\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<snapshot-id>\", \"the snapshot ID (see `krova snapshots list`)\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .description(\"delete a snapshot (permanent)\")\n .action(async (cubeRef: string, snapshotId: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n if (shouldConfirm(opts)) {\n // Show the snapshot's name when we can find it; the ID alone is hard to recognize.\n const name = (await client.snapshots.list(space, id).catch(() => [])).find(\n (s) => s.id === snapshotId,\n )?.name;\n const ok = await confirm(\n `Delete snapshot ${name ? `\"${name}\" (${snapshotId})` : snapshotId} of cube ${cubeRef}? This is permanent and cannot be undone. [y/N] `,\n );\n if (!ok) return printAborted(rt.json);\n }\n await client.snapshots.delete(space, id, snapshotId);\n if (rt.json) return printJSON({ id: snapshotId, result: \"deleted\" });\n process.stdout.write(`Deleted snapshot ${snapshotId}\\n`);\n });\n\n cmd\n .command(\"restore\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<snapshot-id>\", \"the snapshot to restore the Cube's disk from\")\n .description(\"restore a Cube's disk from one of its snapshots (replaces the disk)\")\n .action(async (cubeRef: string, snapshotId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n await client.cubes.restore(space, id, snapshotId);\n if (rt.json) return printJSON({ id, snapshotId, result: \"restore enqueued\" });\n process.stdout.write(`Restore of cube ${id} from ${snapshotId} enqueued\\n`);\n });\n\n return cmd;\n}\n","// SSH: fetch connection info, pin host keys, build a hardened `ssh` argv, exec.\n// Ports the Go CLI's option-injection guards and known_hosts pinning verbatim.\n\nimport { spawn } from \"node:child_process\";\nimport { appendFileSync, chmodSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { isIP } from \"node:net\";\nimport { dirname } from \"node:path\";\n\nimport { constants as osConstants } from \"node:os\";\n\nimport type { Command } from \"commander\";\n\nimport { rawRequest } from \"./client.js\";\nimport { configDir } from \"./config.js\";\nimport { join } from \"node:path\";\nimport { resolveCube } from \"./resolve.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"./runtime.js\";\n\nexport interface SshHostKey {\n type: string;\n key: string;\n}\nexport interface SshInfo {\n host: string;\n port: number;\n user: string;\n hostKeys: SshHostKey[];\n}\n\nexport interface SshOptions {\n /** Extra ssh flags placed before everything else (for example `-N`, `-T`). */\n preArgs?: string[];\n identity?: string;\n localFwd?: string[];\n remoteFwd?: string[];\n knownHosts?: string;\n remoteCmd?: string[];\n}\n\n// Characters an ssh host must never contain (option/metacharacter injection).\nconst HOST_BANNED = new Set(\n \"@/\\\\'\\\"`$;&|<>(){}*?!#=,\".split(\"\")\n);\n// User is slightly looser — it may contain '=' (host may not).\nconst USER_BANNED = new Set(\n \"@/\\\\'\\\"`$;&|<>(){}*?!#,:[]\".split(\"\")\n);\n\n// One DNS label: letters, digits and inner hyphens, at most 63 characters.\nconst DNS_NAME =\n /^(?=.{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])?)*$/;\n\nexport function validateSSHHost(host: string): void {\n const h = host.trim();\n if (!h) throw new Error(\"empty host\");\n if (h.startsWith(\"-\")) throw new Error(\"host must not start with '-'\");\n for (const r of h) {\n const code = r.codePointAt(0) ?? 0;\n if (code <= 0x20 || code === 0x7f) {\n throw new Error(\"host contains whitespace or control characters\");\n }\n if (HOST_BANNED.has(r)) {\n throw new Error(`host contains a disallowed character ${JSON.stringify(r)}`);\n }\n }\n if (isIP(h) === 0 && !DNS_NAME.test(h)) {\n throw new Error(\"host must be an IP address or a DNS hostname\");\n }\n}\n\nexport function validateSSHUser(user: string): void {\n const u = user.trim();\n if (!u) return; // empty user is allowed\n if (u.startsWith(\"-\")) throw new Error(\"user must not start with '-'\");\n for (const r of u) {\n const code = r.codePointAt(0) ?? 0;\n if (code <= 0x20 || code === 0x7f) {\n throw new Error(\"user contains whitespace or control characters\");\n }\n if (USER_BANNED.has(r)) {\n throw new Error(`user contains a disallowed character ${JSON.stringify(r)}`);\n }\n }\n}\n\n/** known_hosts host field: \"[host]:port\" when the port isn't the default 22. */\nexport function knownHostsHost(host: string, port: number): string {\n if (port > 0 && port !== 22) return `[${host}]:${port}`;\n return host;\n}\n\nexport function knownHostsPath(): string {\n return join(configDir(), \"known_hosts\");\n}\n\n/** True for a DNS hostname (e.g. the Cube's stable SSH hostname), false for a\n * bare IPv4/IPv6 address. */\nexport function isHostname(host: string): boolean {\n return isIP(host) === 0;\n}\n\n/** True when `host:port` has no existing known_hosts pin yet — used to print a\n * one-time note the first time we pin a Cube's hostname rather than its IP. */\nexport function isUnpinned(host: string, port: number): boolean {\n const field = knownHostsHost(host, port);\n let existing = \"\";\n try {\n existing = readFileSync(knownHostsPath(), \"utf8\");\n } catch {\n existing = \"\";\n }\n return !existing.split(\"\\n\").some((line) => line.split(/\\s+/)[0] === field);\n}\n\n/** Pin the cube's host keys to ~/.config/krova/known_hosts (0600), pruning any\n * stale line for the same host:port (rebuilt cubes can reuse an IP+DNAT port). */\nexport function writeKnownHosts(info: SshInfo): string {\n const path = knownHostsPath();\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const field = knownHostsHost(info.host, info.port);\n\n let existing = \"\";\n try {\n existing = readFileSync(path, \"utf8\");\n } catch {\n existing = \"\";\n }\n const kept = existing\n .split(\"\\n\")\n .filter((line) => line.trim() && line.split(/\\s+/)[0] !== field);\n writeFileSync(path, kept.length ? `${kept.join(\"\\n\")}\\n` : \"\", { mode: 0o600 });\n chmodSync(path, 0o600);\n\n for (const k of info.hostKeys) {\n appendFileSync(path, `${field} ${k.type} ${k.key}\\n`);\n }\n return path;\n}\n\n/** Build the ssh argv. `--` is placed immediately before the destination —\n * the primary option-injection guard (with the validators above). */\nexport function buildSSHArgs(info: SshInfo, o: SshOptions): string[] {\n const args: string[] = [...(o.preArgs ?? [])];\n if (o.knownHosts) {\n args.push(\"-o\", `UserKnownHostsFile=${o.knownHosts}`, \"-o\", \"StrictHostKeyChecking=yes\");\n }\n if ((o.identity ?? \"\").trim()) args.push(\"-i\", o.identity as string);\n if (info.port > 0) args.push(\"-p\", String(info.port));\n for (const l of o.localFwd ?? []) if (l.trim()) args.push(\"-L\", l);\n for (const r of o.remoteFwd ?? []) if (r.trim()) args.push(\"-R\", r);\n const user = info.user.trim();\n const target = user ? `${user}@${info.host}` : info.host;\n args.push(\"--\", target);\n args.push(...(o.remoteCmd ?? []));\n return args;\n}\n\n/** Exec system ssh, inheriting stdio (interactive unless a remote cmd is given). */\nexport function execSSH(args: string[]): Promise<number> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"ssh\", args, { stdio: \"inherit\" });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => resolve(code ?? 0));\n });\n}\n\n/** Map a child's (code, signal) to a shell-style exit code. */\nexport function exitCodeFor(code: number | null, signal: NodeJS.Signals | null): number {\n if (code !== null) return code;\n if (signal) return 128 + (osConstants.signals[signal] ?? 0);\n return 1;\n}\n\n/** Exec a binary with inherited stdio and resolve to its exit code. A signal\n * death maps to 128 + the signal number; a missing binary names itself. */\nexport function execInherit(bin: string, args: string[]): Promise<number> {\n return new Promise((resolve, reject) => {\n const child = spawn(bin, args, { stdio: \"inherit\" });\n // Ctrl+C already reaches the child through the terminal; a signal sent only\n // to this process (kill, a supervisor) is passed on, and we keep running\n // until the child has exited so its exit code is not lost.\n const forward = (sig: NodeJS.Signals) => {\n child.kill(sig);\n };\n const signals: NodeJS.Signals[] = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"];\n for (const sig of signals) process.on(sig, forward);\n const done = () => {\n for (const sig of signals) process.off(sig, forward);\n };\n child.on(\"error\", (err: NodeJS.ErrnoException) => {\n done();\n if (err.code === \"ENOENT\") reject(new Error(`\\`${bin}\\` was not found on your PATH`));\n else reject(err);\n });\n child.on(\"exit\", (code, signal) => {\n done();\n resolve(exitCodeFor(code, signal));\n });\n });\n}\n\nexport interface SshTarget {\n cubeId: string;\n info: SshInfo;\n /** Path of the pinned known_hosts file, or \"\" when the server sent no host keys. */\n knownHosts: string;\n}\n\n/** Resolve a Cube (name or ID) to its validated SSH endpoint and pin its host\n * keys. Shared by `ssh`, `tunnel`, `connect`, `psql`, `redis`, `mysql`, `exec`\n * and `cp`, so every one of them keeps the same strict host-key checking. */\nexport async function resolveSshTarget(\n cmd: Command,\n cubeRef: string,\n o: { requireHostKeys?: boolean } = {}\n): Promise<SshTarget> {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n\n const { status, data } = await rawRequest<SshInfo>({\n method: \"GET\",\n baseUrl: rt.res.baseUrl,\n path: `/spaces/${space}/cubes/${id}/ssh`,\n apiKey: rt.res.apiKey,\n timeoutMs: rt.timeoutMs,\n });\n if (status === 404) {\n throw new Error(\n `SSH info isn't available on this server yet — try \\`krova cubes get ${cubeRef}\\` for the Cube's IP and ssh manually`\n );\n }\n if (status === 401 || status === 403) {\n throw new Error(`SSH info request was rejected (HTTP ${status})`);\n }\n if (status !== 200 || !data?.host) {\n throw new Error(`couldn't fetch SSH info (HTTP ${status})`);\n }\n\n const info: SshInfo = {\n host: data.host,\n port: data.port ?? 0,\n user: data.user ?? \"\",\n hostKeys: data.hostKeys ?? [],\n };\n validateSSHHost(info.host);\n validateSSHUser(info.user);\n if (info.port < 0 || info.port > 65535) throw new Error(\"invalid ssh port\");\n\n if (o.requireHostKeys && !info.hostKeys.length) {\n // Fail closed: without a recorded key there is nothing to pin, and these\n // commands never fall back to trusting whatever key the host presents.\n throw new Error(\n \"Krova has no recorded host key for this Cube yet; use `krova ssh` to connect interactively\"\n );\n }\n\n let knownHosts = \"\";\n if (info.hostKeys.length) {\n if (isHostname(info.host) && isUnpinned(info.host, info.port)) {\n process.stderr.write(\n \"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\"\n );\n }\n knownHosts = writeKnownHosts(info);\n } else {\n process.stderr.write(\n \"note: this server didn't provide host keys — using ssh trust-on-first-use (host-key checking stays on).\\n\"\n );\n }\n return { cubeId: id, info, knownHosts };\n}\n\n// ── scp ────────────────────────────────────────────────────────────────────\n\nexport interface CpOperands {\n /** Cube name or ID of the one remote side. */\n cube: string;\n direction: \"upload\" | \"download\";\n /** Path on the Cube (may be empty: the login directory). */\n remotePath: string;\n /** Path on this machine, made safe to hand to scp as a local operand. */\n localPath: string;\n}\n\n/** Split `<cube>:<path>`. A prefix with a slash in it (`./a:b`, `/tmp/x:y`) is\n * a local path, and on Windows a one-letter prefix is a drive letter. */\nfunction splitRemote(arg: string): { cube: string; path: string } | undefined {\n const i = arg.indexOf(\":\");\n if (i <= 0) return undefined;\n const cube = arg.slice(0, i);\n if (cube.includes(\"/\") || cube.includes(\"\\\\\")) return undefined;\n if (process.platform === \"win32\" && cube.length === 1) return undefined;\n return { cube, path: arg.slice(i + 1) };\n}\n\n/** scp reads `a:b` as host `a`; a local path with a colon before its first\n * slash gets a `./` so it stays local. */\nfunction safeLocalPath(p: string): string {\n const colon = p.indexOf(\":\");\n // A Windows drive letter (`C:\\\\x`) is not a host.\n if (process.platform === \"win32\" && colon === 1) return p;\n const slash = p.indexOf(\"/\");\n if (colon !== -1 && (slash === -1 || colon < slash)) return `./${p}`;\n return p;\n}\n\n/** Decide which side of `krova cp` is the Cube. Exactly one must be. */\nexport function parseCpOperands(src: string, dst: string): CpOperands {\n if (!src || !dst) throw new Error(\"cp needs a source and a destination\");\n const s = splitRemote(src);\n const d = splitRemote(dst);\n if (s && d) {\n throw new Error(\"cp copies between this machine and a Cube: only one side can be <cube>:<path>\");\n }\n if (!s && !d) {\n throw new Error(\"one side must be a Cube path like <cube>:<path> (both sides are local)\");\n }\n const remote = (s ?? d) as { cube: string; path: string };\n if (remote.path.startsWith(\"-\")) {\n throw new Error(\"a remote path must not start with '-'\");\n }\n if (/[\\0\\r\\n]/.test(remote.path)) {\n throw new Error(\"a remote path must not contain control characters\");\n }\n return s\n ? { cube: s.cube, direction: \"download\", remotePath: s.path, localPath: safeLocalPath(dst) }\n : { cube: remote.cube, direction: \"upload\", remotePath: remote.path, localPath: safeLocalPath(src) };\n}\n\n/** Build the scp argv: strict host keys, `-P` port, and `--` before the operands. */\nexport function buildSCPArgs(\n info: SshInfo,\n o: { knownHosts?: string; identity?: string; recursive?: boolean; operands: CpOperands }\n): string[] {\n // scp splits `user@host:path` on colons, so neither part may carry one.\n const user = info.user.trim();\n if (/[:\\[\\]]/.test(user)) throw new Error(\"user contains a disallowed character\");\n if (info.host.includes(\":\") && isIP(info.host) !== 6) {\n throw new Error(\"host contains a disallowed character\");\n }\n const args: string[] = [];\n if (o.knownHosts) {\n args.push(\"-o\", `UserKnownHostsFile=${o.knownHosts}`, \"-o\", \"StrictHostKeyChecking=yes\");\n }\n if ((o.identity ?? \"\").trim()) args.push(\"-i\", o.identity as string);\n if (info.port > 0) args.push(\"-P\", String(info.port));\n if (o.recursive) args.push(\"-r\");\n const host = isIP(info.host) === 6 ? `[${info.host}]` : info.host;\n const remote = `${user ? `${user}@` : \"\"}${host}:${o.operands.remotePath}`;\n const { direction, localPath } = o.operands;\n args.push(\"--\", ...(direction === \"upload\" ? [localPath, remote] : [remote, localPath]));\n return args;\n}\n","// Private tunnels: `ssh -N -L 127.0.0.1:<local>:localhost:<cube port>` over the\n// same strict host-key path as `krova ssh`, plus the helpers the database\n// client commands use (free loopback port, readiness wait, client on PATH).\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { accessSync, constants, statSync } from \"node:fs\";\nimport { createServer, connect } from \"node:net\";\nimport { delimiter, join } from \"node:path\";\n\nimport { type SshInfo, buildSSHArgs, exitCodeFor } from \"./ssh.js\";\n\n/** The only address a tunnel ever binds. Never 0.0.0.0. */\nexport const LOOPBACK = \"127.0.0.1\";\n\n/** Parse a TCP port: digits only, 1 to 65535. */\nexport function parsePort(value: string, label: string): number {\n const s = String(value ?? \"\").trim();\n const n = Number(s);\n if (!/^\\d{1,5}$/.test(s) || !Number.isInteger(n) || n < 1 || n > 65535) {\n throw new Error(`${label} must be a whole number from 1 to 65535`);\n }\n return n;\n}\n\n/** Parse `[localPort:]cubePort`. The local port defaults to the Cube port. */\nexport function parseTunnelSpec(spec: string): { localPort: number; cubePort: number } {\n const m = /^(\\d+)(?::(\\d+))?$/.exec(String(spec ?? \"\").trim());\n if (!m) {\n throw new Error(`invalid port spec \"${spec}\": use <cubePort> or <localPort>:<cubePort>`);\n }\n if (m[2] === undefined) {\n const cubePort = parsePort(m[1] as string, \"cube port\");\n return { localPort: cubePort, cubePort };\n }\n return {\n localPort: parsePort(m[1] as string, \"local port\"),\n cubePort: parsePort(m[2], \"cube port\"),\n };\n}\n\n/** Build the tunnel argv: loopback-only bind, no remote command, and ssh exits\n * if the forward cannot be set up. Host keys stay strictly checked. */\nexport function buildTunnelArgs(\n info: SshInfo,\n o: { identity?: string; knownHosts?: string; localPort: number; cubePort: number }\n): string[] {\n return buildSSHArgs(info, {\n preArgs: [\"-N\", \"-o\", \"ExitOnForwardFailure=yes\"],\n identity: o.identity,\n knownHosts: o.knownHosts,\n localFwd: [`${LOOPBACK}:${o.localPort}:localhost:${o.cubePort}`],\n });\n}\n\n/** Ask the OS for a free loopback port (bind to port 0, read it, release it). */\nexport function freeLoopbackPort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const srv = createServer();\n srv.once(\"error\", reject);\n srv.listen(0, LOOPBACK, () => {\n const addr = srv.address();\n if (addr && typeof addr === \"object\") {\n const { port } = addr;\n srv.close(() => resolve(port));\n } else {\n srv.close(() => reject(new Error(\"couldn't find a free local port\")));\n }\n });\n });\n}\n\nfunction canConnect(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const sock = connect({ host: LOOPBACK, port });\n sock.once(\"connect\", () => {\n sock.destroy();\n resolve(true);\n });\n sock.once(\"error\", () => {\n sock.destroy();\n resolve(false);\n });\n });\n}\n\nconst READY_GRACE_MS = 150;\n\n/** Wait until the local forward accepts a connection. ssh opens the listener\n * once it has authenticated, so a refused connect means \"not yet\": retry with a\n * short growing delay and stop at once if ssh exits or attempts run out. */\nexport async function waitForPort(\n port: number,\n ssh: { exited: Promise<number> },\n maxAttempts = 480\n): Promise<\"ready\" | \"ssh-exited\" | \"timeout\"> {\n let sshDone = false;\n const markDone = () => {\n sshDone = true;\n };\n void ssh.exited.then(markDone, markDone);\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n if (sshDone) return \"ssh-exited\";\n if (await canConnect(port)) {\n // Something answered. If another process holds the port, ssh fails to bind\n // (ExitOnForwardFailure) and exits right after: give it a short bounded\n // moment to do so, and only call the tunnel ready if ssh is still running.\n await Promise.race([\n ssh.exited.then(markDone, markDone),\n new Promise((r) => setTimeout(r, READY_GRACE_MS)),\n ]);\n return sshDone ? \"ssh-exited\" : \"ready\";\n }\n await new Promise((r) => setTimeout(r, Math.min(20 * 2 ** Math.min(attempt, 4), 250)));\n }\n return \"timeout\";\n}\n\n/** True when `name` is an executable file in one of the PATH directories. */\nexport function findOnPath(name: string, env: NodeJS.ProcessEnv = process.env): boolean {\n const exts =\n process.platform === \"win32\"\n ? [\"\", ...(env.PATHEXT ?? \".EXE;.CMD;.BAT\").split(\";\").filter(Boolean)]\n : [\"\"];\n for (const dir of (env.PATH ?? \"\").split(delimiter)) {\n if (!dir) continue;\n for (const ext of exts) {\n const file = join(dir, name + ext);\n try {\n if (!statSync(file).isFile()) continue;\n accessSync(file, constants.X_OK);\n return true;\n } catch {\n // not here\n }\n }\n }\n return false;\n}\n\nexport interface Spawned {\n child: ChildProcess;\n /** Resolves with a shell-style exit code when the process ends. */\n exited: Promise<number>;\n}\n\n/** Start the tunnel's ssh. stdin and stdout are not used (ssh prompts for a\n * passphrase on the terminal itself); stderr stays visible.\n *\n * `ignoreSigint` keeps a terminal Ctrl+C (sent to the whole foreground process\n * group) from killing the tunnel while a database client is using it: ssh is\n * started through `sh` with SIGINT ignored, which survives the exec. It is NOT\n * `detached: true`, because that calls setsid(), so ssh would lose the\n * controlling terminal and could no longer ask for a key passphrase. */\nexport function spawnTunnel(args: string[], o: { ignoreSigint?: boolean } = {}): Spawned {\n const stdio: [\"ignore\", \"ignore\", \"inherit\"] = [\"ignore\", \"ignore\", \"inherit\"];\n const child =\n o.ignoreSigint && process.platform !== \"win32\"\n ? spawn(\"/bin/sh\", [\"-c\", 'trap \"\" INT; exec ssh \"$@\"', \"sh\", ...args], { stdio })\n : spawn(\"ssh\", args, { stdio });\n const exited = new Promise<number>((resolve, reject) => {\n child.once(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") reject(new Error(\"`ssh` was not found on your PATH\"));\n else reject(err);\n });\n child.once(\"exit\", (code, signal) => resolve(exitCodeFor(code, signal)));\n });\n return { child, exited };\n}\n\nconst STOP_SIGNALS: NodeJS.Signals[] = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"];\n\n/** Hold a tunnel open until it ends. Ctrl+C (or SIGTERM) stops it cleanly and\n * exits 0; otherwise the exit code is ssh's own. `onReady` runs once the local\n * port accepts connections, when a `readyPort` is given. */\nexport async function holdTunnel(\n args: string[],\n opts: { readyPort?: number; onReady?: () => void } = {}\n): Promise<number> {\n const ssh = spawnTunnel(args);\n let stopped = false;\n const stop = (sig: NodeJS.Signals) => {\n stopped = true;\n ssh.child.kill(sig);\n };\n for (const sig of STOP_SIGNALS) process.on(sig, stop);\n try {\n if (opts.readyPort !== undefined) {\n const state = await waitForPort(opts.readyPort, ssh);\n if (state === \"ready\") {\n opts.onReady?.();\n } else if (state === \"timeout\") {\n ssh.child.kill(\"SIGTERM\");\n await ssh.exited;\n throw new Error(\"the tunnel didn't come up in time\");\n }\n }\n const code = await ssh.exited;\n return stopped ? 0 : code;\n } finally {\n for (const sig of STOP_SIGNALS) process.off(sig, stop);\n }\n}\n\n/** Open a tunnel, run `client` against the local port with stdio inherited,\n * then close the tunnel. Exits with the client's code. */\nexport async function runClientThroughTunnel(o: {\n sshArgs: string[];\n localPort: number;\n client: string;\n clientArgs: string[];\n}): Promise<number> {\n const ssh = spawnTunnel(o.sshArgs, { ignoreSigint: true });\n let client: ChildProcess | undefined;\n const onSignal = (sig: NodeJS.Signals) => {\n if (sig === \"SIGINT\") {\n // Once the client runs, Ctrl+C belongs to it (psql cancels the query) and\n // the tunnel ignores it. Before that, it is how the user gives up waiting.\n if (!client) ssh.child.kill(\"SIGTERM\");\n return;\n }\n client?.kill(sig);\n ssh.child.kill(sig);\n };\n // Never leave the tunnel behind, whatever way this process ends.\n const killTunnel = () => {\n if (ssh.child.exitCode === null && ssh.child.signalCode === null) ssh.child.kill(\"SIGTERM\");\n };\n process.on(\"exit\", killTunnel);\n for (const sig of STOP_SIGNALS) process.on(sig, onSignal);\n try {\n const state = await waitForPort(o.localPort, ssh);\n if (state === \"ssh-exited\") {\n const code = await ssh.exited;\n throw new Error(`ssh exited (code ${code}) before the tunnel was ready`);\n }\n if (state === \"timeout\") {\n ssh.child.kill(\"SIGTERM\");\n await ssh.exited;\n throw new Error(\"the tunnel didn't come up in time\");\n }\n const running = spawn(o.client, o.clientArgs, { stdio: \"inherit\" });\n client = running;\n return await new Promise<number>((resolve, reject) => {\n running.once(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") reject(new Error(`\\`${o.client}\\` was not found on your PATH`));\n else reject(err);\n });\n running.once(\"exit\", (code, signal) => resolve(exitCodeFor(code, signal)));\n });\n } finally {\n killTunnel();\n await ssh.exited.catch(() => 0);\n for (const sig of STOP_SIGNALS) process.off(sig, onSignal);\n process.off(\"exit\", killTunnel);\n }\n}\n","import { Command } from \"commander\";\n\nimport { resolveSshTarget } from \"../lib/ssh.js\";\nimport {\n LOOPBACK,\n buildTunnelArgs,\n findOnPath,\n freeLoopbackPort,\n parsePort,\n runClientThroughTunnel,\n} from \"../lib/tunnel.js\";\n\nconst PRIVATE_NOTE =\n \"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.\";\n\n/** A user or database name: no leading `-`, nothing a client could read as a\n * connection string (`=`, `:`, `/`, spaces). */\nconst IDENT = /^[A-Za-z0-9_][A-Za-z0-9_.$-]{0,62}$/;\n\nexport function validateIdent(value: string, label: string): string {\n if (!IDENT.test(value)) {\n throw new Error(\n `${label} may only use letters, digits, '_', '.', '$' and '-', and must not start with '-'`\n );\n }\n return value;\n}\n\nexport interface DbClientSpec {\n command: string;\n client: string;\n defaultPort: number;\n description: string;\n userDefault?: string;\n dbDefault?: string;\n clientArgs(o: { port: number; user?: string; db?: string }): string[];\n}\n\nexport const DB_CLIENTS: DbClientSpec[] = [\n {\n command: \"psql\",\n client: \"psql\",\n defaultPort: 5432,\n userDefault: \"postgres\",\n dbDefault: \"postgres\",\n description: \"open psql against a PostgreSQL server in a Cube\",\n clientArgs: ({ port, user, db }) => [\n \"-h\",\n LOOPBACK,\n \"-p\",\n String(port),\n \"-U\",\n user as string,\n \"-d\",\n db as string,\n ],\n },\n {\n command: \"redis\",\n client: \"redis-cli\",\n defaultPort: 6379,\n description: \"open redis-cli against a Redis server in a Cube\",\n clientArgs: ({ port }) => [\"-h\", LOOPBACK, \"-p\", String(port)],\n },\n {\n command: \"mysql\",\n client: \"mysql\",\n defaultPort: 3306,\n userDefault: \"root\",\n description: \"open mysql against a MySQL or MariaDB server in a Cube\",\n clientArgs: ({ port, user, db }) => [\n \"-h\",\n LOOPBACK,\n \"-P\",\n String(port),\n \"--protocol=tcp\",\n \"-u\",\n user as string,\n ...(db ? [`--database=${db}`] : []),\n ],\n },\n];\n\nfunction dbClientCommand(spec: DbClientSpec): Command {\n const c = new Command(spec.command)\n .argument(\"<cube>\", \"cube name or ID\")\n .description(`${spec.description}. ${PRIVATE_NOTE}`)\n .option(\"--port <cubePort>\", `port inside the Cube (default ${spec.defaultPort})`)\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to ssh -i\");\n if (spec.userDefault) {\n // Commander appends `(default: \"<value>\")` itself when a default is passed.\n c.option(\"--user <user>\", \"database user\", spec.userDefault);\n }\n if (spec.command === \"psql\") c.option(\"--db <name>\", \"database name\", \"postgres\");\n if (spec.command === \"mysql\") c.option(\"--db <name>\", \"database to use\");\n return c.action(async (cubeRef: string, opts, cmd: Command) => {\n // Check everything that needs no network first, so a typo or a missing\n // client fails before any tunnel is opened.\n const cubePort =\n opts.port !== undefined ? parsePort(opts.port as string, \"--port\") : spec.defaultPort;\n const user = spec.userDefault ? validateIdent(opts.user as string, \"--user\") : undefined;\n const db = opts.db ? validateIdent(opts.db as string, \"--db\") : undefined;\n if (!findOnPath(spec.client)) {\n throw new Error(`\\`${spec.client}\\` was not found on your PATH — install it and try again`);\n }\n\n const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });\n const localPort = await freeLoopbackPort();\n const sshArgs = buildTunnelArgs(info, {\n identity: opts.identity as string | undefined,\n knownHosts,\n localPort,\n cubePort,\n });\n process.exitCode = await runClientThroughTunnel({\n sshArgs,\n localPort,\n client: spec.client,\n clientArgs: spec.clientArgs({ port: localPort, user, db }),\n });\n });\n}\n\nexport const psqlCommand = () => dbClientCommand(DB_CLIENTS[0] as DbClientSpec);\nexport const redisCommand = () => dbClientCommand(DB_CLIENTS[1] as DbClientSpec);\nexport const mysqlCommand = () => dbClientCommand(DB_CLIENTS[2] as DbClientSpec);\n","import { Command } from \"commander\";\n\nimport {\n buildSCPArgs,\n buildSSHArgs,\n execInherit,\n parseCpOperands,\n resolveSshTarget,\n} from \"../lib/ssh.js\";\n\nexport function execCommand(): Command {\n return new Command(\"exec\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<command...>\", \"command to run (after --)\")\n .description(\n \"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.\"\n )\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to ssh -i\")\n .action(async (cubeRef: string, command: string[], opts, cmd: Command) => {\n if (!command.some((w) => w.trim())) {\n throw new Error(\"exec needs a command to run, e.g. krova exec <cube> -- uname -a\");\n }\n const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });\n const args = buildSSHArgs(info, {\n preArgs: [\"-T\"],\n identity: opts.identity as string | undefined,\n knownHosts,\n remoteCmd: command,\n });\n process.exitCode = await execInherit(\"ssh\", args);\n });\n}\n\nexport function cpCommand(): Command {\n return new Command(\"cp\")\n .argument(\"<src>\", \"source: a local path or <cube>:<path>\")\n .argument(\"<dst>\", \"destination: a local path or <cube>:<path>\")\n .description(\n \"copy files between this machine and a Cube over scp. Exactly one side is <cube>:<path> (cube by name or ID).\"\n )\n .option(\"-r, --recursive\", \"copy directories recursively\")\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to scp -i\")\n .action(async (src: string, dst: string, opts, cmd: Command) => {\n const operands = parseCpOperands(src, dst);\n const { info, knownHosts } = await resolveSshTarget(cmd, operands.cube, { requireHostKeys: true });\n const args = buildSCPArgs(info, {\n knownHosts,\n identity: opts.identity as string | undefined,\n recursive: Boolean(opts.recursive),\n operands,\n });\n process.exitCode = await execInherit(\"scp\", args);\n });\n}\n","import { Command } from \"commander\";\n\nimport { buildSSHArgs, execSSH, resolveSshTarget } from \"../lib/ssh.js\";\n\nconst collect = (v: string, acc: string[]) => {\n acc.push(v);\n return acc;\n};\n\nexport function sshCommand(): Command {\n return new Command(\"ssh\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"[command...]\", \"command to run non-interactively (after --)\")\n .description(\"open an SSH session to a Cube (by name or ID)\")\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to ssh -i\")\n .option(\"-L, --local-forward <spec>\", \"local port forward, passed to ssh -L (repeatable)\", collect, [])\n .option(\"-R, --remote-forward <spec>\", \"remote port forward, passed to ssh -R (repeatable)\", collect, [])\n .action(async (cubeRef: string, command: string[], opts, cmd: Command) => {\n const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef);\n const args = buildSSHArgs(info, {\n identity: opts.identity as string | undefined,\n localFwd: opts.localForward as string[],\n remoteFwd: opts.remoteForward as string[],\n knownHosts,\n remoteCmd: command,\n });\n process.exitCode = await execSSH(args);\n });\n}\n","import { Command } from \"commander\";\n\nimport { printJSON } from \"../lib/output.js\";\nimport { resolveSshTarget } from \"../lib/ssh.js\";\nimport {\n LOOPBACK,\n buildTunnelArgs,\n freeLoopbackPort,\n holdTunnel,\n parsePort,\n parseTunnelSpec,\n} from \"../lib/tunnel.js\";\n\nconst PRIVATE_NOTE =\n \"The port is reachable only from this machine, over your SSH key. Prefer it to a public `krova tcp add` mapping for databases.\";\n\nfunction announceForwarding(localPort: number, cubeRef: string, cubePort: number): void {\n process.stderr.write(\n `Forwarding localhost:${localPort} -> ${cubeRef}:${cubePort}. Press Ctrl+C to stop.\\n`\n );\n}\n\nexport function tunnelCommand(): Command {\n return new Command(\"tunnel\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<ports>\", \"[localPort:]cubePort (the local port defaults to the Cube port)\")\n .description(\n `forward a local port to a port inside a Cube over SSH. ${PRIVATE_NOTE}`\n )\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to ssh -i\")\n .action(async (cubeRef: string, spec: string, opts, cmd: Command) => {\n const { localPort, cubePort } = parseTunnelSpec(spec);\n const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });\n const args = buildTunnelArgs(info, {\n identity: opts.identity as string | undefined,\n knownHosts,\n localPort,\n cubePort,\n });\n // Say \"Forwarding\" only once the local port is listening, so the line is\n // never printed for a tunnel that failed to come up.\n process.exitCode = await holdTunnel(args, {\n readyPort: localPort,\n onReady: () => announceForwarding(localPort, cubeRef, cubePort),\n });\n });\n}\n\nexport function connectCommand(): Command {\n return new Command(\"connect\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\n `open a private tunnel to a Cube port on a free local port and print the local endpoint. ${PRIVATE_NOTE}`\n )\n .requiredOption(\"--port <cubePort>\", \"port inside the Cube to reach\")\n .option(\"--local-port <port>\", \"local port to listen on (default: a free one)\")\n .option(\"-i, --identity <file>\", \"SSH identity (private key) file, passed to ssh -i\")\n .action(async (cubeRef: string, opts, cmd: Command) => {\n const cubePort = parsePort(opts.port as string, \"--port\");\n const localPort =\n opts.localPort !== undefined\n ? parsePort(opts.localPort as string, \"--local-port\")\n : await freeLoopbackPort();\n const json = Boolean(cmd.optsWithGlobals().json);\n const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });\n const args = buildTunnelArgs(info, {\n identity: opts.identity as string | undefined,\n knownHosts,\n localPort,\n cubePort,\n });\n process.exitCode = await holdTunnel(args, {\n readyPort: localPort,\n onReady: () => {\n if (json) {\n printJSON({ host: LOOPBACK, port: localPort, cube: cubeRef, cubePort });\n } else {\n process.stdout.write(`localhost:${localPort}\\n`);\n }\n announceForwarding(localPort, cubeRef, cubePort);\n },\n });\n });\n}\n","import { Command } from \"commander\";\n\nimport { mappingConnectTarget, printJSON, printTable } from \"../lib/output.js\";\nimport { resolveCube } from \"../lib/resolve.js\";\nimport {\n confirm,\n isOpenWhitelist,\n printAborted,\n publicExposureWarning,\n shouldConfirm,\n} from \"../lib/safety.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\n\n/** `krova tcp` — manage a Cube's TCP port mappings. */\nexport function tcpCommand(): Command {\n const cmd = new Command(\"tcp\").description(\"manage a Cube's TCP port mappings\");\n\n cmd\n .command(\"list\")\n .argument(\"<cube>\", \"cube name or ID\")\n .description(\"list a Cube's TCP port mappings\")\n .action(async (cubeRef: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const maps = await client.tcpMappings.list(space, id);\n if (rt.json) return printJSON(maps);\n // CONNECT is what a reader actually needs: the table used to print a\n // host port with no host, so building a connect string meant a second\n // command and knowing to combine the two. `host` is the Cube's own\n // stable name (it survives migration), so this string keeps working\n // after the Cube moves — unlike the server's hostname.\n printTable(\n [\n \"ID\",\n \"CUBE PORT\",\n \"CONNECT\",\n \"LABEL\",\n \"STATUS\",\n \"SSH\",\n \"UDP\",\n ],\n maps.map((m) => [\n m.id,\n String(m.cubePort),\n mappingConnectTarget(m),\n m.label ?? \"\",\n m.status,\n m.isSsh ? \"yes\" : \"no\",\n m.udpEnabled ? \"yes\" : \"no\",\n ]),\n );\n });\n\n cmd\n .command(\"add\")\n .argument(\"<cube>\", \"cube name or ID\")\n .requiredOption(\"--port <n>\", \"the in-Cube port to expose\")\n .option(\n \"--whitelist <cidr>\",\n \"restrict access to this IP/CIDR (repeatable)\",\n (val: string, acc: string[]) => {\n acc.push(val);\n return acc;\n },\n [] as string[],\n )\n .option(\"-y, --yes\", \"skip the confirmation prompt when the port would be open to the whole internet\")\n .option(\"--no-udp\", \"don't forward UDP on this port (UDP is forwarded by default alongside TCP)\")\n .description(\"expose a Cube TCP port on the host, optionally IP-restricted\")\n .action(async (cubeRef: string, opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n const cubePort = Number(opts.port);\n if (!Number.isInteger(cubePort) || cubePort <= 0 || cubePort > 65535) {\n throw new Error(`--port must be a valid port (got \"${opts.port}\").`);\n }\n const whitelist = opts.whitelist as string[];\n // A port with no whitelist (or 0.0.0.0/0, ::/0) is open to everyone. Warn on\n // stderr every time; only a person at a terminal is asked to confirm, so a\n // script keeps working unchanged.\n if (isOpenWhitelist(whitelist)) {\n process.stderr.write(`${publicExposureWarning(cubeRef, cubePort)}\\n`);\n if (shouldConfirm(opts)) {\n const ok = await confirm(\"Open this port to the whole internet? [y/N] \");\n if (!ok) return printAborted(rt.json);\n }\n }\n // ⛔ `whitelistedIps` — NOT `whitelistIps`. The published spec named the\n // field `whitelistIps` while the server has always read\n // `whitelistedIps`, so every `--whitelist` mapping this CLI created was\n // silently published WORLD-OPEN, with a 201 and no error. Reproduced on\n // production 2026-09-02: a mapping added with `--whitelist\n // 203.0.113.0/24` served content to an off-list address.\n //\n // The server now accepts both names, so an older CLI keeps working; this\n // sends the canonical one.\n //\n // ⛔ `udpEnabled` — omit it unless `--no-udp` was passed. The server\n // defaults `udpEnabled` to `true` when the field is absent, so this must\n // NOT send `udpEnabled: opts.udp` (commander defaults `opts.udp` to\n // `true`, but sending that explicitly is fine — sending `false` on mere\n // silence would not be). Only `--no-udp` sets `opts.udp` to `false`, and\n // only then do we send the field at all.\n const mapping = await client.tcpMappings.create(space, id, {\n cubePort,\n ...(whitelist.length ? { whitelistedIps: whitelist } : {}),\n ...(opts.udp === false ? { udpEnabled: false } : {}),\n });\n if (rt.json) return printJSON(mapping);\n // Say where to reach it, not just which port was picked — the point of\n // adding a mapping is to connect to it. Falls back to the bare port if\n // the Cube has no host yet (no server assigned).\n process.stdout.write(\n `Mapped cube port ${mapping.cubePort} → ${mappingConnectTarget(mapping)} (${mapping.id})\\n`,\n );\n });\n\n cmd\n .command(\"rm\")\n .argument(\"<cube>\", \"cube name or ID\")\n .argument(\"<mapping-id>\", \"the mapping ID (see `krova tcp list`)\")\n .description(\"remove a TCP port mapping\")\n .action(async (cubeRef: string, mappingId: string, _opts, c: Command) => {\n const rt = getRuntime(c);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const id = await resolveCube(client, space, cubeRef);\n await client.tcpMappings.delete(space, id, mappingId);\n if (rt.json) return printJSON({ id: mappingId, result: \"removed\" });\n process.stdout.write(`Removed TCP mapping ${mappingId}\\n`);\n });\n\n return cmd;\n}\n","/** A MAJOR.MINOR.PATCH version, plus its pre-release part when it has one. */\ninterface ParsedVersion {\n core: [number, number, number];\n pre: string[];\n}\n\nexport function parseVersion(input: string): ParsedVersion | undefined {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/.exec(\n input.trim()\n );\n if (!m) return undefined;\n const [major, minor, patch] = [m[1], m[2], m[3]];\n if (major === undefined || minor === undefined || patch === undefined) return undefined;\n const pre = m[4];\n return {\n core: [Number(major), Number(minor), Number(patch)],\n pre: pre ? pre.split(\".\") : [],\n };\n}\n\n/** Semver ordering of two pre-release parts: numeric identifiers below\n * alphanumeric ones, numbers compared as numbers, everything else as text. */\nfunction comparePre(a: string[], b: string[]): number {\n // No pre-release outranks any pre-release of the same release.\n if (a.length === 0 || b.length === 0) return b.length - a.length;\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n const x = a[i] ?? \"\";\n const y = b[i] ?? \"\";\n const xNum = /^\\d+$/.test(x);\n const yNum = /^\\d+$/.test(y);\n if (xNum && yNum) {\n const diff = Number(x) - Number(y);\n if (diff !== 0) return diff;\n continue;\n }\n if (xNum !== yNum) return xNum ? -1 : 1;\n if (x !== y) return x < y ? -1 : 1;\n }\n return a.length - b.length;\n}\n\n/** Negative when `a` is older than `b`, zero when equal, positive when newer.\n * A pre-release sorts below the release it leads to (1.0.0-rc.1 < 1.0.0).\n * Throws on input that is not MAJOR.MINOR.PATCH[-pre][+build]. */\nexport function compareVersions(a: string, b: string): number {\n const va = parseVersion(a);\n const vb = parseVersion(b);\n if (!va) throw new Error(`not a version: ${a}`);\n if (!vb) throw new Error(`not a version: ${b}`);\n for (let i = 0; i < 3; i++) {\n const diff = (va.core[i] ?? 0) - (vb.core[i] ?? 0);\n if (diff !== 0) return diff;\n }\n return comparePre(va.pre, vb.pre);\n}\n","import { createRequire } from \"node:module\";\n\nimport { Command } from \"commander\";\n\nimport { printJSON } from \"../lib/output.js\";\nimport { getRuntime } from \"../lib/runtime.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\") as { version: string };\n\nexport const CLI_VERSION = pkg.version;\n\nexport function versionCommand(): Command {\n return new Command(\"version\")\n .description(\"print the krova CLI version\")\n .action((_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const info = {\n version: CLI_VERSION,\n node: process.version,\n platform: `${process.platform}/${process.arch}`,\n };\n if (rt.json) return printJSON(info);\n process.stdout.write(`krova ${info.version} (node ${info.node}, ${info.platform})\\n`);\n });\n}\n","import { Command } from \"commander\";\n\nimport { ENV } from \"../lib/config.js\";\nimport { printJSON } from \"../lib/output.js\";\nimport { getRuntime } from \"../lib/runtime.js\";\nimport { compareVersions, parseVersion } from \"../lib/semver.js\";\nimport { CLI_VERSION } from \"./version.js\";\n\nconst DEFAULT_REGISTRY = \"https://registry.npmjs.org\";\nconst UPDATE_COMMAND = \"npm install -g @krovacloud/cli@latest\";\n/** Checking npm is a quick metadata lookup, so never wait longer than this,\n * even when the global --timeout is larger. */\nconst CHECK_TIMEOUT_CAP_MS = 10_000;\n\n/** One reason line, plus a hint when the failure looks like the network —\n * the top-level handler names the API base URL for any connection failure,\n * which would be wrong here: this check talks to npm, not to Krova. */\nfunction failureFor(err: unknown, timeoutMs: number): { reason: string; hint?: string } {\n const mirrorHint = `Check your connection or set ${ENV.npmRegistry} to use an npm mirror.`;\n if (!(err instanceof Error)) return { reason: String(err) };\n const code = (err as Error & { code?: unknown }).code;\n if (err.name === \"TimeoutError\" || err.name === \"AbortError\" || code === \"ABORT_ERR\") {\n return { reason: `timed out after ${timeoutMs / 1000}s`, hint: mirrorHint };\n }\n const cause = (err as Error & { cause?: unknown }).cause;\n if (\n cause &&\n typeof cause === \"object\" &&\n typeof (cause as { message?: unknown }).message === \"string\"\n ) {\n return { reason: (cause as { message: string }).message, hint: mirrorHint };\n }\n return { reason: err.message, hint: err.message === \"fetch failed\" ? mirrorHint : undefined };\n}\n\nfunction registryError(reason: string, hint?: string): Error {\n const err = new Error(`could not check the npm registry: ${reason}`);\n return hint ? Object.assign(err, { hint }) : err;\n}\n\n/** The canonical MAJOR.MINOR.PATCH[-prerelease] form: no leading v, no +build metadata. */\nfunction formatVersion(parsed: { core: [number, number, number]; pre: string[] }): string {\n const [major, minor, patch] = parsed.core;\n const pre = parsed.pre.length > 0 ? `-${parsed.pre.join(\".\")}` : \"\";\n return `${major}.${minor}.${patch}${pre}`;\n}\n\n/** The registry's latest published version, normalized, e.g. \"0.7.0\". */\nasync function fetchLatestVersion(baseUrl: string, timeoutMs: number): Promise<string> {\n const base = (baseUrl || DEFAULT_REGISTRY).replace(/\\/+$/, \"\");\n let res: Response;\n try {\n res = await fetch(`${base}/@krovacloud%2fcli/latest`, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (err) {\n const failure = failureFor(err, timeoutMs);\n throw registryError(failure.reason, failure.hint);\n }\n if (!res.ok) throw registryError(`the registry answered HTTP ${res.status}`);\n let body: unknown;\n try {\n body = await res.json();\n } catch (err) {\n // The timeout can fire while the body streams in; that is a timeout, not bad JSON.\n if (err instanceof Error && (err.name === \"TimeoutError\" || err.name === \"AbortError\")) {\n const failure = failureFor(err, timeoutMs);\n throw registryError(failure.reason, failure.hint);\n }\n throw registryError(\"the response was not valid JSON\");\n }\n const version = (body as { version?: unknown } | null)?.version;\n const parsed = typeof version === \"string\" ? parseVersion(version) : undefined;\n if (!parsed) {\n throw registryError(\"the response did not name a version\");\n }\n return formatVersion(parsed);\n}\n\nexport function updateCommand(): Command {\n return new Command(\"update\")\n .description(\"check the npm registry for a newer krova CLI (never installs)\")\n .action(async (_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const latest = await fetchLatestVersion(\n process.env[ENV.npmRegistry] ?? \"\",\n Math.min(rt.timeoutMs, CHECK_TIMEOUT_CAP_MS)\n );\n const current = CLI_VERSION;\n const updateAvailable = compareVersions(latest, current) > 0;\n\n if (rt.json) {\n return printJSON({ current, latest, updateAvailable, command: UPDATE_COMMAND });\n }\n process.stdout.write(\n updateAvailable\n ? `krova ${latest} is available (you have ${current}). Update with: ${UPDATE_COMMAND}\\n`\n : `krova ${latest} is the latest version.\\n`\n );\n });\n}\n","import { createServer } from \"node:http\";\nimport * as readline from \"node:readline\";\n\nimport type { components } from \"@krovacloud/sdk\";\nimport { krovaErrorFrom } from \"@krovacloud/sdk\";\nimport { verifyKrovaWebhookOrThrow } from \"@krovacloud/webhook\";\nimport { Command } from \"commander\";\n\nimport { printJSON, printKeyValue, printTable } from \"../lib/output.js\";\nimport { getRuntime, makeClient, resolveSpace } from \"../lib/runtime.js\";\n\nconst DEFAULT_LISTEN_HOST = \"127.0.0.1\";\nconst DEFAULT_LISTEN_PORT = 4666;\n\n/**\n * Parse a `--addr` value into `{ host, port }`. Handles `host:port`, a bare host\n * (e.g. `localhost`), a bare port, bracketed IPv6 (`[::1]:4666`), and bare IPv6\n * (`::1`). Exported for testing.\n */\nexport function parseListenAddr(addr: string): { host: string; port: number } {\n const s = (addr ?? \"\").trim();\n // Bracketed IPv6: [::1] or [::1]:4666\n const bracket = s.match(/^\\[([^\\]]+)\\](?::(\\d+))?$/);\n if (bracket) {\n return { host: bracket[1] as string, port: bracket[2] ? Number(bracket[2]) : DEFAULT_LISTEN_PORT };\n }\n // Two or more colons and no brackets ⇒ a bare IPv6 address with no port.\n if ((s.match(/:/g)?.length ?? 0) >= 2) {\n return { host: s, port: DEFAULT_LISTEN_PORT };\n }\n // Single colon ⇒ host:port.\n const i = s.lastIndexOf(\":\");\n if (i > 0) {\n const port = Number(s.slice(i + 1));\n return {\n host: s.slice(0, i),\n port: Number.isInteger(port) && port > 0 && port <= 65535 ? port : DEFAULT_LISTEN_PORT,\n };\n }\n // No colon ⇒ a bare port (all digits) or a bare host.\n if (/^\\d+$/.test(s)) {\n const port = Number(s);\n return { host: DEFAULT_LISTEN_HOST, port: port > 0 && port <= 65535 ? port : DEFAULT_LISTEN_PORT };\n }\n return { host: s || DEFAULT_LISTEN_HOST, port: DEFAULT_LISTEN_PORT };\n}\n\nexport function webhooksCommand(): Command {\n const wh = new Command(\"webhooks\").description(\"developer tools for Krova Cloud webhooks\");\n\n // A webhook endpoint as the API returns it. The list endpoint omits\n // `description`; POST and GET /:id include it. Keep it optional so a single\n // type covers both shapes without inventing fields the server didn't send.\n type Webhook = components[\"schemas\"][\"Webhook\"] & { description?: string | null };\n type WebhookWithSecret = Webhook & { secret: string };\n type WebhookDelivery = components[\"schemas\"][\"WebhookDelivery\"];\n\n /** Read a y/N line from stdin. Empty / non-y answers count as \"no\". */\n function confirm(question: string): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n rl.question(question, (answer) => {\n rl.close();\n resolve(/^y(es)?$/i.test(answer.trim()));\n });\n });\n }\n\n wh\n .command(\"list\")\n .description(\"list webhook endpoints in the active space\")\n .action(async (_opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const { data, error, response } = await client.raw.GET(\n \"/spaces/{spaceId}/webhooks\",\n { params: { path: { spaceId: space } } },\n );\n if (!response.ok) throw krovaErrorFrom(response, error);\n const { webhooks } = data as unknown as { webhooks: Webhook[] };\n if (rt.json) return printJSON(webhooks);\n printTable(\n [\"ID\", \"URL\", \"DESCRIPTION\", \"EVENTS\", \"ENABLED\", \"CREATED AT\"],\n webhooks.map((w) => [\n w.id,\n w.url,\n w.description ?? \"—\",\n w.events.join(\",\"),\n String(w.enabled),\n w.createdAt,\n ]),\n );\n });\n\n wh\n .command(\"add\")\n .description(\"create a webhook endpoint (signing secret shown once)\")\n .requiredOption(\"--url <url>\", \"the URL Krova should POST events to\")\n .requiredOption(\n \"--events <list>\",\n \"comma-separated event names (e.g. cube.running,cube.stopped)\",\n )\n .option(\"--description <text>\", \"human-readable description for this endpoint\")\n .action(async (opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const events = String(opts.events)\n .split(\",\")\n .map((e) => e.trim())\n .filter(Boolean);\n if (events.length === 0) {\n throw new Error(\"--events must list at least one event (e.g. cube.running).\");\n }\n const body: { url: string; events: string[]; description?: string } = {\n url: String(opts.url),\n events,\n };\n if (opts.description) body.description = String(opts.description);\n const { data, error, response } = await client.raw.POST(\n \"/spaces/{spaceId}/webhooks\",\n { params: { path: { spaceId: space } }, body: body as never },\n );\n if (!response.ok) throw krovaErrorFrom(response, error);\n const created = (data as unknown as { webhook: WebhookWithSecret }).webhook;\n if (rt.json) {\n // Emit the full { webhook, secret } shape so callers don't have to\n // guess which field carries the secret. After this point, the CLI\n // must NOT echo the secret again.\n return printJSON({ webhook: created, secret: created.secret });\n }\n process.stdout.write(`\\nCreated webhook ${created.id} for ${created.url}\\n`);\n process.stdout.write(\"\\n=== SIGNING SECRET (save now, shown once) ===\\n\");\n process.stdout.write(`${created.secret}\\n`);\n process.stdout.write(\"=== END SIGNING SECRET ===\\n\\n\");\n process.stdout.write(\"Save this now — it is the only time the secret will be shown.\\n\");\n });\n\n wh\n .command(\"get\")\n .argument(\"<endpoint-id>\", \"the webhook endpoint ID\")\n .description(\"show a single webhook endpoint\")\n .action(async (endpointId: string, _opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const { data, error, response } = await client.raw.GET(\n \"/spaces/{spaceId}/webhooks/{endpointId}\",\n { params: { path: { spaceId: space, endpointId } } },\n );\n if (!response.ok) throw krovaErrorFrom(response, error);\n const { webhook } = data as unknown as { webhook: Webhook };\n if (rt.json) return printJSON(webhook);\n const rows: Array<[string, string]> = [\n [\"ID\", webhook.id],\n [\"URL\", webhook.url],\n ];\n if (webhook.description != null) rows.push([\"Description\", webhook.description]);\n rows.push(\n [\"Events\", webhook.events.join(\",\")],\n [\"Enabled\", String(webhook.enabled)],\n [\"Created At\", webhook.createdAt],\n [\"Updated At\", webhook.updatedAt],\n );\n printKeyValue(rows);\n });\n\n wh\n .command(\"rm\")\n .argument(\"<endpoint-id>\", \"the webhook endpoint ID\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .description(\"delete a webhook endpoint (and its delivery history)\")\n .action(async (endpointId: string, opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n if (!opts.yes) {\n const ok = await confirm(\n `Delete webhook ${endpointId}? This also drops its delivery history. [y/N] `,\n );\n if (!ok) {\n process.stdout.write(\"Aborted.\\n\");\n return;\n }\n }\n const { error, response } = await client.raw.DELETE(\n \"/spaces/{spaceId}/webhooks/{endpointId}\",\n { params: { path: { spaceId: space, endpointId } } },\n );\n if (!response.ok) throw krovaErrorFrom(response, error);\n if (rt.json) return printJSON({ id: endpointId, result: \"deleted\" });\n process.stdout.write(`Deleted webhook ${endpointId}\\n`);\n });\n\n wh\n .command(\"deliveries\")\n .argument(\"<endpoint-id>\", \"the webhook endpoint ID\")\n .option(\"--limit <n>\", \"max deliveries to return (1-100)\", \"50\")\n .description(\"list recent delivery attempts for a webhook endpoint\")\n .action(async (endpointId: string, opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const client = makeClient(rt.res);\n const space = await resolveSpace(rt);\n const limit = Number(opts.limit);\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n throw new Error(\"--limit must be an integer between 1 and 100.\");\n }\n const { data, error, response } = await client.raw.GET(\n \"/spaces/{spaceId}/webhooks/{endpointId}/deliveries\",\n { params: { path: { spaceId: space, endpointId }, query: { limit } } },\n );\n if (!response.ok) throw krovaErrorFrom(response, error);\n const { deliveries } = data as unknown as { deliveries: WebhookDelivery[] };\n if (rt.json) return printJSON(deliveries);\n printTable(\n [\"ID\", \"EVENT\", \"STATUS\", \"ATTEMPTS\", \"LAST ATTEMPT\", \"RESPONSE\", \"CREATED AT\"],\n deliveries.map((d) => [\n d.id,\n d.event,\n d.status,\n String(d.attempts),\n d.lastAttemptAt ?? \"—\",\n d.responseStatus != null ? String(d.responseStatus) : \"—\",\n d.createdAt,\n ]),\n );\n });\n\n wh.command(\"listen\")\n .description(\"run a local server that verifies + prints incoming webhook deliveries\")\n .option(\"--addr <host:port>\", \"address to listen on\", \"127.0.0.1:4666\")\n .option(\"--path <path>\", \"path to accept POSTs on\", \"/\")\n .option(\"--secret <secret>\", \"signing secret (or the KROVA_WEBHOOK_SECRET env var)\")\n .action((opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const secret = (opts.secret as string) || process.env.KROVA_WEBHOOK_SECRET || \"\";\n if (!secret) {\n throw new Error(\n \"a signing secret is required: pass --secret or set KROVA_WEBHOOK_SECRET\"\n );\n }\n const { host, port } = parseListenAddr(String(opts.addr));\n const wantPath = String(opts.path);\n\n const server = createServer((req, res) => {\n const reqPath = (req.url ?? \"/\").split(\"?\")[0];\n if (req.method !== \"POST\" || reqPath !== wantPath) {\n res.writeHead(405);\n res.end(\"method not allowed\");\n return;\n }\n const chunks: Buffer[] = [];\n let size = 0;\n req.on(\"data\", (c: Buffer) => {\n size += c.length;\n if (size <= 1_048_576) chunks.push(c);\n });\n req.on(\"end\", () => {\n const body = Buffer.concat(chunks).toString(\"utf8\");\n const sig = (req.headers[\"x-krova-signature\"] as string) || \"\";\n try {\n verifyKrovaWebhookOrThrow({ payload: body, signature: sig, secret });\n } catch (e) {\n process.stderr.write(`✗ rejected delivery: ${(e as Error).message}\\n`);\n res.writeHead(400);\n res.end(\"invalid signature\");\n return;\n }\n try {\n const event = JSON.parse(body);\n if (rt.json) process.stdout.write(`${JSON.stringify(event)}\\n`);\n else printJSON(event);\n } catch {\n process.stdout.write(`${body}\\n`);\n }\n res.writeHead(200);\n res.end(\"ok\");\n });\n });\n\n server.listen(port, host, () => {\n process.stderr.write(`Listening for webhooks on http://${host}:${port}${wantPath}\\n`);\n });\n const stop = () => server.close(() => process.exit(0));\n process.on(\"SIGINT\", stop);\n process.on(\"SIGTERM\", stop);\n });\n\n return wh;\n}\n","import { Command } from \"commander\";\n\nimport { displayKey, find } from \"../lib/config.js\";\nimport { printJSON, printKeyValue } from \"../lib/output.js\";\nimport { getRuntime, probeAuth } from \"../lib/runtime.js\";\n\n/** \"never\", or the ISO date with how far away it is, e.g. `2026-12-16T12:00:00.000Z (in 30 days)`. */\nexport function describeExpiry(expiresAt: string | null, now: number = Date.now()): string {\n if (expiresAt === null) return \"never\";\n const at = Date.parse(expiresAt);\n if (Number.isNaN(at)) return expiresAt;\n const days = Math.floor((at - now) / 86_400_000);\n if (days < 0) return `${expiresAt} (expired)`;\n if (days === 0) return `${expiresAt} (within a day)`;\n return `${expiresAt} (in ${days} ${days === 1 ? \"day\" : \"days\"})`;\n}\n\nexport function whoamiCommand(): Command {\n return new Command(\"whoami\")\n .description(\"show the current context, space, and base URL\")\n .option(\"--show-secrets\", \"print the full API key instead of a masked one\")\n .action(async (opts, cmd: Command) => {\n const rt = getRuntime(cmd);\n const showSecrets = Boolean(opts.showSecrets);\n const ctx = find(rt.cfg, rt.res.contextName);\n let spaceId = rt.res.spaceId;\n let spaceName = ctx?.spaceName ?? \"\";\n\n const probe = await probeAuth(rt.res.baseUrl, rt.res.apiKey, rt.timeoutMs);\n if (probe.state === \"valid\") {\n spaceId = probe.space.id;\n spaceName = probe.space.name ?? spaceName;\n }\n const spaceLive = probe.state === \"valid\";\n // `undefined` when unknown: the key was not checked, the key came from an\n // OAuth token (the API sends `apiKey: null`), or an older server omits it.\n const keyInfo = probe.state === \"valid\" ? probe.space.apiKey : undefined;\n const expiresAt = keyInfo ? keyInfo.expiresAt : undefined;\n\n // A rejected key used to render as a bare \"Space —\", which reads like a\n // missing setting rather than dead credentials. Say so out loud.\n const warning =\n probe.state === \"rejected\"\n ? `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.`\n : probe.state === \"unreachable\"\n ? `could not reach ${rt.res.baseUrl} (${probe.error}) — showing locally cached values.`\n : \"\";\n\n if (rt.json) {\n return printJSON({\n context: rt.res.contextName,\n spaceId,\n spaceName,\n ...(showSecrets\n ? { apiKey: rt.res.apiKey }\n : { apiKeyMasked: displayKey(rt.res.apiKey, false) }),\n ...(expiresAt !== undefined ? { apiKeyExpiresAt: expiresAt } : {}),\n apiKeySource: rt.res.apiKeySource,\n apiKeyStorage: rt.res.apiKeyStorage || undefined,\n baseUrl: rt.res.baseUrl,\n spaceLive,\n checkState: probe.state,\n warning: warning || undefined,\n });\n }\n printKeyValue([\n [\"Context\", rt.res.contextName || \"—\"],\n [\"Space\", spaceName || \"—\"],\n [\"Space ID\", spaceId || \"—\"],\n [\n \"API key\",\n rt.res.apiKey\n ? `${displayKey(rt.res.apiKey, showSecrets)} (${rt.res.apiKeySource}${rt.res.apiKeyStorage ? `, ${rt.res.apiKeyStorage}` : \"\"})`\n : \"—\",\n ],\n ...(expiresAt !== undefined\n ? [[\"Key expires\", describeExpiry(expiresAt)] as [string, string]]\n : []),\n [\"Base URL\", rt.res.baseUrl],\n ]);\n if (warning) process.stdout.write(`\\n${warning}\\n`);\n if (probe.state === \"rejected\") process.exitCode = 1;\n });\n}\n","import { KrovaError, TerminationProtectedError } from \"@krovacloud/sdk\";\n\nimport { ENV } from \"./config.js\";\n\nconst NETWORK_CODES = new Set([\n \"ECONNREFUSED\",\n \"ENOTFOUND\",\n \"ETIMEDOUT\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n]);\n\n/** Hint for an API status, or undefined when a generic hint would not help (e.g. 400, 422). */\nexport function hintForStatus(status: number): string | undefined {\n if (status === 401) return \"Your API key was rejected. Run krova login, or check krova whoami.\";\n if (status === 403) {\n return \"Your key's member lacks the permission for this action. Ask a space owner to grant it.\";\n }\n if (status === 404) return \"Not found. Check the name or ID with the matching list command.\";\n if (status === 409) return \"The resource is busy or in a conflicting state. Try again in a moment.\";\n if (status === 429) return \"Rate limited. Wait a moment and try again.\";\n if (status >= 500 && status <= 599) {\n return \"Krova had a server error. Try again; if it keeps happening, contact support.\";\n }\n return undefined;\n}\n\n/** True when `err` (or anything in its cause chain) is a connection failure. */\nexport function isNetworkError(err: unknown): boolean {\n const seen = new Set<unknown>();\n const walk = (e: unknown, depth: number): boolean => {\n if (!e || typeof e !== \"object\" || depth > 5 || seen.has(e)) return false;\n seen.add(e);\n const { code, message, cause, errors } = e as {\n code?: unknown;\n message?: unknown;\n cause?: unknown;\n errors?: unknown;\n };\n if (typeof code === \"string\" && NETWORK_CODES.has(code)) return true;\n if (typeof message === \"string\") {\n if (message === \"fetch failed\") return true;\n for (const c of NETWORK_CODES) if (message.includes(c)) return true;\n }\n if (walk(cause, depth + 1)) return true;\n return Array.isArray(errors) && errors.some((x) => walk(x, depth + 1));\n };\n return walk(err, 0);\n}\n\n/**\n * The one extra line the top-level error handler prints under `Error: ...`.\n *\n * - An error that carries its own `hint` string wins: it is returned as-is, so\n * a command that already explains itself is never given a second, generic one.\n * - A `KrovaError` (the API answered) gets a hint by status. A termination\n * protection refusal gets none: retrying cannot help and its message is exact.\n * - A connection failure gets a hint naming the base URL being used.\n * - Anything else (validation, local errors) gets none.\n */\nexport function errorHint(err: unknown, baseUrl: string): string | undefined {\n const own = (err as { hint?: unknown } | null)?.hint;\n if (typeof own === \"string\" && own) return own;\n if (err instanceof TerminationProtectedError) return undefined;\n if (err instanceof KrovaError) return hintForStatus(err.status);\n if (isNetworkError(err)) {\n return `Could not reach ${baseUrl}. Check your connection or ${ENV.baseUrl}.`;\n }\n return undefined;\n}\n","import { Command } from \"commander\";\n\nimport { authCommand } from \"./commands/auth.js\";\nimport { backupsCommand } from \"./commands/backups.js\";\nimport { imagesCommand, pricingCommand, regionsCommand } from \"./commands/catalog.js\";\nimport { completionCommand } from \"./commands/completion.js\";\nimport { contextCommand } from \"./commands/context.js\";\nimport { cubesCommand, rootGetCommand, rootListCommand } from \"./commands/cubes.js\";\nimport { domainsCommand } from \"./commands/domains.js\";\nimport { loginCommand } from \"./commands/login.js\";\nimport { snapshotsCommand } from \"./commands/snapshots.js\";\nimport { mysqlCommand, psqlCommand, redisCommand } from \"./commands/dbclients.js\";\nimport { cpCommand, execCommand } from \"./commands/exec.js\";\nimport { sshCommand } from \"./commands/ssh.js\";\nimport { connectCommand, tunnelCommand } from \"./commands/tunnel.js\";\nimport { tcpCommand } from \"./commands/tcp.js\";\nimport { updateCommand } from \"./commands/update.js\";\nimport { CLI_VERSION, versionCommand } from \"./commands/version.js\";\nimport { webhooksCommand } from \"./commands/webhooks.js\";\nimport { whoamiCommand } from \"./commands/whoami.js\";\nimport { DEFAULT_BASE_URL, ENV, load, resolve } from \"./lib/config.js\";\nimport { errorHint } from \"./lib/hints.js\";\nimport { parseOutputFormat } from \"./lib/output-format.js\";\nimport { exitQuietlyOnBrokenPipe } from \"./lib/output.js\";\nimport { activeRuntime } from \"./lib/runtime.js\";\n\nexitQuietlyOnBrokenPipe();\n\nconst program = new Command();\nprogram\n .name(\"krova\")\n .description(\n \"krova is the command-line interface for Krova Cloud — manage Cubes (Firecracker microVMs), browse the catalog, and receive webhooks.\"\n )\n .version(CLI_VERSION, \"-v, --version\", \"print the krova CLI version\")\n .showHelpAfterError();\n\nprogram.addCommand(loginCommand());\nprogram.addCommand(authCommand());\nprogram.addCommand(contextCommand());\nprogram.addCommand(whoamiCommand());\nprogram.addCommand(cubesCommand());\nprogram.addCommand(domainsCommand());\nprogram.addCommand(snapshotsCommand());\nprogram.addCommand(backupsCommand());\nprogram.addCommand(tcpCommand());\nprogram.addCommand(sshCommand());\nprogram.addCommand(tunnelCommand());\nprogram.addCommand(connectCommand());\nprogram.addCommand(psqlCommand());\nprogram.addCommand(redisCommand());\nprogram.addCommand(mysqlCommand());\nprogram.addCommand(execCommand());\nprogram.addCommand(cpCommand());\nprogram.addCommand(rootListCommand()); // `krova list` (alias `ls`)\nprogram.addCommand(rootGetCommand()); // `krova get`\nprogram.addCommand(regionsCommand());\nprogram.addCommand(imagesCommand());\nprogram.addCommand(pricingCommand());\nprogram.addCommand(webhooksCommand());\nprogram.addCommand(versionCommand());\nprogram.addCommand(updateCommand());\nprogram.addCommand(completionCommand());\n\n// cobra-style persistent flags: usable on any command, before or after it.\n// Skips a flag a command already defines locally (e.g. login's own --context).\nconst applyGlobals = (cmd: Command): void => {\n const have = new Set(cmd.options.map((o) => o.long));\n const add = (flags: string, desc: string, def?: string) => {\n const long = flags.split(/[ ,<[]/).find((f) => f.startsWith(\"--\"));\n if (long && !have.has(long)) cmd.option(flags, desc, def);\n };\n add(\"--api-key <key>\", \"Krova Cloud API key (overrides env and context)\");\n add(\"--space <id>\", \"Space ID (overrides KROVA_SPACE_ID and context)\");\n add(\"--base-url <url>\", \"override the API base URL\");\n add(\"--context <name>\", \"use a named context (overrides KROVA_CONTEXT)\");\n add(\"--json\", \"output machine-readable JSON instead of a table\");\n add(\"-o, --output <format>\", \"output format: table (default) or json; -o json is the same as --json\");\n add(\"--timeout <duration>\", \"per-request timeout\", \"30s\");\n for (const c of cmd.commands) applyGlobals(c);\n};\napplyGlobals(program);\n\n// Reject a bad `-o` before any command runs, with a one-line error.\nprogram.hook(\"preAction\", (_root, actionCmd) => {\n parseOutputFormat((actionCmd.optsWithGlobals() as { output?: unknown }).output);\n});\n\n/** The base URL for a connection hint: the one the failing command resolved,\n * else what the environment and saved context would give. */\nfunction hintBaseUrl(): string {\n const active = activeRuntime();\n if (active) return active.baseUrl;\n try {\n return resolve(load(), {}).baseUrl;\n } catch {\n return process.env[ENV.baseUrl] || DEFAULT_BASE_URL;\n }\n}\n\nasync function main(): Promise<void> {\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`Error: ${msg}\\n`);\n // One actionable line under the error. Not in JSON mode: errors there stay\n // exactly as they were (plain text on stderr), so a script's parsing is unchanged.\n if (!activeRuntime()?.json) {\n const hint = errorHint(err, hintBaseUrl());\n if (hint) process.stderr.write(`${hint}\\n`);\n }\n process.exitCode = 1;\n }\n}\n\nvoid main();\n"],"mappings":";;;;;;;;;;;;;;;;AAYA,MAAa,mBAAmB;AAChC,MAAa,kBAAkB;AAE/B,MAAM,aAAa;;AAcnB,IAAa,2BAAb,cAA8C,MAAM;CAGvC;CAFX,YACE,SACA,SAAkB,OAClB;E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