@kvbox/server 0.5.27 → 0.5.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -61,6 +61,16 @@ function paths(home = kvboxHome()) {
61
61
  /** Symlink to the current base image, assets/rootfs-<version>.ext4; boxes keep using the version they were made from. */
62
62
  rootfs: join(home, "assets", "rootfs.ext4"),
63
63
  baseImage: (version) => join(home, "assets", `rootfs-${version}.ext4`),
64
+ /**
65
+ * Every other image (#87), one dir each so nothing collides with the base's `rootfs-*.ext4`:
66
+ * assets/images/<image>/rootfs-<version>.ext4, and rootfs.ext4 there the symlink to its current one.
67
+ */
68
+ images: join(home, "assets", "images"),
69
+ image: (image) => ({
70
+ dir: join(home, "assets", "images", image),
71
+ rootfs: join(home, "assets", "images", image, "rootfs.ext4"),
72
+ version: (version) => join(home, "assets", "images", image, `rootfs-${version}.ext4`)
73
+ }),
64
74
  machines: join(home, "machines"),
65
75
  snapshots: join(home, "snapshots"),
66
76
  /** Boxes and snapshots are filed by owner: machines/<owner>/<name>. The owner is part of a box's identity. */
@@ -71,6 +81,8 @@ function paths(home = kvboxHome()) {
71
81
  return {
72
82
  dir,
73
83
  meta: join(dir, "meta.json"),
84
+ /** The box's own environment variables (#87), merged over its owner's at boot. Mode 600: values in the clear. */
85
+ env: join(dir, "env.json"),
74
86
  /** The box's writable layer, stacked on the read-only base image inside the guest. */
75
87
  overlay: join(dir, "overlay.ext4"),
76
88
  /**
@@ -118,6 +130,8 @@ function paths(home = kvboxHome()) {
118
130
  meta: join(dir, "meta.json"),
119
131
  vmstate: join(dir, "vmstate"),
120
132
  mem: join(dir, "mem"),
133
+ /** The box's own environment variables when it was taken (#87); a restore starts with them. */
134
+ env: join(dir, "env.json"),
121
135
  /** Copy of the box's overlay at the moment of the snapshot; the base image is referenced by version in meta.json. */
122
136
  overlay: join(dir, "overlay.ext4")
123
137
  };
@@ -448,6 +462,9 @@ var PortsRequest = z3.object({
448
462
  ports: z3.array(z3.object({ guestPort: z3.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
449
463
  });
450
464
  var BoxPortSchema = z3.number().int().min(1).max(65535);
465
+ var MAX_BOX_LINKS = 32;
466
+ var BoxLinkSchema = z3.object({ from: z3.string(), port: BoxPortSchema });
467
+ var LinkRequest = z3.object({ from: z3.string().min(1), fromOwner: z3.string().optional(), port: BoxPortSchema });
451
468
  var ClaimSubdomainRequest = z3.object({ name: z3.string(), port: BoxPortSchema });
452
469
  var SubdomainPortRequest = z3.object({ port: BoxPortSchema });
453
470
  var SubdomainRouteRequest = z3.object({ name: z3.string(), port: BoxPortSchema });
@@ -488,7 +505,9 @@ var MachineSchema = z3.object({
488
505
  diskUsedBytes: z3.number().int(),
489
506
  // what that sparse file really occupies on the host
490
507
  base: z3.string(),
491
- // base image version the box's overlay stacks on
508
+ // version of the image the box's overlay stacks on
509
+ /** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
510
+ image: z3.string().optional(),
492
511
  createdAt: z3.string(),
493
512
  source: z3.string(),
494
513
  // "base", "snapshot:<owner/name>" or "fork:<owner/name>" (#79)
@@ -511,7 +530,14 @@ var MachineSchema = z3.object({
511
530
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
512
531
  autoHibernateSec: z3.number().int().positive().optional(),
513
532
  /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
514
- volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional()
533
+ volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional(),
534
+ /** Boxes that may reach this one, each on one port (#98). Absent: none. */
535
+ links: z3.array(BoxLinkSchema).optional(),
536
+ /**
537
+ * Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
538
+ * serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
539
+ */
540
+ connect: z3.string().optional()
515
541
  });
516
542
  var VolumeSchema = z3.object({
517
543
  /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
@@ -548,6 +574,16 @@ var EnvVarSchema = z3.object({
548
574
  secret: z3.boolean(),
549
575
  updatedAt: z3.string()
550
576
  });
577
+ var BoxEnvSchema = z3.object({
578
+ box: z3.string(),
579
+ vars: z3.array(EnvVarSchema)
580
+ });
581
+ var BoxEnvChangeSchema = z3.object({
582
+ box: z3.string(),
583
+ name: z3.string(),
584
+ /** Whether the box is running now: the change waits for its next start. */
585
+ running: z3.boolean()
586
+ });
551
587
  var SetEnvRequest = z3.object({
552
588
  value: z3.string(),
553
589
  secret: z3.boolean().optional()
@@ -576,7 +612,16 @@ var CreateMachineRequest = z3.object({
576
612
  */
577
613
  sshKeys: z3.array(z3.string()).optional(),
578
614
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
579
- autoHibernateSec: z3.number().int().min(0).optional()
615
+ autoHibernateSec: z3.number().int().min(0).optional(),
616
+ /**
617
+ * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
618
+ * control plane reads it; a host has one place to put a box.
619
+ */
620
+ near: z3.string().optional(),
621
+ /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
622
+ image: z3.string().optional(),
623
+ /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
624
+ env: z3.array(z3.object({ name: z3.string(), value: z3.string() })).optional()
580
625
  });
581
626
  var ForkMachineRequest = z3.object({
582
627
  name: z3.string().optional(),
@@ -611,7 +656,9 @@ var SnapshotSchema = z3.object({
611
656
  source: z3.string(),
612
657
  // the box it was taken from, as owner/name
613
658
  base: z3.string(),
614
- // base image version the overlay stacks on; a restore needs the same one
659
+ // version of the image the overlay stacks on; a restore needs the same one
660
+ /** As in MachineSchema: the image when it is not the base one (#87). */
661
+ image: z3.string().optional(),
615
662
  vcpu: z3.number().int(),
616
663
  memMib: z3.number().int(),
617
664
  sizeBytes: z3.number().int(),
@@ -620,7 +667,9 @@ var SnapshotSchema = z3.object({
620
667
  });
621
668
  var CreateSnapshotRequest = z3.object({
622
669
  box: z3.string(),
623
- name: z3.string()
670
+ name: z3.string(),
671
+ /** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
672
+ replace: z3.boolean().optional()
624
673
  });
625
674
  var DiskCapacitySchema = z3.object({
626
675
  totalGib: z3.number().int(),
@@ -636,7 +685,12 @@ var CapacitySchema = z3.object({
636
685
  reservedVcpu: z3.number().int(),
637
686
  running: z3.number().int(),
638
687
  /** Absent on a host from before volumes (#91): it cannot take one. */
639
- disk: DiskCapacitySchema.optional()
688
+ disk: DiskCapacitySchema.optional(),
689
+ /**
690
+ * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
691
+ * Absent on a host from before images: it has only the base.
692
+ */
693
+ images: z3.array(z3.object({ name: z3.string(), version: z3.string() })).optional()
640
694
  });
641
695
  var RecoveryReportSchema = z3.object({
642
696
  at: z3.string(),
@@ -1164,209 +1218,15 @@ async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
1164
1218
  );
1165
1219
  }
1166
1220
 
1167
- // src/core/machines.ts
1168
- import { spawn } from "node:child_process";
1169
- import { closeSync as closeSync2, existsSync as existsSync4, openSync as openSync2, statSync as statSync2 } from "node:fs";
1170
- import { link as link2, mkdir as mkdir6, readFile as readFile6, realpath, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1171
- import { basename } from "node:path";
1172
- import { setTimeout as sleep } from "node:timers/promises";
1173
-
1174
- // src/core/agent.ts
1175
- import { connect } from "node:net";
1176
- var AGENT_PORT = 52;
1177
- async function agentCall(udsPath, req, timeoutMs = 5e3) {
1178
- const reply = await new Promise((resolve, reject) => {
1179
- const sock = connect(udsPath);
1180
- let buf = "";
1181
- let handshaken = false;
1182
- const fail = (err) => {
1183
- sock.destroy();
1184
- reject(err);
1185
- };
1186
- 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`)));
1187
- sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
1188
- sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
1189
- `));
1190
- sock.on("data", (chunk) => {
1191
- buf += chunk.toString("utf8");
1192
- let nl;
1193
- while ((nl = buf.indexOf("\n")) !== -1) {
1194
- const line = buf.slice(0, nl);
1195
- buf = buf.slice(nl + 1);
1196
- if (!handshaken) {
1197
- if (!line.startsWith("OK ")) return fail(new KvboxError(`vsock connect refused: ${line}`));
1198
- handshaken = true;
1199
- sock.write(JSON.stringify(req) + "\n");
1200
- } else {
1201
- sock.end();
1202
- return resolve(line);
1203
- }
1204
- }
1205
- });
1206
- sock.once("close", () => {
1207
- if (!handshaken) fail(new KvboxError("vsock connection closed before the guest accepted"));
1208
- else fail(new KvboxError("kvbox-agent closed the connection without a reply"));
1209
- });
1210
- });
1211
- let parsed;
1212
- try {
1213
- parsed = JSON.parse(reply);
1214
- } catch {
1215
- throw new KvboxError(`kvbox-agent sent something that is not JSON: ${reply}`);
1216
- }
1217
- if (!parsed.ok) throw new KvboxError(`kvbox-agent: ${parsed.error}`);
1218
- return parsed;
1219
- }
1220
- function setIdentity(udsPath, id, timeoutMs) {
1221
- return agentCall(udsPath, { op: "identity", ...id }, timeoutMs);
1222
- }
1223
- function setAuthorizedKeys(udsPath, lines, timeoutMs) {
1224
- return agentCall(udsPath, { op: "authorizedKeys", lines: [...lines] }, timeoutMs);
1225
- }
1226
- async function stats(udsPath, timeoutMs) {
1227
- const reply = GuestStatsSchema.safeParse(await agentCall(udsPath, { op: "stats" }, timeoutMs));
1228
- if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? "invalid"}`);
1229
- return reply.data;
1230
- }
1231
- async function dropVolumes(udsPath, timeoutMs) {
1232
- const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
1233
- return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
1234
- }
1235
- function setEnv(udsPath, vars, timeoutMs) {
1236
- return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
1237
- }
1238
- var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
1239
- var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
1240
- 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 ?? "");
1221
+ // src/core/dns.ts
1222
+ import { createSocket } from "node:dgram";
1241
1223
 
1242
- // src/core/env.ts
1224
+ // src/core/state.ts
1225
+ import { randomBytes } from "node:crypto";
1226
+ import { readFileSync } from "node:fs";
1243
1227
  import { mkdir as mkdir2, readFile as readFile4, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
1244
1228
  import { z as z4 } from "zod";
1245
1229
 
1246
- // ../shared/src/env.ts
1247
- var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
1248
- var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
1249
- var ENV_MAX_VALUE_BYTES = 4096;
1250
- var ENV_MAX_VARS = 100;
1251
- function envNameProblem(name) {
1252
- if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
1253
- if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
1254
- if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
1255
- return null;
1256
- }
1257
- function envValueProblem(value) {
1258
- 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)";
1259
- if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
1260
- return null;
1261
- }
1262
-
1263
- // src/core/locks.ts
1264
- import { AsyncLocalStorage } from "node:async_hooks";
1265
- var tails = /* @__PURE__ */ new Map();
1266
- var held = new AsyncLocalStorage();
1267
- function withBoxLock(ref, fn) {
1268
- return withLock(refKey(ref), fn);
1269
- }
1270
- function withHostLock(name, fn) {
1271
- return withLock(`host:${name}`, fn);
1272
- }
1273
- async function withLock(key, fn) {
1274
- const mine = held.getStore();
1275
- if (mine?.has(key)) return fn();
1276
- const previous = tails.get(key);
1277
- let release;
1278
- const tail = new Promise((resolve) => release = resolve);
1279
- tails.set(key, tail);
1280
- try {
1281
- await previous;
1282
- return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
1283
- } finally {
1284
- release();
1285
- if (tails.get(key) === tail) tails.delete(key);
1286
- }
1287
- }
1288
- function boxBusy(ref) {
1289
- return tails.has(refKey(ref));
1290
- }
1291
- function locked(fn) {
1292
- return (...args) => withBoxLock(args[0], () => fn(...args));
1293
- }
1294
-
1295
- // src/core/env.ts
1296
- var OwnerEnvSchema = z4.object({
1297
- /** The control plane's counter for the list; only ever grows. */
1298
- version: z4.number().int().min(0),
1299
- vars: z4.array(z4.object({ name: z4.string(), value: z4.string() }))
1300
- });
1301
- async function readOwnerEnv(owner, p = paths()) {
1302
- try {
1303
- return OwnerEnvSchema.parse(JSON.parse(await readFile4(p.ownerEnv(owner), "utf8")));
1304
- } catch (err) {
1305
- if (err.code === "ENOENT") return null;
1306
- throw err;
1307
- }
1308
- }
1309
- async function envForBoot(owner, p = paths()) {
1310
- const env = await readOwnerEnv(owner, p).catch(() => null);
1311
- if (env !== null) return env.vars;
1312
- return realmOf(owner) !== null ? [] : null;
1313
- }
1314
- async function setOwnerEnv(owner, req, p = paths()) {
1315
- if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
1316
- if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
1317
- const seen = /* @__PURE__ */ new Set();
1318
- for (const v of req.vars) {
1319
- const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
1320
- if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
1321
- if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);
1322
- seen.add(v.name);
1323
- }
1324
- return withHostLock("env", async () => {
1325
- const have = await readOwnerEnv(owner, p);
1326
- if (have !== null && have.version > req.version) return { version: have.version };
1327
- const file = p.ownerEnv(owner);
1328
- await mkdir2(p.env, { recursive: true, mode: 448 });
1329
- const tmp = `${file}.tmp`;
1330
- await writeFile2(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
1331
- await rename2(tmp, file);
1332
- return { version: req.version };
1333
- });
1334
- }
1335
- async function listEnvVersions(scope, p = paths()) {
1336
- let files;
1337
- try {
1338
- files = await readdir(p.env);
1339
- } catch (err) {
1340
- if (err.code === "ENOENT") return [];
1341
- throw err;
1342
- }
1343
- const out = [];
1344
- for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
1345
- const owner = file.slice(0, -".json".length);
1346
- if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;
1347
- const env = await readOwnerEnv(owner, p).catch(() => null);
1348
- if (env !== null) out.push({ owner, version: env.version });
1349
- }
1350
- return out;
1351
- }
1352
-
1353
- // src/core/volumes.ts
1354
- import { existsSync, statSync } from "node:fs";
1355
- import { lstat, mkdir as mkdir4, readdir as readdir3, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
1356
-
1357
- // ../shared/src/capacity.ts
1358
- var MEM_HEADROOM_MIB = 2048;
1359
- function sellableGib(d) {
1360
- return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);
1361
- }
1362
- function volumeRoomGib(d) {
1363
- return Math.max(0, sellableGib(d) - d.volumesGib);
1364
- }
1365
- function hasDiskRoom(d, sizeGib) {
1366
- return sizeGib <= volumeRoomGib(d);
1367
- }
1368
- var VCPU_OVERSUBSCRIPTION = 2;
1369
-
1370
1230
  // src/core/db.ts
1371
1231
  import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs";
1372
1232
  import { dirname } from "node:path";
@@ -1502,75 +1362,81 @@ function volumeEventsInScope(scope, window, p = paths()) {
1502
1362
  }
1503
1363
 
1504
1364
  // src/core/state.ts
1505
- import { randomBytes } from "node:crypto";
1506
- import { readFileSync } from "node:fs";
1507
- import { mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1508
- import { z as z5 } from "zod";
1509
- var MachineMetaSchema = z5.object({
1365
+ var MachineMetaSchema = z4.object({
1510
1366
  /** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */
1511
- id: z5.string(),
1512
- name: z5.string(),
1367
+ id: z4.string(),
1368
+ name: z4.string(),
1513
1369
  /** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */
1514
- owner: z5.string(),
1515
- ip: z5.string(),
1516
- mac: z5.string(),
1517
- pid: z5.number().int().nullable(),
1370
+ owner: z4.string(),
1371
+ ip: z4.string(),
1372
+ mac: z4.string(),
1373
+ pid: z4.number().int().nullable(),
1518
1374
  // null: stopped on purpose, disk kept
1519
1375
  /**
1520
1376
  * The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot
1521
1377
  * the number can name some other process; a pid from another boot is dead whatever `kill -0` says.
1522
1378
  * Absent (boxes launched before #29): the pid alone decides.
1523
1379
  */
1524
- bootId: z5.string().optional(),
1525
- vcpu: z5.number().int(),
1526
- memMib: z5.number().int(),
1527
- createdAt: z5.string(),
1528
- source: z5.string(),
1529
- /** Base image version (assets/rootfs-<version>.ext4) the box's overlay stacks on. */
1530
- base: z5.string(),
1380
+ bootId: z4.string().optional(),
1381
+ vcpu: z4.number().int(),
1382
+ memMib: z4.number().int(),
1383
+ createdAt: z4.string(),
1384
+ source: z4.string(),
1385
+ /** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */
1386
+ base: z4.string(),
1387
+ /** The image (#87), when not the base one: assets/images/<image>/rootfs-<base>.ext4. `vm update` keeps it. */
1388
+ image: z4.string().optional(),
1531
1389
  /**
1532
1390
  * Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
1533
1391
  * each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
1534
1392
  * is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.
1535
1393
  */
1536
- memSnapshots: z5.number().int().optional(),
1394
+ memSnapshots: z4.number().int().optional(),
1537
1395
  /** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */
1538
- paused: z5.boolean().optional(),
1396
+ paused: z4.boolean().optional(),
1539
1397
  /**
1540
1398
  * authorized_keys lines the box gets on top of the host's own key, as the control plane sent them
1541
1399
  * at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so
1542
1400
  * `start` has to send the same lines again. Absent: host key only.
1543
1401
  */
1544
- sshKeys: z5.array(z5.string()).optional(),
1402
+ sshKeys: z4.array(z4.string()).optional(),
1545
1403
  /**
1546
1404
  * The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,
1547
1405
  * or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.
1548
1406
  */
1549
- sshKeysStale: z5.boolean().optional(),
1407
+ sshKeysStale: z4.boolean().optional(),
1550
1408
  /** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */
1551
- sshPort: z5.number().int().optional(),
1409
+ sshPort: z4.number().int().optional(),
1552
1410
  /**
1553
1411
  * Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,
1554
1412
  * each host port the box's for its life. DNATed while the box runs, rebuilt from here with its
1555
1413
  * current IP every time it comes up. Absent: none.
1556
1414
  */
1557
- ports: z5.array(z5.object({ guestPort: z5.number().int(), hostPort: z5.number().int(), proto: z5.enum(["tcp", "udp"]) })).optional(),
1415
+ ports: z4.array(z4.object({ guestPort: z4.number().int(), hostPort: z4.number().int(), proto: z4.enum(["tcp", "udp"]) })).optional(),
1558
1416
  /** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
1559
- autoHibernateSec: z5.number().int().positive().optional(),
1417
+ autoHibernateSec: z4.number().int().positive().optional(),
1560
1418
  /**
1561
1419
  * Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
1562
1420
  * their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
1563
1421
  * volume's meta.json does not say. Absent: none.
1564
1422
  */
1565
- volumes: z5.array(z5.string()).optional()
1423
+ volumes: z4.array(z4.string()).optional(),
1424
+ /**
1425
+ * Links into this box (#98, `kvbox vm link`): box `owner/name`, at `ip`, may open TCP connections to
1426
+ * `port`. The rule is open while this box runs, rebuilt from here at every boot; `ip` is the other
1427
+ * box's, fixed for its life, and checked against its meta.json before a rule opens. `stale`: that box
1428
+ * was removed but the rule would not close; kept only so this box's next stop closes it, never opened
1429
+ * again, never listed (a new box of the same name may get the same IP). Absent: none.
1430
+ */
1431
+ links: z4.array(z4.object({ owner: z4.string(), name: z4.string(), ip: z4.string(), port: z4.number().int(), stale: z4.literal(true).optional() })).optional()
1566
1432
  });
1567
- var VolumeMetaSchema = z5.object({
1433
+ var VolumeMetaSchema = z4.object({
1568
1434
  /** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
1569
- id: z5.string(),
1570
- name: z5.string(),
1571
- owner: z5.string(),
1572
- sizeGib: z5.number().int(),
1573
- createdAt: z5.string()
1435
+ id: z4.string(),
1436
+ name: z4.string(),
1437
+ owner: z4.string(),
1438
+ sizeGib: z4.number().int(),
1439
+ createdAt: z4.string()
1574
1440
  });
1575
1441
  function newBoxId(taken) {
1576
1442
  for (; ; ) {
@@ -1578,130 +1444,655 @@ function newBoxId(taken) {
1578
1444
  if (!taken.has(id)) return id;
1579
1445
  }
1580
1446
  }
1581
- var SnapshotMetaSchema = z5.object({
1582
- name: z5.string(),
1583
- owner: z5.string(),
1584
- /** The box it was taken from, as owner/name. */
1585
- source: z5.string(),
1586
- base: z5.string(),
1587
- vcpu: z5.number().int(),
1588
- memMib: z5.number().int(),
1589
- sizeBytes: z5.number().int(),
1590
- createdAt: z5.string(),
1591
- /**
1592
- * The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
1593
- * and their mounts in the memory image, but their data is not here. A box restored from the snapshot
1594
- * gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
1595
- */
1596
- volumes: z5.array(z5.object({ name: z5.string(), sizeGib: z5.number().int() })).optional()
1447
+ var SnapshotMetaSchema = z4.object({
1448
+ name: z4.string(),
1449
+ owner: z4.string(),
1450
+ /** The box it was taken from, as owner/name. */
1451
+ source: z4.string(),
1452
+ base: z4.string(),
1453
+ /** As in a box's meta.json (#87). */
1454
+ image: z4.string().optional(),
1455
+ vcpu: z4.number().int(),
1456
+ memMib: z4.number().int(),
1457
+ sizeBytes: z4.number().int(),
1458
+ createdAt: z4.string(),
1459
+ /**
1460
+ * The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
1461
+ * and their mounts in the memory image, but their data is not here. A box restored from the snapshot
1462
+ * gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
1463
+ */
1464
+ volumes: z4.array(z4.object({ name: z4.string(), sizeGib: z4.number().int() })).optional()
1465
+ });
1466
+ async function ensureLayout(p = paths()) {
1467
+ for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
1468
+ await mkdir2(dir, { recursive: true, mode: 448 });
1469
+ }
1470
+ return p;
1471
+ }
1472
+ async function readJson(file, schema) {
1473
+ return schema.parse(JSON.parse(await readFile4(file, "utf8")));
1474
+ }
1475
+ async function listDirs(dir) {
1476
+ try {
1477
+ const entries = await readdir(dir, { withFileTypes: true });
1478
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name);
1479
+ } catch (err) {
1480
+ if (err.code === "ENOENT") return [];
1481
+ throw err;
1482
+ }
1483
+ }
1484
+ async function readMachineMeta(ref, p = paths()) {
1485
+ return readJson(p.machine(ref.owner, ref.name).meta, MachineMetaSchema);
1486
+ }
1487
+ var boxListVersion = 0;
1488
+ var boxListVersionNow = () => boxListVersion;
1489
+ var boxListChanged = () => void (boxListVersion += 1);
1490
+ async function writeMachineMeta(meta, p = paths()) {
1491
+ const m = p.machine(meta.owner, meta.name);
1492
+ await mkdir2(m.dir, { recursive: true });
1493
+ const tmp = `${m.meta}.tmp`;
1494
+ await writeFile2(tmp, JSON.stringify(meta, null, 2) + "\n");
1495
+ await rename2(tmp, m.meta);
1496
+ boxListChanged();
1497
+ }
1498
+ async function listMachineRefs(p = paths()) {
1499
+ return listRefs(p.machines);
1500
+ }
1501
+ async function readSnapshotMeta(ref, p = paths()) {
1502
+ return readJson(p.snapshot(ref.owner, ref.name).meta, SnapshotMetaSchema);
1503
+ }
1504
+ async function writeSnapshotMeta(meta, p = paths(), s = p.snapshot(meta.owner, meta.name)) {
1505
+ await mkdir2(s.dir, { recursive: true });
1506
+ await writeFile2(s.meta, JSON.stringify(meta, null, 2) + "\n");
1507
+ }
1508
+ async function listSnapshotRefs(p = paths()) {
1509
+ return (await listRefs(p.snapshots)).filter((ref) => !ref.name.startsWith("."));
1510
+ }
1511
+ async function readVolumeMeta(ref, p = paths()) {
1512
+ const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z4.string().optional() }));
1513
+ if (raw.id !== void 0) return { ...raw, id: raw.id };
1514
+ const taken = /* @__PURE__ */ new Set();
1515
+ for (const other of await listVolumeRefs(p)) {
1516
+ try {
1517
+ const j = JSON.parse(await readFile4(p.volume(other.owner, other.name).meta, "utf8"));
1518
+ if (typeof j.id === "string") taken.add(j.id);
1519
+ } catch {
1520
+ }
1521
+ }
1522
+ const meta = { ...raw, id: newBoxId(taken) };
1523
+ await writeVolumeMeta(meta, p);
1524
+ insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: meta.createdAt, sizeGib: meta.sizeGib, by: "create" }, p);
1525
+ return meta;
1526
+ }
1527
+ async function writeVolumeMeta(meta, p = paths()) {
1528
+ const v = p.volume(meta.owner, meta.name);
1529
+ await mkdir2(v.dir, { recursive: true, mode: 448 });
1530
+ await writeFile2(v.meta, JSON.stringify(meta, null, 2) + "\n");
1531
+ }
1532
+ async function listVolumeRefs(p = paths()) {
1533
+ return listRefs(p.volumes);
1534
+ }
1535
+ async function listRefs(root) {
1536
+ const out = [];
1537
+ for (const owner of await listDirs(root)) {
1538
+ for (const name of await listDirs(`${root}/${owner}`)) {
1539
+ out.push({ owner, name });
1540
+ }
1541
+ }
1542
+ return out;
1543
+ }
1544
+ function pidAlive(pid) {
1545
+ if (pid === null || pid <= 0) return false;
1546
+ try {
1547
+ process.kill(pid, 0);
1548
+ return true;
1549
+ } catch (err) {
1550
+ return err.code === "EPERM";
1551
+ }
1552
+ }
1553
+ var bootId;
1554
+ function currentBootId() {
1555
+ if (bootId === void 0) {
1556
+ try {
1557
+ bootId = { id: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() };
1558
+ } catch {
1559
+ bootId = { id: void 0 };
1560
+ }
1561
+ }
1562
+ return bootId.id;
1563
+ }
1564
+ function vmAlive(meta) {
1565
+ if (meta.bootId !== void 0 && meta.bootId !== currentBootId()) return false;
1566
+ return pidAlive(meta.pid);
1567
+ }
1568
+ function hostBootTime() {
1569
+ try {
1570
+ const m = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
1571
+ return m ? new Date(Number(m[1]) * 1e3) : null;
1572
+ } catch {
1573
+ return null;
1574
+ }
1575
+ }
1576
+
1577
+ // src/core/dns.ts
1578
+ var DNS_PORT = 10053;
1579
+ var DNS_SUFFIX = ".kvbox";
1580
+ var DNS_RETRY_MS = 1e4;
1581
+ var TTL_SEC = 5;
1582
+ var BOXES_FRESH_MS = 6e4;
1583
+ var TYPE_A = 1;
1584
+ var CLASS_IN = 1;
1585
+ var RCODE = { ok: 0, nxDomain: 3, refused: 5 };
1586
+ function parseQuery(msg) {
1587
+ if (msg.length < 12) return null;
1588
+ const flags = msg.readUInt16BE(2);
1589
+ const isResponse = flags & 32768;
1590
+ const opcode = flags >> 11 & 15;
1591
+ if (isResponse || opcode !== 0 || msg.readUInt16BE(4) < 1) return null;
1592
+ const labels = [];
1593
+ let at = 12;
1594
+ for (; ; ) {
1595
+ if (at >= msg.length) return null;
1596
+ const len = msg[at];
1597
+ at += 1;
1598
+ if (len === 0) break;
1599
+ if (len > 63 || at + len > msg.length) return null;
1600
+ labels.push(msg.subarray(at, at + len).toString("latin1"));
1601
+ at += len;
1602
+ }
1603
+ if (at + 4 > msg.length) return null;
1604
+ return {
1605
+ id: msg.readUInt16BE(0),
1606
+ rd: Boolean(flags & 256),
1607
+ name: labels.join(".").toLowerCase(),
1608
+ type: msg.readUInt16BE(at),
1609
+ class: msg.readUInt16BE(at + 2),
1610
+ question: msg.subarray(12, at + 4)
1611
+ };
1612
+ }
1613
+ function buildAnswer(q, rcode, ip) {
1614
+ const header = Buffer.alloc(12);
1615
+ header.writeUInt16BE(q.id, 0);
1616
+ header.writeUInt16BE(32768 | 1024 | (q.rd ? 256 : 0) | rcode, 2);
1617
+ header.writeUInt16BE(1, 4);
1618
+ header.writeUInt16BE(ip ? 1 : 0, 6);
1619
+ if (!ip) return Buffer.concat([header, q.question]);
1620
+ const rr = Buffer.alloc(16);
1621
+ rr.writeUInt16BE(49164, 0);
1622
+ rr.writeUInt16BE(TYPE_A, 2);
1623
+ rr.writeUInt16BE(CLASS_IN, 4);
1624
+ rr.writeUInt32BE(TTL_SEC, 6);
1625
+ rr.writeUInt16BE(4, 10);
1626
+ ip.split(".").forEach((o, i) => rr.writeUInt8(Number(o), 12 + i));
1627
+ return Buffer.concat([header, q.question, rr]);
1628
+ }
1629
+ var slugOf = (owner) => owner.split("@")[0].toLowerCase();
1630
+ var isOurs = (q) => q.class === CLASS_IN && q.name.endsWith(DNS_SUFFIX);
1631
+ function answerFor(q, asker, boxes) {
1632
+ if (!isOurs(q)) return { rcode: RCODE.refused };
1633
+ const [name, slug, ...rest] = q.name.slice(0, -DNS_SUFFIX.length).split(".");
1634
+ const from = boxes.find((b) => b.ip === asker);
1635
+ let box;
1636
+ if (from && rest.length === 0) {
1637
+ box = slug === void 0 || slug === slugOf(from.owner) ? boxes.find((b) => b.owner === from.owner && b.name === name) : boxes.find((b) => slugOf(b.owner) === slug && b.name === name && b.linkedFrom?.includes(asker));
1638
+ }
1639
+ if (!box) return { rcode: RCODE.nxDomain };
1640
+ return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };
1641
+ }
1642
+ async function boxAddresses(p) {
1643
+ const out = [];
1644
+ for (const ref of await listMachineRefs(p)) {
1645
+ const meta = await readMachineMeta(ref, p).catch(() => null);
1646
+ if (meta) out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {} });
1647
+ }
1648
+ return out;
1649
+ }
1650
+ function sharedBoxes(load, freshMs = BOXES_FRESH_MS, version = boxListVersionNow) {
1651
+ let last = null;
1652
+ return () => {
1653
+ if (!last || last.version !== version() || Date.now() - last.at > freshMs) {
1654
+ const entry = { at: Date.now(), version: version(), list: load() };
1655
+ last = entry;
1656
+ entry.list.catch(() => {
1657
+ if (last === entry) last = null;
1658
+ });
1659
+ }
1660
+ return last.list;
1661
+ };
1662
+ }
1663
+ async function startDns(opts) {
1664
+ const p = opts.p ?? paths();
1665
+ const boxes = sharedBoxes(opts.boxes ?? (() => boxAddresses(p)));
1666
+ const socket = createSocket("udp4");
1667
+ socket.on("message", (msg, rinfo) => {
1668
+ const q = parseQuery(msg);
1669
+ if (!q) return;
1670
+ const reply = (a) => socket.send(buildAnswer(q, a.rcode, a.ip), rinfo.port, rinfo.address);
1671
+ if (!isOurs(q)) return reply({ rcode: RCODE.refused });
1672
+ void boxes().then((list) => answerFor(q, rinfo.address, list)).catch(() => ({ rcode: RCODE.refused })).then(reply);
1673
+ });
1674
+ await new Promise((resolve, reject) => {
1675
+ socket.once("error", (err) => {
1676
+ socket.close();
1677
+ reject(err);
1678
+ });
1679
+ socket.bind(opts.port ?? DNS_PORT, opts.host, () => {
1680
+ socket.removeAllListeners("error");
1681
+ socket.on("error", () => {
1682
+ });
1683
+ resolve();
1684
+ });
1685
+ });
1686
+ return { socket, close: () => new Promise((resolve) => socket.close(() => resolve())) };
1687
+ }
1688
+
1689
+ // src/core/machines.ts
1690
+ import { spawn } from "node:child_process";
1691
+ import { closeSync as closeSync2, existsSync as existsSync6, openSync as openSync2, statSync as statSync2 } from "node:fs";
1692
+ import { link as link2, mkdir as mkdir6, readFile as readFile6, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1693
+ import { setTimeout as sleep } from "node:timers/promises";
1694
+
1695
+ // src/core/agent.ts
1696
+ import { connect } from "node:net";
1697
+ var AGENT_PORT = 52;
1698
+ async function agentCall(udsPath, req, timeoutMs = 5e3) {
1699
+ const reply = await new Promise((resolve, reject) => {
1700
+ const sock = connect(udsPath);
1701
+ let buf = "";
1702
+ let handshaken = false;
1703
+ const fail = (err) => {
1704
+ sock.destroy();
1705
+ reject(err);
1706
+ };
1707
+ 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`)));
1708
+ sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
1709
+ sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
1710
+ `));
1711
+ sock.on("data", (chunk) => {
1712
+ buf += chunk.toString("utf8");
1713
+ let nl;
1714
+ while ((nl = buf.indexOf("\n")) !== -1) {
1715
+ const line = buf.slice(0, nl);
1716
+ buf = buf.slice(nl + 1);
1717
+ if (!handshaken) {
1718
+ if (!line.startsWith("OK ")) return fail(new KvboxError(`vsock connect refused: ${line}`));
1719
+ handshaken = true;
1720
+ sock.write(JSON.stringify(req) + "\n");
1721
+ } else {
1722
+ sock.end();
1723
+ return resolve(line);
1724
+ }
1725
+ }
1726
+ });
1727
+ sock.once("close", () => {
1728
+ if (!handshaken) fail(new KvboxError("vsock connection closed before the guest accepted"));
1729
+ else fail(new KvboxError("kvbox-agent closed the connection without a reply"));
1730
+ });
1731
+ });
1732
+ let parsed;
1733
+ try {
1734
+ parsed = JSON.parse(reply);
1735
+ } catch {
1736
+ throw new KvboxError(`kvbox-agent sent something that is not JSON: ${reply}`);
1737
+ }
1738
+ if (!parsed.ok) throw new KvboxError(`kvbox-agent: ${parsed.error}`);
1739
+ return parsed;
1740
+ }
1741
+ function setIdentity(udsPath, id, timeoutMs) {
1742
+ return agentCall(udsPath, { op: "identity", ...id }, timeoutMs);
1743
+ }
1744
+ function setAuthorizedKeys(udsPath, lines, timeoutMs) {
1745
+ return agentCall(udsPath, { op: "authorizedKeys", lines: [...lines] }, timeoutMs);
1746
+ }
1747
+ async function stats(udsPath, timeoutMs) {
1748
+ const reply = GuestStatsSchema.safeParse(await agentCall(udsPath, { op: "stats" }, timeoutMs));
1749
+ if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? "invalid"}`);
1750
+ return reply.data;
1751
+ }
1752
+ async function dropVolumes(udsPath, timeoutMs) {
1753
+ const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
1754
+ return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
1755
+ }
1756
+ function setEnv(udsPath, vars, timeoutMs) {
1757
+ return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
1758
+ }
1759
+ var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
1760
+ var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
1761
+ var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
1762
+
1763
+ // src/core/env.ts
1764
+ import { existsSync } from "node:fs";
1765
+ import { copyFile, mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1766
+ import { z as z5 } from "zod";
1767
+
1768
+ // ../shared/src/env.ts
1769
+ var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
1770
+ var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
1771
+ var ENV_MAX_VALUE_BYTES = 4096;
1772
+ var ENV_MAX_VARS = 100;
1773
+ function envNameProblem(name) {
1774
+ if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
1775
+ if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
1776
+ if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
1777
+ return null;
1778
+ }
1779
+ function envValueProblem(value) {
1780
+ 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)";
1781
+ if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
1782
+ return null;
1783
+ }
1784
+
1785
+ // src/core/locks.ts
1786
+ import { AsyncLocalStorage } from "node:async_hooks";
1787
+ var tails = /* @__PURE__ */ new Map();
1788
+ var held = new AsyncLocalStorage();
1789
+ function withBoxLock(ref, fn) {
1790
+ return withLock(refKey(ref), fn);
1791
+ }
1792
+ function withSnapshotLock(ref, fn) {
1793
+ return withLock(`snapshot:${refKey(ref)}`, fn);
1794
+ }
1795
+ function withHostLock(name, fn) {
1796
+ return withLock(`host:${name}`, fn);
1797
+ }
1798
+ async function withLock(key, fn) {
1799
+ const mine = held.getStore();
1800
+ if (mine?.has(key)) return fn();
1801
+ const previous = tails.get(key);
1802
+ let release;
1803
+ const tail = new Promise((resolve) => release = resolve);
1804
+ tails.set(key, tail);
1805
+ try {
1806
+ await previous;
1807
+ return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
1808
+ } finally {
1809
+ release();
1810
+ if (tails.get(key) === tail) tails.delete(key);
1811
+ }
1812
+ }
1813
+ function boxBusy(ref) {
1814
+ return tails.has(refKey(ref));
1815
+ }
1816
+ function locked(fn) {
1817
+ return (...args) => withBoxLock(args[0], () => fn(...args));
1818
+ }
1819
+
1820
+ // src/core/env.ts
1821
+ var OwnerEnvSchema = z5.object({
1822
+ /** The control plane's counter for the list; only ever grows. */
1823
+ version: z5.number().int().min(0),
1824
+ vars: z5.array(z5.object({ name: z5.string(), value: z5.string() }))
1597
1825
  });
1598
- async function ensureLayout(p = paths()) {
1599
- for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
1600
- await mkdir3(dir, { recursive: true, mode: 448 });
1826
+ async function readOwnerEnv(owner, p = paths()) {
1827
+ try {
1828
+ return OwnerEnvSchema.parse(JSON.parse(await readFile5(p.ownerEnv(owner), "utf8")));
1829
+ } catch (err) {
1830
+ if (err.code === "ENOENT") return null;
1831
+ throw err;
1601
1832
  }
1602
- return p;
1603
1833
  }
1604
- async function readJson(file, schema) {
1605
- return schema.parse(JSON.parse(await readFile5(file, "utf8")));
1834
+ async function envForBoot(box, p = paths()) {
1835
+ const env = await readOwnerEnv(box.owner, p).catch(() => null);
1836
+ const own = await readBoxEnv(box, p).catch((err) => {
1837
+ console.error(`warning: box ${shown(box)}: its own variables are unreadable, it boots without them: ${err.message}`);
1838
+ return [];
1839
+ });
1840
+ const slug = env?.vars ?? (realmOf(box.owner) !== null ? [] : null);
1841
+ if (own.length === 0) return slug ?? (existsSync(p.machine(box.owner, box.name).env) ? [] : null);
1842
+ const mine = new Set(own.map((v) => v.name));
1843
+ return [...(slug ?? []).filter((v) => !mine.has(v.name)), ...own.map((v) => ({ name: v.name, value: v.value }))];
1606
1844
  }
1607
- async function listDirs(dir) {
1845
+ var BoxEnvFileSchema = z5.object({
1846
+ vars: z5.array(z5.object({ name: z5.string(), value: z5.string(), secret: z5.boolean(), updatedAt: z5.string() }))
1847
+ });
1848
+ async function readBoxEnv(box, p = paths()) {
1608
1849
  try {
1609
- const entries = await readdir2(dir, { withFileTypes: true });
1610
- return entries.filter((e) => e.isDirectory()).map((e) => e.name);
1850
+ return BoxEnvFileSchema.parse(JSON.parse(await readFile5(p.machine(box.owner, box.name).env, "utf8"))).vars;
1611
1851
  } catch (err) {
1612
1852
  if (err.code === "ENOENT") return [];
1613
1853
  throw err;
1614
1854
  }
1615
1855
  }
1616
- async function readMachineMeta(ref, p = paths()) {
1617
- return readJson(p.machine(ref.owner, ref.name).meta, MachineMetaSchema);
1856
+ async function writeBoxEnv(box, vars, p = paths()) {
1857
+ if (vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
1858
+ const seen = /* @__PURE__ */ new Set();
1859
+ for (const v of vars) {
1860
+ const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
1861
+ if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
1862
+ if (seen.has(v.name)) throw new KvboxError(`${v.name} is given twice`);
1863
+ seen.add(v.name);
1864
+ }
1865
+ const file = p.machine(box.owner, box.name).env;
1866
+ const tmp = `${file}.tmp`;
1867
+ await writeFile3(tmp, JSON.stringify({ vars }, null, 2) + "\n", { mode: 384 });
1868
+ await rename3(tmp, file);
1618
1869
  }
1619
- async function writeMachineMeta(meta, p = paths()) {
1620
- const m = p.machine(meta.owner, meta.name);
1621
- await mkdir3(m.dir, { recursive: true });
1622
- const tmp = `${m.meta}.tmp`;
1623
- await writeFile3(tmp, JSON.stringify(meta, null, 2) + "\n");
1624
- await rename3(tmp, m.meta);
1870
+ async function mergeBoxEnv(box, given, p = paths()) {
1871
+ const names = new Set(given.map((v) => v.name));
1872
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1873
+ const kept = (await readBoxEnv(box, p)).filter((v) => !names.has(v.name));
1874
+ await writeBoxEnv(box, [...kept, ...given.map((v) => ({ ...v, secret: false, updatedAt: now }))], p);
1625
1875
  }
1626
- async function listMachineRefs(p = paths()) {
1627
- return listRefs(p.machines);
1876
+ async function copyBoxEnv(from, to) {
1877
+ if (!existsSync(from)) return;
1878
+ await copyFile(from, to);
1628
1879
  }
1629
- async function readSnapshotMeta(ref, p = paths()) {
1630
- return readJson(p.snapshot(ref.owner, ref.name).meta, SnapshotMetaSchema);
1880
+ function shownBoxEnv(vars) {
1881
+ return vars.map((v) => ({ name: v.name, ...v.secret ? {} : { value: v.value }, secret: v.secret, updatedAt: v.updatedAt }));
1631
1882
  }
1632
- async function writeSnapshotMeta(meta, p = paths()) {
1633
- const s = p.snapshot(meta.owner, meta.name);
1634
- await mkdir3(s.dir, { recursive: true });
1635
- await writeFile3(s.meta, JSON.stringify(meta, null, 2) + "\n");
1883
+ async function setBoxVar(box, name, value, secret, p = paths()) {
1884
+ await withBoxLock(box, async () => {
1885
+ if (!existsSync(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);
1886
+ const vars = (await readBoxEnv(box, p)).filter((v) => v.name !== name);
1887
+ await writeBoxEnv(box, [...vars, { name, value, secret, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }], p);
1888
+ });
1636
1889
  }
1637
- async function listSnapshotRefs(p = paths()) {
1638
- return listRefs(p.snapshots);
1890
+ async function rmBoxVar(box, name, p = paths()) {
1891
+ await withBoxLock(box, async () => {
1892
+ if (!existsSync(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);
1893
+ const vars = await readBoxEnv(box, p);
1894
+ if (!vars.some((v) => v.name === name)) throw new NotFoundError(`variable ${name} on box ${shown(box)}`);
1895
+ await writeBoxEnv(box, vars.filter((v) => v.name !== name), p);
1896
+ });
1639
1897
  }
1640
- async function readVolumeMeta(ref, p = paths()) {
1641
- const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z5.string().optional() }));
1642
- if (raw.id !== void 0) return { ...raw, id: raw.id };
1643
- const taken = /* @__PURE__ */ new Set();
1644
- for (const other of await listVolumeRefs(p)) {
1645
- try {
1646
- const j = JSON.parse(await readFile5(p.volume(other.owner, other.name).meta, "utf8"));
1647
- if (typeof j.id === "string") taken.add(j.id);
1648
- } catch {
1649
- }
1898
+ async function setOwnerEnv(owner, req, p = paths()) {
1899
+ if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
1900
+ if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
1901
+ const seen = /* @__PURE__ */ new Set();
1902
+ for (const v of req.vars) {
1903
+ const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
1904
+ if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
1905
+ if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);
1906
+ seen.add(v.name);
1650
1907
  }
1651
- const meta = { ...raw, id: newBoxId(taken) };
1652
- await writeVolumeMeta(meta, p);
1653
- insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: meta.createdAt, sizeGib: meta.sizeGib, by: "create" }, p);
1654
- return meta;
1655
- }
1656
- async function writeVolumeMeta(meta, p = paths()) {
1657
- const v = p.volume(meta.owner, meta.name);
1658
- await mkdir3(v.dir, { recursive: true, mode: 448 });
1659
- await writeFile3(v.meta, JSON.stringify(meta, null, 2) + "\n");
1660
- }
1661
- async function listVolumeRefs(p = paths()) {
1662
- return listRefs(p.volumes);
1908
+ return withHostLock("env", async () => {
1909
+ const have = await readOwnerEnv(owner, p);
1910
+ if (have !== null && have.version > req.version) return { version: have.version };
1911
+ const file = p.ownerEnv(owner);
1912
+ await mkdir3(p.env, { recursive: true, mode: 448 });
1913
+ const tmp = `${file}.tmp`;
1914
+ await writeFile3(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
1915
+ await rename3(tmp, file);
1916
+ return { version: req.version };
1917
+ });
1663
1918
  }
1664
- async function listRefs(root) {
1919
+ async function listEnvVersions(scope, p = paths()) {
1920
+ let files;
1921
+ try {
1922
+ files = await readdir2(p.env);
1923
+ } catch (err) {
1924
+ if (err.code === "ENOENT") return [];
1925
+ throw err;
1926
+ }
1665
1927
  const out = [];
1666
- for (const owner of await listDirs(root)) {
1667
- for (const name of await listDirs(`${root}/${owner}`)) {
1668
- out.push({ owner, name });
1669
- }
1928
+ for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
1929
+ const owner = file.slice(0, -".json".length);
1930
+ if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;
1931
+ const env = await readOwnerEnv(owner, p).catch(() => null);
1932
+ if (env !== null) out.push({ owner, version: env.version });
1670
1933
  }
1671
1934
  return out;
1672
1935
  }
1673
- function pidAlive(pid) {
1674
- if (pid === null || pid <= 0) return false;
1936
+
1937
+ // src/core/images.ts
1938
+ import { randomBytes as randomBytes2 } from "node:crypto";
1939
+ import { existsSync as existsSync2 } from "node:fs";
1940
+ import { readdir as readdir3, realpath } from "node:fs/promises";
1941
+ import { basename } from "node:path";
1942
+ import { z as z6 } from "zod";
1943
+ var BASE_IMAGE = "base";
1944
+ var IMAGE_RE = /^[a-z][a-z0-9-]{0,30}$/;
1945
+ function baseVersionOf(file) {
1946
+ const m = /^rootfs-(.+)\.ext4$/.exec(basename(file));
1947
+ if (!m) throw new KvboxError(`base image ${file} is not versioned (expected assets/rootfs-<version>.ext4); run install-server.sh`);
1948
+ return m[1];
1949
+ }
1950
+ function imageKey(image) {
1951
+ return image === void 0 || image === BASE_IMAGE ? void 0 : image;
1952
+ }
1953
+ var imageLabel = (image) => imageKey(image) === void 0 ? "base image" : `image ${image}`;
1954
+ function imageFile(image, version, p) {
1955
+ const key = imageKey(image);
1956
+ return key === void 0 ? p.baseImage(version) : p.image(key).version(version);
1957
+ }
1958
+ function imageFileFor(meta, p) {
1959
+ const file = imageFile(meta.image, meta.base, p);
1960
+ if (!existsSync2(file)) throw new KvboxError(`box ${meta.name} runs on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);
1961
+ return file;
1962
+ }
1963
+ async function currentImage(image, cfg, p) {
1964
+ const key = imageKey(image);
1965
+ if (key !== void 0 && !IMAGE_RE.test(key)) throw new KvboxError(`invalid image name "${image}"`);
1966
+ const link3 = key === void 0 ? cfg.rootfs : p.image(key).rootfs;
1967
+ if (key !== void 0 && !existsSync2(link3)) {
1968
+ const have = (await listImages(cfg, p)).map((i) => i.name).join(", ");
1969
+ throw new KvboxError(`this host has no image ${key} (it has: ${have}); install-server.sh with IMAGES="${key}:<version>" adds it`);
1970
+ }
1971
+ const file = await realpath(link3);
1972
+ const version = baseVersionOf(file);
1973
+ const expected = imageFile(key, version, p);
1974
+ if (file !== expected) throw new KvboxError(`${imageLabel(key)} ${link3} points outside its directory (${file})`);
1975
+ return { version, file };
1976
+ }
1977
+ async function listImages(cfg, p = paths()) {
1978
+ const out = [];
1979
+ const versionAt = async (image, link3) => {
1980
+ const file = await realpath(link3);
1981
+ const version = baseVersionOf(file);
1982
+ if (file !== imageFile(image, version, p)) throw new Error("outside its directory");
1983
+ return version;
1984
+ };
1675
1985
  try {
1676
- process.kill(pid, 0);
1677
- return true;
1986
+ out.push({ name: BASE_IMAGE, version: await versionAt(void 0, cfg.rootfs) });
1987
+ } catch {
1988
+ }
1989
+ let names = [];
1990
+ try {
1991
+ names = (await readdir3(p.images)).sort();
1678
1992
  } catch (err) {
1679
- return err.code === "EPERM";
1993
+ if (err.code !== "ENOENT") throw err;
1680
1994
  }
1681
- }
1682
- var bootId;
1683
- function currentBootId() {
1684
- if (bootId === void 0) {
1995
+ for (const name of names) {
1996
+ if (!IMAGE_RE.test(name) || name === BASE_IMAGE) continue;
1685
1997
  try {
1686
- bootId = { id: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() };
1998
+ out.push({ name, version: await versionAt(name, p.image(name).rootfs) });
1687
1999
  } catch {
1688
- bootId = { id: void 0 };
1689
2000
  }
1690
2001
  }
1691
- return bootId.id;
1692
- }
1693
- function vmAlive(meta) {
1694
- if (meta.bootId !== void 0 && meta.bootId !== currentBootId()) return false;
1695
- return pidAlive(meta.pid);
2002
+ return out;
1696
2003
  }
1697
- function hostBootTime() {
1698
- try {
1699
- const m = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
1700
- return m ? new Date(Number(m[1]) * 1e3) : null;
1701
- } catch {
1702
- return null;
2004
+ var overlayCapable = /* @__PURE__ */ new Map();
2005
+ async function assertOverlayCapable(file, image, version) {
2006
+ let ok = overlayCapable.get(file);
2007
+ if (ok === void 0) {
2008
+ const { stdout } = await run(["debugfs", "-R", "stat /sbin/overlay-init", file]);
2009
+ ok = /Type:\s+regular/.test(stdout);
2010
+ overlayCapable.set(file, ok);
2011
+ }
2012
+ if (!ok) throw new KvboxError(`${imageLabel(image)} ${version} is not a kvbox image (no /sbin/overlay-init); rerun install-server.sh`);
2013
+ }
2014
+ var ImageManifestSchema = z6.object({
2015
+ /** false: a new box of this image does not auto-hibernate unless asked (nothing wakes it on a TCP connection). */
2016
+ autoHibernate: z6.boolean().optional(),
2017
+ /** Variables the box gets unless the caller or its owner set them; a value may name an earlier one, or a generated one, as `${NAME}`. */
2018
+ env: z6.record(z6.string(), z6.string()).optional(),
2019
+ /** Variables the host fills with a random password when the caller gave none. */
2020
+ generate: z6.array(z6.string()).optional(),
2021
+ /** How to reach what the box serves, `${NAME}` taken from its variables and `${BOX}` its name. */
2022
+ connect: z6.string().optional()
2023
+ });
2024
+ var manifests = /* @__PURE__ */ new Map();
2025
+ async function imageManifest(file) {
2026
+ const cached = manifests.get(file);
2027
+ if (cached !== void 0) return cached;
2028
+ const { stdout } = await run(["debugfs", "-R", "cat /etc/kvbox/image.json", file]);
2029
+ let manifest = {};
2030
+ if (stdout.trim() !== "") {
2031
+ try {
2032
+ manifest = ImageManifestSchema.parse(JSON.parse(stdout));
2033
+ } catch (err) {
2034
+ throw new KvboxError(`${file}: /etc/kvbox/image.json is not a valid image manifest: ${err.message}`);
2035
+ }
1703
2036
  }
2037
+ manifests.set(file, manifest);
2038
+ return manifest;
2039
+ }
2040
+ function expand(text, vars) {
2041
+ return text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => vars.get(name) ?? "");
2042
+ }
2043
+ function generatedSecret() {
2044
+ return randomBytes2(18).toString("base64url");
2045
+ }
2046
+ function imageEnv(manifest, box, given, inherited = []) {
2047
+ const vars = new Map([...inherited, ...given].map((v) => [v.name, v.value]));
2048
+ const givenNames = new Set(given.map((v) => v.name));
2049
+ const owners = new Set(inherited.map((v) => v.name).filter((n) => !givenNames.has(n)));
2050
+ const defaults = manifest.env ?? {};
2051
+ const added = [];
2052
+ const generated = [];
2053
+ for (const name of manifest.generate ?? []) {
2054
+ if (vars.has(name) || name in defaults) continue;
2055
+ const v = generatedSecret();
2056
+ vars.set(name, v);
2057
+ added.push({ name, value: v });
2058
+ generated.push(name);
2059
+ }
2060
+ const secrets = /* @__PURE__ */ new Set();
2061
+ for (const [name, value] of Object.entries(defaults)) {
2062
+ if (vars.has(name)) continue;
2063
+ const v = expand(value, vars);
2064
+ vars.set(name, v);
2065
+ added.push({ name, value: v });
2066
+ const from = namesIn(value);
2067
+ if (from.some((n) => owners.has(n))) owners.add(name);
2068
+ if (from.some((n) => owners.has(n) || generated.includes(n) || secrets.has(n))) secrets.add(name);
2069
+ }
2070
+ const encode = manifest.connect !== void 0 && /^[a-z][a-z0-9+.-]*:\/\//i.test(manifest.connect);
2071
+ const connectVars = new Map([...vars].map(([k, v]) => [k, owners.has(k) ? `\${${k}}` : encode ? encodeURIComponent(v) : v]));
2072
+ connectVars.set("BOX", box);
2073
+ const connect3 = manifest.connect === void 0 ? void 0 : expand(manifest.connect, connectVars);
2074
+ return { vars: [...given, ...added], generated, secrets: [...generated, ...secrets], connect: connect3 };
2075
+ }
2076
+ function namesIn(text) {
2077
+ return [...text.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g)].map((m) => m[1]);
2078
+ }
2079
+
2080
+ // src/core/volumes.ts
2081
+ import { existsSync as existsSync3, statSync } from "node:fs";
2082
+ import { lstat, mkdir as mkdir4, readdir as readdir4, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
2083
+
2084
+ // ../shared/src/capacity.ts
2085
+ var MEM_HEADROOM_MIB = 2048;
2086
+ function sellableGib(d) {
2087
+ return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);
2088
+ }
2089
+ function volumeRoomGib(d) {
2090
+ return Math.max(0, sellableGib(d) - d.volumesGib);
2091
+ }
2092
+ function hasDiskRoom(d, sizeGib) {
2093
+ return sizeGib <= volumeRoomGib(d);
1704
2094
  }
2095
+ var VCPU_OVERSUBSCRIPTION = 2;
1705
2096
 
1706
2097
  // src/core/volumes.ts
1707
2098
  var volumeLabel = (name) => `kv:${name}`;
@@ -1764,7 +2155,7 @@ async function listVolumes(scope, p = paths()) {
1764
2155
  return out.sort((a, b) => a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name));
1765
2156
  }
1766
2157
  async function diskCapacity(p = paths()) {
1767
- const st = await statfs(existsSync(p.volumes) ? p.volumes : p.home);
2158
+ const st = await statfs(existsSync3(p.volumes) ? p.volumes : p.home);
1768
2159
  let volumesGib = 0;
1769
2160
  let usedBytes2 = 0;
1770
2161
  for (const ref of await listVolumeRefs(p)) {
@@ -1793,7 +2184,7 @@ async function createVolume(req, owner, p = paths()) {
1793
2184
  }
1794
2185
  async function makeVolume(req, owner, p) {
1795
2186
  const v = p.volume(owner, req.name);
1796
- if (existsSync(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
2187
+ if (existsSync3(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
1797
2188
  await mkdir4(p.ownerVolumes(owner), { recursive: true, mode: 448 });
1798
2189
  const disk = await diskCapacity(p);
1799
2190
  if (!hasDiskRoom(disk, req.sizeGib)) {
@@ -1866,7 +2257,7 @@ async function captureDrivesOf(box, p) {
1866
2257
  const drives = await volumeDrivesOf(box, p);
1867
2258
  const named = new Set(drives.map((d) => d.name));
1868
2259
  const dir = p.machine(box.owner, box.name).dir;
1869
- for (const entry of (await readdir3(dir).catch(() => [])).sort()) {
2260
+ for (const entry of (await readdir4(dir).catch(() => [])).sort()) {
1870
2261
  const m = /^volume-(.+)\.ext4$/.exec(entry);
1871
2262
  if (!m || named.has(m[1])) continue;
1872
2263
  const st = await lstat(`${dir}/${entry}`);
@@ -1898,7 +2289,7 @@ async function placeVolumeDrives(box, p) {
1898
2289
  return drives;
1899
2290
  }
1900
2291
  async function removeVolumeDrives(boxDir, keep) {
1901
- for (const entry of await readdir3(boxDir).catch(() => [])) {
2292
+ for (const entry of await readdir4(boxDir).catch(() => [])) {
1902
2293
  const m = /^volume-(.+)\.ext4$/.exec(entry);
1903
2294
  if (m && !keep.has(m[1])) await rm(`${boxDir}/${entry}`, { force: true });
1904
2295
  }
@@ -1941,7 +2332,9 @@ async function capacity(p = paths()) {
1941
2332
  reservedMemMib: running.reduce((n, r) => n + r.memMib, 0),
1942
2333
  reservedVcpu: running.reduce((n, r) => n + r.vcpu, 0),
1943
2334
  running: running.length,
1944
- disk: await diskCapacity(p)
2335
+ disk: await diskCapacity(p),
2336
+ // What a box can be made from here (#87): the control plane places `--base postgres` by it.
2337
+ images: await listImages(await loadConfig(p), p)
1945
2338
  };
1946
2339
  }
1947
2340
  function gb(mib) {
@@ -1976,8 +2369,8 @@ async function assertRoomFor(vcpu, memMib, force, p = paths()) {
1976
2369
  }
1977
2370
 
1978
2371
  // src/core/snapshots.ts
1979
- import { existsSync as existsSync2 } from "node:fs";
1980
- import { link, mkdir as mkdir5, readdir as readdir4, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
2372
+ import { existsSync as existsSync4 } from "node:fs";
2373
+ import { link, mkdir as mkdir5, readdir as readdir5, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
1981
2374
 
1982
2375
  // src/core/firecracker.ts
1983
2376
  import { Agent, request as request2 } from "undici";
@@ -2100,6 +2493,7 @@ function toSnapshot(meta) {
2100
2493
  owner: meta.owner,
2101
2494
  source: meta.source,
2102
2495
  base: meta.base,
2496
+ ...meta.image !== void 0 ? { image: meta.image } : {},
2103
2497
  vcpu: meta.vcpu,
2104
2498
  memMib: meta.memMib,
2105
2499
  sizeBytes: meta.sizeBytes,
@@ -2120,7 +2514,7 @@ async function listSnapshots(scope, p = paths()) {
2120
2514
  }
2121
2515
  async function usedBytes(dir) {
2122
2516
  let total = 0;
2123
- for (const entry of await readdir4(dir)) {
2517
+ for (const entry of await readdir5(dir)) {
2124
2518
  total += (await stat2(`${dir}/${entry}`)).blocks * 512;
2125
2519
  }
2126
2520
  return total;
@@ -2143,43 +2537,64 @@ async function saveSnapshot(req, owner, p = paths()) {
2143
2537
  async function snapshotBox(ref, req, owner, p) {
2144
2538
  const box = await readBox(ref, p);
2145
2539
  if (!vmAlive(box)) {
2146
- if (existsSync2(p.machine(box.owner, box.name).hibernateVmstate)) {
2540
+ if (existsSync4(p.machine(box.owner, box.name).hibernateVmstate)) {
2147
2541
  throw new KvboxError(`box ${req.box} is hibernated; a snapshot freezes a running box (kvbox wake ${req.box} first)`);
2148
2542
  }
2149
2543
  throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);
2150
2544
  }
2151
- const s = p.snapshot(owner, req.name);
2152
- if (existsSync2(s.dir)) throw new KvboxError(`snapshot ${req.name} already exists`);
2545
+ const final = p.snapshot(owner, req.name);
2546
+ if (existsSync4(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
2547
+ const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
2153
2548
  const cfg = await loadConfig(p);
2549
+ if (s !== final) await rm2(s.dir, { recursive: true, force: true });
2154
2550
  await mkdir5(s.dir, { recursive: true, mode: 448 });
2155
2551
  try {
2156
2552
  const volumes = await captureDrivesOf(box, p);
2157
2553
  await captureBox(box, s, cfg, p);
2554
+ await copyBoxEnv(p.machine(box.owner, box.name).env, s.env);
2158
2555
  const meta = {
2159
2556
  ...volumes.length > 0 ? { volumes } : {},
2160
2557
  name: req.name,
2161
2558
  owner,
2162
2559
  source: refKey(box),
2163
2560
  base: box.base,
2561
+ ...box.image !== void 0 ? { image: box.image } : {},
2164
2562
  vcpu: box.vcpu,
2165
2563
  memMib: box.memMib,
2166
2564
  sizeBytes: await usedBytes(s.dir),
2167
2565
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
2168
2566
  };
2169
- await writeSnapshotMeta(meta, p);
2567
+ await writeSnapshotMeta(meta, p, s);
2568
+ if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);
2170
2569
  return toSnapshot(meta);
2171
2570
  } catch (err) {
2172
2571
  await rm2(s.dir, { recursive: true, force: true });
2173
2572
  throw err;
2174
2573
  }
2175
2574
  }
2575
+ async function swapIn(ref, from, boxId, p) {
2576
+ const to = p.snapshot(ref.owner, ref.name).dir;
2577
+ const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
2578
+ await withSnapshotLock(ref, async () => {
2579
+ await rm2(old, { recursive: true, force: true });
2580
+ const hadOld = existsSync4(to);
2581
+ if (hadOld) await rename4(to, old);
2582
+ try {
2583
+ await rename4(from, to);
2584
+ } catch (err) {
2585
+ if (hadOld) await rename4(old, to);
2586
+ throw err;
2587
+ }
2588
+ });
2589
+ await rm2(old, { recursive: true, force: true });
2590
+ }
2176
2591
  async function captureBox(box, to, cfg, p) {
2177
2592
  const m = p.machine(box.owner, box.name);
2178
2593
  const fc = new FirecrackerClient(m.sock);
2179
2594
  let lineageTouched = false;
2180
2595
  try {
2181
2596
  const since = box.memSnapshots ?? 0;
2182
- const mode = since === 0 || existsSync2(m.memBase) ? "Diff" : "Full";
2597
+ const mode = since === 0 || existsSync4(m.memBase) ? "Diff" : "Full";
2183
2598
  let failure2;
2184
2599
  await fc.pause();
2185
2600
  try {
@@ -2210,7 +2625,7 @@ async function captureBox(box, to, cfg, p) {
2210
2625
  }
2211
2626
  }
2212
2627
  async function mergeOntoPrevious(previous, diffFile, editor) {
2213
- if (!existsSync2(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
2628
+ if (!existsSync4(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
2214
2629
  const merged = `${diffFile}.merged`;
2215
2630
  await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
2216
2631
  await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
@@ -2218,13 +2633,13 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
2218
2633
  }
2219
2634
  async function deleteSnapshot(ref, p = paths()) {
2220
2635
  const dir = p.snapshot(ref.owner, ref.name).dir;
2221
- if (!existsSync2(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
2222
- await rm2(dir, { recursive: true, force: true });
2636
+ if (ref.name.startsWith(".") || !existsSync4(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
2637
+ await withSnapshotLock(ref, () => rm2(dir, { recursive: true, force: true }));
2223
2638
  }
2224
2639
 
2225
2640
  // src/core/network.ts
2226
2641
  import { randomInt } from "node:crypto";
2227
- import { existsSync as existsSync3 } from "node:fs";
2642
+ import { existsSync as existsSync5 } from "node:fs";
2228
2643
  import { fileURLToPath } from "node:url";
2229
2644
  var TAP_PREFIX = "kv-";
2230
2645
  var PRIVILEGED_SCRIPT = "/usr/local/lib/kvbox/net-setup.sh";
@@ -2234,15 +2649,15 @@ function tapName(box) {
2234
2649
  function netSetupScript() {
2235
2650
  const override = process.env["KVBOX_NET_SETUP"];
2236
2651
  if (override) return override;
2237
- if (existsSync3(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
2652
+ if (existsSync5(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
2238
2653
  for (const rel of ["../scripts/net-setup.sh", "../../scripts/net-setup.sh"]) {
2239
2654
  const candidate = fileURLToPath(new URL(rel, import.meta.url));
2240
- if (existsSync3(candidate)) return candidate;
2655
+ if (existsSync5(candidate)) return candidate;
2241
2656
  }
2242
2657
  throw new KvboxError("net-setup.sh not found next to kvbox-server");
2243
2658
  }
2244
2659
  function bridgeExists(bridge) {
2245
- return existsSync3(`/sys/class/net/${bridge}`);
2660
+ return existsSync5(`/sys/class/net/${bridge}`);
2246
2661
  }
2247
2662
  function netRun(cfg, args) {
2248
2663
  return run([netSetupScript(), ...args], {
@@ -2263,12 +2678,15 @@ async function ensureHostNetwork(cfg) {
2263
2678
  return "created";
2264
2679
  }
2265
2680
  async function createTap(box, cfg, opts = {}) {
2266
- const tap = tapName(box);
2267
- await netRun(cfg, ["tap", "add", tap, ...opts.detached ? ["detached"] : []]);
2681
+ const tap = tapName(box.id);
2682
+ await netRun(cfg, ["tap", "add", tap, box.ip, box.mac, ...opts.detached ? ["detached"] : []]);
2268
2683
  return tap;
2269
2684
  }
2270
2685
  async function attachTap(box, cfg) {
2271
- await netRun(cfg, ["tap", "attach", tapName(box)]);
2686
+ await netRun(cfg, ["tap", "attach", tapName(box.id), box.ip, box.mac]);
2687
+ }
2688
+ async function pinTap(box, cfg) {
2689
+ await netRun(cfg, ["tap", "pin", tapName(box.id), box.ip, box.mac]);
2272
2690
  }
2273
2691
  async function deleteTap(box, cfg) {
2274
2692
  await netRun(cfg, ["tap", "del", tapName(box)]);
@@ -2313,6 +2731,13 @@ var proxyArgs = (p) => [p.box, p.boxIp, String(p.hostPort), String(p.guestPort),
2313
2731
  async function openProxy(proxy, cfg) {
2314
2732
  await netRun(cfg, ["proxy", "add", ...proxyArgs(proxy)]);
2315
2733
  }
2734
+ var linkArgs = (l) => [l.box, l.fromIp, l.toIp, String(l.port)];
2735
+ async function openLink(link3, cfg) {
2736
+ await netRun(cfg, ["link", "add", ...linkArgs(link3)]);
2737
+ }
2738
+ async function closeLink(link3, cfg) {
2739
+ await netRun(cfg, ["link", "rm", ...linkArgs(link3)]);
2740
+ }
2316
2741
  async function closeProxy(proxy, cfg) {
2317
2742
  await netRun(cfg, ["proxy", "rm", ...proxyArgs(proxy)]);
2318
2743
  }
@@ -2348,13 +2773,29 @@ function boxProxies(meta) {
2348
2773
  const ssh = meta.sshPort === void 0 ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];
2349
2774
  return [...ssh, ...(meta.ports ?? []).map((f) => ({ box: meta.id, boxIp: meta.ip, hostPort: f.hostPort, guestPort: f.guestPort, proto: f.proto }))];
2350
2775
  }
2351
- async function openPorts(meta, cfg) {
2776
+ function boxLinks(meta) {
2777
+ return (meta.links ?? []).map((l) => ({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }));
2778
+ }
2779
+ async function standingLinks(meta, p) {
2780
+ const links = boxLinks(meta);
2781
+ const stands = await Promise.all(
2782
+ (meta.links ?? []).map(async (l) => !l.stale && (await readMachineMeta({ owner: l.owner, name: l.name }, p).catch(() => null))?.ip === l.ip)
2783
+ );
2784
+ return links.filter((_, i) => stands[i]);
2785
+ }
2786
+ async function openPorts(meta, cfg, p) {
2352
2787
  for (const proxy of boxProxies(meta)) await openProxy(proxy, cfg);
2788
+ for (const link3 of await standingLinks(meta, p)) {
2789
+ await openLink(link3, cfg).catch((err) => console.error(`warning: could not open the link from ${link3.fromIp}: ${err.message}`));
2790
+ }
2353
2791
  }
2354
2792
  async function closePorts(meta, cfg) {
2355
2793
  for (const proxy of boxProxies(meta)) {
2356
2794
  await closeProxy(proxy, cfg).catch((err) => console.error(`warning: could not close port ${proxy.hostPort}: ${err.message}`));
2357
2795
  }
2796
+ for (const link3 of boxLinks(meta)) {
2797
+ await closeLink(link3, cfg).catch((err) => console.error(`warning: could not close the link from ${link3.fromIp}: ${err.message}`));
2798
+ }
2358
2799
  }
2359
2800
  var reservedPorts = /* @__PURE__ */ new Set();
2360
2801
  async function drawPorts(count, p) {
@@ -2394,7 +2835,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
2394
2835
  }
2395
2836
  }
2396
2837
  function isHibernated(meta, p) {
2397
- return !vmAlive(meta) && existsSync4(p.machine(meta.owner, meta.name).hibernateVmstate);
2838
+ return !vmAlive(meta) && existsSync6(p.machine(meta.owner, meta.name).hibernateVmstate);
2398
2839
  }
2399
2840
  function statusOf(meta, p = paths()) {
2400
2841
  if (vmAlive(meta)) return meta.paused ? "standby" : "running";
@@ -2423,16 +2864,20 @@ function toMachine(meta, p = paths()) {
2423
2864
  memMib: meta.memMib,
2424
2865
  ...diskStats(p.machine(meta.owner, meta.name).overlay),
2425
2866
  base: meta.base,
2867
+ ...meta.image !== void 0 ? { image: meta.image } : {},
2426
2868
  createdAt: meta.createdAt,
2427
2869
  source: meta.source,
2428
2870
  status: statusOf(meta, p),
2429
2871
  ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
2430
2872
  ...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
2431
2873
  ...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
2432
- ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {}
2874
+ ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
2875
+ ...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
2433
2876
  };
2434
2877
  }
2435
- function autoHibernateFor(req, cfg) {
2878
+ var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
2879
+ function autoHibernateFor(req, cfg, manifest = {}) {
2880
+ if (req.autoHibernateSec === void 0 && manifest.autoHibernate === false) return void 0;
2436
2881
  return (req.autoHibernateSec ?? cfg.autoHibernateSec) || void 0;
2437
2882
  }
2438
2883
  async function readAllMeta(p) {
@@ -2487,33 +2932,6 @@ function bootArgs(name, ip, cfg, pubkeyB64) {
2487
2932
  const args = `console=ttyS0 reboot=k panic=1 init=/sbin/overlay-init kvbox.overlay=/dev/vdb ip=${ip}::${cfg.gateway}:255.255.255.0:${name}:eth0:off kvbox.name=${name} kvbox.sshkey=${pubkeyB64}`;
2488
2933
  return process.arch === "arm64" ? `keep_bootcon ${args}` : args;
2489
2934
  }
2490
- function baseVersionOf(file) {
2491
- const m = /^rootfs-(.+)\.ext4$/.exec(basename(file));
2492
- if (!m) throw new KvboxError(`base image ${file} is not versioned (expected assets/rootfs-<version>.ext4); run install-server.sh`);
2493
- return m[1];
2494
- }
2495
- async function currentBase(cfg, p) {
2496
- const file = await realpath(cfg.rootfs);
2497
- const version = baseVersionOf(file);
2498
- const expected = p.baseImage(version);
2499
- if (file !== expected) throw new KvboxError(`base image ${cfg.rootfs} points outside ${p.assets} (${file})`);
2500
- return { version, file };
2501
- }
2502
- function baseFileFor(meta, p) {
2503
- const file = p.baseImage(meta.base);
2504
- if (!existsSync4(file)) throw new KvboxError(`box ${meta.name} runs on base image ${meta.base}, which is gone from ${p.assets}`);
2505
- return file;
2506
- }
2507
- var overlayCapable = /* @__PURE__ */ new Map();
2508
- async function assertOverlayCapable(baseFile, version) {
2509
- let ok = overlayCapable.get(baseFile);
2510
- if (ok === void 0) {
2511
- const { stdout } = await run(["debugfs", "-R", "stat /sbin/overlay-init", baseFile]);
2512
- ok = /Type:\s+regular/.test(stdout);
2513
- overlayCapable.set(baseFile, ok);
2514
- }
2515
- if (!ok) throw new KvboxError(`base image ${version} is not a kvbox base image (no /sbin/overlay-init); rerun install-server.sh`);
2516
- }
2517
2935
  async function createOverlay(file, gib) {
2518
2936
  await writeFile5(file, "", { mode: 384 });
2519
2937
  await truncate2(file, gib * 1024 ** 3);
@@ -2552,7 +2970,7 @@ async function spawnFirecracker(ref, cfg, p) {
2552
2970
  child.unref();
2553
2971
  const pid = child.pid;
2554
2972
  if (pid === void 0) throw new KvboxError("could not start firecracker");
2555
- if (!await waitFor(() => existsSync4(m.sock), 3e3)) {
2973
+ if (!await waitFor(() => existsSync6(m.sock), 3e3)) {
2556
2974
  killQuietly(pid);
2557
2975
  throw new KvboxError(`firecracker did not open its API socket; last log lines:
2558
2976
  ${await tailOf(m.log)}`);
@@ -2567,7 +2985,7 @@ function killQuietly(pid) {
2567
2985
  }
2568
2986
  async function launch(spec, tap, cfg, pubkeyB64, p) {
2569
2987
  const m = p.machine(spec.owner, spec.name);
2570
- const baseFile = baseFileFor(spec, p);
2988
+ const baseFile = imageFileFor(spec, p);
2571
2989
  const volumes = await placeVolumeDrives(spec, p);
2572
2990
  const pid = await spawnFirecracker(spec, cfg, p);
2573
2991
  try {
@@ -2614,7 +3032,7 @@ async function loadSnapshot(spec, image, tap, cfg, p) {
2614
3032
  }
2615
3033
  }
2616
3034
  async function currentBaseVersion(p = paths()) {
2617
- return (await currentBase(await loadConfig(p), p)).version;
3035
+ return (await currentImage(void 0, await loadConfig(p), p)).version;
2618
3036
  }
2619
3037
  async function readHostPubkey(p) {
2620
3038
  try {
@@ -2625,7 +3043,7 @@ async function readHostPubkey(p) {
2625
3043
  }
2626
3044
  function assertAssets(cfg) {
2627
3045
  for (const [what, file] of [["kernel", cfg.kernel], ["base image", cfg.rootfs], ["firecracker", cfg.firecracker]]) {
2628
- if (!existsSync4(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
3046
+ if (!existsSync6(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
2629
3047
  }
2630
3048
  }
2631
3049
  async function createMachine(req, owner, p = paths()) {
@@ -2642,16 +3060,25 @@ async function createMachine(req, owner, p = paths()) {
2642
3060
  const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
2643
3061
  const id = newBoxId(idsInUse(existing));
2644
3062
  const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);
2645
- const base = await currentBase(cfg, p);
2646
- await assertOverlayCapable(base.file, base.version);
2647
- return bootInto(
2648
- { id, name, owner, ip, mac: macFor(ip), vcpu: size.vcpu, memMib: size.memMib, base: base.version, sshKeys },
2649
- // The base image is shared read-only by every box; only the box's own writes land in its overlay.
2650
- (m) => createOverlay(m.overlay, size.diskGib),
2651
- { source: "base", autoHibernateSec: autoHibernateFor(req, cfg) },
3063
+ const image = imageKey(req.image);
3064
+ const base = await currentImage(image, cfg, p);
3065
+ await assertOverlayCapable(base.file, image, base.version);
3066
+ const manifest = await imageManifest(base.file);
3067
+ const env = imageEnv(manifest, name, req.env ?? [], (await readOwnerEnv(owner, p).catch(() => null))?.vars ?? []);
3068
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3069
+ const autoHibernateSec = autoHibernateFor(req, cfg, manifest);
3070
+ const machine = await bootInto(
3071
+ { id, name, owner, ip, mac: macFor(ip), vcpu: size.vcpu, memMib: size.memMib, base: base.version, image, sshKeys },
3072
+ // The image is shared read-only by every box; only the box's own writes land in its overlay.
3073
+ async (m) => {
3074
+ await createOverlay(m.overlay, size.diskGib);
3075
+ if (env.vars.length > 0) await writeBoxEnv({ owner, name }, env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now })), p);
3076
+ },
3077
+ { source: "base", autoHibernateSec },
2652
3078
  cfg,
2653
3079
  p
2654
3080
  );
3081
+ return env.connect === void 0 ? machine : { ...machine, connect: env.connect };
2655
3082
  }
2656
3083
  async function bootInto(box, prepare, origin, cfg, p) {
2657
3084
  const { id, ip, owner, name } = box;
@@ -2667,11 +3094,11 @@ async function bootInto(box, prepare, origin, cfg, p) {
2667
3094
  drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
2668
3095
  sshPort = drawn?.ports[0];
2669
3096
  await prepare(m);
2670
- const tap = await createTap(id, cfg);
3097
+ const tap = await createTap(box, cfg);
2671
3098
  tapCreated = true;
2672
3099
  const spec = { ...box, sshPort };
2673
3100
  pid = await launch(spec, tap, cfg, keysB64, p);
2674
- await openPorts(spec, cfg);
3101
+ await openPorts(spec, cfg, p);
2675
3102
  void pushEnvAfterBoot(spec, pid, m.vsock, p);
2676
3103
  const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
2677
3104
  await writeMachineMeta(meta, p);
@@ -2682,12 +3109,14 @@ async function bootInto(box, prepare, origin, cfg, p) {
2682
3109
  await closePorts({ id, ip, sshPort }, cfg);
2683
3110
  if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
2684
3111
  await rm3(m.dir, { recursive: true, force: true });
3112
+ boxListChanged();
2685
3113
  throw err;
2686
3114
  } finally {
2687
3115
  drawn?.release();
2688
3116
  }
2689
3117
  }
2690
3118
  async function readSnap(ref, p) {
3119
+ if (ref.name.startsWith(".")) throw new NotFoundError(`snapshot ${shown(ref)}`);
2691
3120
  try {
2692
3121
  return await readSnapshotMeta(ref, p);
2693
3122
  } catch (err) {
@@ -2700,13 +3129,20 @@ function prefixLenOf(subnet) {
2700
3129
  }
2701
3130
  async function restoreMachine(fromText, owner, req, cfg, p) {
2702
3131
  const from = parseRef(fromText, owner);
3132
+ return withSnapshotLock(from, () => restoreFrom(from, owner, req, cfg, p));
3133
+ }
3134
+ async function restoreFrom(from, owner, req, cfg, p) {
2703
3135
  const snap = await readSnap(from, p);
2704
3136
  if (req.size !== void 0) {
2705
3137
  throw new KvboxError(`--size cannot be combined with --from: a restored box has the snapshot's size (${shown(from)}: ${snap.vcpu} vCPU, ${snap.memMib} MiB)`);
2706
3138
  }
2707
3139
  assertAssets(cfg);
2708
- if (!existsSync4(p.baseImage(snap.base))) {
2709
- throw new KvboxError(`snapshot ${shown(from)} stacks on base image ${snap.base}, which is gone from ${p.assets}`);
3140
+ if (!existsSync6(imageFile(snap.image, snap.base, p))) {
3141
+ throw new KvboxError(`snapshot ${shown(from)} stacks on ${imageLabel(snap.image)} ${snap.base}, which is gone from ${p.assets}`);
3142
+ }
3143
+ const manifest = await imageManifest(imageFile(snap.image, snap.base, p));
3144
+ if (req.image !== void 0 && imageKey(req.image) !== snap.image) {
3145
+ throw new KvboxError(`--base cannot be combined with --from: a restored box has the snapshot's image (${shown(from)}: ${imageLabel(snap.image)})`);
2710
3146
  }
2711
3147
  await assertRoomFor(snap.vcpu, snap.memMib, req.force ?? false, p);
2712
3148
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
@@ -2717,14 +3153,16 @@ async function restoreMachine(fromText, owner, req, cfg, p) {
2717
3153
  const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);
2718
3154
  const s = p.snapshot(from.owner, from.name);
2719
3155
  return restoreInto(
2720
- { id, name, owner, ip, mac: macFor(ip), vcpu: snap.vcpu, memMib: snap.memMib, base: snap.base, sshKeys },
3156
+ { id, name, owner, ip, mac: macFor(ip), vcpu: snap.vcpu, memMib: snap.memMib, base: snap.base, image: snap.image, sshKeys },
2721
3157
  async (m) => {
2722
3158
  await run(["cp", "--sparse=always", "--reflink=auto", s.overlay, m.overlay]);
3159
+ await copyBoxEnv(s.env, m.env);
3160
+ if (req.env?.length) await mergeBoxEnv({ owner, name }, req.env, p);
2723
3161
  await link2(s.mem, m.memBase);
2724
3162
  await placeholderDrives(m.dir, snap.volumes ?? []);
2725
3163
  return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };
2726
3164
  },
2727
- { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg) },
3165
+ { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest) },
2728
3166
  cfg,
2729
3167
  p
2730
3168
  );
@@ -2742,7 +3180,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
2742
3180
  drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
2743
3181
  sshPort = drawn?.ports[0];
2744
3182
  const image = await prepare(m);
2745
- const tap = await createTap(id, cfg, { detached: true });
3183
+ const tap = await createTap(box, cfg, { detached: true });
2746
3184
  tapCreated = true;
2747
3185
  const spec = { ...box, sshPort };
2748
3186
  pid = await loadSnapshot(spec, image, tap, cfg, p);
@@ -2755,8 +3193,8 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
2755
3193
  if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
2756
3194
  if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
2757
3195
  await pushEnv(box, m.vsock, p);
2758
- await attachTap(id, cfg);
2759
- await openPorts(spec, cfg);
3196
+ await attachTap(box, cfg);
3197
+ await openPorts(spec, cfg, p);
2760
3198
  const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
2761
3199
  await writeMachineMeta(meta, p);
2762
3200
  recordState(meta, "running", "new", p, meta.createdAt);
@@ -2766,6 +3204,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
2766
3204
  await closePorts({ id, ip, sshPort }, cfg);
2767
3205
  if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
2768
3206
  await rm3(m.dir, { recursive: true, force: true });
3207
+ boxListChanged();
2769
3208
  throw err;
2770
3209
  } finally {
2771
3210
  drawn?.release();
@@ -2792,7 +3231,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
2792
3231
  growTo = preset.diskGib > diskGib ? preset.diskGib : void 0;
2793
3232
  }
2794
3233
  assertAssets(cfg);
2795
- baseFileFor(src, p);
3234
+ imageFileFor(src, p);
2796
3235
  await assertRoomFor(shape.vcpu, shape.memMib, req.force ?? false, p);
2797
3236
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
2798
3237
  authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);
@@ -2800,7 +3239,8 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
2800
3239
  const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
2801
3240
  const id = newBoxId(idsInUse(existing));
2802
3241
  const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);
2803
- const box = { id, name, owner, ip, mac: macFor(ip), ...shape, base: src.base, sshKeys };
3242
+ const box = { id, name, owner, ip, mac: macFor(ip), ...shape, base: src.base, image: src.image, sshKeys };
3243
+ const srcEnv = p.machine(src.owner, src.name).env;
2804
3244
  const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0 };
2805
3245
  if (!warm) {
2806
3246
  return bootInto(
@@ -2808,6 +3248,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
2808
3248
  async (m) => {
2809
3249
  await run(["cp", "--sparse=always", "--reflink=auto", srcDisk, m.overlay]);
2810
3250
  if (growTo !== void 0) await growDisk(m.overlay, growTo);
3251
+ await copyBoxEnv(srcEnv, m.env);
2811
3252
  },
2812
3253
  origin,
2813
3254
  cfg,
@@ -2819,6 +3260,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
2819
3260
  box,
2820
3261
  async (m) => {
2821
3262
  await captureBox(src, { vmstate: m.forkVmstate, mem: m.memBase, overlay: m.overlay }, cfg, p);
3263
+ await copyBoxEnv(srcEnv, m.env);
2822
3264
  await placeholderDrives(m.dir, srcVolumes);
2823
3265
  return { vmstate: m.forkVmstate, mem: m.memBase, label: `box ${shown(ref)}`, volumes: srcVolumes };
2824
3266
  },
@@ -2873,7 +3315,7 @@ async function dropGuestVolumes(box, vsock) {
2873
3315
  }
2874
3316
  }
2875
3317
  async function pushEnv(box, vsock, p) {
2876
- const vars = await envForBoot(box.owner, p);
3318
+ const vars = await envForBoot(box, p);
2877
3319
  if (vars === null) return;
2878
3320
  try {
2879
3321
  await setEnv(vsock, vars, AGENT_REPLY_MS);
@@ -2895,7 +3337,7 @@ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS
2895
3337
  const deadline = Date.now() + timing.waitMs;
2896
3338
  for (; ; ) {
2897
3339
  if (!pidAlive(pid)) return;
2898
- const vars = await envForBoot(box.owner, p);
3340
+ const vars = await envForBoot(box, p);
2899
3341
  if (vars === null) return;
2900
3342
  try {
2901
3343
  await setEnv(vsock, vars, timing.replyMs);
@@ -2972,11 +3414,11 @@ var startMachine = locked(async function startMachine2(ref, p = paths()) {
2972
3414
  assertAssets(cfg);
2973
3415
  const keysB64 = authorizedKeysB64(await readHostPubkey(p), meta.sshKeys ?? []);
2974
3416
  await ensureHostNetwork(cfg);
2975
- const tap = await createTap(meta.id, cfg);
3417
+ const tap = await createTap(meta, cfg);
2976
3418
  let pid;
2977
3419
  try {
2978
3420
  pid = await launch(meta, tap, cfg, keysB64, p);
2979
- await openPorts(meta, cfg);
3421
+ await openPorts(meta, cfg, p);
2980
3422
  void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);
2981
3423
  const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0 };
2982
3424
  await writeMachineMeta(started, p);
@@ -3107,12 +3549,12 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
3107
3549
  if (status === "running" || status === "standby") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated`);
3108
3550
  if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated; kvbox start ${shown(ref)} boots it`);
3109
3551
  assertAssets(cfg);
3110
- if (!existsSync4(p.baseImage(meta.base))) {
3111
- throw new KvboxError(`box ${shown(ref)} stacks on base image ${meta.base}, which is gone from ${p.assets}`);
3552
+ if (!existsSync6(imageFile(meta.image, meta.base, p))) {
3553
+ throw new KvboxError(`box ${shown(ref)} stacks on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);
3112
3554
  }
3113
3555
  const m = p.machine(ref.owner, ref.name);
3114
3556
  await ensureHostNetwork(cfg);
3115
- const tap = await createTap(meta.id, cfg, { detached: true });
3557
+ const tap = await createTap(meta, cfg, { detached: true });
3116
3558
  let pid;
3117
3559
  let stale;
3118
3560
  try {
@@ -3124,8 +3566,8 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
3124
3566
  noAnswer: `the box stays hibernated. kvbox-agent inside it took the request but gave no answer; try kvbox wake ${shown(ref)} again`
3125
3567
  });
3126
3568
  stale = await pushAuthorizedKeys(meta, m.vsock, p);
3127
- await attachTap(meta.id, cfg);
3128
- await openPorts(meta, cfg);
3569
+ await attachTap(meta, cfg);
3570
+ await openPorts(meta, cfg, p);
3129
3571
  } catch (err) {
3130
3572
  if (pid !== void 0) killQuietly(pid);
3131
3573
  await closePorts(meta, cfg);
@@ -3162,9 +3604,9 @@ var updateMachine = locked(async function updateMachine2(ref, p = paths()) {
3162
3604
  const cfg = await loadConfig(p);
3163
3605
  assertNotHibernated(meta, p);
3164
3606
  assertAssets(cfg);
3165
- const base = await currentBase(cfg, p);
3607
+ const base = await currentImage(meta.image, cfg, p);
3166
3608
  if (base.version === meta.base) return toMachine(meta, p);
3167
- await assertOverlayCapable(base.file, base.version);
3609
+ await assertOverlayCapable(base.file, meta.image, base.version);
3168
3610
  return applyAtNextBoot(meta, { base: base.version }, "update", cfg, p);
3169
3611
  });
3170
3612
  var rescaleMachine = locked(async function rescaleMachine2(ref, req, p = paths()) {
@@ -3272,6 +3714,49 @@ var removePorts = locked(async function removePorts2(ref, req, p = paths()) {
3272
3714
  await writeMachineMeta(next, p);
3273
3715
  return toMachine(next, p);
3274
3716
  });
3717
+ function linkSource(req, caller, target) {
3718
+ if (req.fromOwner !== void 0) return { owner: ownerFor(req.fromOwner, caller), name: req.from, display: `${req.fromOwner}/${req.from}` };
3719
+ const ref = parseRef(req.from, caller);
3720
+ const realm = realmOf(target);
3721
+ return realm !== null && realmOf(ref.owner) === null && req.from.includes("/") ? { ...ref, owner: `${ref.owner}@${realm}` } : ref;
3722
+ }
3723
+ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
3724
+ const meta = await readMeta(ref, p);
3725
+ const fromRef = linkSource(req, caller, meta.owner);
3726
+ if (fromRef.owner === meta.owner && fromRef.name === meta.name) throw new KvboxError(`box ${shown(ref)} already reaches itself`);
3727
+ const from = await readMeta(fromRef, p);
3728
+ if (realmOf(from.owner) !== realmOf(meta.owner)) {
3729
+ throw new KvboxError(`box ${shown(fromRef)} and box ${shown(ref)} belong to different realms (one is this host's, one a control plane's); a link joins boxes of one realm`);
3730
+ }
3731
+ const links = (meta.links ?? []).filter((l) => !(l.stale && l.owner === from.owner && l.name === from.name && l.ip === from.ip && l.port === req.port));
3732
+ const same = (l) => !l.stale && l.owner === from.owner && l.name === from.name && l.port === req.port;
3733
+ if (links.some(same)) throw new KvboxError(`box ${shown(fromRef)} already reaches box ${shown(ref)} on port ${req.port}`);
3734
+ if (links.length >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${shown(ref)} has ${links.length}`);
3735
+ const added = { owner: from.owner, name: from.name, ip: from.ip, port: req.port };
3736
+ const cfg = await loadConfig(p);
3737
+ if (vmAlive(meta)) await openLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg);
3738
+ const next = { ...meta, links: [...links, added] };
3739
+ try {
3740
+ await writeMachineMeta(next, p);
3741
+ } catch (err) {
3742
+ await closeLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg).catch(() => void 0);
3743
+ throw err;
3744
+ }
3745
+ return toMachine(next, p);
3746
+ });
3747
+ var removeLink = locked(async function removeLink2(ref, req, caller, p = paths()) {
3748
+ const meta = await readMeta(ref, p);
3749
+ const fromRef = linkSource(req, caller, meta.owner);
3750
+ const links = meta.links ?? [];
3751
+ const gone = links.filter((l) => !l.stale && l.owner === fromRef.owner && l.name === fromRef.name && l.port === req.port);
3752
+ if (gone.length === 0) throw new KvboxError(`box ${shown(fromRef)} is not linked to box ${shown(ref)} on port ${req.port}`);
3753
+ const cfg = await loadConfig(p);
3754
+ for (const l of gone) await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg);
3755
+ const kept = links.filter((l) => !gone.includes(l));
3756
+ const next = { ...meta, links: kept.length > 0 ? kept : void 0 };
3757
+ await writeMachineMeta(next, p);
3758
+ return toMachine(next, p);
3759
+ });
3275
3760
  async function growDisk(file, gib) {
3276
3761
  await truncate2(file, gib * 1024 ** 3);
3277
3762
  await run(["e2fsck", "-f", "-p", file], { okExitCodes: [1] });
@@ -3285,13 +3770,54 @@ async function readMeta(ref, p) {
3285
3770
  throw err;
3286
3771
  }
3287
3772
  }
3288
- var destroyMachine = locked(async function destroyMachine2(ref, p = paths()) {
3773
+ async function destroyMachine(ref, p = paths()) {
3774
+ const gone = await destroyBox(ref, p);
3775
+ await dropLinksFrom(gone, p);
3776
+ }
3777
+ var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
3289
3778
  const meta = await readMeta(ref, p);
3290
3779
  const cfg = await loadConfig(p);
3291
3780
  await shutdown(meta, cfg, p, 2e3);
3781
+ await closeLinksFrom(meta, cfg, p).catch((err) => {
3782
+ recordState(meta, "stopped", "stop", p);
3783
+ throw err;
3784
+ });
3292
3785
  recordState(meta, "stopped", "rm", p);
3293
3786
  await rm3(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
3787
+ boxListChanged();
3788
+ return meta;
3294
3789
  });
3790
+ var linkOf = (gone) => (l) => l.owner === gone.owner && l.name === gone.name && l.ip === gone.ip;
3791
+ async function closeLinksFrom(gone, cfg, p) {
3792
+ const isGone = linkOf(gone);
3793
+ for (const ref of await listMachineRefs(p)) {
3794
+ const meta = await readMachineMeta(ref, p).catch(() => null);
3795
+ for (const l of meta?.links?.filter(isGone) ?? []) {
3796
+ await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg).catch((err) => {
3797
+ throw new KvboxError(`box ${shown(gone)} is stopped but not removed: could not close its link into ${shown(meta)} (${err.message}); try again`);
3798
+ });
3799
+ }
3800
+ }
3801
+ }
3802
+ async function dropLinksFrom(gone, p) {
3803
+ const cfg = await loadConfig(p);
3804
+ const isGone = linkOf(gone);
3805
+ for (const ref of await listMachineRefs(p)) {
3806
+ await withBoxLock(ref, async () => {
3807
+ const meta = await readMachineMeta(ref, p).catch(() => null);
3808
+ if (!meta?.links?.some(isGone)) return;
3809
+ const stuck = /* @__PURE__ */ new Set();
3810
+ for (const l of meta.links.filter(isGone)) {
3811
+ await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg).catch((err) => {
3812
+ stuck.add(l);
3813
+ console.error(`warning: could not close the link from removed box ${gone.name} into ${meta.name}: ${err.message}`);
3814
+ });
3815
+ }
3816
+ const kept = meta.links.filter((l) => !isGone(l) || stuck.has(l)).map((l) => stuck.has(l) ? { ...l, stale: true } : l);
3817
+ await writeMachineMeta({ ...meta, links: kept.length > 0 ? kept : void 0 }, p);
3818
+ }).catch((err) => console.error(`warning: links of removed box ${gone.name}: ${err.message}`));
3819
+ }
3820
+ }
3295
3821
  var RECOVERY_CONCURRENCY = 2;
3296
3822
  async function settleDeadBoxes(p = paths()) {
3297
3823
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -3319,6 +3845,14 @@ async function settleDeadBoxes(p = paths()) {
3319
3845
  function cutByReboot(meta) {
3320
3846
  return meta.pid !== null && meta.bootId !== currentBootId();
3321
3847
  }
3848
+ async function pinRunningTaps(p = paths()) {
3849
+ const cfg = await loadConfig(p);
3850
+ if (!bridgeExists(cfg.bridge)) return;
3851
+ for (const meta of await readAllMeta(p)) {
3852
+ if (!vmAlive(meta) || !existsSync6(`/sys/class/net/${tapName(meta.id)}`)) continue;
3853
+ await pinTap(meta, cfg).catch((err) => console.error(`warning: could not pin box ${meta.name}'s tap: ${err.message}`));
3854
+ }
3855
+ }
3322
3856
  var recovery = null;
3323
3857
  var recoveryStopping = false;
3324
3858
  var recoveryRun = Promise.resolve();
@@ -3357,24 +3891,24 @@ async function bootRecovered(settled, p = paths()) {
3357
3891
  import { chmod as chmod3, mkdir as mkdir7, rm as rm4, writeFile as writeFile6 } from "node:fs/promises";
3358
3892
 
3359
3893
  // ../shared/src/relay.ts
3360
- import { z as z6 } from "zod";
3894
+ import { z as z7 } from "zod";
3361
3895
  var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
3362
3896
  var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
3363
3897
  var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
3364
- var RelayJoinSchema = z6.object({
3365
- v: z6.literal(1),
3898
+ var RelayJoinSchema = z7.object({
3899
+ v: z7.literal(1),
3366
3900
  /** How the relay lists this host. */
3367
- name: z6.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
3901
+ name: z7.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
3368
3902
  /** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
3369
- relay: z6.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
3903
+ relay: z7.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
3370
3904
  /** The relay's WireGuard public key. */
3371
- relayKey: z6.string().regex(WG_KEY_RE),
3905
+ relayKey: z7.string().regex(WG_KEY_RE),
3372
3906
  /** This host's address inside the tunnel. */
3373
- tunnelIp: z6.string().regex(IPV4_RE),
3907
+ tunnelIp: z7.string().regex(IPV4_RE),
3374
3908
  /** This host's WireGuard private key, generated on the relay, kept nowhere else. */
3375
- privateKey: z6.string().regex(WG_KEY_RE),
3909
+ privateKey: z7.string().regex(WG_KEY_RE),
3376
3910
  /** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
3377
- publicIp: z6.string().regex(IPV4_RE)
3911
+ publicIp: z7.string().regex(IPV4_RE)
3378
3912
  });
3379
3913
  function decodeRelayJoin(text) {
3380
3914
  let parsed;
@@ -3489,7 +4023,7 @@ function startIdleWatch(opts = {}) {
3489
4023
  const started = [];
3490
4024
  const watched = /* @__PURE__ */ new Set();
3491
4025
  for (const box of await list()) {
3492
- if (!box.autoHibernateSec || box.status !== "running") continue;
4026
+ if (!box.autoHibernateSec || box.status !== "running" || box.links?.length) continue;
3493
4027
  if (inflight.has(box.id)) {
3494
4028
  watched.add(box.id);
3495
4029
  continue;
@@ -3609,7 +4143,7 @@ function versionOf(srcFileUrl, injected) {
3609
4143
  }
3610
4144
 
3611
4145
  // src/version.ts
3612
- var VERSION = versionOf(import.meta.url, true ? "0.5.27" : void 0);
4146
+ var VERSION = versionOf(import.meta.url, true ? "0.5.29" : void 0);
3613
4147
 
3614
4148
  // src/caller.ts
3615
4149
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";
@@ -4028,6 +4562,13 @@ function machineRoutes() {
4028
4562
  if (!body.success) throw new KvboxError("ports: expected a list of box ports");
4029
4563
  return c.json(await removePorts(parseRef(c.req.param("name"), c.get("owner")), body.data));
4030
4564
  });
4565
+ const linkBody = async (c) => {
4566
+ const body = LinkRequest.safeParse(await c.req.json().catch(() => ({})));
4567
+ if (!body.success) throw new KvboxError("links: expected {from, port}");
4568
+ return body.data;
4569
+ };
4570
+ r.post("/:name/links", async (c) => c.json(await addLink(parseRef(c.req.param("name"), c.get("owner")), await linkBody(c), c.get("owner")), 201));
4571
+ r.delete("/:name/links", async (c) => c.json(await removeLink(parseRef(c.req.param("name"), c.get("owner")), await linkBody(c), c.get("owner"))));
4031
4572
  r.get("/:name/usage", async (c) => {
4032
4573
  const since = c.req.query("since");
4033
4574
  let from;
@@ -4038,6 +4579,29 @@ function machineRoutes() {
4038
4579
  }
4039
4580
  return c.json(await machineUsage(parseRef(c.req.param("name"), c.get("owner")), from));
4040
4581
  });
4582
+ r.get("/:name/env", async (c) => {
4583
+ const ref = parseRef(c.req.param("name"), c.get("owner"));
4584
+ await getMachine(ref);
4585
+ return c.json({ box: ref.name, vars: shownBoxEnv(await readBoxEnv(ref)) });
4586
+ });
4587
+ r.post("/:name/env/:var", async (c) => {
4588
+ const ref = parseRef(c.req.param("name"), c.get("owner"));
4589
+ const name = c.req.param("var");
4590
+ const problem = envNameProblem(name);
4591
+ if (problem !== null) throw new KvboxError(problem);
4592
+ const body = SetEnvRequest.safeParse(await c.req.json().catch(() => ({})));
4593
+ if (!body.success) throw new KvboxError("expected {value, secret?}");
4594
+ await setBoxVar(ref, name, body.data.value, body.data.secret ?? false);
4595
+ const box = await getMachine(ref);
4596
+ return c.json({ box: ref.name, name, running: box.status !== "stopped" });
4597
+ });
4598
+ r.delete("/:name/env/:var", async (c) => {
4599
+ const ref = parseRef(c.req.param("name"), c.get("owner"));
4600
+ const name = c.req.param("var");
4601
+ await rmBoxVar(ref, name);
4602
+ const box = await getMachine(ref);
4603
+ return c.json({ box: ref.name, name, running: box.status !== "stopped" });
4604
+ });
4041
4605
  r.get("/:name/stats", async (c) => c.json(await machineStats(parseRef(c.req.param("name"), c.get("owner")))));
4042
4606
  r.delete("/:name", async (c) => {
4043
4607
  await destroyMachine(parseRef(c.req.param("name"), c.get("owner")));
@@ -4258,9 +4822,22 @@ program.command("start", { isDefault: true }).description("serve the API on the
4258
4822
  const cfg = await loadConfig(paths());
4259
4823
  const state = await ensureHostNetwork(cfg);
4260
4824
  console.log(`host network: bridge ${cfg.bridge} ${state}`);
4825
+ await pinRunningTaps(paths());
4261
4826
  } catch (err) {
4262
4827
  console.error(`warning: host network not ready (${err.message}); run: kvbox-server net up`);
4263
4828
  }
4829
+ let dnsWarned = false;
4830
+ const bindDns = () => {
4831
+ loadConfig(paths()).then(async (cfg) => {
4832
+ await startDns({ host: cfg.gateway });
4833
+ console.log(`box names: <name>.kvbox answered on ${cfg.gateway}`);
4834
+ }).catch((err) => {
4835
+ if (!dnsWarned) console.error(`warning: box names (<name>.kvbox) do not resolve yet (${err.message}); retrying`);
4836
+ dnsWarned = true;
4837
+ setTimeout(bindDns, DNS_RETRY_MS).unref();
4838
+ });
4839
+ };
4840
+ bindDns();
4264
4841
  startRelayWatch();
4265
4842
  startIdleWatch();
4266
4843
  const recovery2 = await bootRecovered(settled, paths());