@kvbox/cli 0.5.26 → 0.5.28

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
@@ -149,7 +149,7 @@ async function spin(message, work, opts = {}) {
149
149
  }
150
150
 
151
151
  // src/program.ts
152
- import { Command as Command61 } from "commander";
152
+ import { Command as Command68 } from "commander";
153
153
 
154
154
  // ../shared/src/version.ts
155
155
  import { createRequire } from "module";
@@ -164,10 +164,10 @@ function versionOf(srcFileUrl, injected) {
164
164
  }
165
165
 
166
166
  // src/version.ts
167
- var VERSION = versionOf(import.meta.url, true ? "0.5.26" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.5.28" : void 0);
168
168
 
169
169
  // src/commands/vm/index.ts
170
- import { Command as Command26 } from "commander";
170
+ import { Command as Command29 } from "commander";
171
171
 
172
172
  // src/commands/vm/connect.ts
173
173
  import { spawnSync as spawnSync2 } from "child_process";
@@ -431,6 +431,8 @@ var PortsRequest = z2.object({
431
431
  ports: z2.array(z2.object({ guestPort: z2.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
432
432
  });
433
433
  var BoxPortSchema = z2.number().int().min(1).max(65535);
434
+ var BoxLinkSchema = z2.object({ from: z2.string(), port: BoxPortSchema });
435
+ var LinkRequest = z2.object({ from: z2.string().min(1), fromOwner: z2.string().optional(), port: BoxPortSchema });
434
436
  var ClaimSubdomainRequest = z2.object({ name: z2.string(), port: BoxPortSchema });
435
437
  var SubdomainPortRequest = z2.object({ port: BoxPortSchema });
436
438
  var SubdomainRouteRequest = z2.object({ name: z2.string(), port: BoxPortSchema });
@@ -442,6 +444,19 @@ var SubdomainSchema = z2.object({
442
444
  url: z2.string(),
443
445
  routes: z2.array(z2.object({ name: z2.string(), port: BoxPortSchema, url: z2.string() }))
444
446
  });
447
+ var AddDomainRequest = z2.object({ domain: z2.string(), port: BoxPortSchema.optional() });
448
+ var DomainSchema = z2.object({
449
+ owner: z2.string(),
450
+ box: z2.string(),
451
+ domain: z2.string(),
452
+ port: BoxPortSchema,
453
+ status: z2.enum(["pending", "live"]),
454
+ www: z2.boolean(),
455
+ url: z2.string(),
456
+ error: z2.string().nullable(),
457
+ records: z2.array(z2.object({ type: z2.enum(["A", "TXT", "CNAME"]), name: z2.string(), value: z2.string() })),
458
+ createdAt: z2.string()
459
+ });
445
460
  var MachineSchema = z2.object({
446
461
  /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
447
462
  id: z2.string(),
@@ -481,7 +496,9 @@ var MachineSchema = z2.object({
481
496
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
482
497
  autoHibernateSec: z2.number().int().positive().optional(),
483
498
  /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
484
- volumes: z2.array(z2.object({ name: z2.string(), sizeGib: z2.number().int(), mountPath: z2.string() })).optional()
499
+ volumes: z2.array(z2.object({ name: z2.string(), sizeGib: z2.number().int(), mountPath: z2.string() })).optional(),
500
+ /** Boxes that may reach this one, each on one port (#98). Absent: none. */
501
+ links: z2.array(BoxLinkSchema).optional()
485
502
  });
486
503
  var VolumeSchema = z2.object({
487
504
  /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
@@ -546,7 +563,12 @@ var CreateMachineRequest = z2.object({
546
563
  */
547
564
  sshKeys: z2.array(z2.string()).optional(),
548
565
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
549
- autoHibernateSec: z2.number().int().min(0).optional()
566
+ autoHibernateSec: z2.number().int().min(0).optional(),
567
+ /**
568
+ * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
569
+ * control plane reads it; a host has one place to put a box.
570
+ */
571
+ near: z2.string().optional()
550
572
  });
551
573
  var ForkMachineRequest = z2.object({
552
574
  name: z2.string().optional(),
@@ -590,7 +612,9 @@ var SnapshotSchema = z2.object({
590
612
  });
591
613
  var CreateSnapshotRequest = z2.object({
592
614
  box: z2.string(),
593
- name: z2.string()
615
+ name: z2.string(),
616
+ /** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
617
+ replace: z2.boolean().optional()
594
618
  });
595
619
  var DiskCapacitySchema = z2.object({
596
620
  totalGib: z2.number().int(),
@@ -1124,6 +1148,14 @@ var ServerClient = class {
1124
1148
  removePorts(name, req) {
1125
1149
  return this.call("DELETE", `/machines/${encodeURIComponent(name)}/ports`, MachineSchema, req);
1126
1150
  }
1151
+ /** Let box `from` reach this box's `port` (#98); the answer is the box with every link into it. */
1152
+ addLink(name, req) {
1153
+ return this.call("POST", `/machines/${encodeURIComponent(name)}/links`, MachineSchema, req);
1154
+ }
1155
+ /** Take a link away (#98). */
1156
+ removeLink(name, req) {
1157
+ return this.call("DELETE", `/machines/${encodeURIComponent(name)}/links`, MachineSchema, req);
1158
+ }
1127
1159
  /** HTTPS names (#31), the control plane's only: the box's subdomain, claimed for its default port. */
1128
1160
  claimSubdomain(name, req) {
1129
1161
  return this.call("PUT", `/machines/${encodeURIComponent(name)}/subdomain`, SubdomainSchema, req);
@@ -1145,6 +1177,17 @@ var ServerClient = class {
1145
1177
  listSubdomains() {
1146
1178
  return this.call("GET", "/subdomains", z3.array(SubdomainSchema));
1147
1179
  }
1180
+ /** Custom domains (#89), the control plane's only: serve the box at the user's own name. */
1181
+ addDomain(name, req) {
1182
+ return this.call("POST", `/machines/${encodeURIComponent(name)}/domains`, DomainSchema, req);
1183
+ }
1184
+ removeDomain(name, domain) {
1185
+ return this.call("DELETE", `/machines/${encodeURIComponent(name)}/domains/${encodeURIComponent(domain)}`, DomainSchema);
1186
+ }
1187
+ /** Every readable box's custom domains. */
1188
+ listDomains() {
1189
+ return this.call("GET", "/domains", z3.array(DomainSchema));
1190
+ }
1148
1191
  /** A running box's own load, memory and disk, asked of its guest (#67). */
1149
1192
  machineStats(name) {
1150
1193
  return this.call("GET", `/machines/${encodeURIComponent(name)}/stats`, MachineStatsSchema);
@@ -1294,8 +1337,8 @@ var me = (client) => client.target.kind === "cloud" ? client.target.user : void
1294
1337
  async function clientFor(opts, client = {}) {
1295
1338
  return new ServerClient(await resolveTarget(opts), client);
1296
1339
  }
1297
- function sshEndpoint(box, target) {
1298
- if (target.kind === "local") return { host: box.ip, port: 22, user: BOX_SSH_USER };
1340
+ function sshEndpoint(box, target, direct = false) {
1341
+ if (target.kind === "local" || direct) return { host: box.ip, port: 22, user: BOX_SSH_USER };
1299
1342
  if (box.ssh === void 0) throw new KvboxError(`box ${box.name} has no public SSH port`);
1300
1343
  return { ...box.ssh, alias: `${box.id}.${box.ssh.host}` };
1301
1344
  }
@@ -1338,6 +1381,11 @@ async function waitForSsh(ep, timeoutMs = 3e4) {
1338
1381
  }
1339
1382
  throw new KvboxError(`box at ${ep.host}:${ep.port} did not answer within ${Math.round(timeoutMs / 1e3)}s`);
1340
1383
  }
1384
+ async function checkDirect(ep) {
1385
+ await waitForSsh(ep, 2e3).catch(() => {
1386
+ throw new KvboxError(`--direct: cannot reach ${ep.host}:${ep.port}; it works only on the box's host (leave it out to go through the public address)`);
1387
+ });
1388
+ }
1341
1389
  var NOT_A_HOST_HINT = "kvbox-server is not installed, so this machine is not a kvbox host. Set it up with install-server.sh, or log in to the cloud with: kvbox login";
1342
1390
  async function lastErrorLine(logPath, from = 0) {
1343
1391
  const { readFile: readFile8 } = await import("fs/promises");
@@ -1596,7 +1644,7 @@ async function pickVolume(client, keep, none) {
1596
1644
 
1597
1645
  // src/commands/vm/new.ts
1598
1646
  import { Command, Option } from "commander";
1599
- var newCommand = new Command("new").description("boot a new box from the base image 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("-f, --from <snapshot>", "start from a snapshot instead of the base image").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) => {
1647
+ var newCommand = new Command("new").description("boot a new box from the base image 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("-f, --from <snapshot>", "start from a snapshot instead of the base 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) => {
1600
1648
  const autoHibernateSec = opts.autoHibernate === void 0 ? void 0 : parseIdleTimeout(opts.autoHibernate);
1601
1649
  const client = await clientFor(cmd.optsWithGlobals());
1602
1650
  try {
@@ -1605,6 +1653,7 @@ var newCommand = new Command("new").description("boot a new box from the base im
1605
1653
  ...name !== void 0 ? { name } : {},
1606
1654
  ...opts.size !== void 0 ? { size: opts.size } : {},
1607
1655
  ...opts.from !== void 0 ? { from: opts.from } : {},
1656
+ ...opts.near !== void 0 ? { near: opts.near } : {},
1608
1657
  ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {},
1609
1658
  ...opts.force ? { force: true } : {}
1610
1659
  }));
@@ -1646,8 +1695,12 @@ function parseIdleTimeout(text2) {
1646
1695
 
1647
1696
  // src/commands/vm/connect.ts
1648
1697
  var SSH_FAILED = 255;
1649
- var connectCommand = new Command2("connect").alias("cn").description("open a shell in a box over SSH (or run a command: kvbox connect <name> -- <cmd>)").argument("[name]", "box name (picked from a list when left out)").argument("[cmd...]", "command to run instead of a shell").passThroughOptions().action(async (nameArg, cmdArgs, _opts, cmd) => {
1698
+ var connectCommand = new Command2("connect").alias("cn").description("open a shell in a box over SSH (or run a command: kvbox connect <name> -- <cmd>)").argument("[name]", "box name (picked from a list when left out)").argument("[cmd...]", "command to run instead of a shell").option("--direct", "on the box's host: ssh to the box's private ip, not through the public address or relay").passThroughOptions().action(async (nameArg, cmdArgs, opts, cmd) => {
1650
1699
  if (nameArg === void 0) askOrUsage("give the box: kvbox connect <name>");
1700
+ if (cmdArgs[0] === "--direct") {
1701
+ opts.direct = true;
1702
+ cmdArgs = cmdArgs.slice(cmdArgs[1] === "--" ? 2 : 1);
1703
+ }
1651
1704
  const client = await clientFor(cmd.optsWithGlobals());
1652
1705
  let ep;
1653
1706
  let cert;
@@ -1660,8 +1713,9 @@ var connectCommand = new Command2("connect").alias("cn").description("open a she
1660
1713
  owner = box.owner;
1661
1714
  const wasRunning = box.status === "running";
1662
1715
  if (!wasRunning) box = await wakeUp(client, box, displayName(box, me(client)));
1663
- ep = sshEndpoint(box, client.target);
1716
+ ep = sshEndpoint(box, client.target, opts.direct);
1664
1717
  if (!wasRunning) await spin(`waiting for ${name} to accept SSH\u2026`, waitForSsh(ep));
1718
+ else if (opts.direct) await checkDirect(ep);
1665
1719
  } finally {
1666
1720
  await client.close();
1667
1721
  }
@@ -1726,7 +1780,7 @@ async function runSsh(ssh, opts) {
1726
1780
  }).finally(() => clearTimeout(timer));
1727
1781
  return { status: status2, chunks, timedOut };
1728
1782
  }
1729
- var execCommand = new Command3("exec").description("run a command in a box and exit with its status (kvbox exec <name> -- <cmd>)").argument("<name>", "box name").argument("<cmd...>", "command, passed to the box's shell as one string (pipes, &&, cd work)").option("-e, --env <KEY=VALUE>", "set an environment variable for the command (repeatable)", collect).option("--timeout <seconds>", "kill the command after N seconds and exit 124", positiveSeconds).option("--tty", "allocate a pseudo-terminal (for interactive tools like htop)").option("--json", 'capture output and print {"output": "...", "exit_code": N}').action(async (name, cmdArgs, opts, cmd) => {
1783
+ var execCommand = new Command3("exec").description("run a command in a box and exit with its status (kvbox exec <name> -- <cmd>)").argument("<name>", "box name").argument("<cmd...>", "command, passed to the box's shell as one string (pipes, &&, cd work)").option("-e, --env <KEY=VALUE>", "set an environment variable for the command (repeatable)", collect).option("--timeout <seconds>", "kill the command after N seconds and exit 124", positiveSeconds).option("--tty", "allocate a pseudo-terminal (for interactive tools like htop)").option("--json", 'capture output and print {"output": "...", "exit_code": N}').option("--direct", "on the box's host: ssh to the box's private ip, not through the public address or relay").action(async (name, cmdArgs, opts, cmd) => {
1730
1784
  const client = await clientFor(cmd.optsWithGlobals());
1731
1785
  let ep;
1732
1786
  let cert;
@@ -1739,8 +1793,9 @@ var execCommand = new Command3("exec").description("run a command in a box and e
1739
1793
  owner = box.owner;
1740
1794
  const wasRunning = box.status === "running";
1741
1795
  if (!wasRunning) box = await wakeUp(client, box, displayName(box, me(client)));
1742
- ep = sshEndpoint(box, client.target);
1796
+ ep = sshEndpoint(box, client.target, opts.direct);
1743
1797
  if (!wasRunning) await spin(`waiting for ${name} to accept SSH\u2026`, waitForSsh(ep));
1798
+ else if (opts.direct) await checkDirect(ep);
1744
1799
  } finally {
1745
1800
  await client.close();
1746
1801
  }
@@ -1940,9 +1995,72 @@ var hibernateCommand = new Command7("hibernate").description("save a box's memor
1940
1995
  }
1941
1996
  });
1942
1997
 
1943
- // src/commands/vm/pause.ts
1998
+ // src/commands/vm/link.ts
1944
1999
  import { Command as Command8 } from "commander";
1945
- var pauseCommand = new Command8("pause").description("freeze a box in place (memory and processes kept, no CPU used; kvbox resume continues it instantly)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2000
+ function parseLinkPort(text2) {
2001
+ const port = Number(text2);
2002
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new KvboxError(`--port: expected a port from 1 to 65535, got "${text2}"`);
2003
+ return port;
2004
+ }
2005
+ var linkCommand = new Command8("link").description("let one box reach a port of another (private, same host; never public)").argument("<from>", "the box that connects").argument("<box>", "the box it may reach").requiredOption("-p, --port <port>", "the port in <box>").option("--json", "print the link as JSON").action(async (from, name, opts, cmd) => {
2006
+ const port = parseLinkPort(opts.port);
2007
+ const client = await clientFor(cmd.optsWithGlobals());
2008
+ try {
2009
+ const box = await spin(`linking ${from} to ${name}:${port}\u2026`, client.addLink(name, { from, port }));
2010
+ const user = me(client);
2011
+ const shown = displayName(box, user);
2012
+ if (opts.json) {
2013
+ json({ from, box: shown, port });
2014
+ return;
2015
+ }
2016
+ const fromName = from.slice(from.lastIndexOf("/") + 1);
2017
+ const link = box.links?.find((l) => l.port === port && l.from.slice(l.from.lastIndexOf("/") + 1) === fromName);
2018
+ const apart = link !== void 0 ? link.from.includes("/") : from.includes("/") && from.split("/")[0] !== slugOf(box.owner);
2019
+ const host = apart ? `${box.name}.${slugOf(box.owner)}.kvbox` : `${box.name}.kvbox`;
2020
+ info(`${color.green("\u2713")} box ${color.bold(from)} can reach ${color.bold(`${host}:${port}`)}`);
2021
+ if (box.status !== "running") info(` box ${shown} is ${box.status}: the link opens when it runs`);
2022
+ } finally {
2023
+ await client.close();
2024
+ }
2025
+ });
2026
+
2027
+ // src/commands/vm/links.ts
2028
+ import { Command as Command9 } from "commander";
2029
+ var linksCommand = new Command9("links").description("list the links between boxes (kvbox vm link)").argument("[box]", "only links into or out of this box").option("--json", "print as JSON").action(async (name, opts, cmd) => {
2030
+ const client = await clientFor(cmd.optsWithGlobals());
2031
+ try {
2032
+ const user = me(client);
2033
+ const machines = await client.listMachines();
2034
+ const picked = name === void 0 ? void 0 : pickRef(machines, name, user);
2035
+ const unlisted = name === void 0 || name.includes("/") || user === void 0 ? name : `${client.target.kind === "cloud" ? client.target.org ?? user : user}/${name}`;
2036
+ const wanted = picked === void 0 ? unlisted : `${slugOf(picked.owner)}/${picked.name}`;
2037
+ const rows2 = machines.flatMap((b) => {
2038
+ const box = displayName(b, user);
2039
+ const slug = box.includes("/") ? box.split("/")[0] : void 0;
2040
+ return (b.links ?? []).map((l) => {
2041
+ const source = l.from.includes("/") ? l.from : `${slugOf(b.owner)}/${l.from}`;
2042
+ const from = slug !== void 0 && !l.from.includes("/") ? `${slug}/${l.from}` : l.from;
2043
+ const row = { from: user !== void 0 && from.startsWith(`${user}/`) ? from.slice(user.length + 1) : from, box, port: l.port };
2044
+ return { row, ends: [`${slugOf(b.owner)}/${b.name}`, source] };
2045
+ });
2046
+ }).filter((r) => wanted === void 0 || r.ends.includes(wanted)).map((r) => r.row).sort((a, b) => a.box.localeCompare(b.box) || a.from.localeCompare(b.from) || a.port - b.port);
2047
+ if (opts.json) {
2048
+ json(rows2);
2049
+ return;
2050
+ }
2051
+ if (rows2.length === 0) {
2052
+ info(name === void 0 ? "no links (kvbox vm link <from> <box> --port <port>)" : `box ${name} has no links`);
2053
+ return;
2054
+ }
2055
+ table(rows2);
2056
+ } finally {
2057
+ await client.close();
2058
+ }
2059
+ });
2060
+
2061
+ // src/commands/vm/pause.ts
2062
+ import { Command as Command10 } from "commander";
2063
+ var pauseCommand = new Command10("pause").description("freeze a box in place (memory and processes kept, no CPU used; kvbox resume continues it instantly)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
1946
2064
  const client = await clientFor(cmd.optsWithGlobals());
1947
2065
  try {
1948
2066
  const box = await spin(`pausing ${name}\u2026`, client.pauseMachine(name));
@@ -1954,10 +2072,11 @@ var pauseCommand = new Command8("pause").description("freeze a box in place (mem
1954
2072
  });
1955
2073
 
1956
2074
  // src/commands/vm/proxy/claim.ts
1957
- import { Command as Command9 } from "commander";
2075
+ import { Command as Command11 } from "commander";
1958
2076
 
1959
2077
  // ../shared/src/names.ts
1960
2078
  import { createHmac } from "crypto";
2079
+ var DEFAULT_PROXY_DOMAIN = "kvbox.app";
1961
2080
  var LABEL_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
1962
2081
  var RESERVED_SUBDOMAINS = /* @__PURE__ */ new Set([
1963
2082
  "admin",
@@ -2006,9 +2125,24 @@ function assertRouteName(text2) {
2006
2125
  if (problem) throw new KvboxError(`name ${problem}`);
2007
2126
  return text2;
2008
2127
  }
2128
+ var PLATFORM_DOMAINS = ["kvbox.sh", DEFAULT_PROXY_DOMAIN];
2129
+ function domainProblem(text2, proxyDomain) {
2130
+ if (text2.length > 253) return `"${text2}" is longer than a domain may be`;
2131
+ const labels = text2.split(".");
2132
+ if (labels.length < 2 || labels.some((l) => l.length > 63 || !LABEL_RE.test(l))) return `"${text2}" is not a domain like example.com or www.example.com (lowercase, no "*", no "https://")`;
2133
+ if (!/^[a-z]{2,}$/.test(labels.at(-1)) && !labels.at(-1).startsWith("xn--")) return `"${text2}" does not end in a top-level domain`;
2134
+ const ours = [...PLATFORM_DOMAINS, ...proxyDomain ? [proxyDomain] : []];
2135
+ if (ours.some((d) => text2 === d || text2.endsWith(`.${d}`))) return `"${text2}" belongs to kvbox; bring a domain of your own`;
2136
+ return null;
2137
+ }
2138
+ function assertDomain(text2, proxyDomain) {
2139
+ const problem = domainProblem(text2, proxyDomain);
2140
+ if (problem) throw new KvboxError(`domain ${problem}`);
2141
+ return text2;
2142
+ }
2009
2143
 
2010
2144
  // src/commands/vm/proxy/claim.ts
2011
- var claimCommand = new Command9("claim").description("give a box its HTTPS address, https://<subdomain>.kvbox.app, serving one of its ports").argument("[box]", "box name (picked from a list when left out)").argument("[subdomain]", "3-63 lowercase letters, digits and '-'; must be free (asked for when left out)").option("--port <port>", "the box port the address serves (asked for when left out)").option("--json", "print the subdomain as JSON").action(async (nameArg, subArg, opts, cmd) => {
2145
+ var claimCommand = new Command11("claim").description("give a box its HTTPS address, https://<subdomain>.kvbox.app, serving one of its ports").argument("[box]", "box name (picked from a list when left out)").argument("[subdomain]", "3-63 lowercase letters, digits and '-'; must be free (asked for when left out)").option("--port <port>", "the box port the address serves (asked for when left out)").option("--json", "print the subdomain as JSON").action(async (nameArg, subArg, opts, cmd) => {
2012
2146
  if (nameArg === void 0 || subArg === void 0 || opts.port === void 0) askOrUsage("give the box, the subdomain and the port: kvbox vm proxy claim <box> <subdomain> --port <port>");
2013
2147
  if (subArg !== void 0) assertSubdomain(subArg);
2014
2148
  if (opts.port !== void 0) parsePorts([opts.port]);
@@ -2036,11 +2170,11 @@ var claimCommand = new Command9("claim").description("give a box its HTTPS addre
2036
2170
  });
2037
2171
 
2038
2172
  // src/commands/vm/proxy/index.ts
2039
- import { Command as Command15 } from "commander";
2173
+ import { Command as Command17 } from "commander";
2040
2174
 
2041
2175
  // src/commands/vm/proxy/add.ts
2042
- import { Command as Command10 } from "commander";
2043
- var addCommand = new Command10("add").description("publish box ports on the internet; each gets a random public port, or an HTTPS name with --name").argument("<box>", "box name").argument("<port...>", "ports inside the box, e.g. 3000 8080").option("--udp", "UDP instead of TCP").option("--name <name>", "serve the port at https://<name>.<subdomain>.kvbox.app (one port; needs kvbox vm proxy claim first)").option("--json", "print the new forwards as JSON").action(async (name, portTexts, opts, cmd) => {
2176
+ import { Command as Command12 } from "commander";
2177
+ var addCommand = new Command12("add").description("publish box ports on the internet; each gets a random public port, or an HTTPS name with --name").argument("<box>", "box name").argument("<port...>", "ports inside the box, e.g. 3000 8080").option("--udp", "UDP instead of TCP").option("--name <name>", "serve the port at https://<name>.<subdomain>.kvbox.app (one port; needs kvbox vm proxy claim first)").option("--json", "print the new forwards as JSON").action(async (name, portTexts, opts, cmd) => {
2044
2178
  const guestPorts = parsePorts(portTexts);
2045
2179
  if (opts.name !== void 0) {
2046
2180
  assertRouteName(opts.name);
@@ -2081,7 +2215,7 @@ var addCommand = new Command10("add").description("publish box ports on the inte
2081
2215
  });
2082
2216
 
2083
2217
  // src/commands/vm/proxy/ls.ts
2084
- import { Command as Command11 } from "commander";
2218
+ import { Command as Command13 } from "commander";
2085
2219
  async function subdomainsOf(client) {
2086
2220
  try {
2087
2221
  return await client.listSubdomains();
@@ -2090,7 +2224,7 @@ async function subdomainsOf(client) {
2090
2224
  return [];
2091
2225
  }
2092
2226
  }
2093
- var lsCommand2 = new Command11("ls").description("list the box ports published on the internet").argument("[box]", "only this box").option("--json", "print as JSON").action(async (name, opts, cmd) => {
2227
+ var lsCommand2 = new Command13("ls").description("list the box ports published on the internet").argument("[box]", "only this box").option("--json", "print as JSON").action(async (name, opts, cmd) => {
2094
2228
  const client = await clientFor(cmd.optsWithGlobals());
2095
2229
  try {
2096
2230
  const user = me(client);
@@ -2116,8 +2250,8 @@ var lsCommand2 = new Command11("ls").description("list the box ports published o
2116
2250
  });
2117
2251
 
2118
2252
  // src/commands/vm/proxy/release.ts
2119
- import { Command as Command12 } from "commander";
2120
- var releaseCommand = new Command12("release").description("give up a box's HTTPS address and every name under it").argument("<box>", "box name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
2253
+ import { Command as Command14 } from "commander";
2254
+ var releaseCommand = new Command14("release").description("give up a box's HTTPS address and every name under it").argument("<box>", "box name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
2121
2255
  const client = await clientFor(cmd.optsWithGlobals());
2122
2256
  try {
2123
2257
  requireCloud(client);
@@ -2136,8 +2270,8 @@ var releaseCommand = new Command12("release").description("give up a box's HTTPS
2136
2270
  });
2137
2271
 
2138
2272
  // src/commands/vm/proxy/rm.ts
2139
- import { Command as Command13 } from "commander";
2140
- var rmCommand = new Command13("rm").description("stop publishing box ports, or an HTTPS name with --name").argument("<box>", "box name").argument("[port...]", "ports inside the box, as given to add").option("--udp", "the UDP forwards of those ports").option("--name <name>", "the HTTPS name to free (kvbox vm proxy release frees the whole subdomain)").option("-y, --yes", "do not ask for confirmation").action(async (name, portTexts, opts, cmd) => {
2273
+ import { Command as Command15 } from "commander";
2274
+ var rmCommand = new Command15("rm").description("stop publishing box ports, or an HTTPS name with --name").argument("<box>", "box name").argument("[port...]", "ports inside the box, as given to add").option("--udp", "the UDP forwards of those ports").option("--name <name>", "the HTTPS name to free (kvbox vm proxy release frees the whole subdomain)").option("-y, --yes", "do not ask for confirmation").action(async (name, portTexts, opts, cmd) => {
2141
2275
  if (opts.name !== void 0) {
2142
2276
  assertRouteName(opts.name);
2143
2277
  if (portTexts.length > 0) throw new KvboxError("--name frees a name, not ports: kvbox vm proxy rm <box> --name <name>");
@@ -2169,8 +2303,8 @@ var rmCommand = new Command13("rm").description("stop publishing box ports, or a
2169
2303
  });
2170
2304
 
2171
2305
  // src/commands/vm/proxy/set-port.ts
2172
- import { Command as Command14 } from "commander";
2173
- var setPortCommand = new Command14("set-port").description("point a box's HTTPS address at another of its ports").argument("<box>", "box name").argument("<port>", "the box port https://<subdomain>.kvbox.app serves from now on").option("--json", "print the subdomain as JSON").action(async (name, portText, opts, cmd) => {
2306
+ import { Command as Command16 } from "commander";
2307
+ var setPortCommand = new Command16("set-port").description("point a box's HTTPS address at another of its ports").argument("<box>", "box name").argument("<port>", "the box port https://<subdomain>.kvbox.app serves from now on").option("--json", "print the subdomain as JSON").action(async (name, portText, opts, cmd) => {
2174
2308
  const [port] = parsePorts([portText]);
2175
2309
  const client = await clientFor(cmd.optsWithGlobals());
2176
2310
  try {
@@ -2188,12 +2322,12 @@ var setPortCommand = new Command14("set-port").description("point a box's HTTPS
2188
2322
  });
2189
2323
 
2190
2324
  // src/commands/vm/proxy/index.ts
2191
- var proxyCommand = new Command15("proxy").description("publish box ports on the internet").addCommand(addCommand).addCommand(lsCommand2).addCommand(rmCommand).addCommand(claimCommand).addCommand(setPortCommand).addCommand(releaseCommand);
2325
+ var proxyCommand = new Command17("proxy").description("publish box ports on the internet").addCommand(addCommand).addCommand(lsCommand2).addCommand(rmCommand).addCommand(claimCommand).addCommand(setPortCommand).addCommand(releaseCommand);
2192
2326
  for (const cmd of proxyCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
2193
2327
 
2194
2328
  // src/commands/vm/rescale.ts
2195
- import { Command as Command16, Option as Option3 } from "commander";
2196
- var rescaleCommand = new Command16("rescale").description("change a box's vCPUs, memory or disk (e.g. --vcpu 4 --mem 16GB); a running box restarts").argument("<name>", "box name").addOption(new Option3("-s, --size <size>", "a preset to start from").choices(SIZE_NAMES)).option("--vcpu <n>", "number of vCPUs").option("--mem <size>", "memory, e.g. 16GB or 4096MB").option("--disk <size>", "disk size, e.g. 32GB (grow only)").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2329
+ import { Command as Command18, Option as Option3 } from "commander";
2330
+ var rescaleCommand = new Command18("rescale").description("change a box's vCPUs, memory or disk (e.g. --vcpu 4 --mem 16GB); a running box restarts").argument("<name>", "box name").addOption(new Option3("-s, --size <size>", "a preset to start from").choices(SIZE_NAMES)).option("--vcpu <n>", "number of vCPUs").option("--mem <size>", "memory, e.g. 16GB or 4096MB").option("--disk <size>", "disk size, e.g. 32GB (grow only)").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2197
2331
  const req = {
2198
2332
  ...opts.size !== void 0 ? { size: opts.size } : {},
2199
2333
  ...opts.vcpu !== void 0 ? { vcpu: parseCount(opts.vcpu) } : {},
@@ -2238,8 +2372,8 @@ function parseGib(flag, text2) {
2238
2372
  }
2239
2373
 
2240
2374
  // src/commands/vm/resume.ts
2241
- import { Command as Command17 } from "commander";
2242
- var resumeCommand = new Command17("resume").description("continue a box that is in standby (kvbox pause)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2375
+ import { Command as Command19 } from "commander";
2376
+ var resumeCommand = new Command19("resume").description("continue a box that is in standby (kvbox pause)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2243
2377
  const client = await clientFor(cmd.optsWithGlobals());
2244
2378
  try {
2245
2379
  const box = await spin(`resuming ${name}\u2026`, client.resumeMachine(name));
@@ -2251,8 +2385,8 @@ var resumeCommand = new Command17("resume").description("continue a box that is
2251
2385
  });
2252
2386
 
2253
2387
  // src/commands/vm/rm.ts
2254
- import { Command as Command18 } from "commander";
2255
- var rmCommand2 = new Command18("rm").description("destroy a box (its disk is deleted; snapshots are kept)").argument("<name>", "box name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
2388
+ import { Command as Command20 } from "commander";
2389
+ var rmCommand2 = new Command20("rm").description("destroy a box (its disk is deleted; snapshots are kept)").argument("<name>", "box name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
2256
2390
  const client = await clientFor(cmd.optsWithGlobals());
2257
2391
  try {
2258
2392
  const box = pickRef(await boxesFor(client, name), name, me(client));
@@ -2272,8 +2406,8 @@ var rmCommand2 = new Command18("rm").description("destroy a box (its disk is del
2272
2406
  });
2273
2407
 
2274
2408
  // src/commands/vm/set.ts
2275
- import { Command as Command19 } from "commander";
2276
- var setCommand = new Command19("set").description("change a box's settings, e.g. --auto-hibernate 30m (off: never)").argument("<name>", "box name").option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never)").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2409
+ import { Command as Command21 } from "commander";
2410
+ var setCommand = new Command21("set").description("change a box's settings, e.g. --auto-hibernate 30m (off: never)").argument("<name>", "box name").option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never)").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2277
2411
  if (opts.autoHibernate === void 0) throw new KvboxError("nothing to change: give --auto-hibernate");
2278
2412
  const autoHibernateSec = parseIdleTimeout(opts.autoHibernate);
2279
2413
  const client = await clientFor(cmd.optsWithGlobals());
@@ -2292,8 +2426,8 @@ var setCommand = new Command19("set").description("change a box's settings, e.g.
2292
2426
  });
2293
2427
 
2294
2428
  // src/commands/vm/start.ts
2295
- import { Command as Command20 } from "commander";
2296
- var startCommand = new Command20("start").description("boot a stopped box again (same name, IP and disk)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2429
+ import { Command as Command22 } from "commander";
2430
+ var startCommand = new Command22("start").description("boot a stopped box again (same name, IP and disk)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2297
2431
  const client = await clientFor(cmd.optsWithGlobals());
2298
2432
  try {
2299
2433
  const box = await spin(`booting ${name}\u2026`, client.startMachine(name));
@@ -2305,8 +2439,8 @@ var startCommand = new Command20("start").description("boot a stopped box again
2305
2439
  });
2306
2440
 
2307
2441
  // src/commands/vm/stop.ts
2308
- import { Command as Command21 } from "commander";
2309
- var stopCommand = new Command21("stop").description("shut a box down (its disk is kept; start it again with kvbox start)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2442
+ import { Command as Command23 } from "commander";
2443
+ var stopCommand = new Command23("stop").description("shut a box down (its disk is kept; start it again with kvbox start)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2310
2444
  const client = await clientFor(cmd.optsWithGlobals());
2311
2445
  try {
2312
2446
  const box = await spin(`shutting ${name} down\u2026`, client.stopMachine(name));
@@ -2318,8 +2452,8 @@ var stopCommand = new Command21("stop").description("shut a box down (its disk i
2318
2452
  });
2319
2453
 
2320
2454
  // src/commands/vm/top.ts
2321
- import { Command as Command22 } from "commander";
2322
- var topCommand = new Command22("top").description("load, memory and disk of each running box, as the box itself sees them").option("-a, --all", "every running box on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
2455
+ import { Command as Command24 } from "commander";
2456
+ var topCommand = new Command24("top").description("load, memory and disk of each running box, as the box itself sees them").option("-a, --all", "every running box on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
2323
2457
  const client = await clientFor(cmd.optsWithGlobals());
2324
2458
  try {
2325
2459
  const running = (await client.listMachines({ all: opts.all })).filter((b) => b.status === "running");
@@ -2378,9 +2512,31 @@ function topRows(entries, cloud) {
2378
2512
  });
2379
2513
  }
2380
2514
 
2515
+ // src/commands/vm/unlink.ts
2516
+ import { Command as Command25 } from "commander";
2517
+ var unlinkCommand = new Command25("unlink").description("take a link away (kvbox vm link)").argument("<from>", "the box that connects").argument("<box>", "the box it reaches").requiredOption("-p, --port <port>", "the port in <box>").option("-y, --yes", "do not ask for confirmation").option("--json", "print the removed link as JSON").action(async (from, name, opts, cmd) => {
2518
+ const port = parseLinkPort(opts.port);
2519
+ if (!await confirm(`Cut box ${from} off from box ${name} port ${port}? Its open connections close too.`, opts.yes ?? false)) {
2520
+ info("cancelled");
2521
+ process.exitCode = 1;
2522
+ return;
2523
+ }
2524
+ const client = await clientFor(cmd.optsWithGlobals());
2525
+ try {
2526
+ await spin(`unlinking ${from} from ${name}:${port}\u2026`, client.removeLink(name, { from, port }));
2527
+ if (opts.json) {
2528
+ json({ from, box: name, port });
2529
+ return;
2530
+ }
2531
+ info(`${color.green("\u2713")} box ${color.bold(from)} no longer reaches ${color.bold(name)} port ${port}`);
2532
+ } finally {
2533
+ await client.close();
2534
+ }
2535
+ });
2536
+
2381
2537
  // src/commands/vm/update.ts
2382
- import { Command as Command23 } from "commander";
2383
- var updateCommand = new Command23("update").description("move a box onto the current base image (its files stay; a running box restarts)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2538
+ import { Command as Command26 } from "commander";
2539
+ var updateCommand = new Command26("update").description("move a box onto the current base image (its files stay; a running box restarts)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2384
2540
  const client = await clientFor(cmd.optsWithGlobals());
2385
2541
  try {
2386
2542
  const before = pickRef(await boxesFor(client, name), name, me(client));
@@ -2402,8 +2558,8 @@ var updateCommand = new Command23("update").description("move a box onto the cur
2402
2558
  });
2403
2559
 
2404
2560
  // src/commands/vm/usage.ts
2405
- import { Command as Command24 } from "commander";
2406
- var usageCommand = new Command24("usage").description("how long a box ran, slept and sat stopped, as vCPU-hours, RAM and disk GiB-hours (and cost, when the host prices them)").argument("<name>", "box name").option("--since <date>", "count from this date instead of the box's creation, e.g. 2026-10-01").option("--json", "print as JSON").action(async (name, opts, cmd) => {
2561
+ import { Command as Command27 } from "commander";
2562
+ var usageCommand = new Command27("usage").description("how long a box ran, slept and sat stopped, as vCPU-hours, RAM and disk GiB-hours (and cost, when the host prices them)").argument("<name>", "box name").option("--since <date>", "count from this date instead of the box's creation, e.g. 2026-10-01").option("--json", "print as JSON").action(async (name, opts, cmd) => {
2407
2563
  let since;
2408
2564
  if (opts.since !== void 0) {
2409
2565
  const t = Date.parse(opts.since);
@@ -2450,8 +2606,8 @@ function block(u) {
2450
2606
  }
2451
2607
 
2452
2608
  // src/commands/vm/wake.ts
2453
- import { Command as Command25 } from "commander";
2454
- var wakeCommand = new Command25("wake").description("continue a hibernated box where it left off (same name, IP and disk)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2609
+ import { Command as Command28 } from "commander";
2610
+ var wakeCommand = new Command28("wake").description("continue a hibernated box where it left off (same name, IP and disk)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2455
2611
  const client = await clientFor(cmd.optsWithGlobals());
2456
2612
  try {
2457
2613
  const box = await spin(`waking ${name} (loading its memory from disk)\u2026`, client.wakeMachine(name));
@@ -2463,15 +2619,15 @@ var wakeCommand = new Command25("wake").description("continue a hibernated box w
2463
2619
  });
2464
2620
 
2465
2621
  // src/commands/vm/index.ts
2466
- var vmCommand = new Command26("vm").enablePositionalOptions().description("manage boxes (each one is a Firecracker microVM)").addCommand(newCommand).addCommand(forkCommand).addCommand(lsCommand).addCommand(getCommand).addCommand(connectCommand).addCommand(execCommand).addCommand(stopCommand).addCommand(startCommand).addCommand(pauseCommand).addCommand(resumeCommand).addCommand(hibernateCommand).addCommand(wakeCommand).addCommand(updateCommand).addCommand(rescaleCommand).addCommand(setCommand).addCommand(usageCommand).addCommand(topCommand).addCommand(proxyCommand).addCommand(rmCommand2);
2622
+ var vmCommand = new Command29("vm").enablePositionalOptions().description("manage boxes (each one is a Firecracker microVM)").addCommand(newCommand).addCommand(forkCommand).addCommand(lsCommand).addCommand(getCommand).addCommand(connectCommand).addCommand(execCommand).addCommand(stopCommand).addCommand(startCommand).addCommand(pauseCommand).addCommand(resumeCommand).addCommand(hibernateCommand).addCommand(wakeCommand).addCommand(updateCommand).addCommand(rescaleCommand).addCommand(setCommand).addCommand(usageCommand).addCommand(topCommand).addCommand(proxyCommand).addCommand(linkCommand).addCommand(unlinkCommand).addCommand(linksCommand).addCommand(rmCommand2);
2467
2623
  for (const cmd of vmCommand.commands) if (cmd !== proxyCommand) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
2468
2624
  var vmAliases = [newCommand, lsCommand, getCommand, connectCommand, execCommand, stopCommand, startCommand, pauseCommand, resumeCommand, hibernateCommand, wakeCommand, rmCommand2, claimCommand];
2469
2625
 
2470
2626
  // src/commands/server/index.ts
2471
- import { Command as Command34 } from "commander";
2627
+ import { Command as Command37 } from "commander";
2472
2628
 
2473
2629
  // src/commands/server/join.ts
2474
- import { Command as Command27 } from "commander";
2630
+ import { Command as Command30 } from "commander";
2475
2631
 
2476
2632
  // src/commands/server/daemon.ts
2477
2633
  import { spawn as spawn3 } from "child_process";
@@ -2525,7 +2681,7 @@ function runKvboxServer(args) {
2525
2681
  }
2526
2682
 
2527
2683
  // src/commands/server/join.ts
2528
- var joinCommand = new Command27("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) => {
2684
+ var joinCommand = new Command30("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) => {
2529
2685
  const args = ["join", url, "--token", opts.token];
2530
2686
  if (opts.advertise !== void 0) args.push("--advertise", opts.advertise);
2531
2687
  if (opts.name !== void 0) args.push("--name", opts.name);
@@ -2535,8 +2691,8 @@ var joinCommand = new Command27("join").description("put this machine behind a c
2535
2691
  });
2536
2692
 
2537
2693
  // src/commands/server/leave.ts
2538
- import { Command as Command28 } from "commander";
2539
- var leaveCommand = new Command28("leave").description("take this machine out from behind its control plane and restart its server").action(async () => {
2694
+ import { Command as Command31 } from "commander";
2695
+ var leaveCommand = new Command31("leave").description("take this machine out from behind its control plane and restart its server").action(async () => {
2540
2696
  const p = paths();
2541
2697
  for (const line of (await runKvboxServer(["leave"])).split("\n")) info(line);
2542
2698
  if (await runningPid(p) === null) return;
@@ -2545,14 +2701,14 @@ var leaveCommand = new Command28("leave").description("take this machine out fro
2545
2701
  });
2546
2702
 
2547
2703
  // src/commands/server/relay.ts
2548
- import { Command as Command29 } from "commander";
2549
- var relayCommand = new Command29("relay").description("reach the internet through a relay (paste what `kvbox-relay add` printed on the relay VM); `off` takes the tunnel down").argument("<join-string>", "the line `kvbox-relay add` printed, or `off`").action(async (joinString) => {
2704
+ import { Command as Command32 } from "commander";
2705
+ var relayCommand = new Command32("relay").description("reach the internet through a relay (paste what `kvbox-relay add` printed on the relay VM); `off` takes the tunnel down").argument("<join-string>", "the line `kvbox-relay add` printed, or `off`").action(async (joinString) => {
2550
2706
  for (const line of (await runKvboxServer(["relay", joinString])).split("\n")) info(line);
2551
2707
  });
2552
2708
 
2553
2709
  // src/commands/server/start.ts
2554
- import { Command as Command30 } from "commander";
2555
- var startCommand2 = new Command30("start").description("start the local kvbox-server in the background").action(async (_opts, cmd) => {
2710
+ import { Command as Command33 } from "commander";
2711
+ var startCommand2 = new Command33("start").description("start the local kvbox-server in the background").action(async (_opts, cmd) => {
2556
2712
  const client = await clientFor({ ...cmd.optsWithGlobals(), local: true }, { autoStart: false });
2557
2713
  try {
2558
2714
  const health = await client.health();
@@ -2568,8 +2724,8 @@ var startCommand2 = new Command30("start").description("start the local kvbox-se
2568
2724
  });
2569
2725
 
2570
2726
  // src/commands/server/status.ts
2571
- import { Command as Command31 } from "commander";
2572
- var statusCommand = new Command31("status").description("show whether this machine's server is running, its control plane and which base image new boxes get").option("--json", "print as JSON").action(async (opts, cmd) => {
2727
+ import { Command as Command34 } from "commander";
2728
+ var statusCommand = new Command34("status").description("show whether this machine's server is running, its control plane and which base image new boxes get").option("--json", "print as JSON").action(async (opts, cmd) => {
2573
2729
  const client = await clientFor({ ...cmd.optsWithGlobals(), local: true });
2574
2730
  try {
2575
2731
  const health = await client.health();
@@ -2601,8 +2757,8 @@ var statusCommand = new Command31("status").description("show whether this machi
2601
2757
  });
2602
2758
 
2603
2759
  // src/commands/server/stop.ts
2604
- import { Command as Command32 } from "commander";
2605
- var stopCommand2 = new Command32("stop").description("stop the local server (running boxes are not affected)").action(async () => {
2760
+ import { Command as Command35 } from "commander";
2761
+ var stopCommand2 = new Command35("stop").description("stop the local server (running boxes are not affected)").action(async () => {
2606
2762
  const pid = await runningPid(paths());
2607
2763
  if (pid === null) throw new KvboxError("kvbox-server is not running");
2608
2764
  await stopLocalServer(pid);
@@ -2610,8 +2766,8 @@ var stopCommand2 = new Command32("stop").description("stop the local server (run
2610
2766
  });
2611
2767
 
2612
2768
  // src/commands/server/trust-ca.ts
2613
- import { Command as Command33 } from "commander";
2614
- var trustCaCommand = new Command33("trust-ca").description("make every cloud box on this machine trust a new SSH CA (after `ca rotate` on the control plane)").argument("[public-key]", "the CA public key (or its cert-authority line); or --from-cloud").option("--from-cloud", "ask the control plane this host joined for its current CA, show the fingerprint, then ask").option("-y, --yes", "do not ask for confirmation").option("--json", "print the report as JSON").action(async (publicKey, opts, cmd) => {
2769
+ import { Command as Command36 } from "commander";
2770
+ var trustCaCommand = new Command36("trust-ca").description("make every cloud box on this machine trust a new SSH CA (after `ca rotate` on the control plane)").argument("[public-key]", "the CA public key (or its cert-authority line); or --from-cloud").option("--from-cloud", "ask the control plane this host joined for its current CA, show the fingerprint, then ask").option("-y, --yes", "do not ask for confirmation").option("--json", "print the report as JSON").action(async (publicKey, opts, cmd) => {
2615
2771
  if (publicKey === void 0 && !opts.fromCloud) throw new KvboxError("give the CA public key, or --from-cloud to fetch it from the control plane this host joined");
2616
2772
  if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
2617
2773
  const client = await clientFor({ ...cmd.optsWithGlobals(), local: true });
@@ -2649,7 +2805,7 @@ function describeReport(report) {
2649
2805
  }
2650
2806
 
2651
2807
  // src/commands/server/index.ts
2652
- var serverCommand = new Command34("server").description("run or manage the kvbox server").addCommand(startCommand2).addCommand(statusCommand).addCommand(stopCommand2).addCommand(joinCommand).addCommand(leaveCommand).addCommand(relayCommand).addCommand(trustCaCommand);
2808
+ var serverCommand = new Command37("server").description("run or manage the kvbox server").addCommand(startCommand2).addCommand(statusCommand).addCommand(stopCommand2).addCommand(joinCommand).addCommand(leaveCommand).addCommand(relayCommand).addCommand(trustCaCommand);
2653
2809
 
2654
2810
  // src/commands/login.ts
2655
2811
  import { spawnSync as spawnSync3 } from "child_process";
@@ -2657,8 +2813,8 @@ import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile3 } from
2657
2813
  import { hostname as osHostname } from "os";
2658
2814
  import { createInterface as createInterface2 } from "readline/promises";
2659
2815
  import { Writable } from "stream";
2660
- import { Command as Command35 } from "commander";
2661
- var loginCommand = new Command35("login").description("log in to the kvbox cloud (or your own control plane) and target it from now on").argument("[url]", `control plane URL (default: ${DEFAULT_CLOUD_URL})`).option("-e, --email <email>", "account email (prompted otherwise)").option("--password-stdin", "read the password from the first line of stdin (for scripts)").action(async (urlArg, opts) => {
2816
+ import { Command as Command38 } from "commander";
2817
+ var loginCommand = new Command38("login").description("log in to the kvbox cloud (or your own control plane) and target it from now on").argument("[url]", `control plane URL (default: ${DEFAULT_CLOUD_URL})`).option("-e, --email <email>", "account email (prompted otherwise)").option("--password-stdin", "read the password from the first line of stdin (for scripts)").action(async (urlArg, opts) => {
2662
2818
  const url = normalizeUrl(urlArg ?? DEFAULT_CLOUD_URL);
2663
2819
  const creds = await readCredentials(opts);
2664
2820
  const session = await runLogin(url, creds, paths());
@@ -2738,8 +2894,8 @@ async function firstLine(stream) {
2738
2894
  }
2739
2895
 
2740
2896
  // src/commands/logout.ts
2741
- import { Command as Command36 } from "commander";
2742
- var logoutCommand = new Command36("logout").description("log out of the control plane; commands target this machine's kvbox-server again").action(async () => {
2897
+ import { Command as Command39 } from "commander";
2898
+ var logoutCommand = new Command39("logout").description("log out of the control plane; commands target this machine's kvbox-server again").action(async () => {
2743
2899
  const p = paths();
2744
2900
  const session = await readSession(p).catch(() => null);
2745
2901
  switch (await runLogout(p)) {
@@ -2776,8 +2932,8 @@ async function runLogout(p = paths()) {
2776
2932
  }
2777
2933
 
2778
2934
  // src/commands/whoami.ts
2779
- import { Command as Command37 } from "commander";
2780
- var whoamiCommand = new Command37("whoami").description("show which account and control plane commands target (or local mode)").option("--json", "print as JSON").action(async (opts) => {
2935
+ import { Command as Command40 } from "commander";
2936
+ var whoamiCommand = new Command40("whoami").description("show which account and control plane commands target (or local mode)").option("--json", "print as JSON").action(async (opts) => {
2781
2937
  const session = await readSession();
2782
2938
  if (opts.json) {
2783
2939
  json(session ? { user: session.user, url: session.url, sshCertExpires: session.sshCertExpires ?? null } : null);
@@ -2793,11 +2949,11 @@ function describeSession(session) {
2793
2949
  }
2794
2950
 
2795
2951
  // src/commands/snapshots/index.ts
2796
- import { Command as Command41 } from "commander";
2952
+ import { Command as Command44 } from "commander";
2797
2953
 
2798
2954
  // src/commands/snapshots/ls.ts
2799
- import { Command as Command38 } from "commander";
2800
- var lsCommand3 = new Command38("ls").description("list snapshots (yours and your orgs'; --org <slug> for one org)").option("-a, --all", "every snapshot on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
2955
+ import { Command as Command41 } from "commander";
2956
+ var lsCommand3 = new Command41("ls").description("list snapshots (yours and your orgs'; --org <slug> for one org)").option("-a, --all", "every snapshot on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
2801
2957
  const client = await clientFor(cmd.optsWithGlobals());
2802
2958
  try {
2803
2959
  const cloud = client.target.kind === "cloud";
@@ -2828,21 +2984,22 @@ var lsCommand3 = new Command38("ls").description("list snapshots (yours and your
2828
2984
  });
2829
2985
 
2830
2986
  // src/commands/snapshots/new.ts
2831
- import { Command as Command39 } from "commander";
2832
- var newCommand2 = new Command39("new").description("freeze a running box (memory + disk) into a snapshot; the box keeps running").argument("<box>", "box name").argument("<name>", "snapshot name").option("--json", "print the snapshot as JSON").action(async (box, name, opts, cmd) => {
2987
+ import { Command as Command42 } from "commander";
2988
+ var newCommand2 = new Command42("new").description("freeze a running box (memory + disk) into a snapshot; the box keeps running").argument("<box>", "box name").argument("<name>", "snapshot name").option("--replace", "retake a snapshot that exists under this name; the old one stays until the new one is complete").option("--json", "print the snapshot as JSON").action(async (box, name, opts, cmd) => {
2833
2989
  const client = await clientFor(cmd.optsWithGlobals());
2834
2990
  try {
2835
- const snap = await spin(`saving snapshot ${name} from box ${box} (memory + disk)\u2026`, client.createSnapshot({ box, name }));
2991
+ const req = { box, name, ...opts.replace ? { replace: true } : {} };
2992
+ const snap = await spin(`saving snapshot ${name} from box ${box} (memory + disk)\u2026`, client.createSnapshot(req));
2836
2993
  if (opts.json) json(snap);
2837
- else info(`${color.green("\u2713")} snapshot ${name} saved from box ${box} (${gb(snap.sizeBytes)} on disk); start a warm clone with: kvbox new --from ${name}`);
2994
+ else info(`${color.green("\u2713")} snapshot ${name} ${opts.replace ? "retaken" : "saved"} from box ${box} (${gb(snap.sizeBytes)} on disk); start a warm clone with: kvbox new --from ${name}`);
2838
2995
  } finally {
2839
2996
  await client.close();
2840
2997
  }
2841
2998
  });
2842
2999
 
2843
3000
  // src/commands/snapshots/rm.ts
2844
- import { Command as Command40 } from "commander";
2845
- var rmCommand3 = new Command40("rm").description("delete a snapshot (boxes made from it are not affected)").argument("<name>", "snapshot name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
3001
+ import { Command as Command43 } from "commander";
3002
+ var rmCommand3 = new Command43("rm").description("delete a snapshot (boxes made from it are not affected)").argument("<name>", "snapshot name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
2846
3003
  if (!await confirm(`Delete snapshot ${name}?`, opts.yes ?? false)) {
2847
3004
  info("cancelled");
2848
3005
  process.exitCode = 1;
@@ -2858,14 +3015,14 @@ var rmCommand3 = new Command40("rm").description("delete a snapshot (boxes made
2858
3015
  });
2859
3016
 
2860
3017
  // src/commands/snapshots/index.ts
2861
- var snapshotsCommand = new Command41("snapshots").aliases(["snapshot", "snap"]).description("freeze running boxes into snapshots and manage them").addCommand(newCommand2).addCommand(lsCommand3).addCommand(rmCommand3);
3018
+ var snapshotsCommand = new Command44("snapshots").aliases(["snapshot", "snap"]).description("freeze running boxes into snapshots and manage them").addCommand(newCommand2).addCommand(lsCommand3).addCommand(rmCommand3);
2862
3019
  for (const cmd of snapshotsCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
2863
3020
 
2864
3021
  // src/commands/org/index.ts
2865
- import { Command as Command47 } from "commander";
3022
+ import { Command as Command50 } from "commander";
2866
3023
 
2867
3024
  // src/commands/org/ls.ts
2868
- import { Command as Command42 } from "commander";
3025
+ import { Command as Command45 } from "commander";
2869
3026
 
2870
3027
  // src/commands/org/context.ts
2871
3028
  var NOT_LOGGED_IN = "orgs live on the control plane: kvbox login first";
@@ -2885,7 +3042,7 @@ function orgFor(opts, target) {
2885
3042
  }
2886
3043
 
2887
3044
  // src/commands/org/ls.ts
2888
- var lsCommand4 = new Command42("ls").description("list the orgs you belong to and your role in each").option("--json", "print as JSON").action(async (opts, cmd) => {
3045
+ var lsCommand4 = new Command45("ls").description("list the orgs you belong to and your role in each").option("--json", "print as JSON").action(async (opts, cmd) => {
2889
3046
  const client = await cloudClientFor(cmd.optsWithGlobals());
2890
3047
  try {
2891
3048
  const orgs = await client.listOrgs();
@@ -2907,8 +3064,8 @@ function orgRows(orgs) {
2907
3064
  }
2908
3065
 
2909
3066
  // src/commands/org/members.ts
2910
- import { Command as Command43, Option as Option4 } from "commander";
2911
- var lsCommand5 = new Command43("ls").description("list an org's members and their roles").option("-o, --org <slug>", "the org (or --org before the command)").option("--json", "print as JSON").action(async (opts, cmd) => {
3067
+ import { Command as Command46, Option as Option4 } from "commander";
3068
+ var lsCommand5 = new Command46("ls").description("list an org's members and their roles").option("-o, --org <slug>", "the org (or --org before the command)").option("--json", "print as JSON").action(async (opts, cmd) => {
2912
3069
  const client = await cloudClientFor(cmd.optsWithGlobals());
2913
3070
  try {
2914
3071
  const org = await client.getOrg(orgFor(opts, client.target));
@@ -2922,7 +3079,7 @@ var lsCommand5 = new Command43("ls").description("list an org's members and thei
2922
3079
  await client.close();
2923
3080
  }
2924
3081
  });
2925
- var addCommand2 = new Command43("add").description("add a user to an org (admins and owners; only an owner can add an owner)").argument("<user>", "their username").addOption(new Option4("-r, --role <role>", "their role").choices(ORG_ROLES).default("member")).option("-o, --org <slug>", "the org (or --org before the command)").action(async (user, opts, cmd) => {
3082
+ var addCommand2 = new Command46("add").description("add a user to an org (admins and owners; only an owner can add an owner)").argument("<user>", "their username").addOption(new Option4("-r, --role <role>", "their role").choices(ORG_ROLES).default("member")).option("-o, --org <slug>", "the org (or --org before the command)").action(async (user, opts, cmd) => {
2926
3083
  const client = await cloudClientFor(cmd.optsWithGlobals());
2927
3084
  try {
2928
3085
  const slug = orgFor(opts, client.target);
@@ -2932,7 +3089,7 @@ var addCommand2 = new Command43("add").description("add a user to an org (admins
2932
3089
  await client.close();
2933
3090
  }
2934
3091
  });
2935
- var rmCommand4 = new Command43("rm").description("remove a member (or leave: remove yourself)").argument("<user>", "their username").option("-o, --org <slug>", "the org (or --org before the command)").option("-y, --yes", "do not ask for confirmation").action(async (user, opts, cmd) => {
3092
+ var rmCommand4 = new Command46("rm").description("remove a member (or leave: remove yourself)").argument("<user>", "their username").option("-o, --org <slug>", "the org (or --org before the command)").option("-y, --yes", "do not ask for confirmation").action(async (user, opts, cmd) => {
2936
3093
  const client = await cloudClientFor(cmd.optsWithGlobals());
2937
3094
  try {
2938
3095
  const slug = orgFor(opts, client.target);
@@ -2948,11 +3105,11 @@ var rmCommand4 = new Command43("rm").description("remove a member (or leave: rem
2948
3105
  await client.close();
2949
3106
  }
2950
3107
  });
2951
- var membersCommand = new Command43("members").description("who is in an org and what they may do").addCommand(lsCommand5).addCommand(addCommand2).addCommand(rmCommand4);
3108
+ var membersCommand = new Command46("members").description("who is in an org and what they may do").addCommand(lsCommand5).addCommand(addCommand2).addCommand(rmCommand4);
2952
3109
 
2953
3110
  // src/commands/org/new.ts
2954
- import { Command as Command44 } from "commander";
2955
- var newCommand3 = new Command44("new").description("create an org; you become its owner (the slug is permanent, the name is not)").argument("<slug>", "the org's slug: lowercase, like a username (acme)").option("-n, --name <name>", "display name (default: the slug)").option("--json", "print the org as JSON").action(async (slug, opts, cmd) => {
3111
+ import { Command as Command47 } from "commander";
3112
+ var newCommand3 = new Command47("new").description("create an org; you become its owner (the slug is permanent, the name is not)").argument("<slug>", "the org's slug: lowercase, like a username (acme)").option("-n, --name <name>", "display name (default: the slug)").option("--json", "print the org as JSON").action(async (slug, opts, cmd) => {
2956
3113
  const client = await cloudClientFor(cmd.optsWithGlobals());
2957
3114
  try {
2958
3115
  const org = await client.createOrg({ slug, name: opts.name ?? slug });
@@ -2968,8 +3125,8 @@ var newCommand3 = new Command44("new").description("create an org; you become it
2968
3125
  });
2969
3126
 
2970
3127
  // src/commands/org/rm.ts
2971
- import { Command as Command45 } from "commander";
2972
- var rmCommand5 = new Command45("rm").description("delete an org (owners only; remove its boxes and snapshots first)").argument("<slug>", "the org").option("-y, --yes", "do not ask for confirmation").action(async (slug, opts, cmd) => {
3128
+ import { Command as Command48 } from "commander";
3129
+ var rmCommand5 = new Command48("rm").description("delete an org (owners only; remove its boxes and snapshots first)").argument("<slug>", "the org").option("-y, --yes", "do not ask for confirmation").action(async (slug, opts, cmd) => {
2973
3130
  if (!await confirm(`Delete org ${slug}? Its members lose access; its slug stays taken.`, opts.yes ?? false)) {
2974
3131
  info("cancelled");
2975
3132
  process.exitCode = 1;
@@ -2985,8 +3142,8 @@ var rmCommand5 = new Command45("rm").description("delete an org (owners only; re
2985
3142
  });
2986
3143
 
2987
3144
  // src/commands/org/role.ts
2988
- import { Argument, Command as Command46 } from "commander";
2989
- var roleCommand = new Command46("role").description("change a member's role (owners only)").argument("<user>", "their username").addArgument(new Argument("<role>", "owner, admin or member").choices(ORG_ROLES)).option("-o, --org <slug>", "the org (default: the current context)").action(async (user, role, opts, cmd) => {
3145
+ import { Argument, Command as Command49 } from "commander";
3146
+ var roleCommand = new Command49("role").description("change a member's role (owners only)").argument("<user>", "their username").addArgument(new Argument("<role>", "owner, admin or member").choices(ORG_ROLES)).option("-o, --org <slug>", "the org (default: the current context)").action(async (user, role, opts, cmd) => {
2990
3147
  const client = await cloudClientFor(cmd.optsWithGlobals());
2991
3148
  try {
2992
3149
  const slug = orgFor(opts, client.target);
@@ -2998,10 +3155,10 @@ var roleCommand = new Command46("role").description("change a member's role (own
2998
3155
  });
2999
3156
 
3000
3157
  // src/commands/org/index.ts
3001
- var orgCommand = new Command47("org").description("orgs: shared slugs that own boxes, with owners, admins and members").addCommand(lsCommand4).addCommand(newCommand3).addCommand(membersCommand).addCommand(roleCommand).addCommand(rmCommand5);
3158
+ var orgCommand = new Command50("org").description("orgs: shared slugs that own boxes, with owners, admins and members").addCommand(lsCommand4).addCommand(newCommand3).addCommand(membersCommand).addCommand(roleCommand).addCommand(rmCommand5);
3002
3159
 
3003
3160
  // src/commands/usage.ts
3004
- import { Command as Command48 } from "commander";
3161
+ import { Command as Command51 } from "commander";
3005
3162
 
3006
3163
  // ../shared/src/usage.ts
3007
3164
  import { z as z4 } from "zod";
@@ -3038,7 +3195,7 @@ function sumUsage(items, pricing) {
3038
3195
  }
3039
3196
 
3040
3197
  // src/commands/usage.ts
3041
- var usageCommand2 = new Command48("usage").description("what your boxes and volumes used this month (or --since/--until): running time, vCPU-h, RAM and disk GiB-h, cost").option("--since <date>", "count from this date, e.g. 2026-10-01 (default: the 1st of this month)").option("--until <date>", "count up to this date (default: now)").option("--org <slug>", "one org's boxes only").option("-a, --all", "every box on the platform (platform admins only)").option("--by-user", "one line per user who made the boxes (e.g. who spent what in --org)").option("--json", "print as JSON").action(async (opts, cmd) => {
3198
+ var usageCommand2 = new Command51("usage").description("what your boxes and volumes used this month (or --since/--until): running time, vCPU-h, RAM and disk GiB-h, cost").option("--since <date>", "count from this date, e.g. 2026-10-01 (default: the 1st of this month)").option("--until <date>", "count up to this date (default: now)").option("--org <slug>", "one org's boxes only").option("-a, --all", "every box on the platform (platform admins only)").option("--by-user", "one line per user who made the boxes (e.g. who spent what in --org)").option("--json", "print as JSON").action(async (opts, cmd) => {
3042
3199
  for (const [name, value] of [
3043
3200
  ["since", opts.since],
3044
3201
  ["until", opts.until]
@@ -3184,8 +3341,8 @@ function userRows(r) {
3184
3341
  }
3185
3342
 
3186
3343
  // src/commands/credit.ts
3187
- import { Command as Command49 } from "commander";
3188
- var creditCommand = new Command49("credit").description("the prepaid credit left on your account and on each of your orgs").option("--org <slug>", "one org only").option("--json", "print as JSON").action(async (opts, cmd) => {
3344
+ import { Command as Command52 } from "commander";
3345
+ var creditCommand = new Command52("credit").description("the prepaid credit left on your account and on each of your orgs").option("--org <slug>", "one org only").option("--json", "print as JSON").action(async (opts, cmd) => {
3189
3346
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
3190
3347
  try {
3191
3348
  if (client.target.kind === "local") throw new KvboxError("credit lives on the control plane: kvbox login first");
@@ -3215,7 +3372,7 @@ function creditRow(b, me2) {
3215
3372
  // src/commands/deploy/index.ts
3216
3373
  import { readFile as readFile7 } from "fs/promises";
3217
3374
  import { basename, resolve as resolve2 } from "path";
3218
- import { Command as Command50, Option as Option5 } from "commander";
3375
+ import { Command as Command53, InvalidArgumentError as InvalidArgumentError2, Option as Option5 } from "commander";
3219
3376
 
3220
3377
  // src/commands/deploy/config.ts
3221
3378
  import { readFile as readFile6, writeFile as writeFile4 } from "fs/promises";
@@ -3236,10 +3393,12 @@ function runScript(pm, script) {
3236
3393
  return pm === "yarn" ? [script] : ["run", script];
3237
3394
  }
3238
3395
 
3239
- // src/commands/deploy/templates/nextjs.ts
3396
+ // src/commands/deploy/templates/server.ts
3240
3397
  var APP_DIR = "/srv/app/current";
3241
3398
  var SERVICE = "kvbox-app";
3242
- var PORT = 3e3;
3399
+ var START_WAIT_SEC = 30;
3400
+ var APP_NOT_LISTENING = 4;
3401
+ var LOG_MARKER = "--- kvbox-app log ---";
3243
3402
  function commands(pm) {
3244
3403
  switch (pm) {
3245
3404
  case "pnpm":
@@ -3252,12 +3411,67 @@ function commands(pm) {
3252
3411
  return { setup: [], install: "if [ -f package-lock.json ]; then npm ci; else npm install; fi", build: "npm run build", start: "npm run start" };
3253
3412
  }
3254
3413
  }
3414
+ function serverRemote(opts) {
3415
+ const c = commands(opts.pm);
3416
+ const unit = [
3417
+ "[Unit]",
3418
+ "Description=kvbox deploy: the app in " + APP_DIR,
3419
+ "After=network.target",
3420
+ "",
3421
+ "[Service]",
3422
+ "User=kvbox",
3423
+ `WorkingDirectory=${APP_DIR}`,
3424
+ // PORT on the command line: the proxied address points at it, and nothing in the environment
3425
+ // file below may move the app off it (env's PORT, say, copied from a .env).
3426
+ `ExecStart=/usr/bin/env PORT=${opts.port} ${c.start}`,
3427
+ "Environment=NODE_ENV=production",
3428
+ // The box owner's variables (#88, base v0.10.0+; the `-` makes an older box start without them).
3429
+ "EnvironmentFile=-/etc/kvbox/env",
3430
+ "Restart=always",
3431
+ "RestartSec=2",
3432
+ "",
3433
+ "[Install]",
3434
+ "WantedBy=multi-user.target"
3435
+ ];
3436
+ return [
3437
+ "set -e",
3438
+ "test -d /srv/app -a -w /srv/app || exit 3",
3439
+ "rm -rf /srv/app/.incoming /srv/app/.old",
3440
+ "mkdir -p /srv/app/.incoming",
3441
+ "tar -xf - -C /srv/app/.incoming",
3442
+ "cd /srv/app/.incoming",
3443
+ // Not NODE_ENV=production here: the install would skip devDependencies, which the build needs (TypeScript, Tailwind).
3444
+ `export ${["CI=1", ...opts.env ?? []].join(" ")}`,
3445
+ ...c.setup,
3446
+ c.install,
3447
+ ...opts.build ? [c.build] : [],
3448
+ "cd /",
3449
+ `sudo -n tee /etc/systemd/system/${SERVICE}.service >/dev/null <<'UNIT'`,
3450
+ ...unit,
3451
+ "UNIT",
3452
+ `if [ -e ${APP_DIR} ]; then mv ${APP_DIR} /srv/app/.old; fi`,
3453
+ `mv /srv/app/.incoming ${APP_DIR}`,
3454
+ "sudo -n systemctl daemon-reload",
3455
+ `sudo -n systemctl enable --quiet ${SERVICE}`,
3456
+ `sudo -n systemctl restart ${SERVICE}`,
3457
+ "rm -rf /srv/app/.old",
3458
+ // bash's /dev/tcp: no curl or nc in the image needed.
3459
+ "i=0",
3460
+ `until timeout 1 bash -c '</dev/tcp/127.0.0.1/${opts.port}' 2>/dev/null; do`,
3461
+ " i=$((i+1))",
3462
+ ` if [ "$i" -ge ${START_WAIT_SEC} ]; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${SERVICE} -n 20 --no-pager -o cat || true; exit ${APP_NOT_LISTENING}; fi`,
3463
+ " sleep 1",
3464
+ "done"
3465
+ ].join("\n");
3466
+ }
3467
+
3468
+ // src/commands/deploy/templates/nextjs.ts
3255
3469
  var nextjsTemplate = {
3256
3470
  id: "nextjs",
3257
3471
  label: "Next.js",
3258
3472
  hint: "source shipped; installed, built and run in the box on port 3000",
3259
3473
  size: "s",
3260
- port: PORT,
3474
+ port: 3e3,
3261
3475
  detect(pkg) {
3262
3476
  if (!pkg) return false;
3263
3477
  return "next" in { ...pkg.dependencies, ...pkg.devDependencies };
@@ -3268,60 +3482,37 @@ var nextjsTemplate = {
3268
3482
  if (typeof ctx.pkg?.scripts?.[script] !== "string") throw new KvboxError(`${ctx.dir}: package.json has no "${script}" script; Next.js needs "build": "next build" and "start": "next start"`);
3269
3483
  }
3270
3484
  const pm = await packageManager(ctx.dir);
3271
- return { outDir: ctx.dir, exclude: ["node_modules", ".next", ".git"], pm, what: "the source" };
3485
+ return { outDir: ctx.dir, exclude: ["node_modules", ".next", ".git"], pm, what: "the source", boxBuild: true };
3272
3486
  },
3273
- /**
3274
- * The source lands in a staging directory and is installed and built there while the old app
3275
- * keeps serving; only then is it swapped into place and the service restarted, so a failed
3276
- * install or build leaves the running app alone. The unit is rewritten every time, so a changed
3277
- * package manager or start script takes effect. /srv/app is the kvbox user's (image v0.8.0+). The
3278
- * build runs in the deploy's SSH session, so it sees the owner's variables (`kvbox env`) too.
3279
- */
3280
- remote(built) {
3281
- const c = commands(built.pm);
3282
- const unit = [
3283
- "[Unit]",
3284
- "Description=kvbox deploy: the app in " + APP_DIR,
3285
- "After=network.target",
3286
- "",
3287
- "[Service]",
3288
- "User=kvbox",
3289
- `WorkingDirectory=${APP_DIR}`,
3290
- // PORT on the command line: the proxied address points at it, and nothing in the environment
3291
- // file below may move the app off it (env's PORT, say, copied from a .env).
3292
- `ExecStart=/usr/bin/env PORT=${PORT} ${c.start}`,
3293
- "Environment=NODE_ENV=production",
3294
- // The box owner's variables (#88, base v0.10.0+; the `-` makes an older box start without them).
3295
- "EnvironmentFile=-/etc/kvbox/env",
3296
- "Restart=always",
3297
- "RestartSec=2",
3298
- "",
3299
- "[Install]",
3300
- "WantedBy=multi-user.target"
3301
- ];
3302
- return [
3303
- "set -e",
3304
- "test -d /srv/app -a -w /srv/app || exit 3",
3305
- "rm -rf /srv/app/.incoming /srv/app/.old",
3306
- "mkdir -p /srv/app/.incoming",
3307
- "tar -xf - -C /srv/app/.incoming",
3308
- "cd /srv/app/.incoming",
3309
- // Not NODE_ENV=production here: the install would skip devDependencies, which the build needs (TypeScript, Tailwind).
3310
- "export CI=1 NEXT_TELEMETRY_DISABLED=1",
3311
- ...c.setup,
3312
- c.install,
3313
- c.build,
3314
- "cd /",
3315
- `sudo -n tee /etc/systemd/system/${SERVICE}.service >/dev/null <<'UNIT'`,
3316
- ...unit,
3317
- "UNIT",
3318
- `if [ -e ${APP_DIR} ]; then mv ${APP_DIR} /srv/app/.old; fi`,
3319
- `mv /srv/app/.incoming ${APP_DIR}`,
3320
- "sudo -n systemctl daemon-reload",
3321
- `sudo -n systemctl enable --quiet ${SERVICE}`,
3322
- `sudo -n systemctl restart ${SERVICE}`,
3323
- "rm -rf /srv/app/.old"
3324
- ].join("\n");
3487
+ remote(built, port) {
3488
+ return serverRemote({ pm: built.pm, port, build: true, env: ["NEXT_TELEMETRY_DISABLED=1"] });
3489
+ }
3490
+ };
3491
+
3492
+ // src/commands/deploy/templates/node.ts
3493
+ var FRAMEWORKS = ["express", "fastify", "koa", "@nestjs/core", "@hono/node-server"];
3494
+ var nodeTemplate = {
3495
+ id: "node",
3496
+ label: "Node server",
3497
+ hint: "Express, Fastify, Hono, NestJS\u2026: installed and run in the box on $PORT (3000)",
3498
+ size: "xs",
3499
+ port: 3e3,
3500
+ customPort: true,
3501
+ detect(pkg) {
3502
+ if (!pkg) return false;
3503
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
3504
+ return FRAMEWORKS.some((f) => f in deps);
3505
+ },
3506
+ async build(ctx) {
3507
+ if (typeof ctx.pkg?.scripts?.["start"] !== "string") {
3508
+ throw new KvboxError(`${ctx.dir}: package.json has no "start" script; the box runs it to start the server (for example "start": "node server.js")`);
3509
+ }
3510
+ const pm = await packageManager(ctx.dir);
3511
+ const boxBuild = typeof ctx.pkg.scripts["build"] === "string";
3512
+ return { outDir: ctx.dir, exclude: ["node_modules", ".git"], pm, what: "the source", boxBuild };
3513
+ },
3514
+ remote(built, port) {
3515
+ return serverRemote({ pm: built.pm, port, build: built.boxBuild === true });
3325
3516
  }
3326
3517
  };
3327
3518
 
@@ -3391,7 +3582,7 @@ var reactTemplate = {
3391
3582
  };
3392
3583
 
3393
3584
  // src/commands/deploy/templates/index.ts
3394
- var TEMPLATES = [reactTemplate, nextjsTemplate];
3585
+ var TEMPLATES = [reactTemplate, nextjsTemplate, nodeTemplate];
3395
3586
  var TEMPLATE_IDS = TEMPLATES.map((t) => t.id);
3396
3587
  function templateById(id) {
3397
3588
  const t = TEMPLATES.find((x) => x.id === id);
@@ -3418,7 +3609,9 @@ var DeployConfigSchema = z5.object({
3418
3609
  }).optional(),
3419
3610
  size: z5.enum(SIZE_NAMES).optional(),
3420
3611
  /** The build output directory, relative to the app; the template's default when absent. */
3421
- dist: z5.string().optional()
3612
+ dist: z5.string().optional(),
3613
+ /** The port the app serves, for a Node server that hardcodes one; the template's (3000) when absent. */
3614
+ port: z5.number().int().min(1).max(65535).optional()
3422
3615
  });
3423
3616
  async function readConfig(dir) {
3424
3617
  const path = join4(dir, CONFIG_FILE);
@@ -3507,7 +3700,7 @@ async function ship(ep, dir, remote, exclude = []) {
3507
3700
  var shipping = { ship, measure, waitForSsh };
3508
3701
 
3509
3702
  // src/commands/deploy/index.ts
3510
- var deployCommand = new Command50("deploy").description("put the app in this directory (React or Next.js) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
3703
+ var deployCommand = new Command53("deploy").description("put the app in this directory (React, Next.js or a Node server) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the port a Node server listens on, when it does not use $PORT (default 3000; saved to kvbox.json)", parsePort).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
3511
3704
  const dir = resolve2(dirArg ?? ".");
3512
3705
  const pkg = await readPackageJson(dir);
3513
3706
  const saved = await readConfig(dir);
@@ -3534,8 +3727,10 @@ var deployCommand = new Command50("deploy").description("put the app in this dir
3534
3727
  const box = created || wasRunning ? found : await wakeUp(client, found, ref);
3535
3728
  const ep = sshEndpoint(box, client.target);
3536
3729
  if (!wasRunning) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(ep));
3537
- const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built), built.exclude);
3538
- const doing = built.dist === void 0 ? `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref} and building there, a minute or two\u2026` : `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}\u2026`;
3730
+ const port = config.port ?? template.port;
3731
+ const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built, port), built.exclude);
3732
+ const there = built.boxBuild ? "installing and building there" : "installing there";
3733
+ const doing = built.dist === void 0 ? `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref} and ${there}, a minute or two\u2026` : `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}\u2026`;
3539
3734
  let result = await spin(doing, shipIt);
3540
3735
  if (result.status === SSH_FAILED3 && await renewAfterRefusal(client, cert, box.owner)) {
3541
3736
  info("renewed your SSH certificate, trying again\u2026");
@@ -3548,11 +3743,19 @@ ${result.output.trim()}` : ""}`, SSH_FAILED3);
3548
3743
  `box ${ref} runs an image too old for the ${template.label} template (base v0.8.0 or newer). Update the box (kvbox vm update ${ref}) once its host has the new image, or deploy under another name (--name) to get a fresh box`
3549
3744
  );
3550
3745
  }
3746
+ if (result.status === APP_NOT_LISTENING) {
3747
+ const log = result.output.split(LOG_MARKER)[1]?.trim();
3748
+ throw new KvboxError(
3749
+ `the app did not answer on port ${port} within ${START_WAIT_SEC} s: it crashed, or listens on another port. It must listen on process.env.PORT (${port})${template.customPort ? ", or say its port with --port" : ""}. Its log: kvbox exec ${ref} -- journalctl -u kvbox-app${log ? `
3750
+ last lines:
3751
+ ${log}` : ""}`
3752
+ );
3753
+ }
3551
3754
  if (result.status !== 0) throw new KvboxError(`deploying to ${ref} failed (exit ${result.status}):
3552
3755
  ${result.output.trim()}`);
3553
- let url = `http://${box.ip}`;
3756
+ let url = `http://${box.ip}${port === 80 ? "" : `:${port}`}`;
3554
3757
  if (cloud) {
3555
- const got = await address(client, box, ref, config, template);
3758
+ const got = await address(client, box, ref, config, port);
3556
3759
  url = got.url;
3557
3760
  if (got.subdomain !== config.subdomain) await writeConfig(dir, { ...config, subdomain: got.subdomain, ...built.dist !== void 0 && built.dist !== config.dist ? { dist: built.dist } : {} });
3558
3761
  }
@@ -3569,6 +3772,11 @@ ${result.output.trim()}`);
3569
3772
  await client.close();
3570
3773
  }
3571
3774
  });
3775
+ function parsePort(v) {
3776
+ const n = Number(v);
3777
+ if (!Number.isInteger(n) || n < 1 || n > 65535) throw new InvalidArgumentError2("expected a port, 1-65535");
3778
+ return n;
3779
+ }
3572
3780
  async function readPackageJson(dir) {
3573
3781
  try {
3574
3782
  return JSON.parse(await readFile7(resolve2(dir, "package.json"), "utf8"));
@@ -3612,7 +3820,7 @@ async function settle(dir, pkg, saved, opts, orgFlag, cloud) {
3612
3820
  const initial = detected ? TEMPLATES.indexOf(detected) : 0;
3613
3821
  templateId = await select("Template", TEMPLATES.map((t) => ({ value: t.id, label: t.label, hint: t === detected ? `${t.hint} \xB7 detected` : t.hint })), initial);
3614
3822
  }
3615
- if (templateId === void 0) throw new KvboxError(`could not tell what kind of app ${dir} is (no package.json of a Vite, Create React App or Next.js project): say it with --template ${TEMPLATE_IDS.join("|")}`);
3823
+ if (templateId === void 0) throw new KvboxError(`could not tell what kind of app ${dir} is (no package.json of a Vite, Create React App or Next.js project, or of a server on Express, Fastify, Koa, Hono or NestJS): say it with --template ${TEMPLATE_IDS.join("|")}`);
3616
3824
  const template = templateById(templateId);
3617
3825
  let name = defaults.name;
3618
3826
  if (open.name && ask) name = await text("Box name", { default: defaults.name, validate: (a) => BOX_NAME_RE.test(a) ? void 0 : NAME_RULE });
@@ -3631,6 +3839,8 @@ async function settle(dir, pkg, saved, opts, orgFlag, cloud) {
3631
3839
  if (open.size && ask) {
3632
3840
  size = await select("Box size", SIZE_NAMES.map((s) => ({ value: s, label: s, hint: `${SIZES[s].vcpu} vCPU, ${SIZES[s].memMib / 1024} GB RAM, ${SIZES[s].diskGib} GB disk` })), SIZE_NAMES.indexOf(template.size));
3633
3841
  }
3842
+ if (opts.port !== void 0 && !template.customPort) throw new KvboxError(`--port is for a Node server; the ${template.label} template serves port ${template.port}`);
3843
+ const port = opts.port ?? (template.customPort ? saved?.port : void 0);
3634
3844
  const org = orgFlag ?? saved?.org;
3635
3845
  const config = {
3636
3846
  template: template.id,
@@ -3638,7 +3848,8 @@ async function settle(dir, pkg, saved, opts, orgFlag, cloud) {
3638
3848
  ...org !== void 0 ? { org } : {},
3639
3849
  ...subdomain !== void 0 ? { subdomain } : {},
3640
3850
  size,
3641
- ...saved?.dist !== void 0 ? { dist: saved.dist } : {}
3851
+ ...saved?.dist !== void 0 ? { dist: saved.dist } : {},
3852
+ ...port !== void 0 ? { port } : {}
3642
3853
  };
3643
3854
  return { config, template, fresh };
3644
3855
  }
@@ -3668,15 +3879,15 @@ async function refuseOtherAddress(client, config) {
3668
3879
  `box ${ref} already answers at ${have.url}, not ${config.subdomain}. To keep the address: kvbox deploy --sub ${have.subdomain}. To move it: kvbox vm proxy release ${ref}, then deploy again`
3669
3880
  );
3670
3881
  }
3671
- async function address(client, box, ref, config, template) {
3882
+ async function address(client, box, ref, config, port) {
3672
3883
  const have = (await client.listSubdomains()).find((s) => s.box === box.name && s.owner === slugOf(box.owner));
3673
3884
  if (have) {
3674
- if (have.port !== template.port) await client.setSubdomainPort(ref, { port: template.port });
3885
+ if (have.port !== port) await client.setSubdomainPort(ref, { port });
3675
3886
  return { url: have.url, subdomain: have.subdomain };
3676
3887
  }
3677
3888
  const wanted = config.subdomain ?? subdomainFor(config.name);
3678
3889
  try {
3679
- const sub = await spin(`claiming https://${wanted}.kvbox.app\u2026`, client.claimSubdomain(ref, { name: wanted, port: template.port }));
3890
+ const sub = await spin(`claiming https://${wanted}.kvbox.app\u2026`, client.claimSubdomain(ref, { name: wanted, port }));
3680
3891
  return { url: sub.url, subdomain: sub.subdomain };
3681
3892
  } catch (err) {
3682
3893
  if (!(err instanceof KvboxError)) throw err;
@@ -3686,15 +3897,15 @@ the app is on box ${ref} but has no address yet: pick another with kvbox deploy
3686
3897
  }
3687
3898
 
3688
3899
  // src/commands/volume/index.ts
3689
- import { Command as Command56 } from "commander";
3900
+ import { Command as Command59 } from "commander";
3690
3901
 
3691
3902
  // src/commands/volume/attach.ts
3692
- import { Command as Command51 } from "commander";
3903
+ import { Command as Command54 } from "commander";
3693
3904
  function describeMount(machine, volume, box) {
3694
3905
  const path = machine.volumes?.find((v) => volume === v.name || volume.endsWith(`/${v.name}`))?.mountPath ?? volumeMountPath(volume.slice(volume.lastIndexOf("/") + 1));
3695
3906
  return machine.status === "running" ? ` the box was restarted; the volume is at ${path} inside it` : ` box ${box} is ${machine.status}; the volume is at ${path} once it runs`;
3696
3907
  }
3697
- var attachCommand = new Command51("attach").description("attach a volume to a box at /mnt/<volume> (a running box is restarted to take it)").argument("[volume]", "volume name (picked from a list when left out)").argument("[box]", "box name (picked from a list when left out)").option("--json", "print the box as JSON").action(async (volumeArg, boxArg, opts, cmd) => {
3908
+ var attachCommand = new Command54("attach").description("attach a volume to a box at /mnt/<volume> (a running box is restarted to take it)").argument("[volume]", "volume name (picked from a list when left out)").argument("[box]", "box name (picked from a list when left out)").option("--json", "print the box as JSON").action(async (volumeArg, boxArg, opts, cmd) => {
3698
3909
  if (volumeArg === void 0 || boxArg === void 0) askOrUsage("give the volume and the box: kvbox volume attach <volume> <box>");
3699
3910
  const client = await clientFor(cmd.optsWithGlobals());
3700
3911
  try {
@@ -3713,7 +3924,7 @@ var attachCommand = new Command51("attach").description("attach a volume to a bo
3713
3924
  });
3714
3925
 
3715
3926
  // src/commands/volume/create.ts
3716
- import { Command as Command52 } from "commander";
3927
+ import { Command as Command55 } from "commander";
3717
3928
  function parseGib2(text2) {
3718
3929
  const mib = parseMib(text2);
3719
3930
  if (mib === void 0 || mib % 1024 !== 0) throw new KvboxError(`--size ${text2}: write whole GB, like 50 or 50GB`);
@@ -3729,7 +3940,7 @@ function sizeProblem(answer) {
3729
3940
  return err instanceof KvboxError ? err.message.replace(/^--size \S+: /, "") : String(err);
3730
3941
  }
3731
3942
  }
3732
- var createCommand = new Command52("create").alias("new").description("create a volume for a box: an empty disk of its own at /mnt/<name> inside it (a running box is restarted)").argument("[name]", "volume name (1-12 chars; the box mounts it at /mnt/<name>; asked for when left out)").option("--size <gb>", "size in GB, like 50 or 50GB (whole GB; it only occupies what is written)").option("--box <box>", "the box it is for: made on that box's host and attached to it (required on kvbox.sh; optional with --local)").option("--json", "print the volume as JSON").action(async (nameArg, opts, cmd) => {
3943
+ var createCommand = new Command55("create").alias("new").description("create a volume for a box: an empty disk of its own at /mnt/<name> inside it (a running box is restarted)").argument("[name]", "volume name (1-12 chars; the box mounts it at /mnt/<name>; asked for when left out)").option("--size <gb>", "size in GB, like 50 or 50GB (whole GB; it only occupies what is written)").option("--box <box>", "the box it is for: made on that box's host and attached to it (required on kvbox.sh; optional with --local)").option("--json", "print the volume as JSON").action(async (nameArg, opts, cmd) => {
3733
3944
  const ask = interactive();
3734
3945
  if (nameArg === void 0 || opts.size === void 0) askOrUsage("give the name and the size: kvbox volume create <name> --size <gb> --box <box>");
3735
3946
  const name = nameArg ?? await text("Volume name", { validate: (a) => VOLUME_NAME_RE.test(a) ? void 0 : VOLUME_NAME_RULE });
@@ -3762,8 +3973,8 @@ var createCommand = new Command52("create").alias("new").description("create a v
3762
3973
  });
3763
3974
 
3764
3975
  // src/commands/volume/detach.ts
3765
- import { Command as Command53 } from "commander";
3766
- var detachCommand = new Command53("detach").description("detach a volume from a box; its data is kept (a running box is restarted)").argument("[volume]", "volume name (picked from a list when left out)").argument("[box]", "box name (the one the volume is on when left out)").option("--json", "print the box as JSON").action(async (volumeArg, boxArg, opts, cmd) => {
3976
+ import { Command as Command56 } from "commander";
3977
+ var detachCommand = new Command56("detach").description("detach a volume from a box; its data is kept (a running box is restarted)").argument("[volume]", "volume name (picked from a list when left out)").argument("[box]", "box name (the one the volume is on when left out)").option("--json", "print the box as JSON").action(async (volumeArg, boxArg, opts, cmd) => {
3767
3978
  if (volumeArg === void 0) askOrUsage("give the volume: kvbox volume detach <volume> [box]");
3768
3979
  const client = await clientFor(cmd.optsWithGlobals());
3769
3980
  try {
@@ -3788,8 +3999,8 @@ var detachCommand = new Command53("detach").description("detach a volume from a
3788
3999
  });
3789
4000
 
3790
4001
  // src/commands/volume/ls.ts
3791
- import { Command as Command54 } from "commander";
3792
- var lsCommand6 = new Command54("ls").alias("list").description("list volumes: size, what they occupy, which box has them").option("-a, --all", "every volume on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
4002
+ import { Command as Command57 } from "commander";
4003
+ var lsCommand6 = new Command57("ls").alias("list").description("list volumes: size, what they occupy, which box has them").option("-a, --all", "every volume on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
3793
4004
  const client = await clientFor(cmd.optsWithGlobals());
3794
4005
  try {
3795
4006
  const cloud = client.target.kind === "cloud";
@@ -3820,8 +4031,8 @@ var lsCommand6 = new Command54("ls").alias("list").description("list volumes: si
3820
4031
  });
3821
4032
 
3822
4033
  // src/commands/volume/rm.ts
3823
- import { Command as Command55 } from "commander";
3824
- var rmCommand6 = new Command55("rm").alias("remove").description("delete a volume and everything on it (detach it first)").argument("<name>", "volume name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
4034
+ import { Command as Command58 } from "commander";
4035
+ var rmCommand6 = new Command58("rm").alias("remove").description("delete a volume and everything on it (detach it first)").argument("<name>", "volume name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
3825
4036
  if (!await confirm(`Delete volume ${name} and everything on it?`, opts.yes ?? false)) {
3826
4037
  info("cancelled");
3827
4038
  process.exitCode = 1;
@@ -3837,14 +4048,14 @@ var rmCommand6 = new Command55("rm").alias("remove").description("delete a volum
3837
4048
  });
3838
4049
 
3839
4050
  // src/commands/volume/index.ts
3840
- var volumeCommand = new Command56("volume").aliases(["volumes", "vol"]).description("disks of their own: create one, attach it to a box at /mnt/<name>, move it to another box later").addCommand(createCommand).addCommand(lsCommand6).addCommand(attachCommand).addCommand(detachCommand).addCommand(rmCommand6);
4051
+ var volumeCommand = new Command59("volume").aliases(["volumes", "vol"]).description("disks of their own: create one, attach it to a box at /mnt/<name>, move it to another box later").addCommand(createCommand).addCommand(lsCommand6).addCommand(attachCommand).addCommand(detachCommand).addCommand(rmCommand6);
3841
4052
  for (const cmd of volumeCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal volumes)");
3842
4053
 
3843
4054
  // src/commands/env/index.ts
3844
- import { Command as Command60 } from "commander";
4055
+ import { Command as Command63 } from "commander";
3845
4056
 
3846
4057
  // src/commands/env/ls.ts
3847
- import { Command as Command57 } from "commander";
4058
+ import { Command as Command60 } from "commander";
3848
4059
 
3849
4060
  // src/commands/env/shared.ts
3850
4061
  function requireCloud2(client) {
@@ -3857,7 +4068,7 @@ function reach(boxes, verb) {
3857
4068
  }
3858
4069
 
3859
4070
  // src/commands/env/ls.ts
3860
- var lsCommand7 = new Command57("ls").alias("list").description("list the variables (a secret shows as (sealed))").option("--json", "print as JSON").action(async (opts, cmd) => {
4071
+ var lsCommand7 = new Command60("ls").alias("list").description("list the variables (a secret shows as (sealed))").option("--json", "print as JSON").action(async (opts, cmd) => {
3861
4072
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
3862
4073
  try {
3863
4074
  const owner = requireCloud2(client);
@@ -3877,8 +4088,8 @@ var lsCommand7 = new Command57("ls").alias("list").description("list the variabl
3877
4088
  });
3878
4089
 
3879
4090
  // src/commands/env/rm.ts
3880
- import { Command as Command58 } from "commander";
3881
- var rmCommand7 = new Command58("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("--json", "print as JSON").action(async (names, opts, cmd) => {
4091
+ import { Command as Command61 } from "commander";
4092
+ var rmCommand7 = new Command61("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("--json", "print as JSON").action(async (names, opts, cmd) => {
3882
4093
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
3883
4094
  try {
3884
4095
  const owner = requireCloud2(client);
@@ -3908,7 +4119,7 @@ var rmCommand7 = new Command58("rm").alias("remove").description("remove variabl
3908
4119
  });
3909
4120
 
3910
4121
  // src/commands/env/set.ts
3911
- import { Command as Command59 } from "commander";
4122
+ import { Command as Command62 } from "commander";
3912
4123
 
3913
4124
  // ../shared/src/env.ts
3914
4125
  var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -3927,7 +4138,7 @@ function envValueProblem(value) {
3927
4138
  }
3928
4139
 
3929
4140
  // src/commands/env/set.ts
3930
- var setCommand2 = new Command59("set").description("add or change a variable; boxes get it when they next start").argument("[name]", "variable name, e.g. DATABASE_URL (asked for when left out)").argument("[value]", "its value (asked for when left out; hidden with --secret)").option("--secret", "write-only: the value is never shown again, by any command").option("--json", "print as JSON").action(async (nameArg, valueArg, opts, cmd) => {
4141
+ var setCommand2 = new Command62("set").description("add or change a variable; boxes get it when they next start").argument("[name]", "variable name, e.g. DATABASE_URL (asked for when left out)").argument("[value]", "its value (asked for when left out; hidden with --secret)").option("--secret", "write-only: the value is never shown again, by any command").option("--json", "print as JSON").action(async (nameArg, valueArg, opts, cmd) => {
3931
4142
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
3932
4143
  try {
3933
4144
  const owner = requireCloud2(client);
@@ -3952,16 +4163,132 @@ var setCommand2 = new Command59("set").description("add or change a variable; bo
3952
4163
  });
3953
4164
 
3954
4165
  // src/commands/env/index.ts
3955
- var envCommand = new Command60("env").description("environment variables every box of yours gets when it starts (secrets too)").addCommand(lsCommand7, { isDefault: true }).addCommand(setCommand2).addCommand(rmCommand7);
4166
+ var envCommand = new Command63("env").description("environment variables every box of yours gets when it starts (secrets too)").addCommand(lsCommand7, { isDefault: true }).addCommand(setCommand2).addCommand(rmCommand7);
3956
4167
  for (const cmd of envCommand.commands) cmd.option("--org <slug>", "the org's variables instead of yours");
3957
4168
 
4169
+ // src/commands/domain/index.ts
4170
+ import { Command as Command67 } from "commander";
4171
+
4172
+ // src/commands/domain/add.ts
4173
+ import { Command as Command64 } from "commander";
4174
+
4175
+ // src/commands/domain/shared.ts
4176
+ function requireCloud3(client) {
4177
+ if (client.target.kind !== "cloud") throw new KvboxError("custom domains need the kvbox cloud: kvbox login (this host's own socket has none)");
4178
+ }
4179
+ var boxOf2 = (d, user) => user !== void 0 && d.owner !== user ? `${d.owner}/${d.box}` : d.box;
4180
+ function domainJson(d, user) {
4181
+ return { domain: d.domain, box: boxOf2(d, user), port: d.port, status: d.status, www: d.www, url: d.url, error: d.error, records: d.records, createdAt: d.createdAt };
4182
+ }
4183
+ function zoneOf(domain) {
4184
+ const labels = domain.split(".");
4185
+ const n = labels.length > 2 && labels.at(-1).length === 2 && labels.at(-2).length <= 3 ? 3 : 2;
4186
+ return labels.slice(-n).join(".");
4187
+ }
4188
+ function hostIn(name, zone) {
4189
+ return name === zone ? "@" : name.endsWith(`.${zone}`) ? name.slice(0, -(zone.length + 1)) : name;
4190
+ }
4191
+
4192
+ // src/commands/domain/add.ts
4193
+ var addCommand3 = new Command64("add").description("serve a box at a domain of your own, https://<domain>, with its certificate made for you").argument("<domain>", "a domain you control, like example.com or app.example.com").argument("<box>", "box name").option("--port <port>", "the box port the domain serves (default: the port of its kvbox.app address)").option("--json", "print the domain as JSON").action(async (domainArg, name, opts, cmd) => {
4194
+ const domain = assertDomain(domainArg.trim().toLowerCase());
4195
+ const port = opts.port === void 0 ? void 0 : parsePorts([opts.port])[0];
4196
+ const client = await clientFor(cmd.optsWithGlobals());
4197
+ try {
4198
+ requireCloud3(client);
4199
+ const user = me(client);
4200
+ const box = displayName(await findBox(client, name), user);
4201
+ const d = await spin(`adding ${domain}\u2026`, client.addDomain(box, { domain, ...port !== void 0 ? { port } : {} }));
4202
+ if (opts.json) {
4203
+ json(domainJson(d, user));
4204
+ return;
4205
+ }
4206
+ if (d.status === "live") {
4207
+ info(`${color.green("\u2713")} ${color.bold(d.url)} \u2192 box ${color.bold(box)} port ${d.port}`);
4208
+ info(" the certificate is made on the first visit, which can take a few seconds");
4209
+ return;
4210
+ }
4211
+ info(`${color.green("\u2713")} ${domain} added for box ${color.bold(box)} port ${d.port}, waiting for its DNS`);
4212
+ const zone = zoneOf(domain);
4213
+ info(`
4214
+ At the company that runs the DNS of ${zone}, add:
4215
+ `);
4216
+ table(d.records.map((r) => ({ type: r.type, host: hostIn(r.name, zone), value: r.value })));
4217
+ info(`
4218
+ (the TXT record shows ${domain} is yours; keep it, it is checked again if the domain ever goes back to pending)`);
4219
+ if (d.records.some((r) => r.type === "CNAME")) info(` (the www record is optional: with it, www.${domain} serves the same site)`);
4220
+ info(`
4221
+ kvbox checks every minute; ${domain} is served at ${d.url} once its records are set (kvbox domain ls).`);
4222
+ if (d.error) info(color.dim(` now: ${d.error}`));
4223
+ } finally {
4224
+ await client.close();
4225
+ }
4226
+ });
4227
+
4228
+ // src/commands/domain/ls.ts
4229
+ import { Command as Command65 } from "commander";
4230
+ var lsCommand8 = new Command65("ls").alias("list").description("list your custom domains and whether they are live").option("--json", "print as JSON").action(async (opts, cmd) => {
4231
+ const client = await clientFor(cmd.optsWithGlobals());
4232
+ try {
4233
+ requireCloud3(client);
4234
+ const user = me(client);
4235
+ const domains = await client.listDomains();
4236
+ if (opts.json) {
4237
+ json(domains.map((d) => domainJson(d, user)));
4238
+ return;
4239
+ }
4240
+ if (domains.length === 0) {
4241
+ info("no custom domains (kvbox domain add <domain> <box>)");
4242
+ return;
4243
+ }
4244
+ table(
4245
+ domains.map((d) => ({
4246
+ domain: d.www ? `${d.domain} (+www)` : d.domain,
4247
+ box: boxOf2(d, user),
4248
+ port: d.port,
4249
+ status: d.status === "live" ? "live" : "pending dns",
4250
+ note: d.status === "live" ? d.url : d.error ?? ""
4251
+ }))
4252
+ );
4253
+ } finally {
4254
+ await client.close();
4255
+ }
4256
+ });
4257
+
4258
+ // src/commands/domain/rm.ts
4259
+ import { Command as Command66 } from "commander";
4260
+ var rmCommand8 = new Command66("rm").alias("remove").description("stop serving a box at a custom domain").argument("<domain>", "the domain").option("-y, --yes", "do not ask for confirmation").action(async (domainArg, opts, cmd) => {
4261
+ const domain = domainArg.trim().toLowerCase();
4262
+ const client = await clientFor(cmd.optsWithGlobals());
4263
+ try {
4264
+ requireCloud3(client);
4265
+ const found = (await client.listDomains()).find((d) => d.domain === domain);
4266
+ if (!found) throw new KvboxError(`domain ${domain}: not found (kvbox domain ls)`);
4267
+ const box = boxOf2(found, me(client));
4268
+ if (!await confirm(`Stop serving box ${box} at ${domain}?`, opts.yes ?? false)) {
4269
+ info("cancelled");
4270
+ process.exitCode = 1;
4271
+ return;
4272
+ }
4273
+ await spin(`removing ${domain}\u2026`, client.removeDomain(`${found.owner}/${found.box}`, domain));
4274
+ info(`${color.green("\u2713")} ${domain} no longer serves box ${box} (you can remove its DNS record)`);
4275
+ } finally {
4276
+ await client.close();
4277
+ }
4278
+ });
4279
+
4280
+ // src/commands/domain/index.ts
4281
+ var domainCommand = new Command67("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand3).addCommand(lsCommand8).addCommand(rmCommand8);
4282
+ for (const cmd of domainCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
4283
+
3958
4284
  // src/program.ts
3959
4285
  function buildProgram() {
3960
- const program = new Command61("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").option("--org <slug>", "the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it").showHelpAfterError().enablePositionalOptions();
4286
+ const program = new Command68("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").option("--org <slug>", "the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it").showHelpAfterError().enablePositionalOptions();
3961
4287
  program.addCommand(vmCommand);
3962
4288
  program.addCommand(snapshotsCommand);
3963
4289
  program.addCommand(volumeCommand);
3964
4290
  program.addCommand(envCommand);
4291
+ program.addCommand(domainCommand);
3965
4292
  program.addCommand(serverCommand);
3966
4293
  program.addCommand(loginCommand);
3967
4294
  program.addCommand(logoutCommand);