@kvbox/cli 0.5.28 → 0.5.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kvbox.js CHANGED
@@ -164,7 +164,7 @@ function versionOf(srcFileUrl, injected) {
164
164
  }
165
165
 
166
166
  // src/version.ts
167
- var VERSION = versionOf(import.meta.url, true ? "0.5.28" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.5.29" : void 0);
168
168
 
169
169
  // src/commands/vm/index.ts
170
170
  import { Command as Command29 } from "commander";
@@ -217,6 +217,16 @@ function paths(home = kvboxHome()) {
217
217
  /** Symlink to the current base image, assets/rootfs-<version>.ext4; boxes keep using the version they were made from. */
218
218
  rootfs: join(home, "assets", "rootfs.ext4"),
219
219
  baseImage: (version) => join(home, "assets", `rootfs-${version}.ext4`),
220
+ /**
221
+ * Every other image (#87), one dir each so nothing collides with the base's `rootfs-*.ext4`:
222
+ * assets/images/<image>/rootfs-<version>.ext4, and rootfs.ext4 there the symlink to its current one.
223
+ */
224
+ images: join(home, "assets", "images"),
225
+ image: (image) => ({
226
+ dir: join(home, "assets", "images", image),
227
+ rootfs: join(home, "assets", "images", image, "rootfs.ext4"),
228
+ version: (version) => join(home, "assets", "images", image, `rootfs-${version}.ext4`)
229
+ }),
220
230
  machines: join(home, "machines"),
221
231
  snapshots: join(home, "snapshots"),
222
232
  /** Boxes and snapshots are filed by owner: machines/<owner>/<name>. The owner is part of a box's identity. */
@@ -227,6 +237,8 @@ function paths(home = kvboxHome()) {
227
237
  return {
228
238
  dir,
229
239
  meta: join(dir, "meta.json"),
240
+ /** The box's own environment variables (#87), merged over its owner's at boot. Mode 600: values in the clear. */
241
+ env: join(dir, "env.json"),
230
242
  /** The box's writable layer, stacked on the read-only base image inside the guest. */
231
243
  overlay: join(dir, "overlay.ext4"),
232
244
  /**
@@ -274,6 +286,8 @@ function paths(home = kvboxHome()) {
274
286
  meta: join(dir, "meta.json"),
275
287
  vmstate: join(dir, "vmstate"),
276
288
  mem: join(dir, "mem"),
289
+ /** The box's own environment variables when it was taken (#87); a restore starts with them. */
290
+ env: join(dir, "env.json"),
277
291
  /** Copy of the box's overlay at the moment of the snapshot; the base image is referenced by version in meta.json. */
278
292
  overlay: join(dir, "overlay.ext4")
279
293
  };
@@ -473,7 +487,9 @@ var MachineSchema = z2.object({
473
487
  diskUsedBytes: z2.number().int(),
474
488
  // what that sparse file really occupies on the host
475
489
  base: z2.string(),
476
- // base image version the box's overlay stacks on
490
+ // version of the image the box's overlay stacks on
491
+ /** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
492
+ image: z2.string().optional(),
477
493
  createdAt: z2.string(),
478
494
  source: z2.string(),
479
495
  // "base", "snapshot:<owner/name>" or "fork:<owner/name>" (#79)
@@ -498,7 +514,12 @@ var MachineSchema = z2.object({
498
514
  /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
499
515
  volumes: z2.array(z2.object({ name: z2.string(), sizeGib: z2.number().int(), mountPath: z2.string() })).optional(),
500
516
  /** Boxes that may reach this one, each on one port (#98). Absent: none. */
501
- links: z2.array(BoxLinkSchema).optional()
517
+ links: z2.array(BoxLinkSchema).optional(),
518
+ /**
519
+ * Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
520
+ * serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
521
+ */
522
+ connect: z2.string().optional()
502
523
  });
503
524
  var VolumeSchema = z2.object({
504
525
  /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
@@ -535,6 +556,16 @@ var EnvVarSchema = z2.object({
535
556
  secret: z2.boolean(),
536
557
  updatedAt: z2.string()
537
558
  });
559
+ var BoxEnvSchema = z2.object({
560
+ box: z2.string(),
561
+ vars: z2.array(EnvVarSchema)
562
+ });
563
+ var BoxEnvChangeSchema = z2.object({
564
+ box: z2.string(),
565
+ name: z2.string(),
566
+ /** Whether the box is running now: the change waits for its next start. */
567
+ running: z2.boolean()
568
+ });
538
569
  var SetEnvRequest = z2.object({
539
570
  value: z2.string(),
540
571
  secret: z2.boolean().optional()
@@ -568,7 +599,11 @@ var CreateMachineRequest = z2.object({
568
599
  * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
569
600
  * control plane reads it; a host has one place to put a box.
570
601
  */
571
- near: z2.string().optional()
602
+ near: z2.string().optional(),
603
+ /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
604
+ image: z2.string().optional(),
605
+ /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
606
+ env: z2.array(z2.object({ name: z2.string(), value: z2.string() })).optional()
572
607
  });
573
608
  var ForkMachineRequest = z2.object({
574
609
  name: z2.string().optional(),
@@ -603,7 +638,9 @@ var SnapshotSchema = z2.object({
603
638
  source: z2.string(),
604
639
  // the box it was taken from, as owner/name
605
640
  base: z2.string(),
606
- // base image version the overlay stacks on; a restore needs the same one
641
+ // version of the image the overlay stacks on; a restore needs the same one
642
+ /** As in MachineSchema: the image when it is not the base one (#87). */
643
+ image: z2.string().optional(),
607
644
  vcpu: z2.number().int(),
608
645
  memMib: z2.number().int(),
609
646
  sizeBytes: z2.number().int(),
@@ -630,7 +667,12 @@ var CapacitySchema = z2.object({
630
667
  reservedVcpu: z2.number().int(),
631
668
  running: z2.number().int(),
632
669
  /** Absent on a host from before volumes (#91): it cannot take one. */
633
- disk: DiskCapacitySchema.optional()
670
+ disk: DiskCapacitySchema.optional(),
671
+ /**
672
+ * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
673
+ * Absent on a host from before images: it has only the base.
674
+ */
675
+ images: z2.array(z2.object({ name: z2.string(), version: z2.string() })).optional()
634
676
  });
635
677
  var RecoveryReportSchema = z2.object({
636
678
  at: z2.string(),
@@ -1224,8 +1266,9 @@ var ServerClient = class {
1224
1266
  return this.call("DELETE", `/snapshots/${encodeURIComponent(name)}`, z3.undefined());
1225
1267
  }
1226
1268
  // ---- environment variables (#88), a control plane only: the caller's slug, or `--org`'s ----
1227
- listEnv() {
1228
- return this.call("GET", "/env", z3.array(EnvVarSchema));
1269
+ /** `org`: that org's list instead of `--org`'s (or the caller's own). */
1270
+ listEnv(org) {
1271
+ return this.call("GET", "/env", z3.array(EnvVarSchema), void 0, org);
1229
1272
  }
1230
1273
  setEnv(name, req) {
1231
1274
  return this.call("PUT", `/env/${encodeURIComponent(name)}`, EnvChangeSchema, req);
@@ -1233,6 +1276,16 @@ var ServerClient = class {
1233
1276
  removeEnv(name) {
1234
1277
  return this.call("DELETE", `/env/${encodeURIComponent(name)}`, EnvChangeSchema);
1235
1278
  }
1279
+ // ---- a box's own variables (#87), kept on its host, over its owner's at its next start ----
1280
+ boxEnv(name) {
1281
+ return this.call("GET", `/machines/${encodeURIComponent(name)}/env`, BoxEnvSchema);
1282
+ }
1283
+ setBoxEnv(name, variable, req) {
1284
+ return this.call("POST", `/machines/${encodeURIComponent(name)}/env/${encodeURIComponent(variable)}`, BoxEnvChangeSchema, req);
1285
+ }
1286
+ removeBoxEnv(name, variable) {
1287
+ return this.call("DELETE", `/machines/${encodeURIComponent(name)}/env/${encodeURIComponent(variable)}`, BoxEnvChangeSchema);
1288
+ }
1236
1289
  // ---- volumes (#52) ----
1237
1290
  listVolumes(opts = {}) {
1238
1291
  return this.call("GET", `/volumes${allQuery(opts)}`, z3.array(VolumeSchema), void 0, opts.org);
@@ -1644,20 +1697,49 @@ async function pickVolume(client, keep, none) {
1644
1697
 
1645
1698
  // src/commands/vm/new.ts
1646
1699
  import { Command, Option } from "commander";
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) => {
1700
+
1701
+ // ../shared/src/env.ts
1702
+ var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
1703
+ var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
1704
+ var ENV_MAX_VALUE_BYTES = 4096;
1705
+ function envNameProblem(name) {
1706
+ if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
1707
+ if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
1708
+ if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
1709
+ return null;
1710
+ }
1711
+ function envValueProblem(value) {
1712
+ if (/[\n\r\0]/.test(value)) return "a value is one line: no line breaks (base64 a multi-line value such as a key file)";
1713
+ if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
1714
+ return null;
1715
+ }
1716
+
1717
+ // src/commands/vm/new.ts
1718
+ var newCommand = new Command("new").description("boot a new box from an image (the base one, or e.g. postgres) or a snapshot").argument("[name]", "box name (box1, box2, \u2026 when omitted)").addOption(new Option("-s, --size <size>", "box size (default: server config, s)").choices(SIZE_NAMES)).option("-b, --base <image>", "the image to boot: base (default) or one the host has, e.g. postgres").option("-e, --env <NAME=value>", "a variable of the box's own, over yours (repeatable; change later with kvbox env set --box)", collect, []).option("-f, --from <snapshot>", "start from a snapshot instead of an image").option("--near <box>", "put it on the same host as this box, so the two can be linked (kvbox vm link)").option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never; default: server config, off)").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
1648
1719
  const autoHibernateSec = opts.autoHibernate === void 0 ? void 0 : parseIdleTimeout(opts.autoHibernate);
1720
+ const env = parseEnvFlags(opts.env);
1649
1721
  const client = await clientFor(cmd.optsWithGlobals());
1650
1722
  try {
1651
- const what = opts.from !== void 0 ? `restoring ${name ?? "a new box"} from snapshot ${opts.from}\u2026` : `booting ${name ?? "a new box"}\u2026`;
1723
+ const what = opts.from !== void 0 ? `restoring ${name ?? "a new box"} from snapshot ${opts.from}\u2026` : `booting ${name ?? "a new box"}${opts.base !== void 0 && opts.base !== "base" ? ` from image ${opts.base}` : ""}\u2026`;
1652
1724
  const box = await spin(what, client.createMachine({
1653
1725
  ...name !== void 0 ? { name } : {},
1654
1726
  ...opts.size !== void 0 ? { size: opts.size } : {},
1655
1727
  ...opts.from !== void 0 ? { from: opts.from } : {},
1728
+ ...opts.base !== void 0 ? { image: opts.base } : {},
1729
+ ...env.length > 0 ? { env } : {},
1656
1730
  ...opts.near !== void 0 ? { near: opts.near } : {},
1657
1731
  ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {},
1658
1732
  ...opts.force ? { force: true } : {}
1659
1733
  }));
1660
1734
  if (autoHibernateSec && !box.autoHibernateSec) warn(`box ${name ?? box.name}: its host runs a kvbox-server too old for auto-hibernate; it will not hibernate on its own`);
1735
+ if (opts.base !== void 0 && opts.base !== "base" && box.image === void 0) {
1736
+ warn(`box ${box.name}: its host runs a kvbox-server too old for images; it booted the base image, not ${opts.base}`);
1737
+ }
1738
+ if (env.length > 0) {
1739
+ const kept = await keptVars(client, displayName(box, me(client)), env.map((v) => v.name));
1740
+ if (kept === "too old") warn(`box ${box.name}: its host runs a kvbox-server too old for a box's own variables; it has none of the -e ones`);
1741
+ else if (kept !== true) warn(`box ${box.name}: could not check its -e variables (${kept}); kvbox env ls --box ${displayName(box, me(client))} shows them`);
1742
+ }
1661
1743
  if (opts.json) {
1662
1744
  json(box);
1663
1745
  return;
@@ -1669,10 +1751,24 @@ var newCommand = new Command("new").description("boot a new box from the base im
1669
1751
  if (opts.from !== void 0) info(` connect with: kvbox connect ${displayName(box, user)} (already up: everything that ran in the snapshot is running)`);
1670
1752
  else info(` connect with: kvbox connect ${displayName(box, user)} (SSH is up a couple of seconds after boot)`);
1671
1753
  if (box.autoHibernateSec) info(` it ${autoHibernateText(box.autoHibernateSec)}`);
1754
+ if (box.connect !== void 0) {
1755
+ info(` reach it at: ${box.connect}`);
1756
+ info(` from another box once linked: kvbox vm link <box> ${displayName(box, user)} --port <port>`);
1757
+ info(` its variables: kvbox env ls --box ${displayName(box, user)}`);
1758
+ }
1672
1759
  } finally {
1673
1760
  await client.close();
1674
1761
  }
1675
1762
  });
1763
+ async function keptVars(client, box, names) {
1764
+ try {
1765
+ const have = new Set((await client.boxEnv(box)).vars.map((v) => v.name));
1766
+ return names.every((n) => have.has(n)) ? true : "too old";
1767
+ } catch (err) {
1768
+ const message = err.message;
1769
+ return /no route:|too old/.test(message) ? "too old" : message;
1770
+ }
1771
+ }
1676
1772
  function displayName(box, user) {
1677
1773
  return user !== void 0 && slugOf(box.owner) !== user ? `${slugOf(box.owner)}/${box.name}` : box.name;
1678
1774
  }
@@ -1683,6 +1779,22 @@ function describe(box, user) {
1683
1779
  function autoHibernateText(sec) {
1684
1780
  return sec ? `hibernates after ${duration(sec)} without network traffic (kvbox connect wakes it)` : "never hibernates on its own";
1685
1781
  }
1782
+ function collect(value, previous) {
1783
+ return [...previous, value];
1784
+ }
1785
+ function parseEnvFlags(flags) {
1786
+ const out = /* @__PURE__ */ new Map();
1787
+ for (const flag of flags) {
1788
+ const eq = flag.indexOf("=");
1789
+ if (eq <= 0) throw new KvboxError(`-e ${flag}: expected NAME=value`);
1790
+ const name = flag.slice(0, eq);
1791
+ const value = flag.slice(eq + 1);
1792
+ const problem = envNameProblem(name) ?? envValueProblem(value);
1793
+ if (problem !== null) throw new KvboxError(`-e ${name}: ${problem}`);
1794
+ out.set(name, value);
1795
+ }
1796
+ return [...out].map(([name, value]) => ({ name, value }));
1797
+ }
1686
1798
  var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
1687
1799
  function parseIdleTimeout(text2) {
1688
1800
  const t = text2.trim().toLowerCase();
@@ -1752,7 +1864,7 @@ function remoteCommand(cmdArgs, env) {
1752
1864
  }
1753
1865
  var TIMEOUT_EXIT = 124;
1754
1866
  var SSH_FAILED2 = 255;
1755
- function collect(value, previous) {
1867
+ function collect2(value, previous) {
1756
1868
  return [...previous ?? [], value];
1757
1869
  }
1758
1870
  function positiveSeconds(value) {
@@ -1780,7 +1892,7 @@ async function runSsh(ssh, opts) {
1780
1892
  }).finally(() => clearTimeout(timer));
1781
1893
  return { status: status2, chunks, timedOut };
1782
1894
  }
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) => {
1895
+ 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)", collect2).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) => {
1784
1896
  const client = await clientFor(cmd.optsWithGlobals());
1785
1897
  let ep;
1786
1898
  let cert;
@@ -1897,7 +2009,8 @@ function lsRows(boxes, cloud) {
1897
2009
  address: addressOf(b),
1898
2010
  size: b.status === "unknown" ? "-" : `${shape(b.vcpu, b.memMib, b.diskBytes)} ${color.dim(`(${gbShort(b.diskUsedBytes)} used)`)}`,
1899
2011
  created: age(b.createdAt),
1900
- base: b.status === "unknown" || b.base === "" ? "-" : b.base
2012
+ // An image other than the base one (#87) is named: `postgres v0.1.0`.
2013
+ base: b.status === "unknown" || b.base === "" ? "-" : b.image !== void 0 ? `${b.image} ${b.base}` : b.base
1901
2014
  }));
1902
2015
  }
1903
2016
 
@@ -4066,11 +4179,44 @@ function reach(boxes, verb) {
4066
4179
  if (boxes === 0) return verb === "get" ? "no boxes yet, every new one gets it" : "no boxes yet";
4067
4180
  return boxes === 1 ? `1 box ${verb}s it when it next starts` : `${boxes} boxes ${verb} it when they next start`;
4068
4181
  }
4182
+ async function findBox2(client, name) {
4183
+ const box = pickRef(await boxesFor(client, name), name, me(client));
4184
+ if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
4185
+ return { box, ref: displayName(box, me(client)) };
4186
+ }
4187
+ function boxReach(running, verb) {
4188
+ return running ? `it ${verb} it when it next starts (kvbox stop, kvbox start)` : `it ${verb} it when it starts`;
4189
+ }
4190
+ function firstBootHint(box, name) {
4191
+ if (box.image === "postgres" && /^POSTGRES_(USER|PASSWORD|DB)$/.test(name)) {
4192
+ return `${name} is read once, when the box first boots: the database keeps the user, password and database it was made with (change them with psql in the box)`;
4193
+ }
4194
+ return void 0;
4195
+ }
4069
4196
 
4070
4197
  // src/commands/env/ls.ts
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) => {
4198
+ var lsCommand7 = new Command60("ls").alias("list").description("list the variables (a secret shows as (sealed))").option("--box <box>", "what this box gets: its own variables and the ones it inherits").option("--json", "print as JSON").action(async (opts, cmd) => {
4072
4199
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4073
4200
  try {
4201
+ if (opts.box !== void 0) {
4202
+ const { box, ref } = await findBox2(client, opts.box);
4203
+ const own = await client.boxEnv(ref);
4204
+ const slug = slugOf(box.owner);
4205
+ const theirs = client.target.kind === "cloud" ? await client.listEnv(slug === me(client) ? void 0 : slug) : [];
4206
+ const mine = new Set(own.vars.map((v) => v.name));
4207
+ const inherited = theirs.filter((v) => !mine.has(v.name));
4208
+ if (opts.json) {
4209
+ json({ box: own.box, vars: own.vars, inherited });
4210
+ return;
4211
+ }
4212
+ if (own.vars.length === 0 && inherited.length === 0) {
4213
+ info(`box ${ref} gets no variables; set one with: kvbox env set NAME value --box ${ref}`);
4214
+ return;
4215
+ }
4216
+ const row = (v, from) => ({ name: v.name, value: v.secret ? color.dim("(sealed)") : v.value, from, updated: age(v.updatedAt) });
4217
+ table([...own.vars.map((v) => row(v, "box")), ...inherited.map((v) => row(v, color.dim(slug)))]);
4218
+ return;
4219
+ }
4074
4220
  const owner = requireCloud2(client);
4075
4221
  const vars = await client.listEnv();
4076
4222
  if (opts.json) {
@@ -4089,10 +4235,11 @@ var lsCommand7 = new Command60("ls").alias("list").description("list the variabl
4089
4235
 
4090
4236
  // src/commands/env/rm.ts
4091
4237
  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) => {
4238
+ 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("--box <box>", "remove this box's own variables (yours, or the org's, of the same name come back)").option("--json", "print as JSON").action(async (names, opts, cmd) => {
4093
4239
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4094
4240
  try {
4095
- const owner = requireCloud2(client);
4241
+ const target = opts.box === void 0 ? void 0 : await findBox2(client, opts.box);
4242
+ const owner = target === void 0 ? requireCloud2(client) : `box ${target.ref}`;
4096
4243
  if (!await confirm(`Remove ${names.join(", ")} from ${owner}'s variables?`, opts.yes ?? false)) {
4097
4244
  info("cancelled");
4098
4245
  process.exitCode = 1;
@@ -4102,6 +4249,12 @@ var rmCommand7 = new Command61("rm").alias("remove").description("remove variabl
4102
4249
  const failed = [];
4103
4250
  for (const name of names) {
4104
4251
  try {
4252
+ if (target !== void 0) {
4253
+ const c2 = await spin(`removing ${name}\u2026`, client.removeBoxEnv(target.ref, name));
4254
+ changes.push(c2);
4255
+ if (!opts.json) info(`${color.green("\u2713")} removed ${c2.name} from ${owner}: ${boxReach(c2.running, "loses")}`);
4256
+ continue;
4257
+ }
4105
4258
  const c = await spin(`removing ${name}\u2026`, client.removeEnv(name));
4106
4259
  changes.push(c);
4107
4260
  if (!opts.json) info(`${color.green("\u2713")} removed ${c.name} from ${owner}: ${reach(c.boxes, "lose")}`);
@@ -4120,28 +4273,11 @@ var rmCommand7 = new Command61("rm").alias("remove").description("remove variabl
4120
4273
 
4121
4274
  // src/commands/env/set.ts
4122
4275
  import { Command as Command62 } from "commander";
4123
-
4124
- // ../shared/src/env.ts
4125
- var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
4126
- var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
4127
- var ENV_MAX_VALUE_BYTES = 4096;
4128
- function envNameProblem(name) {
4129
- if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
4130
- if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
4131
- if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
4132
- return null;
4133
- }
4134
- function envValueProblem(value) {
4135
- if (/[\n\r\0]/.test(value)) return "a value is one line: no line breaks (base64 a multi-line value such as a key file)";
4136
- if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
4137
- return null;
4138
- }
4139
-
4140
- // src/commands/env/set.ts
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) => {
4276
+ 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("--box <box>", "this box's own variable, over yours (or the org's) of the same name").option("--json", "print as JSON").action(async (nameArg, valueArg, opts, cmd) => {
4142
4277
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4143
4278
  try {
4144
- const owner = requireCloud2(client);
4279
+ const owner = opts.box === void 0 ? requireCloud2(client) : void 0;
4280
+ const target = opts.box === void 0 ? void 0 : await findBox2(client, opts.box);
4145
4281
  const ask = interactive();
4146
4282
  if ((nameArg === void 0 || valueArg === void 0) && !ask) throw new KvboxError("give the name and the value: kvbox env set NAME VALUE (or run it in a terminal to be asked)");
4147
4283
  const name = nameArg ?? await text("Variable name", { validate: (a) => envNameProblem(a) ?? void 0 });
@@ -4150,12 +4286,23 @@ var setCommand2 = new Command62("set").description("add or change a variable; bo
4150
4286
  const value = valueArg ?? (opts.secret ? await hiddenText(`Value for ${name}`) : await text(`Value for ${name}`, { trim: false }));
4151
4287
  const valueProblem = envValueProblem(value);
4152
4288
  if (valueProblem !== null) throw new KvboxError(valueProblem);
4289
+ const what = opts.secret ? `${name} (secret)` : name;
4290
+ if (target !== void 0) {
4291
+ const change2 = await spin(`setting ${name}\u2026`, client.setBoxEnv(target.ref, name, { value, secret: opts.secret ?? false }));
4292
+ if (opts.json) {
4293
+ json(change2);
4294
+ return;
4295
+ }
4296
+ info(`${color.green("\u2713")} set ${what} on box ${color.bold(target.ref)}: ${boxReach(change2.running, "gets")}`);
4297
+ const hint = firstBootHint(target.box, name);
4298
+ if (hint !== void 0) warn(hint);
4299
+ return;
4300
+ }
4153
4301
  const change = await spin(`setting ${name}\u2026`, client.setEnv(name, { value, secret: opts.secret ?? false }));
4154
4302
  if (opts.json) {
4155
4303
  json(change);
4156
4304
  return;
4157
4305
  }
4158
- const what = opts.secret ? `${name} (secret)` : name;
4159
4306
  info(`${color.green("\u2713")} set ${what} for ${owner}: ${reach(change.boxes, "get")}`);
4160
4307
  } finally {
4161
4308
  await client.close();