@kvbox/cli 0.5.38 → 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.38" : 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;
@@ -587,6 +587,8 @@ var MachineSchema = z2.object({
587
587
  * links to, and a volume attaches to, only a box on the same host.
588
588
  */
589
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(),
590
592
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
591
593
  autoHibernateSec: z2.number().int().positive().optional(),
592
594
  /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
@@ -684,6 +686,11 @@ var CreateMachineRequest = z2.object({
684
686
  * control plane reads it; a host has one place to put a box.
685
687
  */
686
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(),
687
694
  /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
688
695
  image: z2.string().optional(),
689
696
  /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
@@ -1067,7 +1074,9 @@ var HostJoinRequestSchema = z2.object({
1067
1074
  name: z2.string().min(1),
1068
1075
  url: z2.string().url(),
1069
1076
  fingerprint: z2.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
1070
- 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()
1071
1080
  });
1072
1081
  var HostJoinResponseSchema = z2.object({
1073
1082
  hostSecret: z2.string(),
@@ -1079,8 +1088,12 @@ var CloudHostSchema = z2.object({
1079
1088
  publicAddress: z2.string(),
1080
1089
  joinedAt: z2.string(),
1081
1090
  lastSeenAt: z2.string().nullable(),
1082
- 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()
1083
1094
  });
1095
+ var HostPatchRequest = z2.object({ country: z2.string().nullable() });
1096
+ var CountrySchema = z2.object({ code: z2.string(), name: z2.string() });
1084
1097
 
1085
1098
  // src/kvm.ts
1086
1099
  import { accessSync, constants, readFileSync, statSync } from "fs";
@@ -1835,6 +1848,39 @@ function envValueProblem(value) {
1835
1848
  return null;
1836
1849
  }
1837
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
+
1838
1884
  // ../shared/src/duration.ts
1839
1885
  var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
1840
1886
  function parseDuration(text2) {
@@ -1846,10 +1892,16 @@ function parseDuration(text2) {
1846
1892
  }
1847
1893
 
1848
1894
  // src/commands/vm/new.ts
1849
- 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) => {
1850
1896
  const autoHibernateSec = opts.autoHibernate === void 0 ? void 0 : parseIdleTimeout(opts.autoHibernate);
1851
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");
1852
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
+ }
1853
1905
  try {
1854
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`;
1855
1907
  const box = await spin(what, client.createMachine({
@@ -1859,6 +1911,7 @@ var newCommand = new Command("new").description("boot a new box from an image (t
1859
1911
  ...opts.base !== void 0 ? { image: opts.base } : {},
1860
1912
  ...env.length > 0 ? { env } : {},
1861
1913
  ...opts.near !== void 0 ? { near: opts.near } : {},
1914
+ ...country !== void 0 ? { country } : {},
1862
1915
  ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {},
1863
1916
  ...opts.force ? { force: true } : {}
1864
1917
  }));
@@ -1895,10 +1948,10 @@ var newCommand = new Command("new").description("boot a new box from an image (t
1895
1948
  await client.close();
1896
1949
  }
1897
1950
  });
1898
- async function keptVars(client, box, names) {
1951
+ async function keptVars(client, box, names2) {
1899
1952
  try {
1900
1953
  const have = new Set((await client.boxEnv(box)).vars.map((v) => v.name));
1901
- return names.every((n) => have.has(n)) ? true : "too old";
1954
+ return names2.every((n) => have.has(n)) ? true : "too old";
1902
1955
  } catch (err) {
1903
1956
  const message = err.message;
1904
1957
  return /no route:|too old/.test(message) ? "too old" : message;
@@ -2140,12 +2193,13 @@ var lsCommand = new Command5("ls").description("list boxes with status and addre
2140
2193
  await client.close();
2141
2194
  }
2142
2195
  });
2196
+ var hostCell = (b) => b.host === void 0 ? "-" : b.country === void 0 ? b.host : `${b.host} ${color.dim(`(${b.country})`)}`;
2143
2197
  function lsRows(boxes, cloud) {
2144
2198
  return boxes.map((b) => ({
2145
2199
  ...cloud ? { owner: ownerCell(b, cloud.me) } : {},
2146
2200
  name: boxName(b.name),
2147
2201
  status: status(b.status),
2148
- ...cloud?.showHost ? { host: b.host ?? "-" } : {},
2202
+ ...cloud?.showHost ? { host: hostCell(b) } : {},
2149
2203
  address: addressOf(b),
2150
2204
  size: b.status === "unknown" ? "-" : `${shape(b.vcpu, b.memMib, b.diskBytes)} ${color.dim(`(${gbShort(b.diskUsedBytes)} used)`)}`,
2151
2205
  created: age(b.createdAt),
@@ -2518,8 +2572,8 @@ var releaseCommand = new Command14("release").description("give up a box's HTTPS
2518
2572
  return;
2519
2573
  }
2520
2574
  const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box));
2521
- const names = sub.routes.length === 0 ? "" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? "s" : ""} under it`;
2522
- 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)}`);
2523
2577
  } finally {
2524
2578
  await client.close();
2525
2579
  }
@@ -3279,10 +3333,11 @@ function runKvboxServer(args) {
3279
3333
  }
3280
3334
 
3281
3335
  // src/commands/server/join.ts
3282
- 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) => {
3283
3337
  const args = ["join", url, "--token", opts.token];
3284
3338
  if (opts.advertise !== void 0) args.push("--advertise", opts.advertise);
3285
3339
  if (opts.name !== void 0) args.push("--name", opts.name);
3340
+ if (opts.country !== void 0) args.push("--country", opts.country);
3286
3341
  for (const line of (await runKvboxServer(args)).split("\n")) info(line);
3287
3342
  const pid = await spin("restarting kvbox-server\u2026", restartLocalServer(paths()));
3288
3343
  info(`kvbox-server restarted (pid ${pid}); it answers the control plane now`);
@@ -4729,19 +4784,19 @@ var lsCommand9 = new Command68("ls").alias("list").description("list the variabl
4729
4784
 
4730
4785
  // src/commands/env/rm.ts
4731
4786
  import { Command as Command69 } from "commander";
4732
- 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) => {
4733
4788
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4734
4789
  try {
4735
4790
  const target = opts.box === void 0 ? void 0 : await findBox2(client, opts.box);
4736
4791
  const owner = target === void 0 ? requireCloud4(client) : `box ${target.ref}`;
4737
- 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)) {
4738
4793
  info("cancelled");
4739
4794
  process.exitCode = 1;
4740
4795
  return;
4741
4796
  }
4742
4797
  const changes = [];
4743
4798
  const failed = [];
4744
- for (const name of names) {
4799
+ for (const name of names2) {
4745
4800
  try {
4746
4801
  if (target !== void 0) {
4747
4802
  const c2 = await spin(`removing ${name}\u2026`, client.removeBoxEnv(target.ref, name));