@kvbox/server 0.5.26 → 0.5.28

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.
@@ -448,6 +448,9 @@ var PortsRequest = z3.object({
448
448
  ports: z3.array(z3.object({ guestPort: z3.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
449
449
  });
450
450
  var BoxPortSchema = z3.number().int().min(1).max(65535);
451
+ var MAX_BOX_LINKS = 32;
452
+ var BoxLinkSchema = z3.object({ from: z3.string(), port: BoxPortSchema });
453
+ var LinkRequest = z3.object({ from: z3.string().min(1), fromOwner: z3.string().optional(), port: BoxPortSchema });
451
454
  var ClaimSubdomainRequest = z3.object({ name: z3.string(), port: BoxPortSchema });
452
455
  var SubdomainPortRequest = z3.object({ port: BoxPortSchema });
453
456
  var SubdomainRouteRequest = z3.object({ name: z3.string(), port: BoxPortSchema });
@@ -459,6 +462,19 @@ var SubdomainSchema = z3.object({
459
462
  url: z3.string(),
460
463
  routes: z3.array(z3.object({ name: z3.string(), port: BoxPortSchema, url: z3.string() }))
461
464
  });
465
+ var AddDomainRequest = z3.object({ domain: z3.string(), port: BoxPortSchema.optional() });
466
+ var DomainSchema = z3.object({
467
+ owner: z3.string(),
468
+ box: z3.string(),
469
+ domain: z3.string(),
470
+ port: BoxPortSchema,
471
+ status: z3.enum(["pending", "live"]),
472
+ www: z3.boolean(),
473
+ url: z3.string(),
474
+ error: z3.string().nullable(),
475
+ records: z3.array(z3.object({ type: z3.enum(["A", "TXT", "CNAME"]), name: z3.string(), value: z3.string() })),
476
+ createdAt: z3.string()
477
+ });
462
478
  var MachineSchema = z3.object({
463
479
  /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
464
480
  id: z3.string(),
@@ -498,7 +514,9 @@ var MachineSchema = z3.object({
498
514
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
499
515
  autoHibernateSec: z3.number().int().positive().optional(),
500
516
  /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
501
- volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional()
517
+ volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional(),
518
+ /** Boxes that may reach this one, each on one port (#98). Absent: none. */
519
+ links: z3.array(BoxLinkSchema).optional()
502
520
  });
503
521
  var VolumeSchema = z3.object({
504
522
  /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
@@ -563,7 +581,12 @@ var CreateMachineRequest = z3.object({
563
581
  */
564
582
  sshKeys: z3.array(z3.string()).optional(),
565
583
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
566
- autoHibernateSec: z3.number().int().min(0).optional()
584
+ autoHibernateSec: z3.number().int().min(0).optional(),
585
+ /**
586
+ * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
587
+ * control plane reads it; a host has one place to put a box.
588
+ */
589
+ near: z3.string().optional()
567
590
  });
568
591
  var ForkMachineRequest = z3.object({
569
592
  name: z3.string().optional(),
@@ -607,7 +630,9 @@ var SnapshotSchema = z3.object({
607
630
  });
608
631
  var CreateSnapshotRequest = z3.object({
609
632
  box: z3.string(),
610
- name: z3.string()
633
+ name: z3.string(),
634
+ /** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
635
+ replace: z3.boolean().optional()
611
636
  });
612
637
  var DiskCapacitySchema = z3.object({
613
638
  totalGib: z3.number().int(),
@@ -1151,209 +1176,15 @@ async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
1151
1176
  );
1152
1177
  }
1153
1178
 
1154
- // src/core/machines.ts
1155
- import { spawn } from "node:child_process";
1156
- import { closeSync as closeSync2, existsSync as existsSync4, openSync as openSync2, statSync as statSync2 } from "node:fs";
1157
- import { link as link2, mkdir as mkdir6, readFile as readFile6, realpath, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1158
- import { basename } from "node:path";
1159
- import { setTimeout as sleep } from "node:timers/promises";
1179
+ // src/core/dns.ts
1180
+ import { createSocket } from "node:dgram";
1160
1181
 
1161
- // src/core/agent.ts
1162
- import { connect } from "node:net";
1163
- var AGENT_PORT = 52;
1164
- async function agentCall(udsPath, req, timeoutMs = 5e3) {
1165
- const reply = await new Promise((resolve, reject) => {
1166
- const sock = connect(udsPath);
1167
- let buf = "";
1168
- let handshaken = false;
1169
- const fail = (err) => {
1170
- sock.destroy();
1171
- reject(err);
1172
- };
1173
- sock.setTimeout(timeoutMs, () => fail(new KvboxError(handshaken ? `kvbox-agent did not answer within ${timeoutMs} ms` : `the guest did not accept the vsock connection within ${timeoutMs} ms`)));
1174
- sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
1175
- sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
1176
- `));
1177
- sock.on("data", (chunk) => {
1178
- buf += chunk.toString("utf8");
1179
- let nl;
1180
- while ((nl = buf.indexOf("\n")) !== -1) {
1181
- const line = buf.slice(0, nl);
1182
- buf = buf.slice(nl + 1);
1183
- if (!handshaken) {
1184
- if (!line.startsWith("OK ")) return fail(new KvboxError(`vsock connect refused: ${line}`));
1185
- handshaken = true;
1186
- sock.write(JSON.stringify(req) + "\n");
1187
- } else {
1188
- sock.end();
1189
- return resolve(line);
1190
- }
1191
- }
1192
- });
1193
- sock.once("close", () => {
1194
- if (!handshaken) fail(new KvboxError("vsock connection closed before the guest accepted"));
1195
- else fail(new KvboxError("kvbox-agent closed the connection without a reply"));
1196
- });
1197
- });
1198
- let parsed;
1199
- try {
1200
- parsed = JSON.parse(reply);
1201
- } catch {
1202
- throw new KvboxError(`kvbox-agent sent something that is not JSON: ${reply}`);
1203
- }
1204
- if (!parsed.ok) throw new KvboxError(`kvbox-agent: ${parsed.error}`);
1205
- return parsed;
1206
- }
1207
- function setIdentity(udsPath, id, timeoutMs) {
1208
- return agentCall(udsPath, { op: "identity", ...id }, timeoutMs);
1209
- }
1210
- function setAuthorizedKeys(udsPath, lines, timeoutMs) {
1211
- return agentCall(udsPath, { op: "authorizedKeys", lines: [...lines] }, timeoutMs);
1212
- }
1213
- async function stats(udsPath, timeoutMs) {
1214
- const reply = GuestStatsSchema.safeParse(await agentCall(udsPath, { op: "stats" }, timeoutMs));
1215
- if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? "invalid"}`);
1216
- return reply.data;
1217
- }
1218
- async function dropVolumes(udsPath, timeoutMs) {
1219
- const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
1220
- return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
1221
- }
1222
- function setEnv(udsPath, vars, timeoutMs) {
1223
- return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
1224
- }
1225
- var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
1226
- var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
1227
- var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
1228
-
1229
- // src/core/env.ts
1182
+ // src/core/state.ts
1183
+ import { randomBytes } from "node:crypto";
1184
+ import { readFileSync } from "node:fs";
1230
1185
  import { mkdir as mkdir2, readFile as readFile4, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
1231
1186
  import { z as z4 } from "zod";
1232
1187
 
1233
- // ../shared/src/env.ts
1234
- var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
1235
- var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
1236
- var ENV_MAX_VALUE_BYTES = 4096;
1237
- var ENV_MAX_VARS = 100;
1238
- function envNameProblem(name) {
1239
- if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
1240
- if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
1241
- if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
1242
- return null;
1243
- }
1244
- function envValueProblem(value) {
1245
- if (/[\n\r\0]/.test(value)) return "a value is one line: no line breaks (base64 a multi-line value such as a key file)";
1246
- if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
1247
- return null;
1248
- }
1249
-
1250
- // src/core/locks.ts
1251
- import { AsyncLocalStorage } from "node:async_hooks";
1252
- var tails = /* @__PURE__ */ new Map();
1253
- var held = new AsyncLocalStorage();
1254
- function withBoxLock(ref, fn) {
1255
- return withLock(refKey(ref), fn);
1256
- }
1257
- function withHostLock(name, fn) {
1258
- return withLock(`host:${name}`, fn);
1259
- }
1260
- async function withLock(key, fn) {
1261
- const mine = held.getStore();
1262
- if (mine?.has(key)) return fn();
1263
- const previous = tails.get(key);
1264
- let release;
1265
- const tail = new Promise((resolve) => release = resolve);
1266
- tails.set(key, tail);
1267
- try {
1268
- await previous;
1269
- return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
1270
- } finally {
1271
- release();
1272
- if (tails.get(key) === tail) tails.delete(key);
1273
- }
1274
- }
1275
- function boxBusy(ref) {
1276
- return tails.has(refKey(ref));
1277
- }
1278
- function locked(fn) {
1279
- return (...args) => withBoxLock(args[0], () => fn(...args));
1280
- }
1281
-
1282
- // src/core/env.ts
1283
- var OwnerEnvSchema = z4.object({
1284
- /** The control plane's counter for the list; only ever grows. */
1285
- version: z4.number().int().min(0),
1286
- vars: z4.array(z4.object({ name: z4.string(), value: z4.string() }))
1287
- });
1288
- async function readOwnerEnv(owner, p = paths()) {
1289
- try {
1290
- return OwnerEnvSchema.parse(JSON.parse(await readFile4(p.ownerEnv(owner), "utf8")));
1291
- } catch (err) {
1292
- if (err.code === "ENOENT") return null;
1293
- throw err;
1294
- }
1295
- }
1296
- async function envForBoot(owner, p = paths()) {
1297
- const env = await readOwnerEnv(owner, p).catch(() => null);
1298
- if (env !== null) return env.vars;
1299
- return realmOf(owner) !== null ? [] : null;
1300
- }
1301
- async function setOwnerEnv(owner, req, p = paths()) {
1302
- if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
1303
- if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
1304
- const seen = /* @__PURE__ */ new Set();
1305
- for (const v of req.vars) {
1306
- const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
1307
- if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
1308
- if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);
1309
- seen.add(v.name);
1310
- }
1311
- return withHostLock("env", async () => {
1312
- const have = await readOwnerEnv(owner, p);
1313
- if (have !== null && have.version > req.version) return { version: have.version };
1314
- const file = p.ownerEnv(owner);
1315
- await mkdir2(p.env, { recursive: true, mode: 448 });
1316
- const tmp = `${file}.tmp`;
1317
- await writeFile2(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
1318
- await rename2(tmp, file);
1319
- return { version: req.version };
1320
- });
1321
- }
1322
- async function listEnvVersions(scope, p = paths()) {
1323
- let files;
1324
- try {
1325
- files = await readdir(p.env);
1326
- } catch (err) {
1327
- if (err.code === "ENOENT") return [];
1328
- throw err;
1329
- }
1330
- const out = [];
1331
- for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
1332
- const owner = file.slice(0, -".json".length);
1333
- if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;
1334
- const env = await readOwnerEnv(owner, p).catch(() => null);
1335
- if (env !== null) out.push({ owner, version: env.version });
1336
- }
1337
- return out;
1338
- }
1339
-
1340
- // src/core/volumes.ts
1341
- import { existsSync, statSync } from "node:fs";
1342
- import { lstat, mkdir as mkdir4, readdir as readdir3, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
1343
-
1344
- // ../shared/src/capacity.ts
1345
- var MEM_HEADROOM_MIB = 2048;
1346
- function sellableGib(d) {
1347
- return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);
1348
- }
1349
- function volumeRoomGib(d) {
1350
- return Math.max(0, sellableGib(d) - d.volumesGib);
1351
- }
1352
- function hasDiskRoom(d, sizeGib) {
1353
- return sizeGib <= volumeRoomGib(d);
1354
- }
1355
- var VCPU_OVERSUBSCRIPTION = 2;
1356
-
1357
1188
  // src/core/db.ts
1358
1189
  import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs";
1359
1190
  import { dirname } from "node:path";
@@ -1489,75 +1320,79 @@ function volumeEventsInScope(scope, window, p = paths()) {
1489
1320
  }
1490
1321
 
1491
1322
  // src/core/state.ts
1492
- import { randomBytes } from "node:crypto";
1493
- import { readFileSync } from "node:fs";
1494
- import { mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1495
- import { z as z5 } from "zod";
1496
- var MachineMetaSchema = z5.object({
1323
+ var MachineMetaSchema = z4.object({
1497
1324
  /** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */
1498
- id: z5.string(),
1499
- name: z5.string(),
1325
+ id: z4.string(),
1326
+ name: z4.string(),
1500
1327
  /** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */
1501
- owner: z5.string(),
1502
- ip: z5.string(),
1503
- mac: z5.string(),
1504
- pid: z5.number().int().nullable(),
1328
+ owner: z4.string(),
1329
+ ip: z4.string(),
1330
+ mac: z4.string(),
1331
+ pid: z4.number().int().nullable(),
1505
1332
  // null: stopped on purpose, disk kept
1506
1333
  /**
1507
1334
  * The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot
1508
1335
  * the number can name some other process; a pid from another boot is dead whatever `kill -0` says.
1509
1336
  * Absent (boxes launched before #29): the pid alone decides.
1510
1337
  */
1511
- bootId: z5.string().optional(),
1512
- vcpu: z5.number().int(),
1513
- memMib: z5.number().int(),
1514
- createdAt: z5.string(),
1515
- source: z5.string(),
1338
+ bootId: z4.string().optional(),
1339
+ vcpu: z4.number().int(),
1340
+ memMib: z4.number().int(),
1341
+ createdAt: z4.string(),
1342
+ source: z4.string(),
1516
1343
  /** Base image version (assets/rootfs-<version>.ext4) the box's overlay stacks on. */
1517
- base: z5.string(),
1344
+ base: z4.string(),
1518
1345
  /**
1519
1346
  * Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
1520
1347
  * each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
1521
1348
  * is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.
1522
1349
  */
1523
- memSnapshots: z5.number().int().optional(),
1350
+ memSnapshots: z4.number().int().optional(),
1524
1351
  /** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */
1525
- paused: z5.boolean().optional(),
1352
+ paused: z4.boolean().optional(),
1526
1353
  /**
1527
1354
  * authorized_keys lines the box gets on top of the host's own key, as the control plane sent them
1528
1355
  * at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so
1529
1356
  * `start` has to send the same lines again. Absent: host key only.
1530
1357
  */
1531
- sshKeys: z5.array(z5.string()).optional(),
1358
+ sshKeys: z4.array(z4.string()).optional(),
1532
1359
  /**
1533
1360
  * The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,
1534
1361
  * or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.
1535
1362
  */
1536
- sshKeysStale: z5.boolean().optional(),
1363
+ sshKeysStale: z4.boolean().optional(),
1537
1364
  /** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */
1538
- sshPort: z5.number().int().optional(),
1365
+ sshPort: z4.number().int().optional(),
1539
1366
  /**
1540
1367
  * Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,
1541
1368
  * each host port the box's for its life. DNATed while the box runs, rebuilt from here with its
1542
1369
  * current IP every time it comes up. Absent: none.
1543
1370
  */
1544
- ports: z5.array(z5.object({ guestPort: z5.number().int(), hostPort: z5.number().int(), proto: z5.enum(["tcp", "udp"]) })).optional(),
1371
+ ports: z4.array(z4.object({ guestPort: z4.number().int(), hostPort: z4.number().int(), proto: z4.enum(["tcp", "udp"]) })).optional(),
1545
1372
  /** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
1546
- autoHibernateSec: z5.number().int().positive().optional(),
1373
+ autoHibernateSec: z4.number().int().positive().optional(),
1547
1374
  /**
1548
1375
  * Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
1549
1376
  * their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
1550
1377
  * volume's meta.json does not say. Absent: none.
1551
1378
  */
1552
- volumes: z5.array(z5.string()).optional()
1379
+ volumes: z4.array(z4.string()).optional(),
1380
+ /**
1381
+ * Links into this box (#98, `kvbox vm link`): box `owner/name`, at `ip`, may open TCP connections to
1382
+ * `port`. The rule is open while this box runs, rebuilt from here at every boot; `ip` is the other
1383
+ * box's, fixed for its life, and checked against its meta.json before a rule opens. `stale`: that box
1384
+ * was removed but the rule would not close; kept only so this box's next stop closes it, never opened
1385
+ * again, never listed (a new box of the same name may get the same IP). Absent: none.
1386
+ */
1387
+ links: z4.array(z4.object({ owner: z4.string(), name: z4.string(), ip: z4.string(), port: z4.number().int(), stale: z4.literal(true).optional() })).optional()
1553
1388
  });
1554
- var VolumeMetaSchema = z5.object({
1389
+ var VolumeMetaSchema = z4.object({
1555
1390
  /** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
1556
- id: z5.string(),
1557
- name: z5.string(),
1558
- owner: z5.string(),
1559
- sizeGib: z5.number().int(),
1560
- createdAt: z5.string()
1391
+ id: z4.string(),
1392
+ name: z4.string(),
1393
+ owner: z4.string(),
1394
+ sizeGib: z4.number().int(),
1395
+ createdAt: z4.string()
1561
1396
  });
1562
1397
  function newBoxId(taken) {
1563
1398
  for (; ; ) {
@@ -1565,35 +1400,35 @@ function newBoxId(taken) {
1565
1400
  if (!taken.has(id)) return id;
1566
1401
  }
1567
1402
  }
1568
- var SnapshotMetaSchema = z5.object({
1569
- name: z5.string(),
1570
- owner: z5.string(),
1403
+ var SnapshotMetaSchema = z4.object({
1404
+ name: z4.string(),
1405
+ owner: z4.string(),
1571
1406
  /** The box it was taken from, as owner/name. */
1572
- source: z5.string(),
1573
- base: z5.string(),
1574
- vcpu: z5.number().int(),
1575
- memMib: z5.number().int(),
1576
- sizeBytes: z5.number().int(),
1577
- createdAt: z5.string(),
1407
+ source: z4.string(),
1408
+ base: z4.string(),
1409
+ vcpu: z4.number().int(),
1410
+ memMib: z4.number().int(),
1411
+ sizeBytes: z4.number().int(),
1412
+ createdAt: z4.string(),
1578
1413
  /**
1579
1414
  * The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
1580
1415
  * and their mounts in the memory image, but their data is not here. A box restored from the snapshot
1581
1416
  * gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
1582
1417
  */
1583
- volumes: z5.array(z5.object({ name: z5.string(), sizeGib: z5.number().int() })).optional()
1418
+ volumes: z4.array(z4.object({ name: z4.string(), sizeGib: z4.number().int() })).optional()
1584
1419
  });
1585
1420
  async function ensureLayout(p = paths()) {
1586
1421
  for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
1587
- await mkdir3(dir, { recursive: true, mode: 448 });
1422
+ await mkdir2(dir, { recursive: true, mode: 448 });
1588
1423
  }
1589
1424
  return p;
1590
1425
  }
1591
1426
  async function readJson(file, schema) {
1592
- return schema.parse(JSON.parse(await readFile5(file, "utf8")));
1427
+ return schema.parse(JSON.parse(await readFile4(file, "utf8")));
1593
1428
  }
1594
1429
  async function listDirs(dir) {
1595
1430
  try {
1596
- const entries = await readdir2(dir, { withFileTypes: true });
1431
+ const entries = await readdir(dir, { withFileTypes: true });
1597
1432
  return entries.filter((e) => e.isDirectory()).map((e) => e.name);
1598
1433
  } catch (err) {
1599
1434
  if (err.code === "ENOENT") return [];
@@ -1603,12 +1438,16 @@ async function listDirs(dir) {
1603
1438
  async function readMachineMeta(ref, p = paths()) {
1604
1439
  return readJson(p.machine(ref.owner, ref.name).meta, MachineMetaSchema);
1605
1440
  }
1441
+ var boxListVersion = 0;
1442
+ var boxListVersionNow = () => boxListVersion;
1443
+ var boxListChanged = () => void (boxListVersion += 1);
1606
1444
  async function writeMachineMeta(meta, p = paths()) {
1607
1445
  const m = p.machine(meta.owner, meta.name);
1608
- await mkdir3(m.dir, { recursive: true });
1446
+ await mkdir2(m.dir, { recursive: true });
1609
1447
  const tmp = `${m.meta}.tmp`;
1610
- await writeFile3(tmp, JSON.stringify(meta, null, 2) + "\n");
1611
- await rename3(tmp, m.meta);
1448
+ await writeFile2(tmp, JSON.stringify(meta, null, 2) + "\n");
1449
+ await rename2(tmp, m.meta);
1450
+ boxListChanged();
1612
1451
  }
1613
1452
  async function listMachineRefs(p = paths()) {
1614
1453
  return listRefs(p.machines);
@@ -1616,21 +1455,20 @@ async function listMachineRefs(p = paths()) {
1616
1455
  async function readSnapshotMeta(ref, p = paths()) {
1617
1456
  return readJson(p.snapshot(ref.owner, ref.name).meta, SnapshotMetaSchema);
1618
1457
  }
1619
- async function writeSnapshotMeta(meta, p = paths()) {
1620
- const s = p.snapshot(meta.owner, meta.name);
1621
- await mkdir3(s.dir, { recursive: true });
1622
- await writeFile3(s.meta, JSON.stringify(meta, null, 2) + "\n");
1458
+ async function writeSnapshotMeta(meta, p = paths(), s = p.snapshot(meta.owner, meta.name)) {
1459
+ await mkdir2(s.dir, { recursive: true });
1460
+ await writeFile2(s.meta, JSON.stringify(meta, null, 2) + "\n");
1623
1461
  }
1624
1462
  async function listSnapshotRefs(p = paths()) {
1625
- return listRefs(p.snapshots);
1463
+ return (await listRefs(p.snapshots)).filter((ref) => !ref.name.startsWith("."));
1626
1464
  }
1627
1465
  async function readVolumeMeta(ref, p = paths()) {
1628
- const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z5.string().optional() }));
1466
+ const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z4.string().optional() }));
1629
1467
  if (raw.id !== void 0) return { ...raw, id: raw.id };
1630
1468
  const taken = /* @__PURE__ */ new Set();
1631
1469
  for (const other of await listVolumeRefs(p)) {
1632
1470
  try {
1633
- const j = JSON.parse(await readFile5(p.volume(other.owner, other.name).meta, "utf8"));
1471
+ const j = JSON.parse(await readFile4(p.volume(other.owner, other.name).meta, "utf8"));
1634
1472
  if (typeof j.id === "string") taken.add(j.id);
1635
1473
  } catch {
1636
1474
  }
@@ -1642,8 +1480,8 @@ async function readVolumeMeta(ref, p = paths()) {
1642
1480
  }
1643
1481
  async function writeVolumeMeta(meta, p = paths()) {
1644
1482
  const v = p.volume(meta.owner, meta.name);
1645
- await mkdir3(v.dir, { recursive: true, mode: 448 });
1646
- await writeFile3(v.meta, JSON.stringify(meta, null, 2) + "\n");
1483
+ await mkdir2(v.dir, { recursive: true, mode: 448 });
1484
+ await writeFile2(v.meta, JSON.stringify(meta, null, 2) + "\n");
1647
1485
  }
1648
1486
  async function listVolumeRefs(p = paths()) {
1649
1487
  return listRefs(p.volumes);
@@ -1690,6 +1528,324 @@ function hostBootTime() {
1690
1528
  }
1691
1529
  }
1692
1530
 
1531
+ // src/core/dns.ts
1532
+ var DNS_PORT = 10053;
1533
+ var DNS_SUFFIX = ".kvbox";
1534
+ var DNS_RETRY_MS = 1e4;
1535
+ var TTL_SEC = 5;
1536
+ var BOXES_FRESH_MS = 6e4;
1537
+ var TYPE_A = 1;
1538
+ var CLASS_IN = 1;
1539
+ var RCODE = { ok: 0, nxDomain: 3, refused: 5 };
1540
+ function parseQuery(msg) {
1541
+ if (msg.length < 12) return null;
1542
+ const flags = msg.readUInt16BE(2);
1543
+ const isResponse = flags & 32768;
1544
+ const opcode = flags >> 11 & 15;
1545
+ if (isResponse || opcode !== 0 || msg.readUInt16BE(4) < 1) return null;
1546
+ const labels = [];
1547
+ let at = 12;
1548
+ for (; ; ) {
1549
+ if (at >= msg.length) return null;
1550
+ const len = msg[at];
1551
+ at += 1;
1552
+ if (len === 0) break;
1553
+ if (len > 63 || at + len > msg.length) return null;
1554
+ labels.push(msg.subarray(at, at + len).toString("latin1"));
1555
+ at += len;
1556
+ }
1557
+ if (at + 4 > msg.length) return null;
1558
+ return {
1559
+ id: msg.readUInt16BE(0),
1560
+ rd: Boolean(flags & 256),
1561
+ name: labels.join(".").toLowerCase(),
1562
+ type: msg.readUInt16BE(at),
1563
+ class: msg.readUInt16BE(at + 2),
1564
+ question: msg.subarray(12, at + 4)
1565
+ };
1566
+ }
1567
+ function buildAnswer(q, rcode, ip) {
1568
+ const header = Buffer.alloc(12);
1569
+ header.writeUInt16BE(q.id, 0);
1570
+ header.writeUInt16BE(32768 | 1024 | (q.rd ? 256 : 0) | rcode, 2);
1571
+ header.writeUInt16BE(1, 4);
1572
+ header.writeUInt16BE(ip ? 1 : 0, 6);
1573
+ if (!ip) return Buffer.concat([header, q.question]);
1574
+ const rr = Buffer.alloc(16);
1575
+ rr.writeUInt16BE(49164, 0);
1576
+ rr.writeUInt16BE(TYPE_A, 2);
1577
+ rr.writeUInt16BE(CLASS_IN, 4);
1578
+ rr.writeUInt32BE(TTL_SEC, 6);
1579
+ rr.writeUInt16BE(4, 10);
1580
+ ip.split(".").forEach((o, i) => rr.writeUInt8(Number(o), 12 + i));
1581
+ return Buffer.concat([header, q.question, rr]);
1582
+ }
1583
+ var slugOf = (owner) => owner.split("@")[0].toLowerCase();
1584
+ var isOurs = (q) => q.class === CLASS_IN && q.name.endsWith(DNS_SUFFIX);
1585
+ function answerFor(q, asker, boxes) {
1586
+ if (!isOurs(q)) return { rcode: RCODE.refused };
1587
+ const [name, slug, ...rest] = q.name.slice(0, -DNS_SUFFIX.length).split(".");
1588
+ const from = boxes.find((b) => b.ip === asker);
1589
+ let box;
1590
+ if (from && rest.length === 0) {
1591
+ 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));
1592
+ }
1593
+ if (!box) return { rcode: RCODE.nxDomain };
1594
+ return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };
1595
+ }
1596
+ async function boxAddresses(p) {
1597
+ const out = [];
1598
+ for (const ref of await listMachineRefs(p)) {
1599
+ const meta = await readMachineMeta(ref, p).catch(() => null);
1600
+ if (meta) out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {} });
1601
+ }
1602
+ return out;
1603
+ }
1604
+ function sharedBoxes(load, freshMs = BOXES_FRESH_MS, version = boxListVersionNow) {
1605
+ let last = null;
1606
+ return () => {
1607
+ if (!last || last.version !== version() || Date.now() - last.at > freshMs) {
1608
+ const entry = { at: Date.now(), version: version(), list: load() };
1609
+ last = entry;
1610
+ entry.list.catch(() => {
1611
+ if (last === entry) last = null;
1612
+ });
1613
+ }
1614
+ return last.list;
1615
+ };
1616
+ }
1617
+ async function startDns(opts) {
1618
+ const p = opts.p ?? paths();
1619
+ const boxes = sharedBoxes(opts.boxes ?? (() => boxAddresses(p)));
1620
+ const socket = createSocket("udp4");
1621
+ socket.on("message", (msg, rinfo) => {
1622
+ const q = parseQuery(msg);
1623
+ if (!q) return;
1624
+ const reply = (a) => socket.send(buildAnswer(q, a.rcode, a.ip), rinfo.port, rinfo.address);
1625
+ if (!isOurs(q)) return reply({ rcode: RCODE.refused });
1626
+ void boxes().then((list) => answerFor(q, rinfo.address, list)).catch(() => ({ rcode: RCODE.refused })).then(reply);
1627
+ });
1628
+ await new Promise((resolve, reject) => {
1629
+ socket.once("error", (err) => {
1630
+ socket.close();
1631
+ reject(err);
1632
+ });
1633
+ socket.bind(opts.port ?? DNS_PORT, opts.host, () => {
1634
+ socket.removeAllListeners("error");
1635
+ socket.on("error", () => {
1636
+ });
1637
+ resolve();
1638
+ });
1639
+ });
1640
+ return { socket, close: () => new Promise((resolve) => socket.close(() => resolve())) };
1641
+ }
1642
+
1643
+ // src/core/machines.ts
1644
+ import { spawn } from "node:child_process";
1645
+ import { closeSync as closeSync2, existsSync as existsSync4, openSync as openSync2, statSync as statSync2 } from "node:fs";
1646
+ import { link as link2, mkdir as mkdir6, readFile as readFile6, realpath, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1647
+ import { basename } from "node:path";
1648
+ import { setTimeout as sleep } from "node:timers/promises";
1649
+
1650
+ // src/core/agent.ts
1651
+ import { connect } from "node:net";
1652
+ var AGENT_PORT = 52;
1653
+ async function agentCall(udsPath, req, timeoutMs = 5e3) {
1654
+ const reply = await new Promise((resolve, reject) => {
1655
+ const sock = connect(udsPath);
1656
+ let buf = "";
1657
+ let handshaken = false;
1658
+ const fail = (err) => {
1659
+ sock.destroy();
1660
+ reject(err);
1661
+ };
1662
+ 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`)));
1663
+ sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
1664
+ sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
1665
+ `));
1666
+ sock.on("data", (chunk) => {
1667
+ buf += chunk.toString("utf8");
1668
+ let nl;
1669
+ while ((nl = buf.indexOf("\n")) !== -1) {
1670
+ const line = buf.slice(0, nl);
1671
+ buf = buf.slice(nl + 1);
1672
+ if (!handshaken) {
1673
+ if (!line.startsWith("OK ")) return fail(new KvboxError(`vsock connect refused: ${line}`));
1674
+ handshaken = true;
1675
+ sock.write(JSON.stringify(req) + "\n");
1676
+ } else {
1677
+ sock.end();
1678
+ return resolve(line);
1679
+ }
1680
+ }
1681
+ });
1682
+ sock.once("close", () => {
1683
+ if (!handshaken) fail(new KvboxError("vsock connection closed before the guest accepted"));
1684
+ else fail(new KvboxError("kvbox-agent closed the connection without a reply"));
1685
+ });
1686
+ });
1687
+ let parsed;
1688
+ try {
1689
+ parsed = JSON.parse(reply);
1690
+ } catch {
1691
+ throw new KvboxError(`kvbox-agent sent something that is not JSON: ${reply}`);
1692
+ }
1693
+ if (!parsed.ok) throw new KvboxError(`kvbox-agent: ${parsed.error}`);
1694
+ return parsed;
1695
+ }
1696
+ function setIdentity(udsPath, id, timeoutMs) {
1697
+ return agentCall(udsPath, { op: "identity", ...id }, timeoutMs);
1698
+ }
1699
+ function setAuthorizedKeys(udsPath, lines, timeoutMs) {
1700
+ return agentCall(udsPath, { op: "authorizedKeys", lines: [...lines] }, timeoutMs);
1701
+ }
1702
+ async function stats(udsPath, timeoutMs) {
1703
+ const reply = GuestStatsSchema.safeParse(await agentCall(udsPath, { op: "stats" }, timeoutMs));
1704
+ if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? "invalid"}`);
1705
+ return reply.data;
1706
+ }
1707
+ async function dropVolumes(udsPath, timeoutMs) {
1708
+ const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
1709
+ return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
1710
+ }
1711
+ function setEnv(udsPath, vars, timeoutMs) {
1712
+ return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
1713
+ }
1714
+ var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
1715
+ var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
1716
+ var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
1717
+
1718
+ // src/core/env.ts
1719
+ import { mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1720
+ import { z as z5 } from "zod";
1721
+
1722
+ // ../shared/src/env.ts
1723
+ var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
1724
+ var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
1725
+ var ENV_MAX_VALUE_BYTES = 4096;
1726
+ var ENV_MAX_VARS = 100;
1727
+ function envNameProblem(name) {
1728
+ if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
1729
+ if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
1730
+ if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
1731
+ return null;
1732
+ }
1733
+ function envValueProblem(value) {
1734
+ 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)";
1735
+ if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
1736
+ return null;
1737
+ }
1738
+
1739
+ // src/core/locks.ts
1740
+ import { AsyncLocalStorage } from "node:async_hooks";
1741
+ var tails = /* @__PURE__ */ new Map();
1742
+ var held = new AsyncLocalStorage();
1743
+ function withBoxLock(ref, fn) {
1744
+ return withLock(refKey(ref), fn);
1745
+ }
1746
+ function withSnapshotLock(ref, fn) {
1747
+ return withLock(`snapshot:${refKey(ref)}`, fn);
1748
+ }
1749
+ function withHostLock(name, fn) {
1750
+ return withLock(`host:${name}`, fn);
1751
+ }
1752
+ async function withLock(key, fn) {
1753
+ const mine = held.getStore();
1754
+ if (mine?.has(key)) return fn();
1755
+ const previous = tails.get(key);
1756
+ let release;
1757
+ const tail = new Promise((resolve) => release = resolve);
1758
+ tails.set(key, tail);
1759
+ try {
1760
+ await previous;
1761
+ return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
1762
+ } finally {
1763
+ release();
1764
+ if (tails.get(key) === tail) tails.delete(key);
1765
+ }
1766
+ }
1767
+ function boxBusy(ref) {
1768
+ return tails.has(refKey(ref));
1769
+ }
1770
+ function locked(fn) {
1771
+ return (...args) => withBoxLock(args[0], () => fn(...args));
1772
+ }
1773
+
1774
+ // src/core/env.ts
1775
+ var OwnerEnvSchema = z5.object({
1776
+ /** The control plane's counter for the list; only ever grows. */
1777
+ version: z5.number().int().min(0),
1778
+ vars: z5.array(z5.object({ name: z5.string(), value: z5.string() }))
1779
+ });
1780
+ async function readOwnerEnv(owner, p = paths()) {
1781
+ try {
1782
+ return OwnerEnvSchema.parse(JSON.parse(await readFile5(p.ownerEnv(owner), "utf8")));
1783
+ } catch (err) {
1784
+ if (err.code === "ENOENT") return null;
1785
+ throw err;
1786
+ }
1787
+ }
1788
+ async function envForBoot(owner, p = paths()) {
1789
+ const env = await readOwnerEnv(owner, p).catch(() => null);
1790
+ if (env !== null) return env.vars;
1791
+ return realmOf(owner) !== null ? [] : null;
1792
+ }
1793
+ async function setOwnerEnv(owner, req, p = paths()) {
1794
+ if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
1795
+ if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
1796
+ const seen = /* @__PURE__ */ new Set();
1797
+ for (const v of req.vars) {
1798
+ const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
1799
+ if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
1800
+ if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);
1801
+ seen.add(v.name);
1802
+ }
1803
+ return withHostLock("env", async () => {
1804
+ const have = await readOwnerEnv(owner, p);
1805
+ if (have !== null && have.version > req.version) return { version: have.version };
1806
+ const file = p.ownerEnv(owner);
1807
+ await mkdir3(p.env, { recursive: true, mode: 448 });
1808
+ const tmp = `${file}.tmp`;
1809
+ await writeFile3(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
1810
+ await rename3(tmp, file);
1811
+ return { version: req.version };
1812
+ });
1813
+ }
1814
+ async function listEnvVersions(scope, p = paths()) {
1815
+ let files;
1816
+ try {
1817
+ files = await readdir2(p.env);
1818
+ } catch (err) {
1819
+ if (err.code === "ENOENT") return [];
1820
+ throw err;
1821
+ }
1822
+ const out = [];
1823
+ for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
1824
+ const owner = file.slice(0, -".json".length);
1825
+ if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;
1826
+ const env = await readOwnerEnv(owner, p).catch(() => null);
1827
+ if (env !== null) out.push({ owner, version: env.version });
1828
+ }
1829
+ return out;
1830
+ }
1831
+
1832
+ // src/core/volumes.ts
1833
+ import { existsSync, statSync } from "node:fs";
1834
+ import { lstat, mkdir as mkdir4, readdir as readdir3, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
1835
+
1836
+ // ../shared/src/capacity.ts
1837
+ var MEM_HEADROOM_MIB = 2048;
1838
+ function sellableGib(d) {
1839
+ return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);
1840
+ }
1841
+ function volumeRoomGib(d) {
1842
+ return Math.max(0, sellableGib(d) - d.volumesGib);
1843
+ }
1844
+ function hasDiskRoom(d, sizeGib) {
1845
+ return sizeGib <= volumeRoomGib(d);
1846
+ }
1847
+ var VCPU_OVERSUBSCRIPTION = 2;
1848
+
1693
1849
  // src/core/volumes.ts
1694
1850
  var volumeLabel = (name) => `kv:${name}`;
1695
1851
  function toVolume(meta, attachedTo, p) {
@@ -2135,9 +2291,11 @@ async function snapshotBox(ref, req, owner, p) {
2135
2291
  }
2136
2292
  throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);
2137
2293
  }
2138
- const s = p.snapshot(owner, req.name);
2139
- if (existsSync2(s.dir)) throw new KvboxError(`snapshot ${req.name} already exists`);
2294
+ const final = p.snapshot(owner, req.name);
2295
+ if (existsSync2(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
2296
+ const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
2140
2297
  const cfg = await loadConfig(p);
2298
+ if (s !== final) await rm2(s.dir, { recursive: true, force: true });
2141
2299
  await mkdir5(s.dir, { recursive: true, mode: 448 });
2142
2300
  try {
2143
2301
  const volumes = await captureDrivesOf(box, p);
@@ -2153,13 +2311,30 @@ async function snapshotBox(ref, req, owner, p) {
2153
2311
  sizeBytes: await usedBytes(s.dir),
2154
2312
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
2155
2313
  };
2156
- await writeSnapshotMeta(meta, p);
2314
+ await writeSnapshotMeta(meta, p, s);
2315
+ if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);
2157
2316
  return toSnapshot(meta);
2158
2317
  } catch (err) {
2159
2318
  await rm2(s.dir, { recursive: true, force: true });
2160
2319
  throw err;
2161
2320
  }
2162
2321
  }
2322
+ async function swapIn(ref, from, boxId, p) {
2323
+ const to = p.snapshot(ref.owner, ref.name).dir;
2324
+ const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
2325
+ await withSnapshotLock(ref, async () => {
2326
+ await rm2(old, { recursive: true, force: true });
2327
+ const hadOld = existsSync2(to);
2328
+ if (hadOld) await rename4(to, old);
2329
+ try {
2330
+ await rename4(from, to);
2331
+ } catch (err) {
2332
+ if (hadOld) await rename4(old, to);
2333
+ throw err;
2334
+ }
2335
+ });
2336
+ await rm2(old, { recursive: true, force: true });
2337
+ }
2163
2338
  async function captureBox(box, to, cfg, p) {
2164
2339
  const m = p.machine(box.owner, box.name);
2165
2340
  const fc = new FirecrackerClient(m.sock);
@@ -2205,8 +2380,8 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
2205
2380
  }
2206
2381
  async function deleteSnapshot(ref, p = paths()) {
2207
2382
  const dir = p.snapshot(ref.owner, ref.name).dir;
2208
- if (!existsSync2(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
2209
- await rm2(dir, { recursive: true, force: true });
2383
+ if (ref.name.startsWith(".") || !existsSync2(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
2384
+ await withSnapshotLock(ref, () => rm2(dir, { recursive: true, force: true }));
2210
2385
  }
2211
2386
 
2212
2387
  // src/core/network.ts
@@ -2250,12 +2425,15 @@ async function ensureHostNetwork(cfg) {
2250
2425
  return "created";
2251
2426
  }
2252
2427
  async function createTap(box, cfg, opts = {}) {
2253
- const tap = tapName(box);
2254
- await netRun(cfg, ["tap", "add", tap, ...opts.detached ? ["detached"] : []]);
2428
+ const tap = tapName(box.id);
2429
+ await netRun(cfg, ["tap", "add", tap, box.ip, box.mac, ...opts.detached ? ["detached"] : []]);
2255
2430
  return tap;
2256
2431
  }
2257
2432
  async function attachTap(box, cfg) {
2258
- await netRun(cfg, ["tap", "attach", tapName(box)]);
2433
+ await netRun(cfg, ["tap", "attach", tapName(box.id), box.ip, box.mac]);
2434
+ }
2435
+ async function pinTap(box, cfg) {
2436
+ await netRun(cfg, ["tap", "pin", tapName(box.id), box.ip, box.mac]);
2259
2437
  }
2260
2438
  async function deleteTap(box, cfg) {
2261
2439
  await netRun(cfg, ["tap", "del", tapName(box)]);
@@ -2300,6 +2478,13 @@ var proxyArgs = (p) => [p.box, p.boxIp, String(p.hostPort), String(p.guestPort),
2300
2478
  async function openProxy(proxy, cfg) {
2301
2479
  await netRun(cfg, ["proxy", "add", ...proxyArgs(proxy)]);
2302
2480
  }
2481
+ var linkArgs = (l) => [l.box, l.fromIp, l.toIp, String(l.port)];
2482
+ async function openLink(link3, cfg) {
2483
+ await netRun(cfg, ["link", "add", ...linkArgs(link3)]);
2484
+ }
2485
+ async function closeLink(link3, cfg) {
2486
+ await netRun(cfg, ["link", "rm", ...linkArgs(link3)]);
2487
+ }
2303
2488
  async function closeProxy(proxy, cfg) {
2304
2489
  await netRun(cfg, ["proxy", "rm", ...proxyArgs(proxy)]);
2305
2490
  }
@@ -2335,13 +2520,29 @@ function boxProxies(meta) {
2335
2520
  const ssh = meta.sshPort === void 0 ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];
2336
2521
  return [...ssh, ...(meta.ports ?? []).map((f) => ({ box: meta.id, boxIp: meta.ip, hostPort: f.hostPort, guestPort: f.guestPort, proto: f.proto }))];
2337
2522
  }
2338
- async function openPorts(meta, cfg) {
2523
+ function boxLinks(meta) {
2524
+ return (meta.links ?? []).map((l) => ({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }));
2525
+ }
2526
+ async function standingLinks(meta, p) {
2527
+ const links = boxLinks(meta);
2528
+ const stands = await Promise.all(
2529
+ (meta.links ?? []).map(async (l) => !l.stale && (await readMachineMeta({ owner: l.owner, name: l.name }, p).catch(() => null))?.ip === l.ip)
2530
+ );
2531
+ return links.filter((_, i) => stands[i]);
2532
+ }
2533
+ async function openPorts(meta, cfg, p) {
2339
2534
  for (const proxy of boxProxies(meta)) await openProxy(proxy, cfg);
2535
+ for (const link3 of await standingLinks(meta, p)) {
2536
+ await openLink(link3, cfg).catch((err) => console.error(`warning: could not open the link from ${link3.fromIp}: ${err.message}`));
2537
+ }
2340
2538
  }
2341
2539
  async function closePorts(meta, cfg) {
2342
2540
  for (const proxy of boxProxies(meta)) {
2343
2541
  await closeProxy(proxy, cfg).catch((err) => console.error(`warning: could not close port ${proxy.hostPort}: ${err.message}`));
2344
2542
  }
2543
+ for (const link3 of boxLinks(meta)) {
2544
+ await closeLink(link3, cfg).catch((err) => console.error(`warning: could not close the link from ${link3.fromIp}: ${err.message}`));
2545
+ }
2345
2546
  }
2346
2547
  var reservedPorts = /* @__PURE__ */ new Set();
2347
2548
  async function drawPorts(count, p) {
@@ -2416,9 +2617,11 @@ function toMachine(meta, p = paths()) {
2416
2617
  ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
2417
2618
  ...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
2418
2619
  ...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
2419
- ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {}
2620
+ ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
2621
+ ...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
2420
2622
  };
2421
2623
  }
2624
+ var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
2422
2625
  function autoHibernateFor(req, cfg) {
2423
2626
  return (req.autoHibernateSec ?? cfg.autoHibernateSec) || void 0;
2424
2627
  }
@@ -2654,11 +2857,11 @@ async function bootInto(box, prepare, origin, cfg, p) {
2654
2857
  drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
2655
2858
  sshPort = drawn?.ports[0];
2656
2859
  await prepare(m);
2657
- const tap = await createTap(id, cfg);
2860
+ const tap = await createTap(box, cfg);
2658
2861
  tapCreated = true;
2659
2862
  const spec = { ...box, sshPort };
2660
2863
  pid = await launch(spec, tap, cfg, keysB64, p);
2661
- await openPorts(spec, cfg);
2864
+ await openPorts(spec, cfg, p);
2662
2865
  void pushEnvAfterBoot(spec, pid, m.vsock, p);
2663
2866
  const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
2664
2867
  await writeMachineMeta(meta, p);
@@ -2669,12 +2872,14 @@ async function bootInto(box, prepare, origin, cfg, p) {
2669
2872
  await closePorts({ id, ip, sshPort }, cfg);
2670
2873
  if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
2671
2874
  await rm3(m.dir, { recursive: true, force: true });
2875
+ boxListChanged();
2672
2876
  throw err;
2673
2877
  } finally {
2674
2878
  drawn?.release();
2675
2879
  }
2676
2880
  }
2677
2881
  async function readSnap(ref, p) {
2882
+ if (ref.name.startsWith(".")) throw new NotFoundError(`snapshot ${shown(ref)}`);
2678
2883
  try {
2679
2884
  return await readSnapshotMeta(ref, p);
2680
2885
  } catch (err) {
@@ -2687,6 +2892,9 @@ function prefixLenOf(subnet) {
2687
2892
  }
2688
2893
  async function restoreMachine(fromText, owner, req, cfg, p) {
2689
2894
  const from = parseRef(fromText, owner);
2895
+ return withSnapshotLock(from, () => restoreFrom(from, owner, req, cfg, p));
2896
+ }
2897
+ async function restoreFrom(from, owner, req, cfg, p) {
2690
2898
  const snap = await readSnap(from, p);
2691
2899
  if (req.size !== void 0) {
2692
2900
  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)`);
@@ -2729,7 +2937,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
2729
2937
  drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
2730
2938
  sshPort = drawn?.ports[0];
2731
2939
  const image = await prepare(m);
2732
- const tap = await createTap(id, cfg, { detached: true });
2940
+ const tap = await createTap(box, cfg, { detached: true });
2733
2941
  tapCreated = true;
2734
2942
  const spec = { ...box, sshPort };
2735
2943
  pid = await loadSnapshot(spec, image, tap, cfg, p);
@@ -2742,8 +2950,8 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
2742
2950
  if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
2743
2951
  if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
2744
2952
  await pushEnv(box, m.vsock, p);
2745
- await attachTap(id, cfg);
2746
- await openPorts(spec, cfg);
2953
+ await attachTap(box, cfg);
2954
+ await openPorts(spec, cfg, p);
2747
2955
  const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
2748
2956
  await writeMachineMeta(meta, p);
2749
2957
  recordState(meta, "running", "new", p, meta.createdAt);
@@ -2753,6 +2961,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
2753
2961
  await closePorts({ id, ip, sshPort }, cfg);
2754
2962
  if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
2755
2963
  await rm3(m.dir, { recursive: true, force: true });
2964
+ boxListChanged();
2756
2965
  throw err;
2757
2966
  } finally {
2758
2967
  drawn?.release();
@@ -2959,11 +3168,11 @@ var startMachine = locked(async function startMachine2(ref, p = paths()) {
2959
3168
  assertAssets(cfg);
2960
3169
  const keysB64 = authorizedKeysB64(await readHostPubkey(p), meta.sshKeys ?? []);
2961
3170
  await ensureHostNetwork(cfg);
2962
- const tap = await createTap(meta.id, cfg);
3171
+ const tap = await createTap(meta, cfg);
2963
3172
  let pid;
2964
3173
  try {
2965
3174
  pid = await launch(meta, tap, cfg, keysB64, p);
2966
- await openPorts(meta, cfg);
3175
+ await openPorts(meta, cfg, p);
2967
3176
  void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);
2968
3177
  const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0 };
2969
3178
  await writeMachineMeta(started, p);
@@ -3099,7 +3308,7 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
3099
3308
  }
3100
3309
  const m = p.machine(ref.owner, ref.name);
3101
3310
  await ensureHostNetwork(cfg);
3102
- const tap = await createTap(meta.id, cfg, { detached: true });
3311
+ const tap = await createTap(meta, cfg, { detached: true });
3103
3312
  let pid;
3104
3313
  let stale;
3105
3314
  try {
@@ -3111,8 +3320,8 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
3111
3320
  noAnswer: `the box stays hibernated. kvbox-agent inside it took the request but gave no answer; try kvbox wake ${shown(ref)} again`
3112
3321
  });
3113
3322
  stale = await pushAuthorizedKeys(meta, m.vsock, p);
3114
- await attachTap(meta.id, cfg);
3115
- await openPorts(meta, cfg);
3323
+ await attachTap(meta, cfg);
3324
+ await openPorts(meta, cfg, p);
3116
3325
  } catch (err) {
3117
3326
  if (pid !== void 0) killQuietly(pid);
3118
3327
  await closePorts(meta, cfg);
@@ -3259,6 +3468,49 @@ var removePorts = locked(async function removePorts2(ref, req, p = paths()) {
3259
3468
  await writeMachineMeta(next, p);
3260
3469
  return toMachine(next, p);
3261
3470
  });
3471
+ function linkSource(req, caller, target) {
3472
+ if (req.fromOwner !== void 0) return { owner: ownerFor(req.fromOwner, caller), name: req.from, display: `${req.fromOwner}/${req.from}` };
3473
+ const ref = parseRef(req.from, caller);
3474
+ const realm = realmOf(target);
3475
+ return realm !== null && realmOf(ref.owner) === null && req.from.includes("/") ? { ...ref, owner: `${ref.owner}@${realm}` } : ref;
3476
+ }
3477
+ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
3478
+ const meta = await readMeta(ref, p);
3479
+ const fromRef = linkSource(req, caller, meta.owner);
3480
+ if (fromRef.owner === meta.owner && fromRef.name === meta.name) throw new KvboxError(`box ${shown(ref)} already reaches itself`);
3481
+ const from = await readMeta(fromRef, p);
3482
+ if (realmOf(from.owner) !== realmOf(meta.owner)) {
3483
+ 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`);
3484
+ }
3485
+ const links = (meta.links ?? []).filter((l) => !(l.stale && l.owner === from.owner && l.name === from.name && l.ip === from.ip && l.port === req.port));
3486
+ const same = (l) => !l.stale && l.owner === from.owner && l.name === from.name && l.port === req.port;
3487
+ if (links.some(same)) throw new KvboxError(`box ${shown(fromRef)} already reaches box ${shown(ref)} on port ${req.port}`);
3488
+ if (links.length >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${shown(ref)} has ${links.length}`);
3489
+ const added = { owner: from.owner, name: from.name, ip: from.ip, port: req.port };
3490
+ const cfg = await loadConfig(p);
3491
+ if (vmAlive(meta)) await openLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg);
3492
+ const next = { ...meta, links: [...links, added] };
3493
+ try {
3494
+ await writeMachineMeta(next, p);
3495
+ } catch (err) {
3496
+ await closeLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg).catch(() => void 0);
3497
+ throw err;
3498
+ }
3499
+ return toMachine(next, p);
3500
+ });
3501
+ var removeLink = locked(async function removeLink2(ref, req, caller, p = paths()) {
3502
+ const meta = await readMeta(ref, p);
3503
+ const fromRef = linkSource(req, caller, meta.owner);
3504
+ const links = meta.links ?? [];
3505
+ const gone = links.filter((l) => !l.stale && l.owner === fromRef.owner && l.name === fromRef.name && l.port === req.port);
3506
+ if (gone.length === 0) throw new KvboxError(`box ${shown(fromRef)} is not linked to box ${shown(ref)} on port ${req.port}`);
3507
+ const cfg = await loadConfig(p);
3508
+ for (const l of gone) await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg);
3509
+ const kept = links.filter((l) => !gone.includes(l));
3510
+ const next = { ...meta, links: kept.length > 0 ? kept : void 0 };
3511
+ await writeMachineMeta(next, p);
3512
+ return toMachine(next, p);
3513
+ });
3262
3514
  async function growDisk(file, gib) {
3263
3515
  await truncate2(file, gib * 1024 ** 3);
3264
3516
  await run(["e2fsck", "-f", "-p", file], { okExitCodes: [1] });
@@ -3272,13 +3524,54 @@ async function readMeta(ref, p) {
3272
3524
  throw err;
3273
3525
  }
3274
3526
  }
3275
- var destroyMachine = locked(async function destroyMachine2(ref, p = paths()) {
3527
+ async function destroyMachine(ref, p = paths()) {
3528
+ const gone = await destroyBox(ref, p);
3529
+ await dropLinksFrom(gone, p);
3530
+ }
3531
+ var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
3276
3532
  const meta = await readMeta(ref, p);
3277
3533
  const cfg = await loadConfig(p);
3278
3534
  await shutdown(meta, cfg, p, 2e3);
3535
+ await closeLinksFrom(meta, cfg, p).catch((err) => {
3536
+ recordState(meta, "stopped", "stop", p);
3537
+ throw err;
3538
+ });
3279
3539
  recordState(meta, "stopped", "rm", p);
3280
3540
  await rm3(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
3541
+ boxListChanged();
3542
+ return meta;
3281
3543
  });
3544
+ var linkOf = (gone) => (l) => l.owner === gone.owner && l.name === gone.name && l.ip === gone.ip;
3545
+ async function closeLinksFrom(gone, cfg, p) {
3546
+ const isGone = linkOf(gone);
3547
+ for (const ref of await listMachineRefs(p)) {
3548
+ const meta = await readMachineMeta(ref, p).catch(() => null);
3549
+ for (const l of meta?.links?.filter(isGone) ?? []) {
3550
+ await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg).catch((err) => {
3551
+ throw new KvboxError(`box ${shown(gone)} is stopped but not removed: could not close its link into ${shown(meta)} (${err.message}); try again`);
3552
+ });
3553
+ }
3554
+ }
3555
+ }
3556
+ async function dropLinksFrom(gone, p) {
3557
+ const cfg = await loadConfig(p);
3558
+ const isGone = linkOf(gone);
3559
+ for (const ref of await listMachineRefs(p)) {
3560
+ await withBoxLock(ref, async () => {
3561
+ const meta = await readMachineMeta(ref, p).catch(() => null);
3562
+ if (!meta?.links?.some(isGone)) return;
3563
+ const stuck = /* @__PURE__ */ new Set();
3564
+ for (const l of meta.links.filter(isGone)) {
3565
+ await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg).catch((err) => {
3566
+ stuck.add(l);
3567
+ console.error(`warning: could not close the link from removed box ${gone.name} into ${meta.name}: ${err.message}`);
3568
+ });
3569
+ }
3570
+ const kept = meta.links.filter((l) => !isGone(l) || stuck.has(l)).map((l) => stuck.has(l) ? { ...l, stale: true } : l);
3571
+ await writeMachineMeta({ ...meta, links: kept.length > 0 ? kept : void 0 }, p);
3572
+ }).catch((err) => console.error(`warning: links of removed box ${gone.name}: ${err.message}`));
3573
+ }
3574
+ }
3282
3575
  var RECOVERY_CONCURRENCY = 2;
3283
3576
  async function settleDeadBoxes(p = paths()) {
3284
3577
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -3306,6 +3599,14 @@ async function settleDeadBoxes(p = paths()) {
3306
3599
  function cutByReboot(meta) {
3307
3600
  return meta.pid !== null && meta.bootId !== currentBootId();
3308
3601
  }
3602
+ async function pinRunningTaps(p = paths()) {
3603
+ const cfg = await loadConfig(p);
3604
+ if (!bridgeExists(cfg.bridge)) return;
3605
+ for (const meta of await readAllMeta(p)) {
3606
+ if (!vmAlive(meta) || !existsSync4(`/sys/class/net/${tapName(meta.id)}`)) continue;
3607
+ await pinTap(meta, cfg).catch((err) => console.error(`warning: could not pin box ${meta.name}'s tap: ${err.message}`));
3608
+ }
3609
+ }
3309
3610
  var recovery = null;
3310
3611
  var recoveryStopping = false;
3311
3612
  var recoveryRun = Promise.resolve();
@@ -3476,7 +3777,7 @@ function startIdleWatch(opts = {}) {
3476
3777
  const started = [];
3477
3778
  const watched = /* @__PURE__ */ new Set();
3478
3779
  for (const box of await list()) {
3479
- if (!box.autoHibernateSec || box.status !== "running") continue;
3780
+ if (!box.autoHibernateSec || box.status !== "running" || box.links?.length) continue;
3480
3781
  if (inflight.has(box.id)) {
3481
3782
  watched.add(box.id);
3482
3783
  continue;
@@ -3596,7 +3897,7 @@ function versionOf(srcFileUrl, injected) {
3596
3897
  }
3597
3898
 
3598
3899
  // src/version.ts
3599
- var VERSION = versionOf(import.meta.url, true ? "0.5.26" : void 0);
3900
+ var VERSION = versionOf(import.meta.url, true ? "0.5.28" : void 0);
3600
3901
 
3601
3902
  // src/caller.ts
3602
3903
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";
@@ -4015,6 +4316,13 @@ function machineRoutes() {
4015
4316
  if (!body.success) throw new KvboxError("ports: expected a list of box ports");
4016
4317
  return c.json(await removePorts(parseRef(c.req.param("name"), c.get("owner")), body.data));
4017
4318
  });
4319
+ const linkBody = async (c) => {
4320
+ const body = LinkRequest.safeParse(await c.req.json().catch(() => ({})));
4321
+ if (!body.success) throw new KvboxError("links: expected {from, port}");
4322
+ return body.data;
4323
+ };
4324
+ 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));
4325
+ r.delete("/:name/links", async (c) => c.json(await removeLink(parseRef(c.req.param("name"), c.get("owner")), await linkBody(c), c.get("owner"))));
4018
4326
  r.get("/:name/usage", async (c) => {
4019
4327
  const since = c.req.query("since");
4020
4328
  let from;
@@ -4245,9 +4553,22 @@ program.command("start", { isDefault: true }).description("serve the API on the
4245
4553
  const cfg = await loadConfig(paths());
4246
4554
  const state = await ensureHostNetwork(cfg);
4247
4555
  console.log(`host network: bridge ${cfg.bridge} ${state}`);
4556
+ await pinRunningTaps(paths());
4248
4557
  } catch (err) {
4249
4558
  console.error(`warning: host network not ready (${err.message}); run: kvbox-server net up`);
4250
4559
  }
4560
+ let dnsWarned = false;
4561
+ const bindDns = () => {
4562
+ loadConfig(paths()).then(async (cfg) => {
4563
+ await startDns({ host: cfg.gateway });
4564
+ console.log(`box names: <name>.kvbox answered on ${cfg.gateway}`);
4565
+ }).catch((err) => {
4566
+ if (!dnsWarned) console.error(`warning: box names (<name>.kvbox) do not resolve yet (${err.message}); retrying`);
4567
+ dnsWarned = true;
4568
+ setTimeout(bindDns, DNS_RETRY_MS).unref();
4569
+ });
4570
+ };
4571
+ bindDns();
4251
4572
  startRelayWatch();
4252
4573
  startIdleWatch();
4253
4574
  const recovery2 = await bootRecovered(settled, paths());