@kvbox/server 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.
@@ -61,6 +61,16 @@ function paths(home = kvboxHome()) {
61
61
  /** Symlink to the current base image, assets/rootfs-<version>.ext4; boxes keep using the version they were made from. */
62
62
  rootfs: join(home, "assets", "rootfs.ext4"),
63
63
  baseImage: (version) => join(home, "assets", `rootfs-${version}.ext4`),
64
+ /**
65
+ * Every other image (#87), one dir each so nothing collides with the base's `rootfs-*.ext4`:
66
+ * assets/images/<image>/rootfs-<version>.ext4, and rootfs.ext4 there the symlink to its current one.
67
+ */
68
+ images: join(home, "assets", "images"),
69
+ image: (image) => ({
70
+ dir: join(home, "assets", "images", image),
71
+ rootfs: join(home, "assets", "images", image, "rootfs.ext4"),
72
+ version: (version) => join(home, "assets", "images", image, `rootfs-${version}.ext4`)
73
+ }),
64
74
  machines: join(home, "machines"),
65
75
  snapshots: join(home, "snapshots"),
66
76
  /** Boxes and snapshots are filed by owner: machines/<owner>/<name>. The owner is part of a box's identity. */
@@ -71,6 +81,8 @@ function paths(home = kvboxHome()) {
71
81
  return {
72
82
  dir,
73
83
  meta: join(dir, "meta.json"),
84
+ /** The box's own environment variables (#87), merged over its owner's at boot. Mode 600: values in the clear. */
85
+ env: join(dir, "env.json"),
74
86
  /** The box's writable layer, stacked on the read-only base image inside the guest. */
75
87
  overlay: join(dir, "overlay.ext4"),
76
88
  /**
@@ -118,6 +130,8 @@ function paths(home = kvboxHome()) {
118
130
  meta: join(dir, "meta.json"),
119
131
  vmstate: join(dir, "vmstate"),
120
132
  mem: join(dir, "mem"),
133
+ /** The box's own environment variables when it was taken (#87); a restore starts with them. */
134
+ env: join(dir, "env.json"),
121
135
  /** Copy of the box's overlay at the moment of the snapshot; the base image is referenced by version in meta.json. */
122
136
  overlay: join(dir, "overlay.ext4")
123
137
  };
@@ -491,7 +505,9 @@ var MachineSchema = z3.object({
491
505
  diskUsedBytes: z3.number().int(),
492
506
  // what that sparse file really occupies on the host
493
507
  base: z3.string(),
494
- // base image version the box's overlay stacks on
508
+ // version of the image the box's overlay stacks on
509
+ /** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
510
+ image: z3.string().optional(),
495
511
  createdAt: z3.string(),
496
512
  source: z3.string(),
497
513
  // "base", "snapshot:<owner/name>" or "fork:<owner/name>" (#79)
@@ -516,7 +532,12 @@ var MachineSchema = z3.object({
516
532
  /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
517
533
  volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional(),
518
534
  /** Boxes that may reach this one, each on one port (#98). Absent: none. */
519
- links: z3.array(BoxLinkSchema).optional()
535
+ links: z3.array(BoxLinkSchema).optional(),
536
+ /**
537
+ * Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
538
+ * serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
539
+ */
540
+ connect: z3.string().optional()
520
541
  });
521
542
  var VolumeSchema = z3.object({
522
543
  /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
@@ -553,6 +574,16 @@ var EnvVarSchema = z3.object({
553
574
  secret: z3.boolean(),
554
575
  updatedAt: z3.string()
555
576
  });
577
+ var BoxEnvSchema = z3.object({
578
+ box: z3.string(),
579
+ vars: z3.array(EnvVarSchema)
580
+ });
581
+ var BoxEnvChangeSchema = z3.object({
582
+ box: z3.string(),
583
+ name: z3.string(),
584
+ /** Whether the box is running now: the change waits for its next start. */
585
+ running: z3.boolean()
586
+ });
556
587
  var SetEnvRequest = z3.object({
557
588
  value: z3.string(),
558
589
  secret: z3.boolean().optional()
@@ -586,7 +617,11 @@ var CreateMachineRequest = z3.object({
586
617
  * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
587
618
  * control plane reads it; a host has one place to put a box.
588
619
  */
589
- near: z3.string().optional()
620
+ near: z3.string().optional(),
621
+ /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
622
+ image: z3.string().optional(),
623
+ /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
624
+ env: z3.array(z3.object({ name: z3.string(), value: z3.string() })).optional()
590
625
  });
591
626
  var ForkMachineRequest = z3.object({
592
627
  name: z3.string().optional(),
@@ -621,7 +656,9 @@ var SnapshotSchema = z3.object({
621
656
  source: z3.string(),
622
657
  // the box it was taken from, as owner/name
623
658
  base: z3.string(),
624
- // base image version the overlay stacks on; a restore needs the same one
659
+ // version of the image the overlay stacks on; a restore needs the same one
660
+ /** As in MachineSchema: the image when it is not the base one (#87). */
661
+ image: z3.string().optional(),
625
662
  vcpu: z3.number().int(),
626
663
  memMib: z3.number().int(),
627
664
  sizeBytes: z3.number().int(),
@@ -648,7 +685,12 @@ var CapacitySchema = z3.object({
648
685
  reservedVcpu: z3.number().int(),
649
686
  running: z3.number().int(),
650
687
  /** Absent on a host from before volumes (#91): it cannot take one. */
651
- disk: DiskCapacitySchema.optional()
688
+ disk: DiskCapacitySchema.optional(),
689
+ /**
690
+ * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
691
+ * Absent on a host from before images: it has only the base.
692
+ */
693
+ images: z3.array(z3.object({ name: z3.string(), version: z3.string() })).optional()
652
694
  });
653
695
  var RecoveryReportSchema = z3.object({
654
696
  at: z3.string(),
@@ -1340,8 +1382,10 @@ var MachineMetaSchema = z4.object({
1340
1382
  memMib: z4.number().int(),
1341
1383
  createdAt: z4.string(),
1342
1384
  source: z4.string(),
1343
- /** Base image version (assets/rootfs-<version>.ext4) the box's overlay stacks on. */
1385
+ /** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */
1344
1386
  base: z4.string(),
1387
+ /** The image (#87), when not the base one: assets/images/<image>/rootfs-<base>.ext4. `vm update` keeps it. */
1388
+ image: z4.string().optional(),
1345
1389
  /**
1346
1390
  * Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
1347
1391
  * each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
@@ -1406,6 +1450,8 @@ var SnapshotMetaSchema = z4.object({
1406
1450
  /** The box it was taken from, as owner/name. */
1407
1451
  source: z4.string(),
1408
1452
  base: z4.string(),
1453
+ /** As in a box's meta.json (#87). */
1454
+ image: z4.string().optional(),
1409
1455
  vcpu: z4.number().int(),
1410
1456
  memMib: z4.number().int(),
1411
1457
  sizeBytes: z4.number().int(),
@@ -1642,9 +1688,8 @@ async function startDns(opts) {
1642
1688
 
1643
1689
  // src/core/machines.ts
1644
1690
  import { spawn } from "node:child_process";
1645
- import { closeSync as closeSync2, existsSync as existsSync4, openSync as openSync2, statSync as statSync2 } from "node:fs";
1646
- import { link as link2, mkdir as mkdir6, readFile as readFile6, realpath, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1647
- import { basename } from "node:path";
1691
+ import { closeSync as closeSync2, existsSync as existsSync6, openSync as openSync2, statSync as statSync2 } from "node:fs";
1692
+ import { link as link2, mkdir as mkdir6, readFile as readFile6, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1648
1693
  import { setTimeout as sleep } from "node:timers/promises";
1649
1694
 
1650
1695
  // src/core/agent.ts
@@ -1716,7 +1761,8 @@ var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.mes
1716
1761
  var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
1717
1762
 
1718
1763
  // src/core/env.ts
1719
- import { mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1764
+ import { existsSync } from "node:fs";
1765
+ import { copyFile, mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1720
1766
  import { z as z5 } from "zod";
1721
1767
 
1722
1768
  // ../shared/src/env.ts
@@ -1785,10 +1831,69 @@ async function readOwnerEnv(owner, p = paths()) {
1785
1831
  throw err;
1786
1832
  }
1787
1833
  }
1788
- async function envForBoot(owner, p = paths()) {
1789
- const env = await readOwnerEnv(owner, p).catch(() => null);
1790
- if (env !== null) return env.vars;
1791
- return realmOf(owner) !== null ? [] : null;
1834
+ async function envForBoot(box, p = paths()) {
1835
+ const env = await readOwnerEnv(box.owner, p).catch(() => null);
1836
+ const own = await readBoxEnv(box, p).catch((err) => {
1837
+ console.error(`warning: box ${shown(box)}: its own variables are unreadable, it boots without them: ${err.message}`);
1838
+ return [];
1839
+ });
1840
+ const slug = env?.vars ?? (realmOf(box.owner) !== null ? [] : null);
1841
+ if (own.length === 0) return slug ?? (existsSync(p.machine(box.owner, box.name).env) ? [] : null);
1842
+ const mine = new Set(own.map((v) => v.name));
1843
+ return [...(slug ?? []).filter((v) => !mine.has(v.name)), ...own.map((v) => ({ name: v.name, value: v.value }))];
1844
+ }
1845
+ var BoxEnvFileSchema = z5.object({
1846
+ vars: z5.array(z5.object({ name: z5.string(), value: z5.string(), secret: z5.boolean(), updatedAt: z5.string() }))
1847
+ });
1848
+ async function readBoxEnv(box, p = paths()) {
1849
+ try {
1850
+ return BoxEnvFileSchema.parse(JSON.parse(await readFile5(p.machine(box.owner, box.name).env, "utf8"))).vars;
1851
+ } catch (err) {
1852
+ if (err.code === "ENOENT") return [];
1853
+ throw err;
1854
+ }
1855
+ }
1856
+ async function writeBoxEnv(box, vars, p = paths()) {
1857
+ if (vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
1858
+ const seen = /* @__PURE__ */ new Set();
1859
+ for (const v of vars) {
1860
+ const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
1861
+ if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
1862
+ if (seen.has(v.name)) throw new KvboxError(`${v.name} is given twice`);
1863
+ seen.add(v.name);
1864
+ }
1865
+ const file = p.machine(box.owner, box.name).env;
1866
+ const tmp = `${file}.tmp`;
1867
+ await writeFile3(tmp, JSON.stringify({ vars }, null, 2) + "\n", { mode: 384 });
1868
+ await rename3(tmp, file);
1869
+ }
1870
+ async function mergeBoxEnv(box, given, p = paths()) {
1871
+ const names = new Set(given.map((v) => v.name));
1872
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1873
+ const kept = (await readBoxEnv(box, p)).filter((v) => !names.has(v.name));
1874
+ await writeBoxEnv(box, [...kept, ...given.map((v) => ({ ...v, secret: false, updatedAt: now }))], p);
1875
+ }
1876
+ async function copyBoxEnv(from, to) {
1877
+ if (!existsSync(from)) return;
1878
+ await copyFile(from, to);
1879
+ }
1880
+ function shownBoxEnv(vars) {
1881
+ return vars.map((v) => ({ name: v.name, ...v.secret ? {} : { value: v.value }, secret: v.secret, updatedAt: v.updatedAt }));
1882
+ }
1883
+ async function setBoxVar(box, name, value, secret, p = paths()) {
1884
+ await withBoxLock(box, async () => {
1885
+ if (!existsSync(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);
1886
+ const vars = (await readBoxEnv(box, p)).filter((v) => v.name !== name);
1887
+ await writeBoxEnv(box, [...vars, { name, value, secret, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }], p);
1888
+ });
1889
+ }
1890
+ async function rmBoxVar(box, name, p = paths()) {
1891
+ await withBoxLock(box, async () => {
1892
+ if (!existsSync(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);
1893
+ const vars = await readBoxEnv(box, p);
1894
+ if (!vars.some((v) => v.name === name)) throw new NotFoundError(`variable ${name} on box ${shown(box)}`);
1895
+ await writeBoxEnv(box, vars.filter((v) => v.name !== name), p);
1896
+ });
1792
1897
  }
1793
1898
  async function setOwnerEnv(owner, req, p = paths()) {
1794
1899
  if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
@@ -1829,9 +1934,152 @@ async function listEnvVersions(scope, p = paths()) {
1829
1934
  return out;
1830
1935
  }
1831
1936
 
1937
+ // src/core/images.ts
1938
+ import { randomBytes as randomBytes2 } from "node:crypto";
1939
+ import { existsSync as existsSync2 } from "node:fs";
1940
+ import { readdir as readdir3, realpath } from "node:fs/promises";
1941
+ import { basename } from "node:path";
1942
+ import { z as z6 } from "zod";
1943
+ var BASE_IMAGE = "base";
1944
+ var IMAGE_RE = /^[a-z][a-z0-9-]{0,30}$/;
1945
+ function baseVersionOf(file) {
1946
+ const m = /^rootfs-(.+)\.ext4$/.exec(basename(file));
1947
+ if (!m) throw new KvboxError(`base image ${file} is not versioned (expected assets/rootfs-<version>.ext4); run install-server.sh`);
1948
+ return m[1];
1949
+ }
1950
+ function imageKey(image) {
1951
+ return image === void 0 || image === BASE_IMAGE ? void 0 : image;
1952
+ }
1953
+ var imageLabel = (image) => imageKey(image) === void 0 ? "base image" : `image ${image}`;
1954
+ function imageFile(image, version, p) {
1955
+ const key = imageKey(image);
1956
+ return key === void 0 ? p.baseImage(version) : p.image(key).version(version);
1957
+ }
1958
+ function imageFileFor(meta, p) {
1959
+ const file = imageFile(meta.image, meta.base, p);
1960
+ if (!existsSync2(file)) throw new KvboxError(`box ${meta.name} runs on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);
1961
+ return file;
1962
+ }
1963
+ async function currentImage(image, cfg, p) {
1964
+ const key = imageKey(image);
1965
+ if (key !== void 0 && !IMAGE_RE.test(key)) throw new KvboxError(`invalid image name "${image}"`);
1966
+ const link3 = key === void 0 ? cfg.rootfs : p.image(key).rootfs;
1967
+ if (key !== void 0 && !existsSync2(link3)) {
1968
+ const have = (await listImages(cfg, p)).map((i) => i.name).join(", ");
1969
+ throw new KvboxError(`this host has no image ${key} (it has: ${have}); install-server.sh with IMAGES="${key}:<version>" adds it`);
1970
+ }
1971
+ const file = await realpath(link3);
1972
+ const version = baseVersionOf(file);
1973
+ const expected = imageFile(key, version, p);
1974
+ if (file !== expected) throw new KvboxError(`${imageLabel(key)} ${link3} points outside its directory (${file})`);
1975
+ return { version, file };
1976
+ }
1977
+ async function listImages(cfg, p = paths()) {
1978
+ const out = [];
1979
+ const versionAt = async (image, link3) => {
1980
+ const file = await realpath(link3);
1981
+ const version = baseVersionOf(file);
1982
+ if (file !== imageFile(image, version, p)) throw new Error("outside its directory");
1983
+ return version;
1984
+ };
1985
+ try {
1986
+ out.push({ name: BASE_IMAGE, version: await versionAt(void 0, cfg.rootfs) });
1987
+ } catch {
1988
+ }
1989
+ let names = [];
1990
+ try {
1991
+ names = (await readdir3(p.images)).sort();
1992
+ } catch (err) {
1993
+ if (err.code !== "ENOENT") throw err;
1994
+ }
1995
+ for (const name of names) {
1996
+ if (!IMAGE_RE.test(name) || name === BASE_IMAGE) continue;
1997
+ try {
1998
+ out.push({ name, version: await versionAt(name, p.image(name).rootfs) });
1999
+ } catch {
2000
+ }
2001
+ }
2002
+ return out;
2003
+ }
2004
+ var overlayCapable = /* @__PURE__ */ new Map();
2005
+ async function assertOverlayCapable(file, image, version) {
2006
+ let ok = overlayCapable.get(file);
2007
+ if (ok === void 0) {
2008
+ const { stdout } = await run(["debugfs", "-R", "stat /sbin/overlay-init", file]);
2009
+ ok = /Type:\s+regular/.test(stdout);
2010
+ overlayCapable.set(file, ok);
2011
+ }
2012
+ if (!ok) throw new KvboxError(`${imageLabel(image)} ${version} is not a kvbox image (no /sbin/overlay-init); rerun install-server.sh`);
2013
+ }
2014
+ var ImageManifestSchema = z6.object({
2015
+ /** false: a new box of this image does not auto-hibernate unless asked (nothing wakes it on a TCP connection). */
2016
+ autoHibernate: z6.boolean().optional(),
2017
+ /** Variables the box gets unless the caller or its owner set them; a value may name an earlier one, or a generated one, as `${NAME}`. */
2018
+ env: z6.record(z6.string(), z6.string()).optional(),
2019
+ /** Variables the host fills with a random password when the caller gave none. */
2020
+ generate: z6.array(z6.string()).optional(),
2021
+ /** How to reach what the box serves, `${NAME}` taken from its variables and `${BOX}` its name. */
2022
+ connect: z6.string().optional()
2023
+ });
2024
+ var manifests = /* @__PURE__ */ new Map();
2025
+ async function imageManifest(file) {
2026
+ const cached = manifests.get(file);
2027
+ if (cached !== void 0) return cached;
2028
+ const { stdout } = await run(["debugfs", "-R", "cat /etc/kvbox/image.json", file]);
2029
+ let manifest = {};
2030
+ if (stdout.trim() !== "") {
2031
+ try {
2032
+ manifest = ImageManifestSchema.parse(JSON.parse(stdout));
2033
+ } catch (err) {
2034
+ throw new KvboxError(`${file}: /etc/kvbox/image.json is not a valid image manifest: ${err.message}`);
2035
+ }
2036
+ }
2037
+ manifests.set(file, manifest);
2038
+ return manifest;
2039
+ }
2040
+ function expand(text, vars) {
2041
+ return text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => vars.get(name) ?? "");
2042
+ }
2043
+ function generatedSecret() {
2044
+ return randomBytes2(18).toString("base64url");
2045
+ }
2046
+ function imageEnv(manifest, box, given, inherited = []) {
2047
+ const vars = new Map([...inherited, ...given].map((v) => [v.name, v.value]));
2048
+ const givenNames = new Set(given.map((v) => v.name));
2049
+ const owners = new Set(inherited.map((v) => v.name).filter((n) => !givenNames.has(n)));
2050
+ const defaults = manifest.env ?? {};
2051
+ const added = [];
2052
+ const generated = [];
2053
+ for (const name of manifest.generate ?? []) {
2054
+ if (vars.has(name) || name in defaults) continue;
2055
+ const v = generatedSecret();
2056
+ vars.set(name, v);
2057
+ added.push({ name, value: v });
2058
+ generated.push(name);
2059
+ }
2060
+ const secrets = /* @__PURE__ */ new Set();
2061
+ for (const [name, value] of Object.entries(defaults)) {
2062
+ if (vars.has(name)) continue;
2063
+ const v = expand(value, vars);
2064
+ vars.set(name, v);
2065
+ added.push({ name, value: v });
2066
+ const from = namesIn(value);
2067
+ if (from.some((n) => owners.has(n))) owners.add(name);
2068
+ if (from.some((n) => owners.has(n) || generated.includes(n) || secrets.has(n))) secrets.add(name);
2069
+ }
2070
+ const encode = manifest.connect !== void 0 && /^[a-z][a-z0-9+.-]*:\/\//i.test(manifest.connect);
2071
+ const connectVars = new Map([...vars].map(([k, v]) => [k, owners.has(k) ? `\${${k}}` : encode ? encodeURIComponent(v) : v]));
2072
+ connectVars.set("BOX", box);
2073
+ const connect3 = manifest.connect === void 0 ? void 0 : expand(manifest.connect, connectVars);
2074
+ return { vars: [...given, ...added], generated, secrets: [...generated, ...secrets], connect: connect3 };
2075
+ }
2076
+ function namesIn(text) {
2077
+ return [...text.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g)].map((m) => m[1]);
2078
+ }
2079
+
1832
2080
  // src/core/volumes.ts
1833
- import { existsSync, statSync } from "node:fs";
1834
- import { lstat, mkdir as mkdir4, readdir as readdir3, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
2081
+ import { existsSync as existsSync3, statSync } from "node:fs";
2082
+ import { lstat, mkdir as mkdir4, readdir as readdir4, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
1835
2083
 
1836
2084
  // ../shared/src/capacity.ts
1837
2085
  var MEM_HEADROOM_MIB = 2048;
@@ -1907,7 +2155,7 @@ async function listVolumes(scope, p = paths()) {
1907
2155
  return out.sort((a, b) => a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name));
1908
2156
  }
1909
2157
  async function diskCapacity(p = paths()) {
1910
- const st = await statfs(existsSync(p.volumes) ? p.volumes : p.home);
2158
+ const st = await statfs(existsSync3(p.volumes) ? p.volumes : p.home);
1911
2159
  let volumesGib = 0;
1912
2160
  let usedBytes2 = 0;
1913
2161
  for (const ref of await listVolumeRefs(p)) {
@@ -1936,7 +2184,7 @@ async function createVolume(req, owner, p = paths()) {
1936
2184
  }
1937
2185
  async function makeVolume(req, owner, p) {
1938
2186
  const v = p.volume(owner, req.name);
1939
- if (existsSync(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
2187
+ if (existsSync3(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
1940
2188
  await mkdir4(p.ownerVolumes(owner), { recursive: true, mode: 448 });
1941
2189
  const disk = await diskCapacity(p);
1942
2190
  if (!hasDiskRoom(disk, req.sizeGib)) {
@@ -2009,7 +2257,7 @@ async function captureDrivesOf(box, p) {
2009
2257
  const drives = await volumeDrivesOf(box, p);
2010
2258
  const named = new Set(drives.map((d) => d.name));
2011
2259
  const dir = p.machine(box.owner, box.name).dir;
2012
- for (const entry of (await readdir3(dir).catch(() => [])).sort()) {
2260
+ for (const entry of (await readdir4(dir).catch(() => [])).sort()) {
2013
2261
  const m = /^volume-(.+)\.ext4$/.exec(entry);
2014
2262
  if (!m || named.has(m[1])) continue;
2015
2263
  const st = await lstat(`${dir}/${entry}`);
@@ -2041,7 +2289,7 @@ async function placeVolumeDrives(box, p) {
2041
2289
  return drives;
2042
2290
  }
2043
2291
  async function removeVolumeDrives(boxDir, keep) {
2044
- for (const entry of await readdir3(boxDir).catch(() => [])) {
2292
+ for (const entry of await readdir4(boxDir).catch(() => [])) {
2045
2293
  const m = /^volume-(.+)\.ext4$/.exec(entry);
2046
2294
  if (m && !keep.has(m[1])) await rm(`${boxDir}/${entry}`, { force: true });
2047
2295
  }
@@ -2084,7 +2332,9 @@ async function capacity(p = paths()) {
2084
2332
  reservedMemMib: running.reduce((n, r) => n + r.memMib, 0),
2085
2333
  reservedVcpu: running.reduce((n, r) => n + r.vcpu, 0),
2086
2334
  running: running.length,
2087
- disk: await diskCapacity(p)
2335
+ disk: await diskCapacity(p),
2336
+ // What a box can be made from here (#87): the control plane places `--base postgres` by it.
2337
+ images: await listImages(await loadConfig(p), p)
2088
2338
  };
2089
2339
  }
2090
2340
  function gb(mib) {
@@ -2119,8 +2369,8 @@ async function assertRoomFor(vcpu, memMib, force, p = paths()) {
2119
2369
  }
2120
2370
 
2121
2371
  // src/core/snapshots.ts
2122
- import { existsSync as existsSync2 } from "node:fs";
2123
- import { link, mkdir as mkdir5, readdir as readdir4, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
2372
+ import { existsSync as existsSync4 } from "node:fs";
2373
+ import { link, mkdir as mkdir5, readdir as readdir5, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
2124
2374
 
2125
2375
  // src/core/firecracker.ts
2126
2376
  import { Agent, request as request2 } from "undici";
@@ -2243,6 +2493,7 @@ function toSnapshot(meta) {
2243
2493
  owner: meta.owner,
2244
2494
  source: meta.source,
2245
2495
  base: meta.base,
2496
+ ...meta.image !== void 0 ? { image: meta.image } : {},
2246
2497
  vcpu: meta.vcpu,
2247
2498
  memMib: meta.memMib,
2248
2499
  sizeBytes: meta.sizeBytes,
@@ -2263,7 +2514,7 @@ async function listSnapshots(scope, p = paths()) {
2263
2514
  }
2264
2515
  async function usedBytes(dir) {
2265
2516
  let total = 0;
2266
- for (const entry of await readdir4(dir)) {
2517
+ for (const entry of await readdir5(dir)) {
2267
2518
  total += (await stat2(`${dir}/${entry}`)).blocks * 512;
2268
2519
  }
2269
2520
  return total;
@@ -2286,13 +2537,13 @@ async function saveSnapshot(req, owner, p = paths()) {
2286
2537
  async function snapshotBox(ref, req, owner, p) {
2287
2538
  const box = await readBox(ref, p);
2288
2539
  if (!vmAlive(box)) {
2289
- if (existsSync2(p.machine(box.owner, box.name).hibernateVmstate)) {
2540
+ if (existsSync4(p.machine(box.owner, box.name).hibernateVmstate)) {
2290
2541
  throw new KvboxError(`box ${req.box} is hibernated; a snapshot freezes a running box (kvbox wake ${req.box} first)`);
2291
2542
  }
2292
2543
  throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);
2293
2544
  }
2294
2545
  const final = p.snapshot(owner, req.name);
2295
- if (existsSync2(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
2546
+ if (existsSync4(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
2296
2547
  const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
2297
2548
  const cfg = await loadConfig(p);
2298
2549
  if (s !== final) await rm2(s.dir, { recursive: true, force: true });
@@ -2300,12 +2551,14 @@ async function snapshotBox(ref, req, owner, p) {
2300
2551
  try {
2301
2552
  const volumes = await captureDrivesOf(box, p);
2302
2553
  await captureBox(box, s, cfg, p);
2554
+ await copyBoxEnv(p.machine(box.owner, box.name).env, s.env);
2303
2555
  const meta = {
2304
2556
  ...volumes.length > 0 ? { volumes } : {},
2305
2557
  name: req.name,
2306
2558
  owner,
2307
2559
  source: refKey(box),
2308
2560
  base: box.base,
2561
+ ...box.image !== void 0 ? { image: box.image } : {},
2309
2562
  vcpu: box.vcpu,
2310
2563
  memMib: box.memMib,
2311
2564
  sizeBytes: await usedBytes(s.dir),
@@ -2324,7 +2577,7 @@ async function swapIn(ref, from, boxId, p) {
2324
2577
  const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
2325
2578
  await withSnapshotLock(ref, async () => {
2326
2579
  await rm2(old, { recursive: true, force: true });
2327
- const hadOld = existsSync2(to);
2580
+ const hadOld = existsSync4(to);
2328
2581
  if (hadOld) await rename4(to, old);
2329
2582
  try {
2330
2583
  await rename4(from, to);
@@ -2341,7 +2594,7 @@ async function captureBox(box, to, cfg, p) {
2341
2594
  let lineageTouched = false;
2342
2595
  try {
2343
2596
  const since = box.memSnapshots ?? 0;
2344
- const mode = since === 0 || existsSync2(m.memBase) ? "Diff" : "Full";
2597
+ const mode = since === 0 || existsSync4(m.memBase) ? "Diff" : "Full";
2345
2598
  let failure2;
2346
2599
  await fc.pause();
2347
2600
  try {
@@ -2372,7 +2625,7 @@ async function captureBox(box, to, cfg, p) {
2372
2625
  }
2373
2626
  }
2374
2627
  async function mergeOntoPrevious(previous, diffFile, editor) {
2375
- if (!existsSync2(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
2628
+ if (!existsSync4(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
2376
2629
  const merged = `${diffFile}.merged`;
2377
2630
  await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
2378
2631
  await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
@@ -2380,13 +2633,13 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
2380
2633
  }
2381
2634
  async function deleteSnapshot(ref, p = paths()) {
2382
2635
  const dir = p.snapshot(ref.owner, ref.name).dir;
2383
- if (ref.name.startsWith(".") || !existsSync2(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
2636
+ if (ref.name.startsWith(".") || !existsSync4(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
2384
2637
  await withSnapshotLock(ref, () => rm2(dir, { recursive: true, force: true }));
2385
2638
  }
2386
2639
 
2387
2640
  // src/core/network.ts
2388
2641
  import { randomInt } from "node:crypto";
2389
- import { existsSync as existsSync3 } from "node:fs";
2642
+ import { existsSync as existsSync5 } from "node:fs";
2390
2643
  import { fileURLToPath } from "node:url";
2391
2644
  var TAP_PREFIX = "kv-";
2392
2645
  var PRIVILEGED_SCRIPT = "/usr/local/lib/kvbox/net-setup.sh";
@@ -2396,15 +2649,15 @@ function tapName(box) {
2396
2649
  function netSetupScript() {
2397
2650
  const override = process.env["KVBOX_NET_SETUP"];
2398
2651
  if (override) return override;
2399
- if (existsSync3(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
2652
+ if (existsSync5(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
2400
2653
  for (const rel of ["../scripts/net-setup.sh", "../../scripts/net-setup.sh"]) {
2401
2654
  const candidate = fileURLToPath(new URL(rel, import.meta.url));
2402
- if (existsSync3(candidate)) return candidate;
2655
+ if (existsSync5(candidate)) return candidate;
2403
2656
  }
2404
2657
  throw new KvboxError("net-setup.sh not found next to kvbox-server");
2405
2658
  }
2406
2659
  function bridgeExists(bridge) {
2407
- return existsSync3(`/sys/class/net/${bridge}`);
2660
+ return existsSync5(`/sys/class/net/${bridge}`);
2408
2661
  }
2409
2662
  function netRun(cfg, args) {
2410
2663
  return run([netSetupScript(), ...args], {
@@ -2582,7 +2835,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
2582
2835
  }
2583
2836
  }
2584
2837
  function isHibernated(meta, p) {
2585
- return !vmAlive(meta) && existsSync4(p.machine(meta.owner, meta.name).hibernateVmstate);
2838
+ return !vmAlive(meta) && existsSync6(p.machine(meta.owner, meta.name).hibernateVmstate);
2586
2839
  }
2587
2840
  function statusOf(meta, p = paths()) {
2588
2841
  if (vmAlive(meta)) return meta.paused ? "standby" : "running";
@@ -2611,6 +2864,7 @@ function toMachine(meta, p = paths()) {
2611
2864
  memMib: meta.memMib,
2612
2865
  ...diskStats(p.machine(meta.owner, meta.name).overlay),
2613
2866
  base: meta.base,
2867
+ ...meta.image !== void 0 ? { image: meta.image } : {},
2614
2868
  createdAt: meta.createdAt,
2615
2869
  source: meta.source,
2616
2870
  status: statusOf(meta, p),
@@ -2622,7 +2876,8 @@ function toMachine(meta, p = paths()) {
2622
2876
  };
2623
2877
  }
2624
2878
  var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
2625
- function autoHibernateFor(req, cfg) {
2879
+ function autoHibernateFor(req, cfg, manifest = {}) {
2880
+ if (req.autoHibernateSec === void 0 && manifest.autoHibernate === false) return void 0;
2626
2881
  return (req.autoHibernateSec ?? cfg.autoHibernateSec) || void 0;
2627
2882
  }
2628
2883
  async function readAllMeta(p) {
@@ -2677,33 +2932,6 @@ function bootArgs(name, ip, cfg, pubkeyB64) {
2677
2932
  const args = `console=ttyS0 reboot=k panic=1 init=/sbin/overlay-init kvbox.overlay=/dev/vdb ip=${ip}::${cfg.gateway}:255.255.255.0:${name}:eth0:off kvbox.name=${name} kvbox.sshkey=${pubkeyB64}`;
2678
2933
  return process.arch === "arm64" ? `keep_bootcon ${args}` : args;
2679
2934
  }
2680
- function baseVersionOf(file) {
2681
- const m = /^rootfs-(.+)\.ext4$/.exec(basename(file));
2682
- if (!m) throw new KvboxError(`base image ${file} is not versioned (expected assets/rootfs-<version>.ext4); run install-server.sh`);
2683
- return m[1];
2684
- }
2685
- async function currentBase(cfg, p) {
2686
- const file = await realpath(cfg.rootfs);
2687
- const version = baseVersionOf(file);
2688
- const expected = p.baseImage(version);
2689
- if (file !== expected) throw new KvboxError(`base image ${cfg.rootfs} points outside ${p.assets} (${file})`);
2690
- return { version, file };
2691
- }
2692
- function baseFileFor(meta, p) {
2693
- const file = p.baseImage(meta.base);
2694
- if (!existsSync4(file)) throw new KvboxError(`box ${meta.name} runs on base image ${meta.base}, which is gone from ${p.assets}`);
2695
- return file;
2696
- }
2697
- var overlayCapable = /* @__PURE__ */ new Map();
2698
- async function assertOverlayCapable(baseFile, version) {
2699
- let ok = overlayCapable.get(baseFile);
2700
- if (ok === void 0) {
2701
- const { stdout } = await run(["debugfs", "-R", "stat /sbin/overlay-init", baseFile]);
2702
- ok = /Type:\s+regular/.test(stdout);
2703
- overlayCapable.set(baseFile, ok);
2704
- }
2705
- if (!ok) throw new KvboxError(`base image ${version} is not a kvbox base image (no /sbin/overlay-init); rerun install-server.sh`);
2706
- }
2707
2935
  async function createOverlay(file, gib) {
2708
2936
  await writeFile5(file, "", { mode: 384 });
2709
2937
  await truncate2(file, gib * 1024 ** 3);
@@ -2742,7 +2970,7 @@ async function spawnFirecracker(ref, cfg, p) {
2742
2970
  child.unref();
2743
2971
  const pid = child.pid;
2744
2972
  if (pid === void 0) throw new KvboxError("could not start firecracker");
2745
- if (!await waitFor(() => existsSync4(m.sock), 3e3)) {
2973
+ if (!await waitFor(() => existsSync6(m.sock), 3e3)) {
2746
2974
  killQuietly(pid);
2747
2975
  throw new KvboxError(`firecracker did not open its API socket; last log lines:
2748
2976
  ${await tailOf(m.log)}`);
@@ -2757,7 +2985,7 @@ function killQuietly(pid) {
2757
2985
  }
2758
2986
  async function launch(spec, tap, cfg, pubkeyB64, p) {
2759
2987
  const m = p.machine(spec.owner, spec.name);
2760
- const baseFile = baseFileFor(spec, p);
2988
+ const baseFile = imageFileFor(spec, p);
2761
2989
  const volumes = await placeVolumeDrives(spec, p);
2762
2990
  const pid = await spawnFirecracker(spec, cfg, p);
2763
2991
  try {
@@ -2804,7 +3032,7 @@ async function loadSnapshot(spec, image, tap, cfg, p) {
2804
3032
  }
2805
3033
  }
2806
3034
  async function currentBaseVersion(p = paths()) {
2807
- return (await currentBase(await loadConfig(p), p)).version;
3035
+ return (await currentImage(void 0, await loadConfig(p), p)).version;
2808
3036
  }
2809
3037
  async function readHostPubkey(p) {
2810
3038
  try {
@@ -2815,7 +3043,7 @@ async function readHostPubkey(p) {
2815
3043
  }
2816
3044
  function assertAssets(cfg) {
2817
3045
  for (const [what, file] of [["kernel", cfg.kernel], ["base image", cfg.rootfs], ["firecracker", cfg.firecracker]]) {
2818
- if (!existsSync4(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
3046
+ if (!existsSync6(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
2819
3047
  }
2820
3048
  }
2821
3049
  async function createMachine(req, owner, p = paths()) {
@@ -2832,16 +3060,25 @@ async function createMachine(req, owner, p = paths()) {
2832
3060
  const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
2833
3061
  const id = newBoxId(idsInUse(existing));
2834
3062
  const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);
2835
- const base = await currentBase(cfg, p);
2836
- await assertOverlayCapable(base.file, base.version);
2837
- return bootInto(
2838
- { id, name, owner, ip, mac: macFor(ip), vcpu: size.vcpu, memMib: size.memMib, base: base.version, sshKeys },
2839
- // The base image is shared read-only by every box; only the box's own writes land in its overlay.
2840
- (m) => createOverlay(m.overlay, size.diskGib),
2841
- { source: "base", autoHibernateSec: autoHibernateFor(req, cfg) },
3063
+ const image = imageKey(req.image);
3064
+ const base = await currentImage(image, cfg, p);
3065
+ await assertOverlayCapable(base.file, image, base.version);
3066
+ const manifest = await imageManifest(base.file);
3067
+ const env = imageEnv(manifest, name, req.env ?? [], (await readOwnerEnv(owner, p).catch(() => null))?.vars ?? []);
3068
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3069
+ const autoHibernateSec = autoHibernateFor(req, cfg, manifest);
3070
+ const machine = await bootInto(
3071
+ { id, name, owner, ip, mac: macFor(ip), vcpu: size.vcpu, memMib: size.memMib, base: base.version, image, sshKeys },
3072
+ // The image is shared read-only by every box; only the box's own writes land in its overlay.
3073
+ async (m) => {
3074
+ await createOverlay(m.overlay, size.diskGib);
3075
+ if (env.vars.length > 0) await writeBoxEnv({ owner, name }, env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now })), p);
3076
+ },
3077
+ { source: "base", autoHibernateSec },
2842
3078
  cfg,
2843
3079
  p
2844
3080
  );
3081
+ return env.connect === void 0 ? machine : { ...machine, connect: env.connect };
2845
3082
  }
2846
3083
  async function bootInto(box, prepare, origin, cfg, p) {
2847
3084
  const { id, ip, owner, name } = box;
@@ -2900,8 +3137,12 @@ async function restoreFrom(from, owner, req, cfg, p) {
2900
3137
  throw new KvboxError(`--size cannot be combined with --from: a restored box has the snapshot's size (${shown(from)}: ${snap.vcpu} vCPU, ${snap.memMib} MiB)`);
2901
3138
  }
2902
3139
  assertAssets(cfg);
2903
- if (!existsSync4(p.baseImage(snap.base))) {
2904
- throw new KvboxError(`snapshot ${shown(from)} stacks on base image ${snap.base}, which is gone from ${p.assets}`);
3140
+ if (!existsSync6(imageFile(snap.image, snap.base, p))) {
3141
+ throw new KvboxError(`snapshot ${shown(from)} stacks on ${imageLabel(snap.image)} ${snap.base}, which is gone from ${p.assets}`);
3142
+ }
3143
+ const manifest = await imageManifest(imageFile(snap.image, snap.base, p));
3144
+ if (req.image !== void 0 && imageKey(req.image) !== snap.image) {
3145
+ throw new KvboxError(`--base cannot be combined with --from: a restored box has the snapshot's image (${shown(from)}: ${imageLabel(snap.image)})`);
2905
3146
  }
2906
3147
  await assertRoomFor(snap.vcpu, snap.memMib, req.force ?? false, p);
2907
3148
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
@@ -2912,14 +3153,16 @@ async function restoreFrom(from, owner, req, cfg, p) {
2912
3153
  const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);
2913
3154
  const s = p.snapshot(from.owner, from.name);
2914
3155
  return restoreInto(
2915
- { id, name, owner, ip, mac: macFor(ip), vcpu: snap.vcpu, memMib: snap.memMib, base: snap.base, sshKeys },
3156
+ { id, name, owner, ip, mac: macFor(ip), vcpu: snap.vcpu, memMib: snap.memMib, base: snap.base, image: snap.image, sshKeys },
2916
3157
  async (m) => {
2917
3158
  await run(["cp", "--sparse=always", "--reflink=auto", s.overlay, m.overlay]);
3159
+ await copyBoxEnv(s.env, m.env);
3160
+ if (req.env?.length) await mergeBoxEnv({ owner, name }, req.env, p);
2918
3161
  await link2(s.mem, m.memBase);
2919
3162
  await placeholderDrives(m.dir, snap.volumes ?? []);
2920
3163
  return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };
2921
3164
  },
2922
- { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg) },
3165
+ { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest) },
2923
3166
  cfg,
2924
3167
  p
2925
3168
  );
@@ -2988,7 +3231,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
2988
3231
  growTo = preset.diskGib > diskGib ? preset.diskGib : void 0;
2989
3232
  }
2990
3233
  assertAssets(cfg);
2991
- baseFileFor(src, p);
3234
+ imageFileFor(src, p);
2992
3235
  await assertRoomFor(shape.vcpu, shape.memMib, req.force ?? false, p);
2993
3236
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
2994
3237
  authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);
@@ -2996,7 +3239,8 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
2996
3239
  const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
2997
3240
  const id = newBoxId(idsInUse(existing));
2998
3241
  const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);
2999
- const box = { id, name, owner, ip, mac: macFor(ip), ...shape, base: src.base, sshKeys };
3242
+ const box = { id, name, owner, ip, mac: macFor(ip), ...shape, base: src.base, image: src.image, sshKeys };
3243
+ const srcEnv = p.machine(src.owner, src.name).env;
3000
3244
  const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0 };
3001
3245
  if (!warm) {
3002
3246
  return bootInto(
@@ -3004,6 +3248,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
3004
3248
  async (m) => {
3005
3249
  await run(["cp", "--sparse=always", "--reflink=auto", srcDisk, m.overlay]);
3006
3250
  if (growTo !== void 0) await growDisk(m.overlay, growTo);
3251
+ await copyBoxEnv(srcEnv, m.env);
3007
3252
  },
3008
3253
  origin,
3009
3254
  cfg,
@@ -3015,6 +3260,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
3015
3260
  box,
3016
3261
  async (m) => {
3017
3262
  await captureBox(src, { vmstate: m.forkVmstate, mem: m.memBase, overlay: m.overlay }, cfg, p);
3263
+ await copyBoxEnv(srcEnv, m.env);
3018
3264
  await placeholderDrives(m.dir, srcVolumes);
3019
3265
  return { vmstate: m.forkVmstate, mem: m.memBase, label: `box ${shown(ref)}`, volumes: srcVolumes };
3020
3266
  },
@@ -3069,7 +3315,7 @@ async function dropGuestVolumes(box, vsock) {
3069
3315
  }
3070
3316
  }
3071
3317
  async function pushEnv(box, vsock, p) {
3072
- const vars = await envForBoot(box.owner, p);
3318
+ const vars = await envForBoot(box, p);
3073
3319
  if (vars === null) return;
3074
3320
  try {
3075
3321
  await setEnv(vsock, vars, AGENT_REPLY_MS);
@@ -3091,7 +3337,7 @@ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS
3091
3337
  const deadline = Date.now() + timing.waitMs;
3092
3338
  for (; ; ) {
3093
3339
  if (!pidAlive(pid)) return;
3094
- const vars = await envForBoot(box.owner, p);
3340
+ const vars = await envForBoot(box, p);
3095
3341
  if (vars === null) return;
3096
3342
  try {
3097
3343
  await setEnv(vsock, vars, timing.replyMs);
@@ -3303,8 +3549,8 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
3303
3549
  if (status === "running" || status === "standby") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated`);
3304
3550
  if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated; kvbox start ${shown(ref)} boots it`);
3305
3551
  assertAssets(cfg);
3306
- if (!existsSync4(p.baseImage(meta.base))) {
3307
- throw new KvboxError(`box ${shown(ref)} stacks on base image ${meta.base}, which is gone from ${p.assets}`);
3552
+ if (!existsSync6(imageFile(meta.image, meta.base, p))) {
3553
+ throw new KvboxError(`box ${shown(ref)} stacks on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);
3308
3554
  }
3309
3555
  const m = p.machine(ref.owner, ref.name);
3310
3556
  await ensureHostNetwork(cfg);
@@ -3358,9 +3604,9 @@ var updateMachine = locked(async function updateMachine2(ref, p = paths()) {
3358
3604
  const cfg = await loadConfig(p);
3359
3605
  assertNotHibernated(meta, p);
3360
3606
  assertAssets(cfg);
3361
- const base = await currentBase(cfg, p);
3607
+ const base = await currentImage(meta.image, cfg, p);
3362
3608
  if (base.version === meta.base) return toMachine(meta, p);
3363
- await assertOverlayCapable(base.file, base.version);
3609
+ await assertOverlayCapable(base.file, meta.image, base.version);
3364
3610
  return applyAtNextBoot(meta, { base: base.version }, "update", cfg, p);
3365
3611
  });
3366
3612
  var rescaleMachine = locked(async function rescaleMachine2(ref, req, p = paths()) {
@@ -3603,7 +3849,7 @@ async function pinRunningTaps(p = paths()) {
3603
3849
  const cfg = await loadConfig(p);
3604
3850
  if (!bridgeExists(cfg.bridge)) return;
3605
3851
  for (const meta of await readAllMeta(p)) {
3606
- if (!vmAlive(meta) || !existsSync4(`/sys/class/net/${tapName(meta.id)}`)) continue;
3852
+ if (!vmAlive(meta) || !existsSync6(`/sys/class/net/${tapName(meta.id)}`)) continue;
3607
3853
  await pinTap(meta, cfg).catch((err) => console.error(`warning: could not pin box ${meta.name}'s tap: ${err.message}`));
3608
3854
  }
3609
3855
  }
@@ -3645,24 +3891,24 @@ async function bootRecovered(settled, p = paths()) {
3645
3891
  import { chmod as chmod3, mkdir as mkdir7, rm as rm4, writeFile as writeFile6 } from "node:fs/promises";
3646
3892
 
3647
3893
  // ../shared/src/relay.ts
3648
- import { z as z6 } from "zod";
3894
+ import { z as z7 } from "zod";
3649
3895
  var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
3650
3896
  var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
3651
3897
  var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
3652
- var RelayJoinSchema = z6.object({
3653
- v: z6.literal(1),
3898
+ var RelayJoinSchema = z7.object({
3899
+ v: z7.literal(1),
3654
3900
  /** How the relay lists this host. */
3655
- name: z6.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
3901
+ name: z7.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
3656
3902
  /** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
3657
- relay: z6.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
3903
+ relay: z7.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
3658
3904
  /** The relay's WireGuard public key. */
3659
- relayKey: z6.string().regex(WG_KEY_RE),
3905
+ relayKey: z7.string().regex(WG_KEY_RE),
3660
3906
  /** This host's address inside the tunnel. */
3661
- tunnelIp: z6.string().regex(IPV4_RE),
3907
+ tunnelIp: z7.string().regex(IPV4_RE),
3662
3908
  /** This host's WireGuard private key, generated on the relay, kept nowhere else. */
3663
- privateKey: z6.string().regex(WG_KEY_RE),
3909
+ privateKey: z7.string().regex(WG_KEY_RE),
3664
3910
  /** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
3665
- publicIp: z6.string().regex(IPV4_RE)
3911
+ publicIp: z7.string().regex(IPV4_RE)
3666
3912
  });
3667
3913
  function decodeRelayJoin(text) {
3668
3914
  let parsed;
@@ -3897,7 +4143,7 @@ function versionOf(srcFileUrl, injected) {
3897
4143
  }
3898
4144
 
3899
4145
  // src/version.ts
3900
- var VERSION = versionOf(import.meta.url, true ? "0.5.28" : void 0);
4146
+ var VERSION = versionOf(import.meta.url, true ? "0.5.29" : void 0);
3901
4147
 
3902
4148
  // src/caller.ts
3903
4149
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";
@@ -4333,6 +4579,29 @@ function machineRoutes() {
4333
4579
  }
4334
4580
  return c.json(await machineUsage(parseRef(c.req.param("name"), c.get("owner")), from));
4335
4581
  });
4582
+ r.get("/:name/env", async (c) => {
4583
+ const ref = parseRef(c.req.param("name"), c.get("owner"));
4584
+ await getMachine(ref);
4585
+ return c.json({ box: ref.name, vars: shownBoxEnv(await readBoxEnv(ref)) });
4586
+ });
4587
+ r.post("/:name/env/:var", async (c) => {
4588
+ const ref = parseRef(c.req.param("name"), c.get("owner"));
4589
+ const name = c.req.param("var");
4590
+ const problem = envNameProblem(name);
4591
+ if (problem !== null) throw new KvboxError(problem);
4592
+ const body = SetEnvRequest.safeParse(await c.req.json().catch(() => ({})));
4593
+ if (!body.success) throw new KvboxError("expected {value, secret?}");
4594
+ await setBoxVar(ref, name, body.data.value, body.data.secret ?? false);
4595
+ const box = await getMachine(ref);
4596
+ return c.json({ box: ref.name, name, running: box.status !== "stopped" });
4597
+ });
4598
+ r.delete("/:name/env/:var", async (c) => {
4599
+ const ref = parseRef(c.req.param("name"), c.get("owner"));
4600
+ const name = c.req.param("var");
4601
+ await rmBoxVar(ref, name);
4602
+ const box = await getMachine(ref);
4603
+ return c.json({ box: ref.name, name, running: box.status !== "stopped" });
4604
+ });
4336
4605
  r.get("/:name/stats", async (c) => c.json(await machineStats(parseRef(c.req.param("name"), c.get("owner")))));
4337
4606
  r.delete("/:name", async (c) => {
4338
4607
  await destroyMachine(parseRef(c.req.param("name"), c.get("owner")));