@kvbox/server 0.5.24 → 0.5.26

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.
@@ -37,6 +37,8 @@ function paths(home = kvboxHome()) {
37
37
  serverLog: join(home, "server.log"),
38
38
  /** The CLI's login to the control plane (`kvbox login`): url, bearer token, user. Mode 600. */
39
39
  cli: join(home, "cli.json"),
40
+ /** The CLI's last look at npm for a newer @kvbox/cli: `{checkedAt, latest}`, at most once a day (cli update.ts). */
41
+ updateCheck: join(home, "update-check.json"),
40
42
  ssh: join(home, "ssh"),
41
43
  sshKey: join(home, "ssh", "id_ed25519"),
42
44
  /** The device key signed by the control plane's CA (#51); ssh loads it by itself next to `-i id_ed25519`. */
@@ -106,6 +108,9 @@ function paths(home = kvboxHome()) {
106
108
  disk: join(dir, "disk.ext4")
107
109
  };
108
110
  },
111
+ /** Each owner's environment variables as the control plane last sent them (#88): env/<owner>.json, mode 600. */
112
+ env: join(home, "env"),
113
+ ownerEnv: (owner) => join(home, "env", `${owner}.json`),
109
114
  snapshot: (owner, name) => {
110
115
  const dir = join(home, "snapshots", owner, name);
111
116
  return {
@@ -509,6 +514,8 @@ var VolumeSchema = z3.object({
509
514
  ownerKind: z3.enum(["user", "org"]).optional()
510
515
  });
511
516
  var MAX_VOLUME_GIB = 4096;
517
+ var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
518
+ var VOLUME_NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
512
519
  var CreateVolumeRequest = z3.object({
513
520
  name: z3.string(),
514
521
  sizeGib: z3.number().int().min(1).max(MAX_VOLUME_GIB),
@@ -522,6 +529,26 @@ var CreateVolumeRequest = z3.object({
522
529
  var AttachVolumeRequest = z3.object({
523
530
  box: z3.string()
524
531
  });
532
+ var EnvVarSchema = z3.object({
533
+ name: z3.string(),
534
+ value: z3.string().optional(),
535
+ secret: z3.boolean(),
536
+ updatedAt: z3.string()
537
+ });
538
+ var SetEnvRequest = z3.object({
539
+ value: z3.string(),
540
+ secret: z3.boolean().optional()
541
+ });
542
+ var EnvChangeSchema = z3.object({
543
+ owner: z3.string(),
544
+ name: z3.string(),
545
+ boxes: z3.number().int()
546
+ });
547
+ var HostEnvRequest = z3.object({
548
+ version: z3.number().int().min(0),
549
+ vars: z3.array(z3.object({ name: z3.string(), value: z3.string() }))
550
+ });
551
+ var HostEnvVersionsSchema = z3.array(z3.object({ owner: z3.string(), version: z3.number().int() }));
525
552
  var CreateMachineRequest = z3.object({
526
553
  name: z3.string().optional(),
527
554
  /** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
@@ -818,10 +845,26 @@ var TopUpSchema = z3.object({
818
845
  slug: z3.string(),
819
846
  amount: z3.number(),
820
847
  currency: z3.string(),
821
- source: z3.enum(["admin", "card", "trial"]),
848
+ /** `transfer` (#93): an owner moving credit to an org they own, a negative row on their slug and a positive one on the org's. */
849
+ source: z3.enum(["admin", "card", "trial", "transfer"]),
822
850
  note: z3.string().nullable(),
823
851
  at: z3.string()
824
852
  });
853
+ var TOP_UP_AMOUNTS = [10, 25, 50, 100];
854
+ var BillingInfoSchema = z3.object({
855
+ card: z3.object({ brand: z3.string(), last4: z3.string() }).nullable(),
856
+ cardInUse: z3.boolean(),
857
+ balance: BalanceSchema
858
+ });
859
+ var BillingRedirectSchema = z3.object({ url: z3.string() });
860
+ var TopUpCheckoutRequestSchema = z3.object({
861
+ amount: z3.literal(TOP_UP_AMOUNTS)
862
+ });
863
+ var TransferRequestSchema = z3.object({
864
+ org: z3.string().min(1),
865
+ amount: z3.number().positive().multipleOf(0.01, "amount is in cents at most")
866
+ });
867
+ var TransferResponseSchema = z3.object({ from: BalanceSchema, to: BalanceSchema, activated: z3.boolean() });
825
868
  var LoginRequestSchema = z3.object({
826
869
  email: z3.string().min(1),
827
870
  password: z3.string().min(1),
@@ -1111,7 +1154,7 @@ async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
1111
1154
  // src/core/machines.ts
1112
1155
  import { spawn } from "node:child_process";
1113
1156
  import { closeSync as closeSync2, existsSync as existsSync4, openSync as openSync2, statSync as statSync2 } from "node:fs";
1114
- import { link as link2, mkdir as mkdir5, readFile as readFile5, realpath, rm as rm3, truncate as truncate2, writeFile as writeFile4 } from "node:fs/promises";
1157
+ import { link as link2, mkdir as mkdir6, readFile as readFile6, realpath, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1115
1158
  import { basename } from "node:path";
1116
1159
  import { setTimeout as sleep } from "node:timers/promises";
1117
1160
 
@@ -1127,7 +1170,7 @@ async function agentCall(udsPath, req, timeoutMs = 5e3) {
1127
1170
  sock.destroy();
1128
1171
  reject(err);
1129
1172
  };
1130
- sock.setTimeout(timeoutMs, () => fail(new KvboxError(`kvbox-agent did not answer within ${timeoutMs} ms`)));
1173
+ sock.setTimeout(timeoutMs, () => fail(new KvboxError(handshaken ? `kvbox-agent did not answer within ${timeoutMs} ms` : `the guest did not accept the vsock connection within ${timeoutMs} ms`)));
1131
1174
  sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
1132
1175
  sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
1133
1176
  `));
@@ -1176,12 +1219,127 @@ async function dropVolumes(udsPath, timeoutMs) {
1176
1219
  const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
1177
1220
  return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
1178
1221
  }
1222
+ function setEnv(udsPath, vars, timeoutMs) {
1223
+ return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
1224
+ }
1179
1225
  var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
1180
- var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
1226
+ var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
1227
+ 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 ?? "");
1228
+
1229
+ // src/core/env.ts
1230
+ import { mkdir as mkdir2, readFile as readFile4, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
1231
+ import { z as z4 } from "zod";
1232
+
1233
+ // ../shared/src/env.ts
1234
+ var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
1235
+ var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
1236
+ var ENV_MAX_VALUE_BYTES = 4096;
1237
+ var ENV_MAX_VARS = 100;
1238
+ function envNameProblem(name) {
1239
+ if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
1240
+ if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
1241
+ if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
1242
+ return null;
1243
+ }
1244
+ function envValueProblem(value) {
1245
+ if (/[\n\r\0]/.test(value)) return "a value is one line: no line breaks (base64 a multi-line value such as a key file)";
1246
+ if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
1247
+ return null;
1248
+ }
1249
+
1250
+ // src/core/locks.ts
1251
+ import { AsyncLocalStorage } from "node:async_hooks";
1252
+ var tails = /* @__PURE__ */ new Map();
1253
+ var held = new AsyncLocalStorage();
1254
+ function withBoxLock(ref, fn) {
1255
+ return withLock(refKey(ref), fn);
1256
+ }
1257
+ function withHostLock(name, fn) {
1258
+ return withLock(`host:${name}`, fn);
1259
+ }
1260
+ async function withLock(key, fn) {
1261
+ const mine = held.getStore();
1262
+ if (mine?.has(key)) return fn();
1263
+ const previous = tails.get(key);
1264
+ let release;
1265
+ const tail = new Promise((resolve) => release = resolve);
1266
+ tails.set(key, tail);
1267
+ try {
1268
+ await previous;
1269
+ return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
1270
+ } finally {
1271
+ release();
1272
+ if (tails.get(key) === tail) tails.delete(key);
1273
+ }
1274
+ }
1275
+ function boxBusy(ref) {
1276
+ return tails.has(refKey(ref));
1277
+ }
1278
+ function locked(fn) {
1279
+ return (...args) => withBoxLock(args[0], () => fn(...args));
1280
+ }
1281
+
1282
+ // src/core/env.ts
1283
+ var OwnerEnvSchema = z4.object({
1284
+ /** The control plane's counter for the list; only ever grows. */
1285
+ version: z4.number().int().min(0),
1286
+ vars: z4.array(z4.object({ name: z4.string(), value: z4.string() }))
1287
+ });
1288
+ async function readOwnerEnv(owner, p = paths()) {
1289
+ try {
1290
+ return OwnerEnvSchema.parse(JSON.parse(await readFile4(p.ownerEnv(owner), "utf8")));
1291
+ } catch (err) {
1292
+ if (err.code === "ENOENT") return null;
1293
+ throw err;
1294
+ }
1295
+ }
1296
+ async function envForBoot(owner, p = paths()) {
1297
+ const env = await readOwnerEnv(owner, p).catch(() => null);
1298
+ if (env !== null) return env.vars;
1299
+ return realmOf(owner) !== null ? [] : null;
1300
+ }
1301
+ async function setOwnerEnv(owner, req, p = paths()) {
1302
+ if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
1303
+ if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
1304
+ const seen = /* @__PURE__ */ new Set();
1305
+ for (const v of req.vars) {
1306
+ const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
1307
+ if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
1308
+ if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);
1309
+ seen.add(v.name);
1310
+ }
1311
+ return withHostLock("env", async () => {
1312
+ const have = await readOwnerEnv(owner, p);
1313
+ if (have !== null && have.version > req.version) return { version: have.version };
1314
+ const file = p.ownerEnv(owner);
1315
+ await mkdir2(p.env, { recursive: true, mode: 448 });
1316
+ const tmp = `${file}.tmp`;
1317
+ await writeFile2(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
1318
+ await rename2(tmp, file);
1319
+ return { version: req.version };
1320
+ });
1321
+ }
1322
+ async function listEnvVersions(scope, p = paths()) {
1323
+ let files;
1324
+ try {
1325
+ files = await readdir(p.env);
1326
+ } catch (err) {
1327
+ if (err.code === "ENOENT") return [];
1328
+ throw err;
1329
+ }
1330
+ const out = [];
1331
+ for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
1332
+ const owner = file.slice(0, -".json".length);
1333
+ if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;
1334
+ const env = await readOwnerEnv(owner, p).catch(() => null);
1335
+ if (env !== null) out.push({ owner, version: env.version });
1336
+ }
1337
+ return out;
1338
+ }
1181
1339
 
1182
1340
  // src/core/volumes.ts
1183
1341
  import { existsSync, statSync } from "node:fs";
1184
- import { lstat, mkdir as mkdir3, readdir as readdir2, rm, statfs, symlink, truncate, writeFile as writeFile3 } from "node:fs/promises";
1342
+ import { lstat, mkdir as mkdir4, readdir as readdir3, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
1185
1343
 
1186
1344
  // ../shared/src/capacity.ts
1187
1345
  var MEM_HEADROOM_MIB = 2048;
@@ -1330,108 +1488,76 @@ function volumeEventsInScope(scope, window, p = paths()) {
1330
1488
  return rows.filter((r) => inScope(r.owner, scope)).map(volumeWithId);
1331
1489
  }
1332
1490
 
1333
- // src/core/locks.ts
1334
- import { AsyncLocalStorage } from "node:async_hooks";
1335
- var tails = /* @__PURE__ */ new Map();
1336
- var held = new AsyncLocalStorage();
1337
- function withBoxLock(ref, fn) {
1338
- return withLock(refKey(ref), fn);
1339
- }
1340
- function withHostLock(name, fn) {
1341
- return withLock(`host:${name}`, fn);
1342
- }
1343
- async function withLock(key, fn) {
1344
- const mine = held.getStore();
1345
- if (mine?.has(key)) return fn();
1346
- const previous = tails.get(key);
1347
- let release;
1348
- const tail = new Promise((resolve) => release = resolve);
1349
- tails.set(key, tail);
1350
- try {
1351
- await previous;
1352
- return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
1353
- } finally {
1354
- release();
1355
- if (tails.get(key) === tail) tails.delete(key);
1356
- }
1357
- }
1358
- function boxBusy(ref) {
1359
- return tails.has(refKey(ref));
1360
- }
1361
- function locked(fn) {
1362
- return (...args) => withBoxLock(args[0], () => fn(...args));
1363
- }
1364
-
1365
1491
  // src/core/state.ts
1366
1492
  import { randomBytes } from "node:crypto";
1367
1493
  import { readFileSync } from "node:fs";
1368
- import { mkdir as mkdir2, readFile as readFile4, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
1369
- import { z as z4 } from "zod";
1370
- var MachineMetaSchema = z4.object({
1494
+ import { mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1495
+ import { z as z5 } from "zod";
1496
+ var MachineMetaSchema = z5.object({
1371
1497
  /** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */
1372
- id: z4.string(),
1373
- name: z4.string(),
1498
+ id: z5.string(),
1499
+ name: z5.string(),
1374
1500
  /** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */
1375
- owner: z4.string(),
1376
- ip: z4.string(),
1377
- mac: z4.string(),
1378
- pid: z4.number().int().nullable(),
1501
+ owner: z5.string(),
1502
+ ip: z5.string(),
1503
+ mac: z5.string(),
1504
+ pid: z5.number().int().nullable(),
1379
1505
  // null: stopped on purpose, disk kept
1380
1506
  /**
1381
1507
  * The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot
1382
1508
  * the number can name some other process; a pid from another boot is dead whatever `kill -0` says.
1383
1509
  * Absent (boxes launched before #29): the pid alone decides.
1384
1510
  */
1385
- bootId: z4.string().optional(),
1386
- vcpu: z4.number().int(),
1387
- memMib: z4.number().int(),
1388
- createdAt: z4.string(),
1389
- source: z4.string(),
1511
+ bootId: z5.string().optional(),
1512
+ vcpu: z5.number().int(),
1513
+ memMib: z5.number().int(),
1514
+ createdAt: z5.string(),
1515
+ source: z5.string(),
1390
1516
  /** Base image version (assets/rootfs-<version>.ext4) the box's overlay stacks on. */
1391
- base: z4.string(),
1517
+ base: z5.string(),
1392
1518
  /**
1393
1519
  * Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
1394
1520
  * each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
1395
1521
  * is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.
1396
1522
  */
1397
- memSnapshots: z4.number().int().optional(),
1523
+ memSnapshots: z5.number().int().optional(),
1398
1524
  /** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */
1399
- paused: z4.boolean().optional(),
1525
+ paused: z5.boolean().optional(),
1400
1526
  /**
1401
1527
  * authorized_keys lines the box gets on top of the host's own key, as the control plane sent them
1402
1528
  * at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so
1403
1529
  * `start` has to send the same lines again. Absent: host key only.
1404
1530
  */
1405
- sshKeys: z4.array(z4.string()).optional(),
1531
+ sshKeys: z5.array(z5.string()).optional(),
1406
1532
  /**
1407
1533
  * The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,
1408
1534
  * or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.
1409
1535
  */
1410
- sshKeysStale: z4.boolean().optional(),
1536
+ sshKeysStale: z5.boolean().optional(),
1411
1537
  /** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */
1412
- sshPort: z4.number().int().optional(),
1538
+ sshPort: z5.number().int().optional(),
1413
1539
  /**
1414
1540
  * Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,
1415
1541
  * each host port the box's for its life. DNATed while the box runs, rebuilt from here with its
1416
1542
  * current IP every time it comes up. Absent: none.
1417
1543
  */
1418
- ports: z4.array(z4.object({ guestPort: z4.number().int(), hostPort: z4.number().int(), proto: z4.enum(["tcp", "udp"]) })).optional(),
1544
+ ports: z5.array(z5.object({ guestPort: z5.number().int(), hostPort: z5.number().int(), proto: z5.enum(["tcp", "udp"]) })).optional(),
1419
1545
  /** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
1420
- autoHibernateSec: z4.number().int().positive().optional(),
1546
+ autoHibernateSec: z5.number().int().positive().optional(),
1421
1547
  /**
1422
1548
  * Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
1423
1549
  * their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
1424
1550
  * volume's meta.json does not say. Absent: none.
1425
1551
  */
1426
- volumes: z4.array(z4.string()).optional()
1552
+ volumes: z5.array(z5.string()).optional()
1427
1553
  });
1428
- var VolumeMetaSchema = z4.object({
1554
+ var VolumeMetaSchema = z5.object({
1429
1555
  /** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
1430
- id: z4.string(),
1431
- name: z4.string(),
1432
- owner: z4.string(),
1433
- sizeGib: z4.number().int(),
1434
- createdAt: z4.string()
1556
+ id: z5.string(),
1557
+ name: z5.string(),
1558
+ owner: z5.string(),
1559
+ sizeGib: z5.number().int(),
1560
+ createdAt: z5.string()
1435
1561
  });
1436
1562
  function newBoxId(taken) {
1437
1563
  for (; ; ) {
@@ -1439,35 +1565,35 @@ function newBoxId(taken) {
1439
1565
  if (!taken.has(id)) return id;
1440
1566
  }
1441
1567
  }
1442
- var SnapshotMetaSchema = z4.object({
1443
- name: z4.string(),
1444
- owner: z4.string(),
1568
+ var SnapshotMetaSchema = z5.object({
1569
+ name: z5.string(),
1570
+ owner: z5.string(),
1445
1571
  /** The box it was taken from, as owner/name. */
1446
- source: z4.string(),
1447
- base: z4.string(),
1448
- vcpu: z4.number().int(),
1449
- memMib: z4.number().int(),
1450
- sizeBytes: z4.number().int(),
1451
- createdAt: z4.string(),
1572
+ source: z5.string(),
1573
+ base: z5.string(),
1574
+ vcpu: z5.number().int(),
1575
+ memMib: z5.number().int(),
1576
+ sizeBytes: z5.number().int(),
1577
+ createdAt: z5.string(),
1452
1578
  /**
1453
1579
  * The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
1454
1580
  * and their mounts in the memory image, but their data is not here. A box restored from the snapshot
1455
1581
  * gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
1456
1582
  */
1457
- volumes: z4.array(z4.object({ name: z4.string(), sizeGib: z4.number().int() })).optional()
1583
+ volumes: z5.array(z5.object({ name: z5.string(), sizeGib: z5.number().int() })).optional()
1458
1584
  });
1459
1585
  async function ensureLayout(p = paths()) {
1460
1586
  for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
1461
- await mkdir2(dir, { recursive: true, mode: 448 });
1587
+ await mkdir3(dir, { recursive: true, mode: 448 });
1462
1588
  }
1463
1589
  return p;
1464
1590
  }
1465
1591
  async function readJson(file, schema) {
1466
- return schema.parse(JSON.parse(await readFile4(file, "utf8")));
1592
+ return schema.parse(JSON.parse(await readFile5(file, "utf8")));
1467
1593
  }
1468
1594
  async function listDirs(dir) {
1469
1595
  try {
1470
- const entries = await readdir(dir, { withFileTypes: true });
1596
+ const entries = await readdir2(dir, { withFileTypes: true });
1471
1597
  return entries.filter((e) => e.isDirectory()).map((e) => e.name);
1472
1598
  } catch (err) {
1473
1599
  if (err.code === "ENOENT") return [];
@@ -1479,10 +1605,10 @@ async function readMachineMeta(ref, p = paths()) {
1479
1605
  }
1480
1606
  async function writeMachineMeta(meta, p = paths()) {
1481
1607
  const m = p.machine(meta.owner, meta.name);
1482
- await mkdir2(m.dir, { recursive: true });
1608
+ await mkdir3(m.dir, { recursive: true });
1483
1609
  const tmp = `${m.meta}.tmp`;
1484
- await writeFile2(tmp, JSON.stringify(meta, null, 2) + "\n");
1485
- await rename2(tmp, m.meta);
1610
+ await writeFile3(tmp, JSON.stringify(meta, null, 2) + "\n");
1611
+ await rename3(tmp, m.meta);
1486
1612
  }
1487
1613
  async function listMachineRefs(p = paths()) {
1488
1614
  return listRefs(p.machines);
@@ -1492,19 +1618,19 @@ async function readSnapshotMeta(ref, p = paths()) {
1492
1618
  }
1493
1619
  async function writeSnapshotMeta(meta, p = paths()) {
1494
1620
  const s = p.snapshot(meta.owner, meta.name);
1495
- await mkdir2(s.dir, { recursive: true });
1496
- await writeFile2(s.meta, JSON.stringify(meta, null, 2) + "\n");
1621
+ await mkdir3(s.dir, { recursive: true });
1622
+ await writeFile3(s.meta, JSON.stringify(meta, null, 2) + "\n");
1497
1623
  }
1498
1624
  async function listSnapshotRefs(p = paths()) {
1499
1625
  return listRefs(p.snapshots);
1500
1626
  }
1501
1627
  async function readVolumeMeta(ref, p = paths()) {
1502
- const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z4.string().optional() }));
1628
+ const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z5.string().optional() }));
1503
1629
  if (raw.id !== void 0) return { ...raw, id: raw.id };
1504
1630
  const taken = /* @__PURE__ */ new Set();
1505
1631
  for (const other of await listVolumeRefs(p)) {
1506
1632
  try {
1507
- const j = JSON.parse(await readFile4(p.volume(other.owner, other.name).meta, "utf8"));
1633
+ const j = JSON.parse(await readFile5(p.volume(other.owner, other.name).meta, "utf8"));
1508
1634
  if (typeof j.id === "string") taken.add(j.id);
1509
1635
  } catch {
1510
1636
  }
@@ -1516,8 +1642,8 @@ async function readVolumeMeta(ref, p = paths()) {
1516
1642
  }
1517
1643
  async function writeVolumeMeta(meta, p = paths()) {
1518
1644
  const v = p.volume(meta.owner, meta.name);
1519
- await mkdir2(v.dir, { recursive: true, mode: 448 });
1520
- await writeFile2(v.meta, JSON.stringify(meta, null, 2) + "\n");
1645
+ await mkdir3(v.dir, { recursive: true, mode: 448 });
1646
+ await writeFile3(v.meta, JSON.stringify(meta, null, 2) + "\n");
1521
1647
  }
1522
1648
  async function listVolumeRefs(p = paths()) {
1523
1649
  return listRefs(p.volumes);
@@ -1565,7 +1691,6 @@ function hostBootTime() {
1565
1691
  }
1566
1692
 
1567
1693
  // src/core/volumes.ts
1568
- var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
1569
1694
  var volumeLabel = (name) => `kv:${name}`;
1570
1695
  function toVolume(meta, attachedTo, p) {
1571
1696
  let usedBytes2 = 0;
@@ -1646,7 +1771,7 @@ async function diskCapacity(p = paths()) {
1646
1771
  }
1647
1772
  async function createVolume(req, owner, p = paths()) {
1648
1773
  if (!VOLUME_NAME_RE.test(req.name)) {
1649
- throw new KvboxError(`invalid volume name "${req.name}": 1-12 chars, lowercase letters, digits and '-', starting with a letter or digit`);
1774
+ throw new KvboxError(`invalid volume name "${req.name}": ${VOLUME_NAME_RULE}`);
1650
1775
  }
1651
1776
  if (!Number.isInteger(req.sizeGib) || req.sizeGib < 1 || req.sizeGib > MAX_VOLUME_GIB) {
1652
1777
  throw new KvboxError(`volume size: whole GB between 1 and ${MAX_VOLUME_GIB}`);
@@ -1656,7 +1781,7 @@ async function createVolume(req, owner, p = paths()) {
1656
1781
  async function makeVolume(req, owner, p) {
1657
1782
  const v = p.volume(owner, req.name);
1658
1783
  if (existsSync(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
1659
- await mkdir3(p.ownerVolumes(owner), { recursive: true, mode: 448 });
1784
+ await mkdir4(p.ownerVolumes(owner), { recursive: true, mode: 448 });
1660
1785
  const disk = await diskCapacity(p);
1661
1786
  if (!hasDiskRoom(disk, req.sizeGib)) {
1662
1787
  throw new KvboxError(
@@ -1671,13 +1796,13 @@ async function makeVolume(req, owner, p) {
1671
1796
  }
1672
1797
  }
1673
1798
  try {
1674
- await mkdir3(v.dir, { mode: 448 });
1799
+ await mkdir4(v.dir, { mode: 448 });
1675
1800
  } catch (err) {
1676
1801
  if (err.code === "EEXIST") throw new KvboxError(`volume ${req.name} already exists`);
1677
1802
  throw err;
1678
1803
  }
1679
1804
  try {
1680
- await writeFile3(v.disk, "", { mode: 384 });
1805
+ await writeFile4(v.disk, "", { mode: 384 });
1681
1806
  await truncate(v.disk, req.sizeGib * 1024 ** 3);
1682
1807
  await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", volumeLabel(req.name), "-E", "lazy_itable_init=1,lazy_journal_init=1", v.disk]);
1683
1808
  const meta = { id: newBoxId(taken), name: req.name, owner, sizeGib: req.sizeGib, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
@@ -1728,7 +1853,7 @@ async function captureDrivesOf(box, p) {
1728
1853
  const drives = await volumeDrivesOf(box, p);
1729
1854
  const named = new Set(drives.map((d) => d.name));
1730
1855
  const dir = p.machine(box.owner, box.name).dir;
1731
- for (const entry of (await readdir2(dir).catch(() => [])).sort()) {
1856
+ for (const entry of (await readdir3(dir).catch(() => [])).sort()) {
1732
1857
  const m = /^volume-(.+)\.ext4$/.exec(entry);
1733
1858
  if (!m || named.has(m[1])) continue;
1734
1859
  const st = await lstat(`${dir}/${entry}`);
@@ -1760,7 +1885,7 @@ async function placeVolumeDrives(box, p) {
1760
1885
  return drives;
1761
1886
  }
1762
1887
  async function removeVolumeDrives(boxDir, keep) {
1763
- for (const entry of await readdir2(boxDir).catch(() => [])) {
1888
+ for (const entry of await readdir3(boxDir).catch(() => [])) {
1764
1889
  const m = /^volume-(.+)\.ext4$/.exec(entry);
1765
1890
  if (m && !keep.has(m[1])) await rm(`${boxDir}/${entry}`, { force: true });
1766
1891
  }
@@ -1769,7 +1894,7 @@ async function placeholderDrives(boxDir, volumes) {
1769
1894
  for (const v of volumes) {
1770
1895
  const file = `${boxDir}/${volumeDriveRel(v.name)}`;
1771
1896
  await rm(file, { force: true });
1772
- await writeFile3(file, "", { mode: 384 });
1897
+ await writeFile4(file, "", { mode: 384 });
1773
1898
  await truncate(file, v.sizeGib * 1024 ** 3);
1774
1899
  }
1775
1900
  }
@@ -1839,7 +1964,7 @@ async function assertRoomFor(vcpu, memMib, force, p = paths()) {
1839
1964
 
1840
1965
  // src/core/snapshots.ts
1841
1966
  import { existsSync as existsSync2 } from "node:fs";
1842
- import { link, mkdir as mkdir4, readdir as readdir3, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
1967
+ import { link, mkdir as mkdir5, readdir as readdir4, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
1843
1968
 
1844
1969
  // src/core/firecracker.ts
1845
1970
  import { Agent, request as request2 } from "undici";
@@ -1982,7 +2107,7 @@ async function listSnapshots(scope, p = paths()) {
1982
2107
  }
1983
2108
  async function usedBytes(dir) {
1984
2109
  let total = 0;
1985
- for (const entry of await readdir3(dir)) {
2110
+ for (const entry of await readdir4(dir)) {
1986
2111
  total += (await stat2(`${dir}/${entry}`)).blocks * 512;
1987
2112
  }
1988
2113
  return total;
@@ -2013,7 +2138,7 @@ async function snapshotBox(ref, req, owner, p) {
2013
2138
  const s = p.snapshot(owner, req.name);
2014
2139
  if (existsSync2(s.dir)) throw new KvboxError(`snapshot ${req.name} already exists`);
2015
2140
  const cfg = await loadConfig(p);
2016
- await mkdir4(s.dir, { recursive: true, mode: 448 });
2141
+ await mkdir5(s.dir, { recursive: true, mode: 448 });
2017
2142
  try {
2018
2143
  const volumes = await captureDrivesOf(box, p);
2019
2144
  await captureBox(box, s, cfg, p);
@@ -2076,7 +2201,7 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
2076
2201
  const merged = `${diffFile}.merged`;
2077
2202
  await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
2078
2203
  await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
2079
- await rename3(merged, diffFile);
2204
+ await rename4(merged, diffFile);
2080
2205
  }
2081
2206
  async function deleteSnapshot(ref, p = paths()) {
2082
2207
  const dir = p.snapshot(ref.owner, ref.name).dir;
@@ -2377,7 +2502,7 @@ async function assertOverlayCapable(baseFile, version) {
2377
2502
  if (!ok) throw new KvboxError(`base image ${version} is not a kvbox base image (no /sbin/overlay-init); rerun install-server.sh`);
2378
2503
  }
2379
2504
  async function createOverlay(file, gib) {
2380
- await writeFile4(file, "", { mode: 384 });
2505
+ await writeFile5(file, "", { mode: 384 });
2381
2506
  await truncate2(file, gib * 1024 ** 3);
2382
2507
  await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", "kvbox-box", "-E", "lazy_itable_init=1,lazy_journal_init=1", file]);
2383
2508
  }
@@ -2391,7 +2516,7 @@ async function waitFor(pred, timeoutMs, stepMs = 50) {
2391
2516
  }
2392
2517
  async function tailOf(file, lines = 5) {
2393
2518
  try {
2394
- return (await readFile5(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
2519
+ return (await readFile6(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
2395
2520
  } catch {
2396
2521
  return "";
2397
2522
  }
@@ -2480,7 +2605,7 @@ async function currentBaseVersion(p = paths()) {
2480
2605
  }
2481
2606
  async function readHostPubkey(p) {
2482
2607
  try {
2483
- return (await readFile5(`${p.sshKey}.pub`, "utf8")).trim();
2608
+ return (await readFile6(`${p.sshKey}.pub`, "utf8")).trim();
2484
2609
  } catch {
2485
2610
  throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);
2486
2611
  }
@@ -2520,7 +2645,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
2520
2645
  const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
2521
2646
  const m = p.machine(owner, name);
2522
2647
  await ensureHostNetwork(cfg);
2523
- await mkdir5(m.dir, { recursive: true, mode: 448 });
2648
+ await mkdir6(m.dir, { recursive: true, mode: 448 });
2524
2649
  let tapCreated = false;
2525
2650
  let pid;
2526
2651
  let sshPort;
@@ -2534,6 +2659,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
2534
2659
  const spec = { ...box, sshPort };
2535
2660
  pid = await launch(spec, tap, cfg, keysB64, p);
2536
2661
  await openPorts(spec, cfg);
2662
+ void pushEnvAfterBoot(spec, pid, m.vsock, p);
2537
2663
  const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
2538
2664
  await writeMachineMeta(meta, p);
2539
2665
  recordState(meta, "running", "new", p, meta.createdAt);
@@ -2594,7 +2720,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
2594
2720
  const { id, ip, owner, name } = box;
2595
2721
  const m = p.machine(owner, name);
2596
2722
  await ensureHostNetwork(cfg);
2597
- await mkdir5(m.dir, { recursive: true, mode: 448 });
2723
+ await mkdir6(m.dir, { recursive: true, mode: 448 });
2598
2724
  let tapCreated = false;
2599
2725
  let pid;
2600
2726
  let sshPort;
@@ -2615,6 +2741,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
2615
2741
  const stale = await pushAuthorizedKeys(box, m.vsock, p);
2616
2742
  if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
2617
2743
  if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
2744
+ await pushEnv(box, m.vsock, p);
2618
2745
  await attachTap(id, cfg);
2619
2746
  await openPorts(spec, cfg);
2620
2747
  const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
@@ -2732,6 +2859,46 @@ async function dropGuestVolumes(box, vsock) {
2732
2859
  console.error(`warning: box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);
2733
2860
  }
2734
2861
  }
2862
+ async function pushEnv(box, vsock, p) {
2863
+ const vars = await envForBoot(box.owner, p);
2864
+ if (vars === null) return;
2865
+ try {
2866
+ await setEnv(vsock, vars, AGENT_REPLY_MS);
2867
+ } catch (err) {
2868
+ warnEnv(box, vars, err);
2869
+ }
2870
+ }
2871
+ function warnEnv(box, vars, err) {
2872
+ if (isUnknownOp(err)) {
2873
+ if (vars.length === 0) return;
2874
+ console.error(`warning: box ${shown(box)} did not get its environment variables: its image predates base v0.10.0, whose kvbox-agent takes them (kvbox vm update ${shown(box)} moves it onto the current base)`);
2875
+ return;
2876
+ }
2877
+ console.error(`warning: box ${shown(box)} did not get its environment variables: ${err.message}`);
2878
+ }
2879
+ var ENV_BOOT_WAIT_MS = 12e4;
2880
+ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS, waitMs: ENV_BOOT_WAIT_MS }) {
2881
+ return (async () => {
2882
+ const deadline = Date.now() + timing.waitMs;
2883
+ for (; ; ) {
2884
+ if (!pidAlive(pid)) return;
2885
+ const vars = await envForBoot(box.owner, p);
2886
+ if (vars === null) return;
2887
+ try {
2888
+ await setEnv(vsock, vars, timing.replyMs);
2889
+ return;
2890
+ } catch (err) {
2891
+ if (!pidAlive(pid)) return;
2892
+ if (isNoAgent(err) && Date.now() < deadline) {
2893
+ await sleep(500);
2894
+ continue;
2895
+ }
2896
+ warnEnv(box, vars, err);
2897
+ return;
2898
+ }
2899
+ }
2900
+ })();
2901
+ }
2735
2902
  async function resumeVm(sock) {
2736
2903
  const fc = new FirecrackerClient(sock);
2737
2904
  try {
@@ -2797,6 +2964,7 @@ var startMachine = locked(async function startMachine2(ref, p = paths()) {
2797
2964
  try {
2798
2965
  pid = await launch(meta, tap, cfg, keysB64, p);
2799
2966
  await openPorts(meta, cfg);
2967
+ void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);
2800
2968
  const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0 };
2801
2969
  await writeMachineMeta(started, p);
2802
2970
  recordState(started, "running", "start", p);
@@ -2895,7 +3063,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
2895
3063
  if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
2896
3064
  const m = p.machine(ref.owner, ref.name);
2897
3065
  await rm3(m.hibernateDir, { recursive: true, force: true });
2898
- await mkdir5(m.hibernateDir, { recursive: true, mode: 448 });
3066
+ await mkdir6(m.hibernateDir, { recursive: true, mode: 448 });
2899
3067
  const fc = new FirecrackerClient(m.sock);
2900
3068
  try {
2901
3069
  try {
@@ -3173,27 +3341,27 @@ async function bootRecovered(settled, p = paths()) {
3173
3341
  }
3174
3342
 
3175
3343
  // src/core/relay.ts
3176
- import { chmod as chmod3, mkdir as mkdir6, rm as rm4, writeFile as writeFile5 } from "node:fs/promises";
3344
+ import { chmod as chmod3, mkdir as mkdir7, rm as rm4, writeFile as writeFile6 } from "node:fs/promises";
3177
3345
 
3178
3346
  // ../shared/src/relay.ts
3179
- import { z as z5 } from "zod";
3347
+ import { z as z6 } from "zod";
3180
3348
  var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
3181
3349
  var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
3182
3350
  var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
3183
- var RelayJoinSchema = z5.object({
3184
- v: z5.literal(1),
3351
+ var RelayJoinSchema = z6.object({
3352
+ v: z6.literal(1),
3185
3353
  /** How the relay lists this host. */
3186
- name: z5.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
3354
+ name: z6.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
3187
3355
  /** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
3188
- relay: z5.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
3356
+ relay: z6.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
3189
3357
  /** The relay's WireGuard public key. */
3190
- relayKey: z5.string().regex(WG_KEY_RE),
3358
+ relayKey: z6.string().regex(WG_KEY_RE),
3191
3359
  /** This host's address inside the tunnel. */
3192
- tunnelIp: z5.string().regex(IPV4_RE),
3360
+ tunnelIp: z6.string().regex(IPV4_RE),
3193
3361
  /** This host's WireGuard private key, generated on the relay, kept nowhere else. */
3194
- privateKey: z5.string().regex(WG_KEY_RE),
3362
+ privateKey: z6.string().regex(WG_KEY_RE),
3195
3363
  /** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
3196
- publicIp: z5.string().regex(IPV4_RE)
3364
+ publicIp: z6.string().regex(IPV4_RE)
3197
3365
  });
3198
3366
  function decodeRelayJoin(text) {
3199
3367
  let parsed;
@@ -3237,8 +3405,8 @@ async function useRelay(joinString, p = paths()) {
3237
3405
  `${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join2.publicIp}; run kvbox server leave first, then join again`
3238
3406
  );
3239
3407
  }
3240
- await mkdir6(p.relay, { recursive: true, mode: 448 });
3241
- await writeFile5(p.relayConf, relayConf(join2), { mode: 384 });
3408
+ await mkdir7(p.relay, { recursive: true, mode: 448 });
3409
+ await writeFile6(p.relayConf, relayConf(join2), { mode: 384 });
3242
3410
  await chmod3(p.relayConf, 384);
3243
3411
  await netSetup(cfg, ["relay", "up", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);
3244
3412
  const relay = { name: join2.name, publicIp: join2.publicIp, tunnelIp: join2.tunnelIp, endpoint: join2.relay };
@@ -3260,12 +3428,12 @@ async function dropRelay(p = paths()) {
3260
3428
  }
3261
3429
 
3262
3430
  // src/core/idle.ts
3263
- import { readFile as readFile6 } from "node:fs/promises";
3431
+ import { readFile as readFile7 } from "node:fs/promises";
3264
3432
  var HIBERNATE_CONCURRENCY = 2;
3265
3433
  async function tapTraffic(id) {
3266
3434
  const dir = `/sys/class/net/${tapName(id)}/statistics`;
3267
3435
  try {
3268
- const [rx, tx] = await Promise.all([readFile6(`${dir}/rx_bytes`, "utf8"), readFile6(`${dir}/tx_bytes`, "utf8")]);
3436
+ const [rx, tx] = await Promise.all([readFile7(`${dir}/rx_bytes`, "utf8"), readFile7(`${dir}/tx_bytes`, "utf8")]);
3269
3437
  return Number(rx) + Number(tx);
3270
3438
  } catch {
3271
3439
  return null;
@@ -3408,12 +3576,12 @@ function startRelayWatch(opts = {}) {
3408
3576
  }
3409
3577
 
3410
3578
  // src/listen.ts
3411
- import { readFile as readFile7, rm as rm5, writeFile as writeFile6 } from "node:fs/promises";
3579
+ import { readFile as readFile8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
3412
3580
  import { createServer as createHttpsServer } from "node:https";
3413
3581
  import { createAdaptorServer } from "@hono/node-server";
3414
3582
 
3415
3583
  // src/app.ts
3416
- import { Hono as Hono8 } from "hono";
3584
+ import { Hono as Hono9 } from "hono";
3417
3585
 
3418
3586
  // ../shared/src/version.ts
3419
3587
  import { createRequire } from "node:module";
@@ -3428,7 +3596,7 @@ function versionOf(srcFileUrl, injected) {
3428
3596
  }
3429
3597
 
3430
3598
  // src/version.ts
3431
- var VERSION = versionOf(import.meta.url, true ? "0.5.24" : void 0);
3599
+ var VERSION = versionOf(import.meta.url, true ? "0.5.26" : void 0);
3432
3600
 
3433
3601
  // src/caller.ts
3434
3602
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";
@@ -3469,8 +3637,8 @@ function resolveCaller(opts = {}) {
3469
3637
  const user = c.req.header(OWNER_HEADER);
3470
3638
  if (user === void 0) {
3471
3639
  const path = c.req.path.replace(/\/$/, "");
3472
- const realmListing = c.req.method === "GET" && (path === "/machines" || path === "/snapshots" || path === "/volumes");
3473
- if (!realmListing && /^\/(machines|snapshots|volumes)(\/|$)/.test(c.req.path)) {
3640
+ const realmListing = c.req.method === "GET" && (path === "/machines" || path === "/snapshots" || path === "/volumes" || path === "/env");
3641
+ if (!realmListing && /^\/(machines|snapshots|volumes|env)(\/|$)/.test(c.req.path)) {
3474
3642
  return c.json({ error: "X-Kvbox-Owner header required" }, 400);
3475
3643
  }
3476
3644
  c.set("owner", "");
@@ -3756,18 +3924,31 @@ function capacityRoutes() {
3756
3924
  return r;
3757
3925
  }
3758
3926
 
3759
- // src/routes/machines.ts
3927
+ // src/routes/env.ts
3760
3928
  import { Hono as Hono3 } from "hono";
3929
+ function envRoutes() {
3930
+ const r = new Hono3();
3931
+ r.get("/", async (c) => c.json(await listEnvVersions(c.get("listScope"))));
3932
+ r.post("/", async (c) => {
3933
+ const body = HostEnvRequest.safeParse(await c.req.json().catch(() => ({})));
3934
+ if (!body.success) throw new KvboxError("env: expected {version, vars: [{name, value}]}");
3935
+ return c.json(await setOwnerEnv(c.get("owner"), body.data));
3936
+ });
3937
+ return r;
3938
+ }
3939
+
3940
+ // src/routes/machines.ts
3941
+ import { Hono as Hono4 } from "hono";
3761
3942
 
3762
3943
  // src/core/stats.ts
3763
3944
  var STATS_REPLY_MS = 3e3;
3764
- async function machineStats(ref, p = paths()) {
3945
+ async function machineStats(ref, p = paths(), replyMs = STATS_REPLY_MS) {
3765
3946
  const m = await getMachine(ref, p);
3766
3947
  if (m.status !== "running") throw new KvboxError(`${stateMessage(ref, m.status)}; only a running box can say how it is doing`);
3767
3948
  try {
3768
- return { name: m.name, owner: m.owner, stats: await stats(p.machine(m.owner, m.name).vsock, STATS_REPLY_MS) };
3949
+ return { name: m.name, owner: m.owner, stats: await stats(p.machine(m.owner, m.name).vsock, replyMs) };
3769
3950
  } catch (err) {
3770
- if (isUnknownOp(err) || isNoAgent(err)) return { name: m.name, owner: m.owner, stats: null };
3951
+ if (isUnknownOp(err) || isNoAgent(err) && !isGuestBooting(err)) return { name: m.name, owner: m.owner, stats: null };
3771
3952
  throw err;
3772
3953
  }
3773
3954
  }
@@ -3791,7 +3972,7 @@ async function usageReport(scope, window, p = paths()) {
3791
3972
 
3792
3973
  // src/routes/machines.ts
3793
3974
  function machineRoutes() {
3794
- const r = new Hono3();
3975
+ const r = new Hono4();
3795
3976
  r.get("/", async (c) => c.json(await listMachines(c.get("listScope"))));
3796
3977
  r.post("/", async (c) => {
3797
3978
  const body = CreateMachineRequest.parse(await c.req.json().catch(() => ({})));
@@ -3853,9 +4034,9 @@ function machineRoutes() {
3853
4034
  }
3854
4035
 
3855
4036
  // src/routes/snapshots.ts
3856
- import { Hono as Hono4 } from "hono";
4037
+ import { Hono as Hono5 } from "hono";
3857
4038
  function snapshotRoutes() {
3858
- const r = new Hono4();
4039
+ const r = new Hono5();
3859
4040
  r.get("/", async (c) => c.json(await listSnapshots(c.get("listScope"))));
3860
4041
  r.post("/", async (c) => {
3861
4042
  const body = CreateSnapshotRequest.parse(await c.req.json());
@@ -3869,9 +4050,9 @@ function snapshotRoutes() {
3869
4050
  }
3870
4051
 
3871
4052
  // src/routes/ssh.ts
3872
- import { Hono as Hono5 } from "hono";
4053
+ import { Hono as Hono6 } from "hono";
3873
4054
  function sshRoutes(opts = {}) {
3874
- const r = new Hono5();
4055
+ const r = new Hono6();
3875
4056
  if (opts.controlPlane) {
3876
4057
  r.all("/*", (c) => c.json({ error: "trusting a CA is done on the host itself (kvbox server trust-ca there); the control plane cannot ask a host to" }, 403));
3877
4058
  return r;
@@ -3886,10 +4067,10 @@ function sshRoutes(opts = {}) {
3886
4067
  }
3887
4068
 
3888
4069
  // src/routes/usage.ts
3889
- import { Hono as Hono6 } from "hono";
4070
+ import { Hono as Hono7 } from "hono";
3890
4071
  var PULL_LIMIT = 1e3;
3891
4072
  function usageRoutes(opts = {}) {
3892
- const r = new Hono6();
4073
+ const r = new Hono7();
3893
4074
  r.get("/", async (c) => {
3894
4075
  let window;
3895
4076
  try {
@@ -3922,9 +4103,9 @@ function whole(value, name) {
3922
4103
  }
3923
4104
 
3924
4105
  // src/routes/volumes.ts
3925
- import { Hono as Hono7 } from "hono";
4106
+ import { Hono as Hono8 } from "hono";
3926
4107
  function volumeRoutes() {
3927
- const r = new Hono7();
4108
+ const r = new Hono8();
3928
4109
  r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
3929
4110
  r.post("/", async (c) => {
3930
4111
  const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
@@ -3950,7 +4131,7 @@ function volumeRoutes() {
3950
4131
 
3951
4132
  // src/app.ts
3952
4133
  function createApp(opts = {}) {
3953
- const app = new Hono8();
4134
+ const app = new Hono9();
3954
4135
  app.use(resolveCaller(opts));
3955
4136
  app.get("/health", async (c) => {
3956
4137
  const cfg = await loadConfig();
@@ -3971,6 +4152,7 @@ function createApp(opts = {}) {
3971
4152
  app.route("/snapshots", snapshotRoutes());
3972
4153
  app.route("/volumes", volumeRoutes());
3973
4154
  app.route("/capacity", capacityRoutes());
4155
+ app.route("/env", envRoutes());
3974
4156
  app.route("/ssh", sshRoutes(opts));
3975
4157
  app.route("/usage", usageRoutes(opts));
3976
4158
  app.notFound((c) => c.json({ error: `no route: ${c.req.method} ${c.req.path}` }, 404));
@@ -3999,13 +4181,13 @@ async function listen(opts = {}) {
3999
4181
  server.once("error", reject);
4000
4182
  server.listen(socketPath, () => resolve());
4001
4183
  });
4002
- await writeFile6(p.serverPid, `${process.pid}
4184
+ await writeFile7(p.serverPid, `${process.pid}
4003
4185
  `);
4004
4186
  let https;
4005
4187
  let httpsServer;
4006
4188
  const cp = cfg.controlPlane;
4007
4189
  if (cp) {
4008
- const [key, cert] = await Promise.all([readFile7(p.tlsKey), readFile7(p.tlsCert)]).catch((err) => {
4190
+ const [key, cert] = await Promise.all([readFile8(p.tlsKey), readFile8(p.tlsCert)]).catch((err) => {
4009
4191
  throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
4010
4192
  });
4011
4193
  httpsServer = createAdaptorServer({