@kvbox/server 0.5.28 → 0.5.30

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
  };
@@ -156,7 +170,8 @@ var PricingSchema = z.object({
156
170
  ramGibHour: z.number().nonnegative(),
157
171
  diskGibHour: z.number().nonnegative(),
158
172
  volumeHour: z.number().nonnegative().default(0),
159
- volumeGibHour: z.number().nonnegative().default(0)
173
+ volumeGibHour: z.number().nonnegative().default(0),
174
+ diskIncludedGib: z.number().int().nonnegative().default(0)
160
175
  });
161
176
  var HOUR_MS = 36e5;
162
177
  var round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
@@ -168,6 +183,7 @@ function computeUsage(events, w) {
168
183
  let vcpuHours = 0;
169
184
  let ramGibHours = 0;
170
185
  let diskGibHours = 0;
186
+ const included = w.pricing?.diskIncludedGib ?? 0;
171
187
  sorted.forEach((e, i) => {
172
188
  const start = Math.max(Date.parse(e.at), from);
173
189
  const next = sorted[i + 1];
@@ -177,7 +193,7 @@ function computeUsage(events, w) {
177
193
  ms[e.state] += end - start;
178
194
  if (e.state === "running") vcpuHours += h * e.vcpu;
179
195
  if (e.state === "running" || e.state === "standby") ramGibHours += h * e.memMib / 1024;
180
- diskGibHours += h * e.diskGib;
196
+ diskGibHours += h * Math.max(0, e.diskGib - included);
181
197
  });
182
198
  const totals = {
183
199
  seconds: {
@@ -475,6 +491,21 @@ var DomainSchema = z3.object({
475
491
  records: z3.array(z3.object({ type: z3.enum(["A", "TXT", "CNAME"]), name: z3.string(), value: z3.string() })),
476
492
  createdAt: z3.string()
477
493
  });
494
+ var WakeHookSchema = z3.object({
495
+ id: z3.string(),
496
+ owner: z3.string(),
497
+ box: z3.string(),
498
+ url: z3.string(),
499
+ createdBy: z3.string().nullable(),
500
+ createdAt: z3.string(),
501
+ lastCalledAt: z3.string().nullable()
502
+ });
503
+ var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z3.string() });
504
+ var WakeHookCallSchema = z3.object({
505
+ box: z3.string(),
506
+ action: z3.enum(["wake", "resume", "none"]),
507
+ reason: z3.string().optional()
508
+ });
478
509
  var MachineSchema = z3.object({
479
510
  /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
480
511
  id: z3.string(),
@@ -491,7 +522,9 @@ var MachineSchema = z3.object({
491
522
  diskUsedBytes: z3.number().int(),
492
523
  // what that sparse file really occupies on the host
493
524
  base: z3.string(),
494
- // base image version the box's overlay stacks on
525
+ // version of the image the box's overlay stacks on
526
+ /** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
527
+ image: z3.string().optional(),
495
528
  createdAt: z3.string(),
496
529
  source: z3.string(),
497
530
  // "base", "snapshot:<owner/name>" or "fork:<owner/name>" (#79)
@@ -516,7 +549,14 @@ var MachineSchema = z3.object({
516
549
  /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
517
550
  volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional(),
518
551
  /** Boxes that may reach this one, each on one port (#98). Absent: none. */
519
- links: z3.array(BoxLinkSchema).optional()
552
+ links: z3.array(BoxLinkSchema).optional(),
553
+ /** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */
554
+ url: z3.string().optional(),
555
+ /**
556
+ * Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
557
+ * serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
558
+ */
559
+ connect: z3.string().optional()
520
560
  });
521
561
  var VolumeSchema = z3.object({
522
562
  /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
@@ -553,6 +593,16 @@ var EnvVarSchema = z3.object({
553
593
  secret: z3.boolean(),
554
594
  updatedAt: z3.string()
555
595
  });
596
+ var BoxEnvSchema = z3.object({
597
+ box: z3.string(),
598
+ vars: z3.array(EnvVarSchema)
599
+ });
600
+ var BoxEnvChangeSchema = z3.object({
601
+ box: z3.string(),
602
+ name: z3.string(),
603
+ /** Whether the box is running now: the change waits for its next start. */
604
+ running: z3.boolean()
605
+ });
556
606
  var SetEnvRequest = z3.object({
557
607
  value: z3.string(),
558
608
  secret: z3.boolean().optional()
@@ -586,7 +636,11 @@ var CreateMachineRequest = z3.object({
586
636
  * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
587
637
  * control plane reads it; a host has one place to put a box.
588
638
  */
589
- near: z3.string().optional()
639
+ near: z3.string().optional(),
640
+ /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
641
+ image: z3.string().optional(),
642
+ /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
643
+ env: z3.array(z3.object({ name: z3.string(), value: z3.string() })).optional()
590
644
  });
591
645
  var ForkMachineRequest = z3.object({
592
646
  name: z3.string().optional(),
@@ -621,7 +675,9 @@ var SnapshotSchema = z3.object({
621
675
  source: z3.string(),
622
676
  // the box it was taken from, as owner/name
623
677
  base: z3.string(),
624
- // base image version the overlay stacks on; a restore needs the same one
678
+ // version of the image the overlay stacks on; a restore needs the same one
679
+ /** As in MachineSchema: the image when it is not the base one (#87). */
680
+ image: z3.string().optional(),
625
681
  vcpu: z3.number().int(),
626
682
  memMib: z3.number().int(),
627
683
  sizeBytes: z3.number().int(),
@@ -648,7 +704,12 @@ var CapacitySchema = z3.object({
648
704
  reservedVcpu: z3.number().int(),
649
705
  running: z3.number().int(),
650
706
  /** Absent on a host from before volumes (#91): it cannot take one. */
651
- disk: DiskCapacitySchema.optional()
707
+ disk: DiskCapacitySchema.optional(),
708
+ /**
709
+ * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
710
+ * Absent on a host from before images: it has only the base.
711
+ */
712
+ images: z3.array(z3.object({ name: z3.string(), version: z3.string() })).optional()
652
713
  });
653
714
  var RecoveryReportSchema = z3.object({
654
715
  at: z3.string(),
@@ -1340,8 +1401,12 @@ var MachineMetaSchema = z4.object({
1340
1401
  memMib: z4.number().int(),
1341
1402
  createdAt: z4.string(),
1342
1403
  source: z4.string(),
1343
- /** Base image version (assets/rootfs-<version>.ext4) the box's overlay stacks on. */
1404
+ /** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */
1344
1405
  base: z4.string(),
1406
+ /** The image (#87), when not the base one: assets/images/<image>/rootfs-<base>.ext4. `vm update` keeps it. */
1407
+ image: z4.string().optional(),
1408
+ /** The image's connect line with its secrets masked and `${BOX}` unfilled (#87, `maskedUrl`). Absent: the image declares none. */
1409
+ url: z4.string().optional(),
1345
1410
  /**
1346
1411
  * Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
1347
1412
  * each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
@@ -1406,6 +1471,8 @@ var SnapshotMetaSchema = z4.object({
1406
1471
  /** The box it was taken from, as owner/name. */
1407
1472
  source: z4.string(),
1408
1473
  base: z4.string(),
1474
+ /** As in a box's meta.json (#87). */
1475
+ image: z4.string().optional(),
1409
1476
  vcpu: z4.number().int(),
1410
1477
  memMib: z4.number().int(),
1411
1478
  sizeBytes: z4.number().int(),
@@ -1642,9 +1709,8 @@ async function startDns(opts) {
1642
1709
 
1643
1710
  // src/core/machines.ts
1644
1711
  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";
1712
+ import { closeSync as closeSync2, existsSync as existsSync6, openSync as openSync2, statSync as statSync2 } from "node:fs";
1713
+ import { link as link2, mkdir as mkdir6, readFile as readFile6, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1648
1714
  import { setTimeout as sleep } from "node:timers/promises";
1649
1715
 
1650
1716
  // src/core/agent.ts
@@ -1716,7 +1782,8 @@ var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.mes
1716
1782
  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
1783
 
1718
1784
  // 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";
1785
+ import { existsSync } from "node:fs";
1786
+ import { copyFile, mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1720
1787
  import { z as z5 } from "zod";
1721
1788
 
1722
1789
  // ../shared/src/env.ts
@@ -1785,10 +1852,72 @@ async function readOwnerEnv(owner, p = paths()) {
1785
1852
  throw err;
1786
1853
  }
1787
1854
  }
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;
1855
+ async function envForBoot(box, p = paths()) {
1856
+ const env = await readOwnerEnv(box.owner, p).catch(() => null);
1857
+ const own = await readBoxEnv(box, p).catch((err) => {
1858
+ console.error(`warning: box ${shown(box)}: its own variables are unreadable, it boots without them: ${err.message}`);
1859
+ return [];
1860
+ });
1861
+ const slug = env?.vars ?? (realmOf(box.owner) !== null ? [] : null);
1862
+ if (own.length === 0) return slug ?? (existsSync(p.machine(box.owner, box.name).env) ? [] : null);
1863
+ const mine = new Set(own.map((v) => v.name));
1864
+ return [...(slug ?? []).filter((v) => !mine.has(v.name)), ...own.map((v) => ({ name: v.name, value: v.value }))];
1865
+ }
1866
+ var BoxEnvFileSchema = z5.object({
1867
+ vars: z5.array(z5.object({ name: z5.string(), value: z5.string(), secret: z5.boolean(), updatedAt: z5.string() }))
1868
+ });
1869
+ async function readBoxEnv(box, p = paths()) {
1870
+ return readBoxEnvFile(p.machine(box.owner, box.name).env);
1871
+ }
1872
+ async function readBoxEnvFile(file) {
1873
+ try {
1874
+ return BoxEnvFileSchema.parse(JSON.parse(await readFile5(file, "utf8"))).vars;
1875
+ } catch (err) {
1876
+ if (err.code === "ENOENT") return [];
1877
+ throw err;
1878
+ }
1879
+ }
1880
+ async function writeBoxEnv(box, vars, p = paths()) {
1881
+ if (vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
1882
+ const seen = /* @__PURE__ */ new Set();
1883
+ for (const v of vars) {
1884
+ const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
1885
+ if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
1886
+ if (seen.has(v.name)) throw new KvboxError(`${v.name} is given twice`);
1887
+ seen.add(v.name);
1888
+ }
1889
+ const file = p.machine(box.owner, box.name).env;
1890
+ const tmp = `${file}.tmp`;
1891
+ await writeFile3(tmp, JSON.stringify({ vars }, null, 2) + "\n", { mode: 384 });
1892
+ await rename3(tmp, file);
1893
+ }
1894
+ async function mergeBoxEnv(box, given, p = paths()) {
1895
+ const names = new Set(given.map((v) => v.name));
1896
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1897
+ const kept = (await readBoxEnv(box, p)).filter((v) => !names.has(v.name));
1898
+ await writeBoxEnv(box, [...kept, ...given.map((v) => ({ ...v, secret: false, updatedAt: now }))], p);
1899
+ }
1900
+ async function copyBoxEnv(from, to) {
1901
+ if (!existsSync(from)) return;
1902
+ await copyFile(from, to);
1903
+ }
1904
+ function shownBoxEnv(vars) {
1905
+ return vars.map((v) => ({ name: v.name, ...v.secret ? {} : { value: v.value }, secret: v.secret, updatedAt: v.updatedAt }));
1906
+ }
1907
+ async function setBoxVar(box, name, value, secret, p = paths()) {
1908
+ await withBoxLock(box, async () => {
1909
+ if (!existsSync(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);
1910
+ const vars = (await readBoxEnv(box, p)).filter((v) => v.name !== name);
1911
+ await writeBoxEnv(box, [...vars, { name, value, secret, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }], p);
1912
+ });
1913
+ }
1914
+ async function rmBoxVar(box, name, p = paths()) {
1915
+ await withBoxLock(box, async () => {
1916
+ if (!existsSync(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);
1917
+ const vars = await readBoxEnv(box, p);
1918
+ if (!vars.some((v) => v.name === name)) throw new NotFoundError(`variable ${name} on box ${shown(box)}`);
1919
+ await writeBoxEnv(box, vars.filter((v) => v.name !== name), p);
1920
+ });
1792
1921
  }
1793
1922
  async function setOwnerEnv(owner, req, p = paths()) {
1794
1923
  if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
@@ -1829,9 +1958,161 @@ async function listEnvVersions(scope, p = paths()) {
1829
1958
  return out;
1830
1959
  }
1831
1960
 
1961
+ // src/core/images.ts
1962
+ import { randomBytes as randomBytes2 } from "node:crypto";
1963
+ import { existsSync as existsSync2 } from "node:fs";
1964
+ import { readdir as readdir3, realpath } from "node:fs/promises";
1965
+ import { basename } from "node:path";
1966
+ import { z as z6 } from "zod";
1967
+ var BASE_IMAGE = "base";
1968
+ var IMAGE_RE = /^[a-z][a-z0-9-]{0,30}$/;
1969
+ function baseVersionOf(file) {
1970
+ const m = /^rootfs-(.+)\.ext4$/.exec(basename(file));
1971
+ if (!m) throw new KvboxError(`base image ${file} is not versioned (expected assets/rootfs-<version>.ext4); run install-server.sh`);
1972
+ return m[1];
1973
+ }
1974
+ function imageKey(image) {
1975
+ return image === void 0 || image === BASE_IMAGE ? void 0 : image;
1976
+ }
1977
+ var imageLabel = (image) => imageKey(image) === void 0 ? "base image" : `image ${image}`;
1978
+ function imageFile(image, version, p) {
1979
+ const key = imageKey(image);
1980
+ return key === void 0 ? p.baseImage(version) : p.image(key).version(version);
1981
+ }
1982
+ function imageFileFor(meta, p) {
1983
+ const file = imageFile(meta.image, meta.base, p);
1984
+ if (!existsSync2(file)) throw new KvboxError(`box ${meta.name} runs on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);
1985
+ return file;
1986
+ }
1987
+ async function currentImage(image, cfg, p) {
1988
+ const key = imageKey(image);
1989
+ if (key !== void 0 && !IMAGE_RE.test(key)) throw new KvboxError(`invalid image name "${image}"`);
1990
+ const link3 = key === void 0 ? cfg.rootfs : p.image(key).rootfs;
1991
+ if (key !== void 0 && !existsSync2(link3)) {
1992
+ const have = (await listImages(cfg, p)).map((i) => i.name).join(", ");
1993
+ throw new KvboxError(`this host has no image ${key} (it has: ${have}); install-server.sh with IMAGES="${key}:<version>" adds it`);
1994
+ }
1995
+ const file = await realpath(link3);
1996
+ const version = baseVersionOf(file);
1997
+ const expected = imageFile(key, version, p);
1998
+ if (file !== expected) throw new KvboxError(`${imageLabel(key)} ${link3} points outside its directory (${file})`);
1999
+ return { version, file };
2000
+ }
2001
+ async function listImages(cfg, p = paths()) {
2002
+ const out = [];
2003
+ const versionAt = async (image, link3) => {
2004
+ const file = await realpath(link3);
2005
+ const version = baseVersionOf(file);
2006
+ if (file !== imageFile(image, version, p)) throw new Error("outside its directory");
2007
+ return version;
2008
+ };
2009
+ try {
2010
+ out.push({ name: BASE_IMAGE, version: await versionAt(void 0, cfg.rootfs) });
2011
+ } catch {
2012
+ }
2013
+ let names = [];
2014
+ try {
2015
+ names = (await readdir3(p.images)).sort();
2016
+ } catch (err) {
2017
+ if (err.code !== "ENOENT") throw err;
2018
+ }
2019
+ for (const name of names) {
2020
+ if (!IMAGE_RE.test(name) || name === BASE_IMAGE) continue;
2021
+ try {
2022
+ out.push({ name, version: await versionAt(name, p.image(name).rootfs) });
2023
+ } catch {
2024
+ }
2025
+ }
2026
+ return out;
2027
+ }
2028
+ var overlayCapable = /* @__PURE__ */ new Map();
2029
+ async function assertOverlayCapable(file, image, version) {
2030
+ let ok = overlayCapable.get(file);
2031
+ if (ok === void 0) {
2032
+ const { stdout } = await run(["debugfs", "-R", "stat /sbin/overlay-init", file]);
2033
+ ok = /Type:\s+regular/.test(stdout);
2034
+ overlayCapable.set(file, ok);
2035
+ }
2036
+ if (!ok) throw new KvboxError(`${imageLabel(image)} ${version} is not a kvbox image (no /sbin/overlay-init); rerun install-server.sh`);
2037
+ }
2038
+ var ImageManifestSchema = z6.object({
2039
+ /** false: a new box of this image does not auto-hibernate unless asked (nothing wakes it on a TCP connection). */
2040
+ autoHibernate: z6.boolean().optional(),
2041
+ /** 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}`. */
2042
+ env: z6.record(z6.string(), z6.string()).optional(),
2043
+ /** Variables the host fills with a random password when the caller gave none. */
2044
+ generate: z6.array(z6.string()).optional(),
2045
+ /** How to reach what the box serves, `${NAME}` taken from its variables and `${BOX}` its name. */
2046
+ connect: z6.string().optional()
2047
+ });
2048
+ var manifests = /* @__PURE__ */ new Map();
2049
+ async function imageManifest(file) {
2050
+ const cached = manifests.get(file);
2051
+ if (cached !== void 0) return cached;
2052
+ const { stdout } = await run(["debugfs", "-R", "cat /etc/kvbox/image.json", file]);
2053
+ let manifest = {};
2054
+ if (stdout.trim() !== "") {
2055
+ try {
2056
+ manifest = ImageManifestSchema.parse(JSON.parse(stdout));
2057
+ } catch (err) {
2058
+ throw new KvboxError(`${file}: /etc/kvbox/image.json is not a valid image manifest: ${err.message}`);
2059
+ }
2060
+ }
2061
+ manifests.set(file, manifest);
2062
+ return manifest;
2063
+ }
2064
+ function expand(text, vars) {
2065
+ return text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => vars.get(name) ?? "");
2066
+ }
2067
+ function generatedSecret() {
2068
+ return randomBytes2(18).toString("base64url");
2069
+ }
2070
+ function imageEnv(manifest, box, given, inherited = []) {
2071
+ const vars = new Map([...inherited, ...given].map((v) => [v.name, v.value]));
2072
+ const givenNames = new Set(given.map((v) => v.name));
2073
+ const owners = new Set(inherited.map((v) => v.name).filter((n) => !givenNames.has(n)));
2074
+ const defaults = manifest.env ?? {};
2075
+ const added = [];
2076
+ const generated = [];
2077
+ for (const name of manifest.generate ?? []) {
2078
+ if (vars.has(name) || name in defaults) continue;
2079
+ const v = generatedSecret();
2080
+ vars.set(name, v);
2081
+ added.push({ name, value: v });
2082
+ generated.push(name);
2083
+ }
2084
+ const secrets = /* @__PURE__ */ new Set();
2085
+ for (const [name, value] of Object.entries(defaults)) {
2086
+ if (vars.has(name)) continue;
2087
+ const v = expand(value, vars);
2088
+ vars.set(name, v);
2089
+ added.push({ name, value: v });
2090
+ const from = namesIn(value);
2091
+ if (from.some((n) => owners.has(n))) owners.add(name);
2092
+ if (from.some((n) => owners.has(n) || generated.includes(n) || secrets.has(n))) secrets.add(name);
2093
+ }
2094
+ const encode = manifest.connect !== void 0 && /^[a-z][a-z0-9+.-]*:\/\//i.test(manifest.connect);
2095
+ const connectVars = new Map([...vars].map(([k, v]) => [k, owners.has(k) ? `\${${k}}` : encode ? encodeURIComponent(v) : v]));
2096
+ connectVars.set("BOX", box);
2097
+ const connect3 = manifest.connect === void 0 ? void 0 : expand(manifest.connect, connectVars);
2098
+ return { vars: [...given, ...added], generated, secrets: [...generated, ...secrets], connect: connect3 };
2099
+ }
2100
+ var MASK = "****";
2101
+ function maskedUrl(manifest, vars) {
2102
+ if (manifest.connect === void 0) return void 0;
2103
+ const encode = /^[a-z][a-z0-9+.-]*:\/\//i.test(manifest.connect);
2104
+ const generated = new Set(manifest.generate ?? []);
2105
+ const shown2 = new Map(vars.map((v) => [v.name, v.secret || generated.has(v.name) ? MASK : encode ? encodeURIComponent(v.value) : v.value]));
2106
+ return manifest.connect.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (all, name) => name === "BOX" ? all : shown2.get(name) ?? all);
2107
+ }
2108
+ var urlFor = (url, name) => url.replaceAll("${BOX}", name);
2109
+ function namesIn(text) {
2110
+ return [...text.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g)].map((m) => m[1]);
2111
+ }
2112
+
1832
2113
  // 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";
2114
+ import { existsSync as existsSync3, statSync } from "node:fs";
2115
+ import { lstat, mkdir as mkdir4, readdir as readdir4, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
1835
2116
 
1836
2117
  // ../shared/src/capacity.ts
1837
2118
  var MEM_HEADROOM_MIB = 2048;
@@ -1907,7 +2188,7 @@ async function listVolumes(scope, p = paths()) {
1907
2188
  return out.sort((a, b) => a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name));
1908
2189
  }
1909
2190
  async function diskCapacity(p = paths()) {
1910
- const st = await statfs(existsSync(p.volumes) ? p.volumes : p.home);
2191
+ const st = await statfs(existsSync3(p.volumes) ? p.volumes : p.home);
1911
2192
  let volumesGib = 0;
1912
2193
  let usedBytes2 = 0;
1913
2194
  for (const ref of await listVolumeRefs(p)) {
@@ -1936,7 +2217,7 @@ async function createVolume(req, owner, p = paths()) {
1936
2217
  }
1937
2218
  async function makeVolume(req, owner, p) {
1938
2219
  const v = p.volume(owner, req.name);
1939
- if (existsSync(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
2220
+ if (existsSync3(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
1940
2221
  await mkdir4(p.ownerVolumes(owner), { recursive: true, mode: 448 });
1941
2222
  const disk = await diskCapacity(p);
1942
2223
  if (!hasDiskRoom(disk, req.sizeGib)) {
@@ -2009,7 +2290,7 @@ async function captureDrivesOf(box, p) {
2009
2290
  const drives = await volumeDrivesOf(box, p);
2010
2291
  const named = new Set(drives.map((d) => d.name));
2011
2292
  const dir = p.machine(box.owner, box.name).dir;
2012
- for (const entry of (await readdir3(dir).catch(() => [])).sort()) {
2293
+ for (const entry of (await readdir4(dir).catch(() => [])).sort()) {
2013
2294
  const m = /^volume-(.+)\.ext4$/.exec(entry);
2014
2295
  if (!m || named.has(m[1])) continue;
2015
2296
  const st = await lstat(`${dir}/${entry}`);
@@ -2041,7 +2322,7 @@ async function placeVolumeDrives(box, p) {
2041
2322
  return drives;
2042
2323
  }
2043
2324
  async function removeVolumeDrives(boxDir, keep) {
2044
- for (const entry of await readdir3(boxDir).catch(() => [])) {
2325
+ for (const entry of await readdir4(boxDir).catch(() => [])) {
2045
2326
  const m = /^volume-(.+)\.ext4$/.exec(entry);
2046
2327
  if (m && !keep.has(m[1])) await rm(`${boxDir}/${entry}`, { force: true });
2047
2328
  }
@@ -2084,7 +2365,9 @@ async function capacity(p = paths()) {
2084
2365
  reservedMemMib: running.reduce((n, r) => n + r.memMib, 0),
2085
2366
  reservedVcpu: running.reduce((n, r) => n + r.vcpu, 0),
2086
2367
  running: running.length,
2087
- disk: await diskCapacity(p)
2368
+ disk: await diskCapacity(p),
2369
+ // What a box can be made from here (#87): the control plane places `--base postgres` by it.
2370
+ images: await listImages(await loadConfig(p), p)
2088
2371
  };
2089
2372
  }
2090
2373
  function gb(mib) {
@@ -2119,8 +2402,8 @@ async function assertRoomFor(vcpu, memMib, force, p = paths()) {
2119
2402
  }
2120
2403
 
2121
2404
  // 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";
2405
+ import { existsSync as existsSync4 } from "node:fs";
2406
+ import { link, mkdir as mkdir5, readdir as readdir5, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
2124
2407
 
2125
2408
  // src/core/firecracker.ts
2126
2409
  import { Agent, request as request2 } from "undici";
@@ -2243,6 +2526,7 @@ function toSnapshot(meta) {
2243
2526
  owner: meta.owner,
2244
2527
  source: meta.source,
2245
2528
  base: meta.base,
2529
+ ...meta.image !== void 0 ? { image: meta.image } : {},
2246
2530
  vcpu: meta.vcpu,
2247
2531
  memMib: meta.memMib,
2248
2532
  sizeBytes: meta.sizeBytes,
@@ -2263,7 +2547,7 @@ async function listSnapshots(scope, p = paths()) {
2263
2547
  }
2264
2548
  async function usedBytes(dir) {
2265
2549
  let total = 0;
2266
- for (const entry of await readdir4(dir)) {
2550
+ for (const entry of await readdir5(dir)) {
2267
2551
  total += (await stat2(`${dir}/${entry}`)).blocks * 512;
2268
2552
  }
2269
2553
  return total;
@@ -2286,13 +2570,13 @@ async function saveSnapshot(req, owner, p = paths()) {
2286
2570
  async function snapshotBox(ref, req, owner, p) {
2287
2571
  const box = await readBox(ref, p);
2288
2572
  if (!vmAlive(box)) {
2289
- if (existsSync2(p.machine(box.owner, box.name).hibernateVmstate)) {
2573
+ if (existsSync4(p.machine(box.owner, box.name).hibernateVmstate)) {
2290
2574
  throw new KvboxError(`box ${req.box} is hibernated; a snapshot freezes a running box (kvbox wake ${req.box} first)`);
2291
2575
  }
2292
2576
  throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);
2293
2577
  }
2294
2578
  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)`);
2579
+ if (existsSync4(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
2296
2580
  const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
2297
2581
  const cfg = await loadConfig(p);
2298
2582
  if (s !== final) await rm2(s.dir, { recursive: true, force: true });
@@ -2300,12 +2584,14 @@ async function snapshotBox(ref, req, owner, p) {
2300
2584
  try {
2301
2585
  const volumes = await captureDrivesOf(box, p);
2302
2586
  await captureBox(box, s, cfg, p);
2587
+ await copyBoxEnv(p.machine(box.owner, box.name).env, s.env);
2303
2588
  const meta = {
2304
2589
  ...volumes.length > 0 ? { volumes } : {},
2305
2590
  name: req.name,
2306
2591
  owner,
2307
2592
  source: refKey(box),
2308
2593
  base: box.base,
2594
+ ...box.image !== void 0 ? { image: box.image } : {},
2309
2595
  vcpu: box.vcpu,
2310
2596
  memMib: box.memMib,
2311
2597
  sizeBytes: await usedBytes(s.dir),
@@ -2324,7 +2610,7 @@ async function swapIn(ref, from, boxId, p) {
2324
2610
  const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
2325
2611
  await withSnapshotLock(ref, async () => {
2326
2612
  await rm2(old, { recursive: true, force: true });
2327
- const hadOld = existsSync2(to);
2613
+ const hadOld = existsSync4(to);
2328
2614
  if (hadOld) await rename4(to, old);
2329
2615
  try {
2330
2616
  await rename4(from, to);
@@ -2341,7 +2627,7 @@ async function captureBox(box, to, cfg, p) {
2341
2627
  let lineageTouched = false;
2342
2628
  try {
2343
2629
  const since = box.memSnapshots ?? 0;
2344
- const mode = since === 0 || existsSync2(m.memBase) ? "Diff" : "Full";
2630
+ const mode = since === 0 || existsSync4(m.memBase) ? "Diff" : "Full";
2345
2631
  let failure2;
2346
2632
  await fc.pause();
2347
2633
  try {
@@ -2372,7 +2658,7 @@ async function captureBox(box, to, cfg, p) {
2372
2658
  }
2373
2659
  }
2374
2660
  async function mergeOntoPrevious(previous, diffFile, editor) {
2375
- if (!existsSync2(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
2661
+ if (!existsSync4(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
2376
2662
  const merged = `${diffFile}.merged`;
2377
2663
  await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
2378
2664
  await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
@@ -2380,13 +2666,13 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
2380
2666
  }
2381
2667
  async function deleteSnapshot(ref, p = paths()) {
2382
2668
  const dir = p.snapshot(ref.owner, ref.name).dir;
2383
- if (ref.name.startsWith(".") || !existsSync2(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
2669
+ if (ref.name.startsWith(".") || !existsSync4(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
2384
2670
  await withSnapshotLock(ref, () => rm2(dir, { recursive: true, force: true }));
2385
2671
  }
2386
2672
 
2387
2673
  // src/core/network.ts
2388
2674
  import { randomInt } from "node:crypto";
2389
- import { existsSync as existsSync3 } from "node:fs";
2675
+ import { existsSync as existsSync5 } from "node:fs";
2390
2676
  import { fileURLToPath } from "node:url";
2391
2677
  var TAP_PREFIX = "kv-";
2392
2678
  var PRIVILEGED_SCRIPT = "/usr/local/lib/kvbox/net-setup.sh";
@@ -2396,15 +2682,15 @@ function tapName(box) {
2396
2682
  function netSetupScript() {
2397
2683
  const override = process.env["KVBOX_NET_SETUP"];
2398
2684
  if (override) return override;
2399
- if (existsSync3(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
2685
+ if (existsSync5(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
2400
2686
  for (const rel of ["../scripts/net-setup.sh", "../../scripts/net-setup.sh"]) {
2401
2687
  const candidate = fileURLToPath(new URL(rel, import.meta.url));
2402
- if (existsSync3(candidate)) return candidate;
2688
+ if (existsSync5(candidate)) return candidate;
2403
2689
  }
2404
2690
  throw new KvboxError("net-setup.sh not found next to kvbox-server");
2405
2691
  }
2406
2692
  function bridgeExists(bridge) {
2407
- return existsSync3(`/sys/class/net/${bridge}`);
2693
+ return existsSync5(`/sys/class/net/${bridge}`);
2408
2694
  }
2409
2695
  function netRun(cfg, args) {
2410
2696
  return run([netSetupScript(), ...args], {
@@ -2582,7 +2868,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
2582
2868
  }
2583
2869
  }
2584
2870
  function isHibernated(meta, p) {
2585
- return !vmAlive(meta) && existsSync4(p.machine(meta.owner, meta.name).hibernateVmstate);
2871
+ return !vmAlive(meta) && existsSync6(p.machine(meta.owner, meta.name).hibernateVmstate);
2586
2872
  }
2587
2873
  function statusOf(meta, p = paths()) {
2588
2874
  if (vmAlive(meta)) return meta.paused ? "standby" : "running";
@@ -2611,6 +2897,8 @@ function toMachine(meta, p = paths()) {
2611
2897
  memMib: meta.memMib,
2612
2898
  ...diskStats(p.machine(meta.owner, meta.name).overlay),
2613
2899
  base: meta.base,
2900
+ ...meta.image !== void 0 ? { image: meta.image } : {},
2901
+ ...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
2614
2902
  createdAt: meta.createdAt,
2615
2903
  source: meta.source,
2616
2904
  status: statusOf(meta, p),
@@ -2622,7 +2910,8 @@ function toMachine(meta, p = paths()) {
2622
2910
  };
2623
2911
  }
2624
2912
  var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
2625
- function autoHibernateFor(req, cfg) {
2913
+ function autoHibernateFor(req, cfg, manifest = {}) {
2914
+ if (req.autoHibernateSec === void 0 && manifest.autoHibernate === false) return void 0;
2626
2915
  return (req.autoHibernateSec ?? cfg.autoHibernateSec) || void 0;
2627
2916
  }
2628
2917
  async function readAllMeta(p) {
@@ -2677,33 +2966,6 @@ function bootArgs(name, ip, cfg, pubkeyB64) {
2677
2966
  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
2967
  return process.arch === "arm64" ? `keep_bootcon ${args}` : args;
2679
2968
  }
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
2969
  async function createOverlay(file, gib) {
2708
2970
  await writeFile5(file, "", { mode: 384 });
2709
2971
  await truncate2(file, gib * 1024 ** 3);
@@ -2742,7 +3004,7 @@ async function spawnFirecracker(ref, cfg, p) {
2742
3004
  child.unref();
2743
3005
  const pid = child.pid;
2744
3006
  if (pid === void 0) throw new KvboxError("could not start firecracker");
2745
- if (!await waitFor(() => existsSync4(m.sock), 3e3)) {
3007
+ if (!await waitFor(() => existsSync6(m.sock), 3e3)) {
2746
3008
  killQuietly(pid);
2747
3009
  throw new KvboxError(`firecracker did not open its API socket; last log lines:
2748
3010
  ${await tailOf(m.log)}`);
@@ -2757,7 +3019,7 @@ function killQuietly(pid) {
2757
3019
  }
2758
3020
  async function launch(spec, tap, cfg, pubkeyB64, p) {
2759
3021
  const m = p.machine(spec.owner, spec.name);
2760
- const baseFile = baseFileFor(spec, p);
3022
+ const baseFile = imageFileFor(spec, p);
2761
3023
  const volumes = await placeVolumeDrives(spec, p);
2762
3024
  const pid = await spawnFirecracker(spec, cfg, p);
2763
3025
  try {
@@ -2804,7 +3066,7 @@ async function loadSnapshot(spec, image, tap, cfg, p) {
2804
3066
  }
2805
3067
  }
2806
3068
  async function currentBaseVersion(p = paths()) {
2807
- return (await currentBase(await loadConfig(p), p)).version;
3069
+ return (await currentImage(void 0, await loadConfig(p), p)).version;
2808
3070
  }
2809
3071
  async function readHostPubkey(p) {
2810
3072
  try {
@@ -2815,7 +3077,7 @@ async function readHostPubkey(p) {
2815
3077
  }
2816
3078
  function assertAssets(cfg) {
2817
3079
  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`);
3080
+ if (!existsSync6(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
2819
3081
  }
2820
3082
  }
2821
3083
  async function createMachine(req, owner, p = paths()) {
@@ -2832,16 +3094,26 @@ async function createMachine(req, owner, p = paths()) {
2832
3094
  const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
2833
3095
  const id = newBoxId(idsInUse(existing));
2834
3096
  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) },
3097
+ const image = imageKey(req.image);
3098
+ const base = await currentImage(image, cfg, p);
3099
+ await assertOverlayCapable(base.file, image, base.version);
3100
+ const manifest = await imageManifest(base.file);
3101
+ const env = imageEnv(manifest, name, req.env ?? [], (await readOwnerEnv(owner, p).catch(() => null))?.vars ?? []);
3102
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3103
+ const autoHibernateSec = autoHibernateFor(req, cfg, manifest);
3104
+ const vars = env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now }));
3105
+ const machine = await bootInto(
3106
+ { id, name, owner, ip, mac: macFor(ip), vcpu: size.vcpu, memMib: size.memMib, base: base.version, image, sshKeys },
3107
+ // The image is shared read-only by every box; only the box's own writes land in its overlay.
3108
+ async (m) => {
3109
+ await createOverlay(m.overlay, size.diskGib);
3110
+ if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);
3111
+ },
3112
+ { source: "base", autoHibernateSec, url: maskedUrl(manifest, vars) },
2842
3113
  cfg,
2843
3114
  p
2844
3115
  );
3116
+ return env.connect === void 0 ? machine : { ...machine, connect: env.connect };
2845
3117
  }
2846
3118
  async function bootInto(box, prepare, origin, cfg, p) {
2847
3119
  const { id, ip, owner, name } = box;
@@ -2900,8 +3172,12 @@ async function restoreFrom(from, owner, req, cfg, p) {
2900
3172
  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
3173
  }
2902
3174
  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}`);
3175
+ if (!existsSync6(imageFile(snap.image, snap.base, p))) {
3176
+ throw new KvboxError(`snapshot ${shown(from)} stacks on ${imageLabel(snap.image)} ${snap.base}, which is gone from ${p.assets}`);
3177
+ }
3178
+ const manifest = await imageManifest(imageFile(snap.image, snap.base, p));
3179
+ if (req.image !== void 0 && imageKey(req.image) !== snap.image) {
3180
+ throw new KvboxError(`--base cannot be combined with --from: a restored box has the snapshot's image (${shown(from)}: ${imageLabel(snap.image)})`);
2905
3181
  }
2906
3182
  await assertRoomFor(snap.vcpu, snap.memMib, req.force ?? false, p);
2907
3183
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
@@ -2911,15 +3187,19 @@ async function restoreFrom(from, owner, req, cfg, p) {
2911
3187
  const id = newBoxId(idsInUse(existing));
2912
3188
  const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);
2913
3189
  const s = p.snapshot(from.owner, from.name);
3190
+ const given = new Set((req.env ?? []).map((v) => v.name));
3191
+ const vars = [...(await readBoxEnvFile(s.env)).filter((v) => !given.has(v.name)), ...(req.env ?? []).map((v) => ({ ...v, secret: false }))];
2914
3192
  return restoreInto(
2915
- { id, name, owner, ip, mac: macFor(ip), vcpu: snap.vcpu, memMib: snap.memMib, base: snap.base, sshKeys },
3193
+ { id, name, owner, ip, mac: macFor(ip), vcpu: snap.vcpu, memMib: snap.memMib, base: snap.base, image: snap.image, sshKeys },
2916
3194
  async (m) => {
2917
3195
  await run(["cp", "--sparse=always", "--reflink=auto", s.overlay, m.overlay]);
3196
+ await copyBoxEnv(s.env, m.env);
3197
+ if (req.env?.length) await mergeBoxEnv({ owner, name }, req.env, p);
2918
3198
  await link2(s.mem, m.memBase);
2919
3199
  await placeholderDrives(m.dir, snap.volumes ?? []);
2920
3200
  return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };
2921
3201
  },
2922
- { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg) },
3202
+ { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), url: maskedUrl(manifest, vars) },
2923
3203
  cfg,
2924
3204
  p
2925
3205
  );
@@ -2988,7 +3268,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
2988
3268
  growTo = preset.diskGib > diskGib ? preset.diskGib : void 0;
2989
3269
  }
2990
3270
  assertAssets(cfg);
2991
- baseFileFor(src, p);
3271
+ imageFileFor(src, p);
2992
3272
  await assertRoomFor(shape.vcpu, shape.memMib, req.force ?? false, p);
2993
3273
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
2994
3274
  authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);
@@ -2996,14 +3276,16 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
2996
3276
  const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
2997
3277
  const id = newBoxId(idsInUse(existing));
2998
3278
  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 };
3000
- const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0 };
3279
+ const box = { id, name, owner, ip, mac: macFor(ip), ...shape, base: src.base, image: src.image, sshKeys };
3280
+ const srcEnv = p.machine(src.owner, src.name).env;
3281
+ const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, url: src.url };
3001
3282
  if (!warm) {
3002
3283
  return bootInto(
3003
3284
  box,
3004
3285
  async (m) => {
3005
3286
  await run(["cp", "--sparse=always", "--reflink=auto", srcDisk, m.overlay]);
3006
3287
  if (growTo !== void 0) await growDisk(m.overlay, growTo);
3288
+ await copyBoxEnv(srcEnv, m.env);
3007
3289
  },
3008
3290
  origin,
3009
3291
  cfg,
@@ -3015,6 +3297,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
3015
3297
  box,
3016
3298
  async (m) => {
3017
3299
  await captureBox(src, { vmstate: m.forkVmstate, mem: m.memBase, overlay: m.overlay }, cfg, p);
3300
+ await copyBoxEnv(srcEnv, m.env);
3018
3301
  await placeholderDrives(m.dir, srcVolumes);
3019
3302
  return { vmstate: m.forkVmstate, mem: m.memBase, label: `box ${shown(ref)}`, volumes: srcVolumes };
3020
3303
  },
@@ -3069,7 +3352,7 @@ async function dropGuestVolumes(box, vsock) {
3069
3352
  }
3070
3353
  }
3071
3354
  async function pushEnv(box, vsock, p) {
3072
- const vars = await envForBoot(box.owner, p);
3355
+ const vars = await envForBoot(box, p);
3073
3356
  if (vars === null) return;
3074
3357
  try {
3075
3358
  await setEnv(vsock, vars, AGENT_REPLY_MS);
@@ -3091,7 +3374,7 @@ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS
3091
3374
  const deadline = Date.now() + timing.waitMs;
3092
3375
  for (; ; ) {
3093
3376
  if (!pidAlive(pid)) return;
3094
- const vars = await envForBoot(box.owner, p);
3377
+ const vars = await envForBoot(box, p);
3095
3378
  if (vars === null) return;
3096
3379
  try {
3097
3380
  await setEnv(vsock, vars, timing.replyMs);
@@ -3303,8 +3586,8 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
3303
3586
  if (status === "running" || status === "standby") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated`);
3304
3587
  if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated; kvbox start ${shown(ref)} boots it`);
3305
3588
  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}`);
3589
+ if (!existsSync6(imageFile(meta.image, meta.base, p))) {
3590
+ throw new KvboxError(`box ${shown(ref)} stacks on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);
3308
3591
  }
3309
3592
  const m = p.machine(ref.owner, ref.name);
3310
3593
  await ensureHostNetwork(cfg);
@@ -3358,9 +3641,9 @@ var updateMachine = locked(async function updateMachine2(ref, p = paths()) {
3358
3641
  const cfg = await loadConfig(p);
3359
3642
  assertNotHibernated(meta, p);
3360
3643
  assertAssets(cfg);
3361
- const base = await currentBase(cfg, p);
3644
+ const base = await currentImage(meta.image, cfg, p);
3362
3645
  if (base.version === meta.base) return toMachine(meta, p);
3363
- await assertOverlayCapable(base.file, base.version);
3646
+ await assertOverlayCapable(base.file, meta.image, base.version);
3364
3647
  return applyAtNextBoot(meta, { base: base.version }, "update", cfg, p);
3365
3648
  });
3366
3649
  var rescaleMachine = locked(async function rescaleMachine2(ref, req, p = paths()) {
@@ -3603,7 +3886,7 @@ async function pinRunningTaps(p = paths()) {
3603
3886
  const cfg = await loadConfig(p);
3604
3887
  if (!bridgeExists(cfg.bridge)) return;
3605
3888
  for (const meta of await readAllMeta(p)) {
3606
- if (!vmAlive(meta) || !existsSync4(`/sys/class/net/${tapName(meta.id)}`)) continue;
3889
+ if (!vmAlive(meta) || !existsSync6(`/sys/class/net/${tapName(meta.id)}`)) continue;
3607
3890
  await pinTap(meta, cfg).catch((err) => console.error(`warning: could not pin box ${meta.name}'s tap: ${err.message}`));
3608
3891
  }
3609
3892
  }
@@ -3645,24 +3928,24 @@ async function bootRecovered(settled, p = paths()) {
3645
3928
  import { chmod as chmod3, mkdir as mkdir7, rm as rm4, writeFile as writeFile6 } from "node:fs/promises";
3646
3929
 
3647
3930
  // ../shared/src/relay.ts
3648
- import { z as z6 } from "zod";
3931
+ import { z as z7 } from "zod";
3649
3932
  var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
3650
3933
  var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
3651
3934
  var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
3652
- var RelayJoinSchema = z6.object({
3653
- v: z6.literal(1),
3935
+ var RelayJoinSchema = z7.object({
3936
+ v: z7.literal(1),
3654
3937
  /** How the relay lists this host. */
3655
- name: z6.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
3938
+ name: z7.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
3656
3939
  /** `<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}$/),
3940
+ relay: z7.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
3658
3941
  /** The relay's WireGuard public key. */
3659
- relayKey: z6.string().regex(WG_KEY_RE),
3942
+ relayKey: z7.string().regex(WG_KEY_RE),
3660
3943
  /** This host's address inside the tunnel. */
3661
- tunnelIp: z6.string().regex(IPV4_RE),
3944
+ tunnelIp: z7.string().regex(IPV4_RE),
3662
3945
  /** This host's WireGuard private key, generated on the relay, kept nowhere else. */
3663
- privateKey: z6.string().regex(WG_KEY_RE),
3946
+ privateKey: z7.string().regex(WG_KEY_RE),
3664
3947
  /** 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)
3948
+ publicIp: z7.string().regex(IPV4_RE)
3666
3949
  });
3667
3950
  function decodeRelayJoin(text) {
3668
3951
  let parsed;
@@ -3897,7 +4180,7 @@ function versionOf(srcFileUrl, injected) {
3897
4180
  }
3898
4181
 
3899
4182
  // src/version.ts
3900
- var VERSION = versionOf(import.meta.url, true ? "0.5.28" : void 0);
4183
+ var VERSION = versionOf(import.meta.url, true ? "0.5.30" : void 0);
3901
4184
 
3902
4185
  // src/caller.ts
3903
4186
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";
@@ -4333,6 +4616,29 @@ function machineRoutes() {
4333
4616
  }
4334
4617
  return c.json(await machineUsage(parseRef(c.req.param("name"), c.get("owner")), from));
4335
4618
  });
4619
+ r.get("/:name/env", async (c) => {
4620
+ const ref = parseRef(c.req.param("name"), c.get("owner"));
4621
+ await getMachine(ref);
4622
+ return c.json({ box: ref.name, vars: shownBoxEnv(await readBoxEnv(ref)) });
4623
+ });
4624
+ r.post("/:name/env/:var", async (c) => {
4625
+ const ref = parseRef(c.req.param("name"), c.get("owner"));
4626
+ const name = c.req.param("var");
4627
+ const problem = envNameProblem(name);
4628
+ if (problem !== null) throw new KvboxError(problem);
4629
+ const body = SetEnvRequest.safeParse(await c.req.json().catch(() => ({})));
4630
+ if (!body.success) throw new KvboxError("expected {value, secret?}");
4631
+ await setBoxVar(ref, name, body.data.value, body.data.secret ?? false);
4632
+ const box = await getMachine(ref);
4633
+ return c.json({ box: ref.name, name, running: box.status !== "stopped" });
4634
+ });
4635
+ r.delete("/:name/env/:var", async (c) => {
4636
+ const ref = parseRef(c.req.param("name"), c.get("owner"));
4637
+ const name = c.req.param("var");
4638
+ await rmBoxVar(ref, name);
4639
+ const box = await getMachine(ref);
4640
+ return c.json({ box: ref.name, name, running: box.status !== "stopped" });
4641
+ });
4336
4642
  r.get("/:name/stats", async (c) => c.json(await machineStats(parseRef(c.req.param("name"), c.get("owner")))));
4337
4643
  r.delete("/:name", async (c) => {
4338
4644
  await destroyMachine(parseRef(c.req.param("name"), c.get("owner")));