@kvbox/cli 0.5.37 → 0.5.39

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/kvbox.js CHANGED
@@ -164,7 +164,7 @@ function versionOf(srcFileUrl, injected) {
164
164
  }
165
165
 
166
166
  // src/version.ts
167
- var VERSION = versionOf(import.meta.url, true ? "0.5.37" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.5.39" : void 0);
168
168
 
169
169
  // src/commands/vm/index.ts
170
170
  import { Command as Command37 } from "commander";
@@ -391,8 +391,8 @@ async function ensureCert(client, p = paths(), now = Date.now(), opts = {}) {
391
391
  if (!session) return "local";
392
392
  const expires = session.sshCertExpires ? new Date(session.sshCertExpires).getTime() : 0;
393
393
  const onDisk = await readFile2(p.sshCert, "utf8").then(() => true, () => false);
394
- const names = opts.owner === void 0 || (session.sshCertPrincipals ?? []).includes(opts.owner);
395
- if (onDisk && expires - now > RENEW_BEFORE_MS && names && !opts.force) return "kept";
394
+ const names2 = opts.owner === void 0 || (session.sshCertPrincipals ?? []).includes(opts.owner);
395
+ if (onDisk && expires - now > RENEW_BEFORE_MS && names2 && !opts.force) return "kept";
396
396
  const publicKey = await readFile2(`${p.sshKey}.pub`, "utf8").catch(() => null);
397
397
  if (publicKey === null) throw new KvboxError(`could not renew your SSH certificate: no key at ${p.sshKey}.pub; run: kvbox login`);
398
398
  let signed;
@@ -582,6 +582,13 @@ var MachineSchema = z2.object({
582
582
  ports: z2.array(PortForwardSchema).optional(),
583
583
  /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
584
584
  ownerKind: z2.enum(["user", "org"]).optional(),
585
+ /**
586
+ * The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
587
+ * links to, and a volume attaches to, only a box on the same host.
588
+ */
589
+ host: z2.string().optional(),
590
+ /** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
591
+ country: z2.string().optional(),
585
592
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
586
593
  autoHibernateSec: z2.number().int().positive().optional(),
587
594
  /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
@@ -609,7 +616,9 @@ var VolumeSchema = z2.object({
609
616
  attachedTo: z2.string().nullable(),
610
617
  createdAt: z2.string(),
611
618
  /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
612
- ownerKind: z2.enum(["user", "org"]).optional()
619
+ ownerKind: z2.enum(["user", "org"]).optional(),
620
+ /** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
621
+ host: z2.string().optional()
613
622
  });
614
623
  var MAX_VOLUME_GIB = 4096;
615
624
  var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
@@ -677,6 +686,11 @@ var CreateMachineRequest = z2.object({
677
686
  * control plane reads it; a host has one place to put a box.
678
687
  */
679
688
  near: z2.string().optional(),
689
+ /**
690
+ * Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
691
+ * `@kvbox/shared/country`. Only the control plane reads it.
692
+ */
693
+ country: z2.string().optional(),
680
694
  /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
681
695
  image: z2.string().optional(),
682
696
  /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
@@ -758,6 +772,7 @@ var CapacitySchema = z2.object({
758
772
  */
759
773
  images: z2.array(z2.object({ name: z2.string(), version: z2.string() })).optional()
760
774
  });
775
+ var ImageSchema = z2.object({ name: z2.string(), version: z2.string().nullable() });
761
776
  var RecoveryReportSchema = z2.object({
762
777
  at: z2.string(),
763
778
  booted: z2.array(z2.string()),
@@ -1059,7 +1074,9 @@ var HostJoinRequestSchema = z2.object({
1059
1074
  name: z2.string().min(1),
1060
1075
  url: z2.string().url(),
1061
1076
  fingerprint: z2.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
1062
- publicAddress: z2.string().min(1)
1077
+ publicAddress: z2.string().min(1),
1078
+ /** Where the host is (`kvbox server join --country`): a code or an English name. */
1079
+ country: z2.string().optional()
1063
1080
  });
1064
1081
  var HostJoinResponseSchema = z2.object({
1065
1082
  hostSecret: z2.string(),
@@ -1071,8 +1088,12 @@ var CloudHostSchema = z2.object({
1071
1088
  publicAddress: z2.string(),
1072
1089
  joinedAt: z2.string(),
1073
1090
  lastSeenAt: z2.string().nullable(),
1074
- capacity: CapacitySchema.nullable()
1091
+ capacity: CapacitySchema.nullable(),
1092
+ /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
1093
+ country: z2.string().nullable()
1075
1094
  });
1095
+ var HostPatchRequest = z2.object({ country: z2.string().nullable() });
1096
+ var CountrySchema = z2.object({ code: z2.string(), name: z2.string() });
1076
1097
 
1077
1098
  // src/kvm.ts
1078
1099
  import { accessSync, constants, readFileSync, statSync } from "fs";
@@ -1284,6 +1305,9 @@ var ServerClient = class {
1284
1305
  return this.call("DELETE", `/machines/${encodeURIComponent(name)}/links`, MachineSchema, req);
1285
1306
  }
1286
1307
  /** Backups, the control plane's only: a box's disk in object storage. Newest first. */
1308
+ listBackups() {
1309
+ return this.call("GET", "/backups", z3.array(BackupSchema));
1310
+ }
1287
1311
  boxBackups(name) {
1288
1312
  return this.call("GET", `/machines/${encodeURIComponent(name)}/backups`, z3.array(BackupSchema));
1289
1313
  }
@@ -1824,6 +1848,39 @@ function envValueProblem(value) {
1824
1848
  return null;
1825
1849
  }
1826
1850
 
1851
+ // ../shared/src/country.ts
1852
+ var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
1853
+ var NOT_COUNTRIES = /* @__PURE__ */ new Set(["EU", "EZ", "UN", "QO", "XA", "XB", "ZZ"]);
1854
+ var ALIASES = { usa: "US", america: "US", uk: "GB", britain: "GB", england: "GB", holland: "NL" };
1855
+ var fold = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z]/g, "");
1856
+ var byName;
1857
+ function nameIndex() {
1858
+ if (byName) return byName;
1859
+ byName = new Map(Object.entries(ALIASES));
1860
+ for (let a = 65; a <= 90; a++) {
1861
+ for (let b = 65; b <= 90; b++) {
1862
+ const code = String.fromCharCode(a, b);
1863
+ const name = countryName(code);
1864
+ if (name !== void 0 && canonical(code) === code) byName.set(fold(name), code);
1865
+ }
1866
+ }
1867
+ return byName;
1868
+ }
1869
+ function canonical(code) {
1870
+ return /-([A-Z]{2})$/.exec(Intl.getCanonicalLocales(`und-${code}`)[0] ?? "")?.[1] ?? code;
1871
+ }
1872
+ function countryName(code) {
1873
+ if (!/^[A-Z]{2}$/.test(code) || NOT_COUNTRIES.has(code)) return void 0;
1874
+ return names.of(code);
1875
+ }
1876
+ function parseCountry(input) {
1877
+ const t = input.trim();
1878
+ const upper = t.toUpperCase();
1879
+ const code = countryName(upper) !== void 0 ? canonical(upper) : nameIndex().get(fold(t));
1880
+ if (code !== void 0) return code;
1881
+ throw new KvboxError(`unknown country "${input}": give its name or its two-letter code, e.g. RO or US`);
1882
+ }
1883
+
1827
1884
  // ../shared/src/duration.ts
1828
1885
  var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
1829
1886
  function parseDuration(text2) {
@@ -1835,10 +1892,16 @@ function parseDuration(text2) {
1835
1892
  }
1836
1893
 
1837
1894
  // src/commands/vm/new.ts
1838
- var newCommand = new Command("new").description("boot a new box from an image (the base one, or e.g. postgres) or a snapshot").argument("[name]", "box name (box1, box2, \u2026 when omitted)").addOption(new Option("-s, --size <size>", "box size (default: server config, s)").choices(SIZE_NAMES)).option("-b, --base <image>", "the image to boot: base (default) or one the host has, e.g. postgres").option("-e, --env <NAME=value>", "a variable of the box's own, over yours (repeatable; change later with kvbox env set --box)", collect, []).option("-f, --from <snapshot>", "start from a snapshot instead of an image").option("--near <box>", "put it on the same host as this box, so the two can be linked (kvbox vm link)").option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never; default: server config, off)").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
1895
+ var newCommand = new Command("new").description("boot a new box from an image (the base one, or e.g. postgres) or a snapshot").argument("[name]", "box name (box1, box2, \u2026 when omitted)").addOption(new Option("-s, --size <size>", "box size (default: server config, s)").choices(SIZE_NAMES)).option("-b, --base <image>", "the image to boot: base (default) or one the host has, e.g. postgres").option("-e, --env <NAME=value>", "a variable of the box's own, over yours (repeatable; change later with kvbox env set --box)", collect, []).option("-f, --from <snapshot>", "start from a snapshot instead of an image").option("--near <box>", "put it on the same host as this box, so the two can be linked (kvbox vm link)").option("--country <country>", "put it on a host in this country, a name or a code, e.g. romania or US").option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never; default: server config, off)").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
1839
1896
  const autoHibernateSec = opts.autoHibernate === void 0 ? void 0 : parseIdleTimeout(opts.autoHibernate);
1840
1897
  const env = parseEnvFlags(opts.env);
1898
+ const country = opts.country === void 0 ? void 0 : parseCountry(opts.country);
1899
+ if (country !== void 0 && opts.from !== void 0) throw new KvboxError("--country cannot be given with --from: a snapshot is restored on its own host");
1841
1900
  const client = await clientFor(cmd.optsWithGlobals());
1901
+ if (country !== void 0 && client.target.kind !== "cloud") {
1902
+ await client.close();
1903
+ throw new KvboxError("--country picks a host through the control plane; this machine is the only host here (kvbox login first)");
1904
+ }
1842
1905
  try {
1843
1906
  const what = opts.from !== void 0 ? `restoring ${name ?? "a new box"} from snapshot ${opts.from}\u2026` : `booting ${name ?? "a new box"}${opts.base !== void 0 && opts.base !== "base" ? ` from image ${opts.base}` : ""}\u2026`;
1844
1907
  const box = await spin(what, client.createMachine({
@@ -1848,6 +1911,7 @@ var newCommand = new Command("new").description("boot a new box from an image (t
1848
1911
  ...opts.base !== void 0 ? { image: opts.base } : {},
1849
1912
  ...env.length > 0 ? { env } : {},
1850
1913
  ...opts.near !== void 0 ? { near: opts.near } : {},
1914
+ ...country !== void 0 ? { country } : {},
1851
1915
  ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {},
1852
1916
  ...opts.force ? { force: true } : {}
1853
1917
  }));
@@ -1884,10 +1948,10 @@ var newCommand = new Command("new").description("boot a new box from an image (t
1884
1948
  await client.close();
1885
1949
  }
1886
1950
  });
1887
- async function keptVars(client, box, names) {
1951
+ async function keptVars(client, box, names2) {
1888
1952
  try {
1889
1953
  const have = new Set((await client.boxEnv(box)).vars.map((v) => v.name));
1890
- return names.every((n) => have.has(n)) ? true : "too old";
1954
+ return names2.every((n) => have.has(n)) ? true : "too old";
1891
1955
  } catch (err) {
1892
1956
  const message = err.message;
1893
1957
  return /no route:|too old/.test(message) ? "too old" : message;
@@ -2109,7 +2173,11 @@ function addressOf(b) {
2109
2173
  var lsCommand = new Command5("ls").description("list boxes with status and address (yours and your orgs'; --org <slug> for one org)").option("-a, --all", "every box on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
2110
2174
  const client = await clientFor(cmd.optsWithGlobals());
2111
2175
  try {
2112
- const boxes = await spin("listing boxes\u2026", client.listMachines({ all: opts.all }));
2176
+ const cloud = client.target.kind === "cloud";
2177
+ const [boxes, admin] = await spin(
2178
+ "listing boxes\u2026",
2179
+ Promise.all([client.listMachines({ all: opts.all }), cloud && !opts.json ? client.me().then((u) => u.role === "admin", () => false) : Promise.resolve(false)])
2180
+ );
2113
2181
  if (opts.json) {
2114
2182
  json(boxes);
2115
2183
  return;
@@ -2120,16 +2188,18 @@ var lsCommand = new Command5("ls").description("list boxes with status and addre
2120
2188
  return;
2121
2189
  }
2122
2190
  if (org !== void 0) info(`boxes of ${org}`);
2123
- table(lsRows(boxes, client.target.kind === "cloud" ? { me: client.target.user } : void 0));
2191
+ table(lsRows(boxes, cloud ? { me: me(client), showHost: admin } : void 0));
2124
2192
  } finally {
2125
2193
  await client.close();
2126
2194
  }
2127
2195
  });
2196
+ var hostCell = (b) => b.host === void 0 ? "-" : b.country === void 0 ? b.host : `${b.host} ${color.dim(`(${b.country})`)}`;
2128
2197
  function lsRows(boxes, cloud) {
2129
2198
  return boxes.map((b) => ({
2130
2199
  ...cloud ? { owner: ownerCell(b, cloud.me) } : {},
2131
2200
  name: boxName(b.name),
2132
2201
  status: status(b.status),
2202
+ ...cloud?.showHost ? { host: hostCell(b) } : {},
2133
2203
  address: addressOf(b),
2134
2204
  size: b.status === "unknown" ? "-" : `${shape(b.vcpu, b.memMib, b.diskBytes)} ${color.dim(`(${gbShort(b.diskUsedBytes)} used)`)}`,
2135
2205
  created: age(b.createdAt),
@@ -2502,8 +2572,8 @@ var releaseCommand = new Command14("release").description("give up a box's HTTPS
2502
2572
  return;
2503
2573
  }
2504
2574
  const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box));
2505
- const names = sub.routes.length === 0 ? "" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? "s" : ""} under it`;
2506
- info(`${color.green("\u2713")} ${sub.url.replace(/^https:\/\//, "")}${names} no longer reach box ${color.bold(box)}`);
2575
+ const names2 = sub.routes.length === 0 ? "" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? "s" : ""} under it`;
2576
+ info(`${color.green("\u2713")} ${sub.url.replace(/^https:\/\//, "")}${names2} no longer reach box ${color.bold(box)}`);
2507
2577
  } finally {
2508
2578
  await client.close();
2509
2579
  }
@@ -2690,7 +2760,7 @@ function sizeLine(b) {
2690
2760
  }
2691
2761
 
2692
2762
  // src/commands/vm/backup/create.ts
2693
- var createCommand2 = new Command22("create").description("back up a box's disk to the kvbox cloud (encrypted; memory and volumes not included)").argument("<box>", "box name").option("--no-wait", "start it and return; kvbox vm backup ls <box> shows when it is ready").option("--json", "print the backup as JSON").action(async (name, opts, cmd) => {
2763
+ var createCommand2 = new Command22("create").description("back up a box's disk to the kvbox cloud (encrypted; memory and volumes not included)").argument("<box>", "box name").option("--wait", "stay until the backup is ready (by default it runs in the background)").option("--json", "print the backup as JSON").action(async (name, opts, cmd) => {
2694
2764
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
2695
2765
  try {
2696
2766
  requireCloud3(client);
@@ -2699,7 +2769,10 @@ var createCommand2 = new Command22("create").description("back up a box's disk t
2699
2769
  const started = await client.createBoxBackup(box);
2700
2770
  if (!opts.wait) {
2701
2771
  if (opts.json) json(started);
2702
- else info(`${color.green("\u2713")} backup ${started.id} of box ${color.bold(box)} started; kvbox vm backup ls ${box} shows when it is ready`);
2772
+ else {
2773
+ info(`${color.green("\u2713")} backup ${started.id} of box ${color.bold(box)} started; it runs in the background`);
2774
+ info(color.dim(` status: kvbox vm backup ls ${box}`));
2775
+ }
2703
2776
  return;
2704
2777
  }
2705
2778
  const done = await spin(`backing up ${box}\u2026`, untilDone(client, box, started.id));
@@ -2716,30 +2789,32 @@ var createCommand2 = new Command22("create").description("back up a box's disk t
2716
2789
 
2717
2790
  // src/commands/vm/backup/ls.ts
2718
2791
  import { Command as Command23 } from "commander";
2719
- var lsCommand4 = new Command23("ls").alias("list").description("list a box's backups").argument("<box>", "box name").option("--json", "print as JSON").action(async (name, opts, cmd) => {
2792
+ var lsCommand4 = new Command23("ls").alias("list").description("list backups: every box's, or one box's").argument("[box]", "box name (default: every box)").option("--json", "print as JSON").action(async (name, opts, cmd) => {
2720
2793
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
2721
2794
  try {
2722
2795
  requireCloud3(client);
2723
- const box = displayName(await findBox(client, name), me(client));
2724
- const list = await client.boxBackups(box);
2796
+ const box = name === void 0 ? void 0 : displayName(await findBox(client, name), me(client));
2797
+ const list = box === void 0 ? await client.listBackups() : await client.boxBackups(box);
2725
2798
  if (opts.json) {
2726
2799
  json(list);
2727
2800
  return;
2728
2801
  }
2729
2802
  if (list.length === 0) {
2730
- info(`box ${box} has no backups; make one with: kvbox vm backup create ${box}`);
2803
+ info(box === void 0 ? "no backups yet; make one with: kvbox vm backup create <box>" : `box ${box} has no backups; make one with: kvbox vm backup create ${box}`);
2731
2804
  return;
2732
2805
  }
2806
+ const anyError = list.some((b) => b.error !== null);
2733
2807
  table(
2734
2808
  list.map((b) => ({
2735
2809
  id: b.id,
2810
+ ...box === void 0 ? { box: b.owner === me(client) ? b.box : `${b.owner}/${b.box}` } : {},
2736
2811
  status: b.status === "ready" ? color.green(b.status) : b.status === "failed" ? color.red(b.status) : color.yellow(b.status),
2737
2812
  data: b.dataBytes === null ? "-" : gbShort(b.dataBytes),
2738
2813
  uploaded: b.uploadedBytes === null ? "-" : gbShort(b.uploadedBytes),
2739
2814
  disk: b.diskBytes === null ? "-" : gbShort(b.diskBytes),
2740
2815
  by: b.createdBy ?? "-",
2741
2816
  taken: age(b.createdAt),
2742
- ...b.error !== null ? { error: b.error } : {}
2817
+ ...anyError ? { error: b.error ?? "" } : {}
2743
2818
  }))
2744
2819
  );
2745
2820
  } finally {
@@ -3258,10 +3333,11 @@ function runKvboxServer(args) {
3258
3333
  }
3259
3334
 
3260
3335
  // src/commands/server/join.ts
3261
- var joinCommand = new Command38("join").description("put this machine behind a control plane (needs a one-time token minted there) and restart its server").argument("<control-plane-url>", "the control plane, e.g. https://api.kvbox.sh").requiredOption("--token <token>", "one-time join token from the control plane").option("--advertise <host-or-ip>", "address the control plane reaches this machine at (default: its default-route address)").option("--name <name>", "how the control plane lists this machine (default: hostname)").action(async (url, opts) => {
3336
+ var joinCommand = new Command38("join").description("put this machine behind a control plane (needs a one-time token minted there) and restart its server").argument("<control-plane-url>", "the control plane, e.g. https://api.kvbox.sh").requiredOption("--token <token>", "one-time join token from the control plane").option("--advertise <host-or-ip>", "address the control plane reaches this machine at (default: its default-route address)").option("--name <name>", "how the control plane lists this machine (default: hostname)").option("--country <country>", "where this machine is, a name or a code (romania, US); kvbox new --country places boxes by it").action(async (url, opts) => {
3262
3337
  const args = ["join", url, "--token", opts.token];
3263
3338
  if (opts.advertise !== void 0) args.push("--advertise", opts.advertise);
3264
3339
  if (opts.name !== void 0) args.push("--name", opts.name);
3340
+ if (opts.country !== void 0) args.push("--country", opts.country);
3265
3341
  for (const line of (await runKvboxServer(args)).split("\n")) info(line);
3266
3342
  const pid = await spin("restarting kvbox-server\u2026", restartLocalServer(paths()));
3267
3343
  info(`kvbox-server restarted (pid ${pid}); it answers the control plane now`);
@@ -4708,19 +4784,19 @@ var lsCommand9 = new Command68("ls").alias("list").description("list the variabl
4708
4784
 
4709
4785
  // src/commands/env/rm.ts
4710
4786
  import { Command as Command69 } from "commander";
4711
- var rmCommand8 = new Command69("rm").alias("remove").description("remove variables; boxes lose them when they next start").argument("<names...>", "variable names").option("-y, --yes", "do not ask for confirmation").option("--box <box>", "remove this box's own variables (yours, or the org's, of the same name come back)").option("--json", "print as JSON").action(async (names, opts, cmd) => {
4787
+ var rmCommand8 = new Command69("rm").alias("remove").description("remove variables; boxes lose them when they next start").argument("<names...>", "variable names").option("-y, --yes", "do not ask for confirmation").option("--box <box>", "remove this box's own variables (yours, or the org's, of the same name come back)").option("--json", "print as JSON").action(async (names2, opts, cmd) => {
4712
4788
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4713
4789
  try {
4714
4790
  const target = opts.box === void 0 ? void 0 : await findBox2(client, opts.box);
4715
4791
  const owner = target === void 0 ? requireCloud4(client) : `box ${target.ref}`;
4716
- if (!await confirm(`Remove ${names.join(", ")} from ${owner}'s variables?`, opts.yes ?? false)) {
4792
+ if (!await confirm(`Remove ${names2.join(", ")} from ${owner}'s variables?`, opts.yes ?? false)) {
4717
4793
  info("cancelled");
4718
4794
  process.exitCode = 1;
4719
4795
  return;
4720
4796
  }
4721
4797
  const changes = [];
4722
4798
  const failed = [];
4723
- for (const name of names) {
4799
+ for (const name of names2) {
4724
4800
  try {
4725
4801
  if (target !== void 0) {
4726
4802
  const c2 = await spin(`removing ${name}\u2026`, client.removeBoxEnv(target.ref, name));