@kvbox/server 0.5.42 → 0.5.44

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.
@@ -1,9 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/index.ts
4
- import { spawnSync } from "node:child_process";
5
- import { Command } from "commander";
6
-
7
3
  // ../shared/src/errors.ts
8
4
  var KvboxError = class extends Error {
9
5
  constructor(message, exitCode = 1) {
@@ -20,6 +16,9 @@ var NotFoundError = class extends KvboxError {
20
16
  }
21
17
  };
22
18
 
19
+ // src/commands/start.ts
20
+ import { Command } from "commander";
21
+
23
22
  // ../shared/src/paths.ts
24
23
  import { homedir } from "node:os";
25
24
  import { join } from "node:path";
@@ -49,7 +48,7 @@ function paths(home = kvboxHome()) {
49
48
  tls: join(home, "tls"),
50
49
  tlsKey: join(home, "tls", "key.pem"),
51
50
  tlsCert: join(home, "tls", "cert.pem"),
52
- /** The host's WireGuard tunnel to its relay (`kvbox server relay`, #50): the conf net-setup.sh installs for wg-quick. Mode 600. */
51
+ /** The host's WireGuard tunnel to its relay (`kvbox-server relay`, #50): the conf net-setup.sh installs for wg-quick. Mode 600. */
53
52
  relay: join(home, "relay"),
54
53
  relayConf: join(home, "relay", "kvbox.conf"),
55
54
  bin: join(home, "bin"),
@@ -454,1414 +453,1211 @@ async function loadConfig(p = paths()) {
454
453
  }
455
454
  }
456
455
 
457
- // src/core/controlPlane.ts
458
- import { X509Certificate } from "node:crypto";
459
- import { chmod as chmod2, mkdir, readFile as readFile2 } from "node:fs/promises";
460
- import { hostname as osHostname } from "node:os";
461
- import { request } from "undici";
456
+ // src/core/kvm.ts
457
+ import { access, constants, readFile as readFile2, stat } from "node:fs/promises";
458
+ var KVM_DEVICE = "/dev/kvm";
459
+ async function groupName(gid, groupFile = "/etc/group") {
460
+ const text = await readFile2(groupFile, "utf8").catch(() => "");
461
+ for (const line of text.split("\n")) {
462
+ const [name, , id] = line.split(":");
463
+ if (id !== void 0 && Number.parseInt(id, 10) === gid && name) return name;
464
+ }
465
+ return "kvm";
466
+ }
467
+ async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
468
+ try {
469
+ await access(device, constants.R_OK | constants.W_OK);
470
+ return;
471
+ } catch (err) {
472
+ const code = err.code;
473
+ if (code === "ENOENT") {
474
+ throw new KvboxError(`${device} is missing: this machine has no KVM, so boxes cannot run here (enable virtualization in the BIOS, then install-server.sh checks the rest)`);
475
+ }
476
+ if (code !== "EACCES" && code !== "EPERM") throw new KvboxError(`cannot open ${device}: ${err.message}`);
477
+ }
478
+ const owner = await stat(device).then((s) => groupName(s.gid, groupFile), () => "kvm");
479
+ throw new KvboxError(
480
+ `cannot start: this process is not allowed to open ${device}, so no box could run. It was started from a shell without the ${owner} group (a login from before you were added to it). Log out and back in, or start it from a shell that has the group: sg ${owner} -c "kvbox-server start -d"`
481
+ );
482
+ }
462
483
 
463
- // ../shared/src/country.ts
464
- var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
465
- var NOT_COUNTRIES = /* @__PURE__ */ new Set(["EU", "EZ", "UN", "QO", "XA", "XB", "ZZ"]);
466
- var ALIASES = { usa: "US", america: "US", uk: "GB", britain: "GB", england: "GB", holland: "NL" };
467
- var fold = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z]/g, "");
468
- var byName;
469
- function nameIndex() {
470
- if (byName) return byName;
471
- byName = new Map(Object.entries(ALIASES));
472
- for (let a = 65; a <= 90; a++) {
473
- for (let b = 65; b <= 90; b++) {
474
- const code = String.fromCharCode(a, b);
475
- const name = countryName(code);
476
- if (name !== void 0 && canonical(code) === code) byName.set(fold(name), code);
484
+ // src/core/dns.ts
485
+ import { createSocket } from "node:dgram";
486
+
487
+ // src/core/state.ts
488
+ import { randomBytes } from "node:crypto";
489
+ import { readFileSync } from "node:fs";
490
+ import { mkdir, readFile as readFile3, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
491
+ import { z as z3 } from "zod";
492
+
493
+ // src/core/db.ts
494
+ import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs";
495
+ import { dirname } from "node:path";
496
+ import { DatabaseSync } from "node:sqlite";
497
+ var MIGRATIONS = [
498
+ `create table usage_events (
499
+ id integer primary key,
500
+ box_id text not null,
501
+ owner text not null,
502
+ name text not null,
503
+ at text not null,
504
+ state text not null,
505
+ vcpu integer not null,
506
+ mem_mib integer not null,
507
+ disk_gib integer not null,
508
+ by text not null
509
+ );
510
+ create index usage_events_box_at on usage_events (box_id, at);`,
511
+ // The ledger's identity (#42): a control plane keys pulled rows by it, so a re-join is recognised
512
+ // and a fresh ledger (KVBOX_HOME wiped) restarts its cursor instead of waiting for ids it already saw.
513
+ `create table ledger (id text not null);
514
+ insert into ledger (id) values (lower(hex(randomblob(16))));
515
+ create index usage_events_at on usage_events (at);`,
516
+ // Volumes (#91): a row per create, resize and rm, the size from that moment on. Its own table and
517
+ // ids, pulled by the control plane like usage_events, in the same ledger.
518
+ `create table volume_events (
519
+ id integer primary key,
520
+ volume_id text not null,
521
+ owner text not null,
522
+ name text not null,
523
+ at text not null,
524
+ size_gib integer not null,
525
+ by text not null
526
+ );
527
+ create index volume_events_volume_at on volume_events (volume_id, at);`
528
+ ];
529
+ var handles = /* @__PURE__ */ new Map();
530
+ function openDb(p = paths()) {
531
+ const have = handles.get(p.db);
532
+ if (have !== void 0) return have;
533
+ mkdirSync(dirname(p.db), { recursive: true, mode: 448 });
534
+ closeSync(openSync(p.db, "a", 384));
535
+ chmodSync(p.db, 384);
536
+ const db = new DatabaseSync(p.db);
537
+ db.exec("pragma journal_mode = wal");
538
+ db.exec("pragma busy_timeout = 5000");
539
+ migrate(db);
540
+ handles.set(p.db, db);
541
+ return db;
542
+ }
543
+ function migrate(db) {
544
+ db.exec("create table if not exists schema_version (version integer not null)");
545
+ const row = db.prepare("select version from schema_version").get();
546
+ let version = row?.version ?? 0;
547
+ if (row === void 0) db.prepare("insert into schema_version (version) values (0)").run();
548
+ while (version < MIGRATIONS.length) {
549
+ db.exec("begin");
550
+ try {
551
+ db.exec(MIGRATIONS[version]);
552
+ version += 1;
553
+ db.prepare("update schema_version set version = ?").run(version);
554
+ db.exec("commit");
555
+ } catch (err) {
556
+ db.exec("rollback");
557
+ throw err;
477
558
  }
478
559
  }
479
- return byName;
480
560
  }
481
- function canonical(code) {
482
- return /-([A-Z]{2})$/.exec(Intl.getCanonicalLocales(`und-${code}`)[0] ?? "")?.[1] ?? code;
561
+ var LIVE_STATES = ["running", "standby"];
562
+ function fromRaw(r) {
563
+ return { boxId: r.box_id, owner: r.owner, name: r.name, at: r.at, state: r.state, vcpu: r.vcpu, memMib: r.mem_mib, diskGib: r.disk_gib, by: r.by };
483
564
  }
484
- function countryName(code) {
485
- if (!/^[A-Z]{2}$/.test(code) || NOT_COUNTRIES.has(code)) return void 0;
486
- return names.of(code);
565
+ function lastEvent(boxId, db) {
566
+ const raw = db.prepare("select * from usage_events where box_id = ? order by at desc, id desc limit 1").get(boxId);
567
+ return raw === void 0 ? void 0 : fromRaw(raw);
487
568
  }
488
- function parseCountry(input) {
489
- const t = input.trim();
490
- const upper = t.toUpperCase();
491
- const code = countryName(upper) !== void 0 ? canonical(upper) : nameIndex().get(fold(t));
492
- if (code !== void 0) return code;
493
- throw new KvboxError(`unknown country "${input}": give its name or its two-letter code, e.g. RO or US`);
569
+ function insertRaw(e, db) {
570
+ db.prepare(
571
+ "insert into usage_events (box_id, owner, name, at, state, vcpu, mem_mib, disk_gib, by) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"
572
+ ).run(e.boxId, e.owner, e.name, e.at, e.state, e.vcpu, e.memMib, e.diskGib, e.by);
573
+ }
574
+ function insertUsageEvent(e, p = paths()) {
575
+ const db = openDb(p);
576
+ if (e.state === "running" && e.by !== "resume") closeOpenRun(e.boxId, e.at, p);
577
+ insertRaw(e, db);
578
+ }
579
+ function closeOpenRun(boxId, at, p = paths()) {
580
+ const db = openDb(p);
581
+ const last = lastEvent(boxId, db);
582
+ if (last === void 0 || !LIVE_STATES.includes(last.state)) return false;
583
+ insertRaw({ ...last, at, state: "stopped", by: "server" }, db);
584
+ return true;
585
+ }
586
+ function closeRunCutByBoot(boxId, bootAt, now, p = paths()) {
587
+ const last = lastEvent(boxId, openDb(p));
588
+ return closeOpenRun(boxId, last !== void 0 && last.at < bootAt ? bootAt : now, p);
589
+ }
590
+ function usageEventsFor(boxId, since, p = paths()) {
591
+ const rows = openDb(p).prepare("select * from usage_events where box_id = ? and at >= ? order by at, id").all(boxId, since);
592
+ return rows.map(fromRaw);
593
+ }
594
+ var withId = (r) => ({ ...fromRaw(r), id: r.id });
595
+ function ledgerId(p = paths()) {
596
+ return openDb(p).prepare("select id from ledger").get().id;
597
+ }
598
+ function usageEventsAfter(after, limit, scope, p = paths()) {
599
+ const db = openDb(p);
600
+ const rows = scope === null ? db.prepare("select * from usage_events where id > ? order by id limit ?").all(after, limit) : typeof scope === "string" ? db.prepare("select * from usage_events where id > ? and owner = ? order by id limit ?").all(after, scope, limit) : db.prepare("select * from usage_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?").all(after, `@${scope.realm}`, `@${scope.realm}`, limit);
601
+ return rows.map(withId);
602
+ }
603
+ function usageEventsInScope(scope, window, p = paths()) {
604
+ const rows = openDb(p).prepare(
605
+ `select * from usage_events where at < ? and (at >= ? or id in (select max(id) from usage_events where at < ? group by box_id))
606
+ order by at, id`
607
+ ).all(window.to, window.from, window.from);
608
+ return rows.filter((r) => inScope(r.owner, scope)).map(withId);
609
+ }
610
+ var volumeWithId = (r) => ({ id: r.id, volumeId: r.volume_id, owner: r.owner, name: r.name, at: r.at, sizeGib: r.size_gib, by: r.by });
611
+ function insertVolumeEvent(e, p = paths()) {
612
+ openDb(p).prepare("insert into volume_events (volume_id, owner, name, at, size_gib, by) values (?, ?, ?, ?, ?, ?)").run(e.volumeId, e.owner, e.name, e.at, e.sizeGib, e.by);
613
+ }
614
+ function volumeEventsAfter(after, limit, scope, p = paths()) {
615
+ const db = openDb(p);
616
+ const rows = scope === null ? db.prepare("select * from volume_events where id > ? order by id limit ?").all(after, limit) : typeof scope === "string" ? db.prepare("select * from volume_events where id > ? and owner = ? order by id limit ?").all(after, scope, limit) : db.prepare("select * from volume_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?").all(after, `@${scope.realm}`, `@${scope.realm}`, limit);
617
+ return rows.map(volumeWithId);
618
+ }
619
+ function volumeEventsInScope(scope, window, p = paths()) {
620
+ const rows = openDb(p).prepare(
621
+ `select * from volume_events where at < ? and (at >= ? or id in (select max(id) from volume_events where at < ? group by volume_id))
622
+ order by at, id`
623
+ ).all(window.to, window.from, window.from);
624
+ return rows.filter((r) => inScope(r.owner, scope)).map(volumeWithId);
494
625
  }
495
626
 
496
- // ../shared/src/api.ts
497
- import { z as z3 } from "zod";
498
- var SizeSchema = z3.enum(SIZE_NAMES);
499
- var BoxStatusSchema = z3.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
500
- var PortProtoSchema = z3.enum(["tcp", "udp"]);
501
- var MAX_BOX_PORTS = 16;
502
- var PortForwardSchema = z3.object({
503
- guestPort: z3.number().int().min(1).max(65535),
504
- hostPort: z3.number().int(),
505
- proto: PortProtoSchema,
506
- /** The host's public address; only the control plane fills it in, as for `ssh`. */
507
- address: z3.string().optional()
508
- });
509
- var PortsRequest = z3.object({
510
- ports: z3.array(z3.object({ guestPort: z3.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
511
- });
512
- var BoxPortSchema = z3.number().int().min(1).max(65535);
513
- var MAX_BOX_LINKS = 32;
514
- var BoxLinkSchema = z3.object({ from: z3.string(), port: BoxPortSchema });
515
- var LinkRequest = z3.object({ from: z3.string().min(1), fromOwner: z3.string().optional(), port: BoxPortSchema });
516
- var ClaimSubdomainRequest = z3.object({ name: z3.string(), port: BoxPortSchema });
517
- var SubdomainPortRequest = z3.object({ port: BoxPortSchema });
518
- var SubdomainRouteRequest = z3.object({ name: z3.string(), port: BoxPortSchema });
519
- var SubdomainSchema = z3.object({
520
- owner: z3.string(),
521
- box: z3.string(),
522
- subdomain: z3.string(),
523
- port: BoxPortSchema,
524
- url: z3.string(),
525
- routes: z3.array(z3.object({ name: z3.string(), port: BoxPortSchema, url: z3.string() }))
526
- });
527
- var AddDomainRequest = z3.object({ domain: z3.string(), port: BoxPortSchema.optional() });
528
- var DomainSchema = z3.object({
529
- owner: z3.string(),
530
- box: z3.string(),
531
- domain: z3.string(),
532
- port: BoxPortSchema,
533
- status: z3.enum(["pending", "live"]),
534
- www: z3.boolean(),
535
- url: z3.string(),
536
- error: z3.string().nullable(),
537
- records: z3.array(z3.object({ type: z3.enum(["A", "TXT", "CNAME"]), name: z3.string(), value: z3.string() })),
538
- createdAt: z3.string()
539
- });
540
- var WakeHookSchema = z3.object({
541
- id: z3.string(),
542
- owner: z3.string(),
543
- box: z3.string(),
544
- url: z3.string(),
545
- createdBy: z3.string().nullable(),
546
- createdAt: z3.string(),
547
- lastCalledAt: z3.string().nullable()
548
- });
549
- var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z3.string() });
550
- var WakeHookCallSchema = z3.object({
551
- box: z3.string(),
552
- action: z3.enum(["wake", "resume", "none"]),
553
- reason: z3.string().optional()
554
- });
555
- var BACKUP_STATUSES = ["running", "ready", "failed"];
556
- var BackupSchema = z3.object({
557
- id: z3.string(),
558
- owner: z3.string(),
559
- box: z3.string(),
560
- status: z3.enum(BACKUP_STATUSES),
561
- /** Why it failed; null otherwise. */
562
- error: z3.string().nullable(),
563
- /** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
564
- base: z3.string().nullable(),
565
- image: z3.string().optional(),
566
- vcpu: z3.number().int().nullable(),
567
- memMib: z3.number().int().nullable(),
568
- /** The disk's size. */
569
- diskBytes: z3.number().int().nullable(),
570
- /** What it holds: the slots that are not all zeros. */
571
- dataBytes: z3.number().int().nullable(),
572
- /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
573
- uploadedBytes: z3.number().int().nullable(),
574
- createdBy: z3.string().nullable(),
575
- createdAt: z3.string(),
576
- finishedAt: z3.string().nullable()
577
- });
578
- var HostBackupRequest = z3.object({ id: z3.string(), key: z3.string() });
579
- var HostBackupManifestSchema = z3.object({
580
- id: z3.string(),
581
- sizeBytes: z3.number().int(),
582
- chunks: z3.array(z3.string().nullable()),
583
- env: z3.string().nullable(),
584
- base: z3.string(),
585
- image: z3.string().optional(),
586
- vcpu: z3.number().int(),
587
- memMib: z3.number().int()
588
- });
589
- var HostUploadRequest = z3.object({ key: z3.string(), urls: z3.record(z3.string(), z3.string()) });
590
- var HostUploadResultSchema = z3.object({ chunks: z3.number().int(), bytes: z3.number().int(), sizes: z3.record(z3.string(), z3.number().int()) });
591
- var HostRestoreRequest = z3.object({
592
- /** The backup's id: its variables were sealed under it. */
593
- id: z3.string(),
594
- key: z3.string(),
595
- sizeBytes: z3.number().int().positive(),
596
- base: z3.string(),
597
- image: z3.string().optional(),
598
- env: z3.string().nullable(),
599
- chunks: z3.array(z3.object({ index: z3.number().int().nonnegative(), hash: z3.string(), url: z3.string() }))
600
- });
601
- var MachineSchema = z3.object({
602
- /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
627
+ // src/core/state.ts
628
+ var MachineMetaSchema = z3.object({
629
+ /** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */
603
630
  id: z3.string(),
604
631
  name: z3.string(),
605
- /** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */
632
+ /** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */
606
633
  owner: z3.string(),
607
634
  ip: z3.string(),
608
635
  mac: z3.string(),
609
636
  pid: z3.number().int().nullable(),
637
+ // null: stopped on purpose, disk kept
638
+ /**
639
+ * The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot
640
+ * the number can name some other process; a pid from another boot is dead whatever `kill -0` says.
641
+ * Absent (boxes launched before #29): the pid alone decides.
642
+ */
643
+ bootId: z3.string().optional(),
610
644
  vcpu: z3.number().int(),
611
645
  memMib: z3.number().int(),
612
- diskBytes: z3.number().int(),
613
- // the box's own writable disk, as the guest sees it
614
- diskUsedBytes: z3.number().int(),
615
- // what the box uses of it: the filesystem's own count, like the guest's `df` (#115)
616
- /** What the disk's sparse file occupies on the host. Grows while the box runs, `kvbox stop` trims it back. Hosts before 0.5.42 do not send it. */
617
- diskHostBytes: z3.number().int().optional(),
618
- base: z3.string(),
619
- // version of the image the box's overlay stacks on
620
- /** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
621
- image: z3.string().optional(),
622
646
  createdAt: z3.string(),
623
647
  source: z3.string(),
624
- // "base", "snapshot:<owner/name>" or "fork:<owner/name>" (#79)
625
- status: BoxStatusSchema,
626
- /**
627
- * Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made
628
- * through a control plane have one; the control plane adds the host's address for `connect` (#21).
629
- */
630
- sshPort: z3.number().int().optional(),
631
- /**
632
- * Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only
633
- * the control plane fills it in (a host does not know its own public address); absent for a box
634
- * whose host reported no port or did not answer.
635
- */
636
- ssh: z3.object({ host: z3.string(), port: z3.number().int(), user: z3.string() }).optional(),
637
- /** Box ports published on the host (#30). Absent: none. */
638
- ports: z3.array(PortForwardSchema).optional(),
639
- /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
640
- ownerKind: z3.enum(["user", "org"]).optional(),
641
- /**
642
- * The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
643
- * links to, and a volume attaches to, only a box on the same host.
644
- */
645
- host: z3.string().optional(),
646
- /** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
647
- country: z3.string().optional(),
648
- /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
649
- autoHibernateSec: z3.number().int().positive().optional(),
650
- /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
651
- idleCheck: z3.string().optional(),
652
- /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
653
- volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional(),
654
- /** Boxes that may reach this one, each on one port (#98). Absent: none. */
655
- links: z3.array(BoxLinkSchema).optional(),
656
- /** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */
648
+ /** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */
649
+ base: z3.string(),
650
+ /** The image (#87), when not the base one: assets/images/<image>/rootfs-<base>.ext4. `vm update` keeps it. */
651
+ image: z3.string().optional(),
652
+ /** The image's connect line with its secrets masked and `${BOX}` unfilled (#87, `maskedUrl`). Absent: the image declares none. */
657
653
  url: z3.string().optional(),
658
654
  /**
659
- * Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
660
- * serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
661
- */
662
- connect: z3.string().optional()
663
- });
664
- var VolumeSchema = z3.object({
665
- /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
666
- id: z3.string(),
667
- name: z3.string(),
668
- owner: z3.string(),
669
- sizeGib: z3.number().int(),
670
- /** What the sparse file really occupies on the host. */
671
- usedBytes: z3.number().int(),
672
- attachedTo: z3.string().nullable(),
673
- createdAt: z3.string(),
674
- /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
675
- ownerKind: z3.enum(["user", "org"]).optional(),
676
- /** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
677
- host: z3.string().optional()
678
- });
679
- var MAX_VOLUME_GIB = 4096;
680
- var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
681
- var VOLUME_NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
682
- var CreateVolumeRequest = z3.object({
683
- name: z3.string(),
684
- sizeGib: z3.number().int().min(1).max(MAX_VOLUME_GIB),
685
- /**
686
- * Through a control plane (#91): the box this volume is for, so it is made on that box's host; the
687
- * control plane requires it (a volume attaches only to a box on its own host, so one made for no box
688
- * could never attach) and the CLI attaches right after. A host ignores it.
655
+ * Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
656
+ * each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
657
+ * is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.
689
658
  */
690
- box: z3.string().optional()
691
- });
692
- var AttachVolumeRequest = z3.object({
693
- box: z3.string()
694
- });
695
- var EnvVarSchema = z3.object({
696
- name: z3.string(),
697
- value: z3.string().optional(),
698
- secret: z3.boolean(),
699
- updatedAt: z3.string()
700
- });
701
- var BoxEnvSchema = z3.object({
702
- box: z3.string(),
703
- vars: z3.array(EnvVarSchema)
704
- });
705
- var BoxEnvChangeSchema = z3.object({
706
- box: z3.string(),
707
- name: z3.string(),
708
- /** Whether the box is running now: the change waits for its next start. */
709
- running: z3.boolean()
710
- });
711
- var SetEnvRequest = z3.object({
712
- value: z3.string(),
713
- secret: z3.boolean().optional()
714
- });
715
- var EnvChangeSchema = z3.object({
716
- owner: z3.string(),
717
- name: z3.string(),
718
- boxes: z3.number().int()
719
- });
720
- var HostEnvRequest = z3.object({
721
- version: z3.number().int().min(0),
722
- vars: z3.array(z3.object({ name: z3.string(), value: z3.string() }))
723
- });
724
- var HostEnvVersionsSchema = z3.array(z3.object({ owner: z3.string(), version: z3.number().int() }));
725
- var CreateMachineRequest = z3.object({
726
- name: z3.string().optional(),
727
- /** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
728
- owner: z3.string().optional(),
729
- size: SizeSchema.optional(),
730
- from: z3.string().optional(),
731
- force: z3.boolean().optional(),
659
+ memSnapshots: z3.number().int().optional(),
660
+ /** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */
661
+ paused: z3.boolean().optional(),
732
662
  /**
733
- * Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends
734
- * its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every
735
- * boot (#49); a host older than that ignores them.
663
+ * authorized_keys lines the box gets on top of the host's own key, as the control plane sent them
664
+ * at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so
665
+ * `start` has to send the same lines again. Absent: host key only.
736
666
  */
737
667
  sshKeys: z3.array(z3.string()).optional(),
738
- /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
739
- autoHibernateSec: z3.number().int().min(0).optional(),
740
668
  /**
741
- * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
742
- * control plane reads it; a host has one place to put a box.
669
+ * The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,
670
+ * or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.
743
671
  */
744
- near: z3.string().optional(),
672
+ sshKeysStale: z3.boolean().optional(),
673
+ /** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */
674
+ sshPort: z3.number().int().optional(),
745
675
  /**
746
- * Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
747
- * `@kvbox/shared/country`. Only the control plane reads it.
676
+ * Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,
677
+ * each host port the box's for its life. DNATed while the box runs, rebuilt from here with its
678
+ * current IP every time it comes up. Absent: none.
748
679
  */
749
- country: z3.string().optional(),
750
- /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
751
- image: z3.string().optional(),
752
- /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
753
- env: z3.array(z3.object({ name: z3.string(), value: z3.string() })).optional()
754
- });
755
- var ForkMachineRequest = z3.object({
756
- name: z3.string().optional(),
680
+ ports: z3.array(z3.object({ guestPort: z3.number().int(), hostPort: z3.number().int(), proto: z3.enum(["tcp", "udp"]) })).optional(),
681
+ /** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
682
+ autoHibernateSec: z3.number().int().positive().optional(),
757
683
  /**
758
- * The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host
759
- * qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.
684
+ * A script inside the box auto-hibernate asks instead of watching the tap (#102, core/idle.ts): run by
685
+ * kvbox-agent, exit 0 = idle. A new box gets its image's `idle` (image.json); `kvbox vm set --idle-check`
686
+ * changes it. The one place the host looks. Absent: the traffic rule.
760
687
  */
761
- owner: z3.string().optional(),
762
- /** A cold fork only: a warm one keeps the source's vCPU and memory. */
763
- size: SizeSchema.optional(),
764
- force: z3.boolean().optional(),
765
- /** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */
766
- sshKeys: z3.array(z3.string()).optional(),
767
- autoHibernateSec: z3.number().int().min(0).optional()
768
- });
769
- var SetSshKeysRequest = z3.object({
770
- sshKeys: z3.array(z3.string())
771
- });
772
- var RescaleMachineRequest = z3.object({
773
- size: SizeSchema.optional(),
774
- vcpu: z3.number().int().min(1).max(64).optional(),
775
- memMib: z3.number().int().min(256).optional(),
776
- diskGib: z3.number().int().min(1).optional(),
777
- /** Skip the capacity guard when a running box grows (#37). */
778
- force: z3.boolean().optional()
779
- });
780
- var StartMachineRequest = z3.object({
781
- force: z3.boolean().optional()
782
- });
783
- var SetMachineRequest = z3.object({
784
- /** Seconds without network traffic before the box is hibernated (#47); 0: never. */
785
- autoHibernateSec: z3.number().int().min(0).optional(),
786
- /** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
787
- idleCheck: z3.union([z3.literal(""), z3.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
788
- });
789
- var SnapshotSchema = z3.object({
790
- name: z3.string(),
791
- owner: z3.string(),
792
- source: z3.string(),
793
- // the box it was taken from, as owner/name
794
- base: z3.string(),
795
- // version of the image the overlay stacks on; a restore needs the same one
796
- /** As in MachineSchema: the image when it is not the base one (#87). */
797
- image: z3.string().optional(),
798
- vcpu: z3.number().int(),
799
- memMib: z3.number().int(),
800
- sizeBytes: z3.number().int(),
801
- // what vmstate + mem + overlay really occupy on the host
802
- createdAt: z3.string()
803
- });
804
- var CreateSnapshotRequest = z3.object({
805
- box: z3.string(),
806
- name: z3.string(),
807
- /** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
808
- replace: z3.boolean().optional()
809
- });
810
- var DiskCapacitySchema = z3.object({
811
- totalGib: z3.number().int(),
812
- freeGib: z3.number().int(),
813
- volumesGib: z3.number().int(),
814
- volumesUsedGib: z3.number().int(),
815
- headroomGib: z3.number().int()
816
- });
817
- var CapacitySchema = z3.object({
818
- hostMemMib: z3.number().int(),
819
- hostCores: z3.number().int(),
820
- reservedMemMib: z3.number().int(),
821
- reservedVcpu: z3.number().int(),
822
- running: z3.number().int(),
823
- /** Absent on a host from before volumes (#91): it cannot take one. */
824
- disk: DiskCapacitySchema.optional(),
688
+ idleCheck: z3.string().optional(),
825
689
  /**
826
- * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
827
- * Absent on a host from before images: it has only the base.
690
+ * Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
691
+ * their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
692
+ * volume's meta.json does not say. Absent: none.
828
693
  */
829
- images: z3.array(z3.object({ name: z3.string(), version: z3.string() })).optional()
830
- });
831
- var ImageSchema = z3.object({ name: z3.string(), version: z3.string().nullable() });
832
- var RecoveryReportSchema = z3.object({
833
- at: z3.string(),
834
- booted: z3.array(z3.string()),
835
- leftStopped: z3.array(z3.string()),
836
- failed: z3.array(z3.object({ box: z3.string(), error: z3.string() }))
837
- });
838
- var HealthSchema = z3.object({
839
- ok: z3.literal(true),
840
- version: z3.string(),
841
- pid: z3.number().int(),
842
- /** Base image version new boxes get (null when the host has no usable base image yet). */
843
- base: z3.string().nullable(),
844
- /** Owner that boxes made over the local socket get (the Unix user running the server). */
845
- owner: z3.string(),
846
- /** The control plane this host joined (null when none). */
847
- controlPlane: z3.object({
848
- /** Realm name, e.g. kvbox.sh. */
849
- name: z3.string(),
850
- url: z3.string(),
851
- /** Where this host answers the control plane. */
852
- hostUrl: z3.string()
853
- }).nullable(),
854
- /** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */
855
- relay: z3.object({
856
- name: z3.string(),
857
- /** The public IP the relay owns for this host. */
858
- publicIp: z3.string(),
859
- /** The relay's WireGuard endpoint the tunnel dials. */
860
- endpoint: z3.string(),
861
- /** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */
862
- restarts: z3.number().int().optional(),
863
- lastRestartAt: z3.string().nullable().optional()
864
- }).nullable().optional(),
865
- /** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */
866
- recovery: RecoveryReportSchema.nullable().optional()
867
- });
868
- var MachineUsageSchema = z3.object({
869
- name: z3.string(),
870
- owner: z3.string(),
871
- status: BoxStatusSchema,
872
- window: z3.object({ from: z3.string(), to: z3.string() }),
873
- seconds: z3.object({
874
- running: z3.number().int(),
875
- standby: z3.number().int(),
876
- hibernated: z3.number().int(),
877
- stopped: z3.number().int()
878
- }),
879
- vcpuHours: z3.number(),
880
- ramGibHours: z3.number(),
881
- diskGibHours: z3.number(),
882
- cost: z3.object({ amount: z3.number(), currency: z3.string() }).optional(),
883
- /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */
884
- estimatedStops: z3.number().int(),
885
- historyFrom: z3.string().nullable()
886
- });
887
- var GuestStatsSchema = z3.object({
888
- /** Load average over 1, 5 and 15 minutes. */
889
- load: z3.tuple([z3.number(), z3.number(), z3.number()]),
890
- cpus: z3.number().int(),
891
- memTotalMib: z3.number().int(),
892
- /** Total minus available: page cache counts as free. */
893
- memUsedMib: z3.number().int(),
894
- /** The box's root, which is its overlay disk: the box's own writes, not the shared base. */
895
- diskTotalBytes: z3.number().int(),
896
- diskUsedBytes: z3.number().int(),
897
- uptimeSec: z3.number().int()
898
- });
899
- var MachineStatsSchema = z3.object({
900
- name: z3.string(),
901
- owner: z3.string(),
902
- stats: GuestStatsSchema.nullable()
903
- });
904
- var UsageStatusSchema = z3.enum([...BoxStatusSchema.options, "removed"]);
905
- var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({
906
- /** The host's box id; a name removed and recreated appears twice, with two ids. */
907
- id: z3.string(),
908
- status: UsageStatusSchema,
909
- /** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */
910
- ownerKind: z3.enum(["user", "org"]).optional(),
694
+ volumes: z3.array(z3.string()).optional(),
911
695
  /**
912
- * Through a control plane: the username that made the box (#60), absent when the box is gone from
913
- * the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.
696
+ * Links into this box (#98, `kvbox vm link`): box `owner/name`, at `ip`, may open TCP connections to
697
+ * `port`. The rule is open while this box runs, rebuilt from here at every boot; `ip` is the other
698
+ * box's, fixed for its life, and checked against its meta.json before a rule opens. `stale`: that box
699
+ * was removed but the rule would not close; kept only so this box's next stop closes it, never opened
700
+ * again, never listed (a new box of the same name may get the same IP). Absent: none.
914
701
  */
915
- createdBy: z3.string().optional()
702
+ links: z3.array(z3.object({ owner: z3.string(), name: z3.string(), ip: z3.string(), port: z3.number().int(), stale: z3.literal(true).optional() })).optional()
916
703
  });
917
- var VolumeUsageSchema = z3.object({
918
- /** The host's volume id; a name removed and made again appears twice, with two ids. */
704
+ var VolumeMetaSchema = z3.object({
705
+ /** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
919
706
  id: z3.string(),
920
707
  name: z3.string(),
921
708
  owner: z3.string(),
922
- ownerKind: z3.enum(["user", "org"]).optional(),
923
- /** The size at the end of the window (or when removed). */
924
709
  sizeGib: z3.number().int(),
925
- status: z3.enum(["present", "removed"]),
926
- volumeHours: z3.number(),
927
- volumeGibHours: z3.number(),
928
- cost: z3.object({ amount: z3.number(), currency: z3.string() }).optional(),
929
- historyFrom: z3.string().nullable()
930
- });
931
- var UsageReportSchema = z3.object({
932
- window: z3.object({ from: z3.string(), to: z3.string() }),
933
- boxes: z3.array(BoxUsageSchema),
934
- /** Absent from a side older than #91. */
935
- volumes: z3.array(VolumeUsageSchema).optional(),
936
- totals: z3.object({
937
- seconds: MachineUsageSchema.shape.seconds,
938
- vcpuHours: z3.number(),
939
- ramGibHours: z3.number(),
940
- diskGibHours: z3.number(),
941
- volumeHours: z3.number().optional(),
942
- volumeGibHours: z3.number().optional(),
943
- /** Boxes and volumes together. */
944
- cost: z3.object({ amount: z3.number(), currency: z3.string() }).optional()
945
- })
710
+ createdAt: z3.string()
946
711
  });
947
- var UsageEventRowSchema = z3.object({
948
- id: z3.number().int(),
949
- boxId: z3.string(),
950
- owner: z3.string(),
712
+ function newBoxId(taken) {
713
+ for (; ; ) {
714
+ const id = randomBytes(3).toString("hex");
715
+ if (!taken.has(id)) return id;
716
+ }
717
+ }
718
+ var SnapshotMetaSchema = z3.object({
951
719
  name: z3.string(),
952
- at: z3.string(),
953
- state: z3.enum(["running", "standby", "hibernated", "stopped"]),
720
+ owner: z3.string(),
721
+ /** The box it was taken from, as owner/name. */
722
+ source: z3.string(),
723
+ base: z3.string(),
724
+ /** As in a box's meta.json (#87). */
725
+ image: z3.string().optional(),
954
726
  vcpu: z3.number().int(),
955
727
  memMib: z3.number().int(),
956
- diskGib: z3.number().int(),
957
- by: z3.string()
958
- });
959
- var UsageEventsResponseSchema = z3.object({
960
- ledger: z3.string().min(1),
961
- events: z3.array(UsageEventRowSchema),
962
- next: z3.number().int()
963
- });
964
- var VolumeEventRowSchema = z3.object({
965
- id: z3.number().int(),
966
- volumeId: z3.string(),
967
- owner: z3.string(),
968
- name: z3.string(),
969
- at: z3.string(),
970
- sizeGib: z3.number().int(),
971
- by: z3.enum(["create", "resize", "rm"])
972
- });
973
- var VolumeEventsResponseSchema = z3.object({
974
- ledger: z3.string().min(1),
975
- events: z3.array(VolumeEventRowSchema),
976
- next: z3.number().int()
977
- });
978
- var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
979
- var ApiErrorCodeSchema = z3.enum(API_ERROR_CODES);
980
- var ApiErrorSchema = z3.object({
981
- error: z3.string(),
982
- code: ApiErrorCodeSchema.optional()
983
- });
984
- var ACTIVATED_BY = ["card", "admin"];
985
- var ActivatedBySchema = z3.enum(ACTIVATED_BY);
986
- var CloudUserSchema = z3.object({
987
- /** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */
988
- username: z3.string(),
989
- /** Display name, free text ("Alexandru Ghiura"). */
990
- name: z3.string(),
991
- /** Login identity, unique. */
992
- email: z3.string(),
993
- role: z3.enum(["admin", "user"]),
728
+ sizeBytes: z3.number().int(),
994
729
  createdAt: z3.string(),
995
730
  /**
996
- * False until a card is on file or an admin activates the account (#74): then only `/me` and
997
- * `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and
998
- * gates nobody, hence the defaults: a newer CLI must still parse its answers.
731
+ * The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
732
+ * and their mounts in the memory image, but their data is not here. A box restored from the snapshot
733
+ * gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
999
734
  */
1000
- active: z3.boolean().default(true),
1001
- activatedBy: ActivatedBySchema.nullable().default(null)
1002
- });
1003
- var ORG_ROLES = ["owner", "admin", "member"];
1004
- var OrgRoleSchema = z3.enum(ORG_ROLES);
1005
- var CloudOrgSchema = z3.object({
1006
- slug: z3.string(),
1007
- /** Display name; the slug never changes, this may. */
1008
- name: z3.string(),
1009
- createdAt: z3.string(),
1010
- /** An org pays for itself (#74): off until it has a card or an admin activates it; its boxes are 402. Defaults as on CloudUser. */
1011
- active: z3.boolean().default(true),
1012
- activatedBy: ActivatedBySchema.nullable().default(null)
1013
- });
1014
- var OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });
1015
- var OrgMemberSchema = z3.object({
1016
- username: z3.string(),
1017
- name: z3.string(),
1018
- role: OrgRoleSchema,
1019
- addedAt: z3.string()
1020
- });
1021
- var OrgDetailSchema = CloudOrgSchema.extend({ members: z3.array(OrgMemberSchema) });
1022
- var CreateOrgRequestSchema = z3.object({
1023
- slug: z3.string().min(1),
1024
- name: z3.string().min(1)
1025
- });
1026
- var RenameOrgRequestSchema = z3.object({ name: z3.string().min(1) });
1027
- var AddMemberRequestSchema = z3.object({
1028
- username: z3.string().min(1),
1029
- role: OrgRoleSchema.default("member")
735
+ volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int() })).optional()
1030
736
  });
1031
- var SetRoleRequestSchema = z3.object({ role: OrgRoleSchema });
1032
- var MeResponseSchema = CloudUserSchema.extend({ orgs: z3.array(OrgMembershipSchema) });
1033
- var BalanceSchema = z3.object({
1034
- slug: z3.string(),
1035
- balance: z3.number(),
1036
- currency: z3.string(),
1037
- topUps: z3.number(),
1038
- spent: z3.number(),
1039
- /** The first moment usage counts from: the slug's first top-up; null when it has none. */
1040
- since: z3.string().nullable(),
1041
- /** When the slug ran out and its boxes were hibernated (the `sweep-credit` job); null in good standing. Absent from a control plane older than this field. */
1042
- suspendedAt: z3.string().nullable().default(null)
1043
- });
1044
- var TopUpRequestSchema = z3.object({
1045
- slug: z3.string().min(1),
1046
- /** In the control plane's currency; negative corrects a mistake. */
1047
- amount: z3.number().finite(),
1048
- note: z3.string().max(200).optional()
1049
- });
1050
- var TopUpSchema = z3.object({
1051
- id: z3.string(),
1052
- slug: z3.string(),
1053
- amount: z3.number(),
1054
- currency: z3.string(),
1055
- /** `transfer` (#93): an owner moving credit to an org they own, a negative row on their slug and a positive one on the org's. */
1056
- source: z3.enum(["admin", "card", "trial", "transfer"]),
1057
- note: z3.string().nullable(),
1058
- at: z3.string()
1059
- });
1060
- var TOP_UP_AMOUNTS = [10, 25, 50, 100];
1061
- var BillingInfoSchema = z3.object({
1062
- card: z3.object({ brand: z3.string(), last4: z3.string() }).nullable(),
1063
- cardInUse: z3.boolean(),
1064
- balance: BalanceSchema
1065
- });
1066
- var BillingRedirectSchema = z3.object({ url: z3.string() });
1067
- var TopUpCheckoutRequestSchema = z3.object({
1068
- amount: z3.literal(TOP_UP_AMOUNTS)
1069
- });
1070
- var TransferRequestSchema = z3.object({
1071
- org: z3.string().min(1),
1072
- amount: z3.number().positive().multipleOf(0.01, "amount is in cents at most")
1073
- });
1074
- var TransferResponseSchema = z3.object({ from: BalanceSchema, to: BalanceSchema, activated: z3.boolean() });
1075
- var LoginRequestSchema = z3.object({
1076
- email: z3.string().min(1),
1077
- password: z3.string().min(1),
1078
- publicKey: z3.string().optional()
1079
- });
1080
- var SignupRequestSchema = z3.object({
1081
- username: z3.string().min(1),
1082
- name: z3.string().min(1),
1083
- email: z3.string().min(1),
1084
- password: z3.string().min(1)
1085
- });
1086
- var LoginResponseSchema = z3.object({
1087
- token: z3.string(),
1088
- user: CloudUserSchema,
1089
- sshCert: z3.string().optional(),
1090
- sshCertExpires: z3.string().optional(),
1091
- /** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
1092
- sshCertPrincipals: z3.array(z3.string()).optional()
1093
- });
1094
- var SshCertRequestSchema = z3.object({
1095
- publicKey: z3.string().min(1)
1096
- });
1097
- var SshCertResponseSchema = z3.object({
1098
- cert: z3.string(),
1099
- expires: z3.string(),
1100
- principals: z3.array(z3.string())
1101
- });
1102
- var SshCaResponseSchema = z3.object({
1103
- publicKey: z3.string(),
1104
- /** CAs replaced by `ca rotate` (#55), newest first; a box still holding one of these has not had `kvbox server trust-ca` run on its host. */
1105
- retired: z3.array(z3.object({ publicKey: z3.string(), retiredAt: z3.string() })).optional()
1106
- });
1107
- var HostSshCaResponseSchema = z3.object({
1108
- publicKey: z3.string()
1109
- });
1110
- var CloudCaSchema = z3.object({
1111
- controlPlane: z3.string(),
1112
- publicKey: z3.string(),
1113
- fingerprint: z3.string()
1114
- });
1115
- var TrustCaRequestSchema = z3.object({
1116
- publicKey: z3.string().min(1)
1117
- });
1118
- var SshKeysAppliedSchema = z3.enum(["now", "start", "wake", "resume", "later"]);
1119
- var TrustCaReportSchema = z3.object({
1120
- publicKey: z3.string(),
1121
- fingerprint: z3.string(),
1122
- /** The guest trusts the CA now. */
1123
- updated: z3.array(z3.string()),
1124
- /** meta.json has the line; the guest gets it at `when`. */
1125
- pending: z3.array(z3.object({ box: z3.string(), when: SshKeysAppliedSchema, why: z3.string().optional() })),
1126
- failed: z3.array(z3.object({ box: z3.string(), error: z3.string() })),
1127
- /** Local boxes, untouched: they trust the host's key only. */
1128
- local: z3.number().int()
1129
- });
1130
- var HostJoinRequestSchema = z3.object({
1131
- token: z3.string().min(1),
1132
- name: z3.string().min(1),
1133
- url: z3.string().url(),
1134
- fingerprint: z3.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
1135
- publicAddress: z3.string().min(1),
1136
- /** Where the host is (`kvbox server join --country`): a code or an English name. */
1137
- country: z3.string().optional()
1138
- });
1139
- var HostJoinResponseSchema = z3.object({
1140
- hostSecret: z3.string(),
1141
- controlPlane: z3.object({ name: z3.string() })
1142
- });
1143
- var CloudHostSchema = z3.object({
1144
- name: z3.string(),
1145
- url: z3.string(),
1146
- publicAddress: z3.string(),
1147
- joinedAt: z3.string(),
1148
- lastSeenAt: z3.string().nullable(),
1149
- capacity: CapacitySchema.nullable(),
1150
- /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
1151
- country: z3.string().nullable()
1152
- });
1153
- var HostPatchRequest = z3.object({ country: z3.string().nullable() });
1154
- var CountrySchema = z3.object({ code: z3.string(), name: z3.string() });
1155
-
1156
- // ../shared/src/ssh.ts
1157
- import { createHash } from "node:crypto";
1158
- var SSH_PUBLIC_KEY_RE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com) ([A-Za-z0-9+/]+=*)(?: [^\r\n]*)?$/;
1159
- function parseSshPublicKey(text) {
1160
- const key = text.trim().replace(/^cert-authority\s+/, "");
1161
- if (!SSH_PUBLIC_KEY_RE.test(key)) {
1162
- throw new KvboxError("that is not an SSH public key; expected one line like: ssh-ed25519 AAAA\u2026 kvbox-ca@kvbox.sh");
737
+ async function ensureLayout(p = paths()) {
738
+ for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
739
+ await mkdir(dir, { recursive: true, mode: 448 });
1163
740
  }
1164
- return key;
1165
- }
1166
- function sshKeyFingerprint(publicKey) {
1167
- const m = SSH_PUBLIC_KEY_RE.exec(publicKey.trim());
1168
- if (!m) throw new KvboxError("cannot fingerprint: not an SSH public key");
1169
- return `SHA256:${createHash("sha256").update(Buffer.from(m[2], "base64")).digest("base64").replace(/=+$/, "")}`;
741
+ return p;
1170
742
  }
1171
- function caLineFor(principal, caPublicKey) {
1172
- return `cert-authority,principals="${principal}" ${caPublicKey}`;
743
+ async function readJson(file, schema) {
744
+ return schema.parse(JSON.parse(await readFile3(file, "utf8")));
1173
745
  }
1174
- var isCaLine = (line) => /^cert-authority(,|\s)/.test(line.trim());
1175
-
1176
- // src/core/exec.ts
1177
- import { execFile } from "node:child_process";
1178
- import { promisify } from "node:util";
1179
- var execFileAsync = promisify(execFile);
1180
- async function run(argv, opts = {}) {
1181
- const [cmd, ...args] = opts.sudo ? ["sudo", "-n", ...argv] : argv;
1182
- if (!cmd) throw new KvboxError("run: empty argv");
1183
- if (process.env["KVBOX_DEBUG"]) console.error(`[exec] ${[cmd, ...args].join(" ")}`);
746
+ async function listDirs(dir) {
1184
747
  try {
1185
- const { stdout, stderr } = await execFileAsync(cmd, args, {
1186
- cwd: opts.cwd,
1187
- env: opts.env ?? process.env,
1188
- timeout: opts.timeoutMs ?? 3e4,
1189
- maxBuffer: 8 * 1024 * 1024
1190
- });
1191
- return { stdout, stderr };
748
+ const entries = await readdir(dir, { withFileTypes: true });
749
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name);
1192
750
  } catch (err) {
1193
- const e = err;
1194
- if (typeof e.code === "number" && opts.okExitCodes?.includes(e.code)) return { stdout: e.stdout ?? "", stderr: e.stderr ?? "" };
1195
- const detail = (e.stderr ?? e.message ?? "").trim();
1196
- throw new KvboxError(`${[cmd, ...args].join(" ")} failed${detail ? `: ${detail}` : ""}`);
751
+ if (err.code === "ENOENT") return [];
752
+ throw err;
1197
753
  }
1198
754
  }
1199
-
1200
- // src/core/controlPlane.ts
1201
- var DEFAULT_HTTPS_PORT = 7777;
1202
- async function ensureTlsCert(p = paths()) {
1203
- const have = await readFile2(p.tlsCert, "utf8").catch(() => null);
1204
- const haveKey = await readFile2(p.tlsKey).then(() => true, () => false);
1205
- if (have === null || !haveKey) {
1206
- await mkdir(p.tls, { recursive: true, mode: 448 });
755
+ async function readMachineMeta(ref, p = paths()) {
756
+ return readJson(p.machine(ref.owner, ref.name).meta, MachineMetaSchema);
757
+ }
758
+ var boxListVersion = 0;
759
+ var boxListVersionNow = () => boxListVersion;
760
+ var boxListChanged = () => void (boxListVersion += 1);
761
+ async function writeMachineMeta(meta, p = paths()) {
762
+ const m = p.machine(meta.owner, meta.name);
763
+ await mkdir(m.dir, { recursive: true });
764
+ const tmp = `${m.meta}.tmp`;
765
+ await writeFile2(tmp, JSON.stringify(meta, null, 2) + "\n");
766
+ await rename2(tmp, m.meta);
767
+ boxListChanged();
768
+ }
769
+ async function listMachineRefs(p = paths()) {
770
+ return listRefs(p.machines);
771
+ }
772
+ async function readSnapshotMeta(ref, p = paths()) {
773
+ return readJson(p.snapshot(ref.owner, ref.name).meta, SnapshotMetaSchema);
774
+ }
775
+ async function writeSnapshotMeta(meta, p = paths(), s = p.snapshot(meta.owner, meta.name)) {
776
+ await mkdir(s.dir, { recursive: true });
777
+ await writeFile2(s.meta, JSON.stringify(meta, null, 2) + "\n");
778
+ }
779
+ async function listSnapshotRefs(p = paths()) {
780
+ return (await listRefs(p.snapshots)).filter((ref) => !ref.name.startsWith("."));
781
+ }
782
+ async function readVolumeMeta(ref, p = paths()) {
783
+ const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z3.string().optional() }));
784
+ if (raw.id !== void 0) return { ...raw, id: raw.id };
785
+ const taken = /* @__PURE__ */ new Set();
786
+ for (const other of await listVolumeRefs(p)) {
1207
787
  try {
1208
- await run([
1209
- "openssl",
1210
- "req",
1211
- "-x509",
1212
- "-newkey",
1213
- "ec",
1214
- "-pkeyopt",
1215
- "ec_paramgen_curve:prime256v1",
1216
- "-nodes",
1217
- "-keyout",
1218
- p.tlsKey,
1219
- "-out",
1220
- p.tlsCert,
1221
- "-subj",
1222
- "/CN=kvbox-host",
1223
- "-days",
1224
- "3650"
1225
- ]);
1226
- } catch (err) {
1227
- throw new KvboxError(`could not make the host's certificate (is openssl installed?): ${err.message}`);
788
+ const j = JSON.parse(await readFile3(p.volume(other.owner, other.name).meta, "utf8"));
789
+ if (typeof j.id === "string") taken.add(j.id);
790
+ } catch {
1228
791
  }
1229
- await chmod2(p.tlsKey, 384);
1230
792
  }
1231
- const pem = await readFile2(p.tlsCert, "utf8");
1232
- return { fingerprint: new X509Certificate(pem).fingerprint256 };
793
+ const meta = { ...raw, id: newBoxId(taken) };
794
+ await writeVolumeMeta(meta, p);
795
+ insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: meta.createdAt, sizeGib: meta.sizeGib, by: "create" }, p);
796
+ return meta;
1233
797
  }
1234
- function isPrivateAddress(ip) {
1235
- const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(ip);
1236
- if (!m) return false;
1237
- const [a, b] = [Number(m[1]), Number(m[2])];
1238
- return a === 10 || a === 127 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127;
798
+ async function writeVolumeMeta(meta, p = paths()) {
799
+ const v = p.volume(meta.owner, meta.name);
800
+ await mkdir(v.dir, { recursive: true, mode: 448 });
801
+ await writeFile2(v.meta, JSON.stringify(meta, null, 2) + "\n");
1239
802
  }
1240
- async function defaultAdvertise() {
1241
- const { stdout } = await run(["ip", "-4", "route", "get", "1.1.1.1"]).catch((err) => {
1242
- throw new KvboxError(`cannot tell this host's address (${err.message}); pass --advertise <host-or-ip>`);
1243
- });
1244
- const m = /\bsrc\s+(\S+)/.exec(stdout);
1245
- if (!m) throw new KvboxError("cannot tell this host's address from its routes; pass --advertise <host-or-ip>");
1246
- return m[1];
803
+ async function listVolumeRefs(p = paths()) {
804
+ return listRefs(p.volumes);
1247
805
  }
1248
- async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdvertise) {
1249
- const url = opts.url.replace(/\/+$/, "");
1250
- const port = opts.port ?? DEFAULT_HTTPS_PORT;
1251
- const cfg = await loadConfig(p);
1252
- if (cfg.controlPlane) throw new KvboxError(`this host has already joined ${cfg.controlPlane.name} (${cfg.controlPlane.url}); run kvbox server leave first`);
1253
- let advertise = opts.advertise;
1254
- if (advertise === void 0 && cfg.relay) {
1255
- advertise = cfg.relay.publicIp;
1256
- } else if (advertise === void 0) {
1257
- advertise = await guessAddress();
1258
- if (isPrivateAddress(advertise)) {
1259
- throw new KvboxError(
1260
- `${advertise} is a private address: a control plane on the internet cannot reach this host there.
1261
- Pass --advertise <public host or ip>, or --advertise ${advertise} if the control plane is on the same network.`
1262
- );
806
+ async function listRefs(root) {
807
+ const out = [];
808
+ for (const owner of await listDirs(root)) {
809
+ for (const name of await listDirs(`${root}/${owner}`)) {
810
+ out.push({ owner, name });
1263
811
  }
1264
812
  }
1265
- const name = opts.name ?? osHostname();
1266
- const country = opts.country === void 0 ? void 0 : parseCountry(opts.country);
1267
- const { fingerprint } = await ensureTlsCert(p);
1268
- const hostUrl = `https://${advertise}:${port}`;
1269
- const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
1270
- const res = await request(`${url}/hosts/join`, {
1271
- method: "POST",
1272
- headers: { "content-type": "application/json" },
1273
- body: JSON.stringify(body),
1274
- headersTimeout: 1e4,
1275
- bodyTimeout: 1e4
1276
- }).catch((err) => {
1277
- throw new KvboxError(`cannot reach ${url} (${err.message})`);
1278
- });
1279
- const text = await res.body.text();
1280
- if (res.statusCode < 200 || res.statusCode >= 300) {
1281
- throw new KvboxError(errorIn(text) ?? `control plane answered ${res.statusCode}`);
1282
- }
1283
- const parsed = HostJoinResponseSchema.safeParse(jsonOrNull(text));
1284
- if (!parsed.success) throw new KvboxError(`${url} did not answer like a kvbox control plane`);
1285
- if (!REALM_RE.test(parsed.data.controlPlane.name)) {
1286
- throw new KvboxError(`${url} calls itself "${parsed.data.controlPlane.name}", which cannot name a realm (letters, digits, '.', '-')`);
813
+ return out;
814
+ }
815
+ function pidAlive(pid) {
816
+ if (pid === null || pid <= 0) return false;
817
+ try {
818
+ process.kill(pid, 0);
819
+ return true;
820
+ } catch (err) {
821
+ return err.code === "EPERM";
1287
822
  }
1288
- await saveConfig({ ...cfg, controlPlane: { url, name: parsed.data.controlPlane.name, secret: parsed.data.hostSecret, advertise, port } }, p);
1289
- return { hostName: name, controlPlane: parsed.data.controlPlane.name, hostUrl };
1290
823
  }
1291
- async function fetchCloudCa(p = paths()) {
1292
- const cfg = await loadConfig(p);
1293
- const cp = cfg.controlPlane;
1294
- if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no CA to fetch; paste the key instead: kvbox server trust-ca <public-key>");
1295
- const res = await request(`${cp.url}/hosts/self/ssh-ca`, {
1296
- headers: { authorization: `Bearer ${cp.secret}` },
1297
- headersTimeout: 1e4,
1298
- bodyTimeout: 1e4
1299
- }).catch((err) => {
1300
- throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
1301
- });
1302
- const text = await res.body.text();
1303
- if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not answer /hosts/self/ssh-ca: it is older than this host; paste the key instead`);
1304
- if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(errorIn(text) ?? `${cp.name} answered ${res.statusCode}`);
1305
- const parsed = HostSshCaResponseSchema.safeParse(jsonOrNull(text));
1306
- if (!parsed.success) throw new KvboxError(`${cp.name} did not answer with a CA key`);
1307
- const publicKey = parseSshPublicKey(parsed.data.publicKey);
1308
- return { controlPlane: cp.name, publicKey, fingerprint: sshKeyFingerprint(publicKey) };
824
+ var bootId;
825
+ function currentBootId() {
826
+ if (bootId === void 0) {
827
+ try {
828
+ bootId = { id: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() };
829
+ } catch {
830
+ bootId = { id: void 0 };
831
+ }
832
+ }
833
+ return bootId.id;
1309
834
  }
1310
- async function leaveControlPlane(p = paths()) {
1311
- const cfg = await loadConfig(p);
1312
- const cp = cfg.controlPlane;
1313
- if (!cp) throw new KvboxError("this host has not joined a control plane");
1314
- const told = await request(`${cp.url}/hosts/self`, {
1315
- method: "DELETE",
1316
- headers: { authorization: `Bearer ${cp.secret}` },
1317
- headersTimeout: 3e3,
1318
- bodyTimeout: 3e3
1319
- }).then(async (res) => {
1320
- await res.body.dump();
1321
- return res.statusCode >= 200 && res.statusCode < 300;
1322
- }).catch(() => false);
1323
- const { controlPlane: _gone, ...rest } = cfg;
1324
- await saveConfig(rest, p);
1325
- return { controlPlane: cp.name, told };
835
+ function vmAlive(meta) {
836
+ if (meta.bootId !== void 0 && meta.bootId !== currentBootId()) return false;
837
+ return pidAlive(meta.pid);
1326
838
  }
1327
- function jsonOrNull(text) {
839
+ function hostBootTime() {
1328
840
  try {
1329
- return JSON.parse(text);
841
+ const m = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
842
+ return m ? new Date(Number(m[1]) * 1e3) : null;
1330
843
  } catch {
1331
844
  return null;
1332
845
  }
1333
846
  }
1334
- function errorIn(text) {
1335
- const v = jsonOrNull(text);
1336
- if (v && typeof v === "object" && typeof v.error === "string") return v.error;
1337
- return void 0;
1338
- }
1339
-
1340
- // src/core/kvm.ts
1341
- import { access, constants, readFile as readFile3, stat } from "node:fs/promises";
1342
- var KVM_DEVICE = "/dev/kvm";
1343
- async function groupName(gid, groupFile = "/etc/group") {
1344
- const text = await readFile3(groupFile, "utf8").catch(() => "");
1345
- for (const line of text.split("\n")) {
1346
- const [name, , id] = line.split(":");
1347
- if (id !== void 0 && Number.parseInt(id, 10) === gid && name) return name;
1348
- }
1349
- return "kvm";
1350
- }
1351
- async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
1352
- try {
1353
- await access(device, constants.R_OK | constants.W_OK);
1354
- return;
1355
- } catch (err) {
1356
- const code = err.code;
1357
- if (code === "ENOENT") {
1358
- throw new KvboxError(`${device} is missing: this machine has no KVM, so boxes cannot run here (enable virtualization in the BIOS, then install-server.sh checks the rest)`);
1359
- }
1360
- if (code !== "EACCES" && code !== "EPERM") throw new KvboxError(`cannot open ${device}: ${err.message}`);
1361
- }
1362
- const owner = await stat(device).then((s) => groupName(s.gid, groupFile), () => "kvm");
1363
- throw new KvboxError(
1364
- `cannot start: this process is not allowed to open ${device}, so no box could run. It was started from a shell without the ${owner} group (a login from before you were added to it). Log out and back in, or start it from a shell that has the group: sg ${owner} -c "kvbox server start"`
1365
- );
1366
- }
1367
847
 
1368
848
  // src/core/dns.ts
1369
- import { createSocket } from "node:dgram";
1370
-
1371
- // src/core/state.ts
1372
- import { randomBytes } from "node:crypto";
1373
- import { readFileSync } from "node:fs";
1374
- import { mkdir as mkdir2, readFile as readFile4, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
1375
- import { z as z4 } from "zod";
1376
-
1377
- // src/core/db.ts
1378
- import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs";
1379
- import { dirname } from "node:path";
1380
- import { DatabaseSync } from "node:sqlite";
1381
- var MIGRATIONS = [
1382
- `create table usage_events (
1383
- id integer primary key,
1384
- box_id text not null,
1385
- owner text not null,
1386
- name text not null,
1387
- at text not null,
1388
- state text not null,
1389
- vcpu integer not null,
1390
- mem_mib integer not null,
1391
- disk_gib integer not null,
1392
- by text not null
1393
- );
1394
- create index usage_events_box_at on usage_events (box_id, at);`,
1395
- // The ledger's identity (#42): a control plane keys pulled rows by it, so a re-join is recognised
1396
- // and a fresh ledger (KVBOX_HOME wiped) restarts its cursor instead of waiting for ids it already saw.
1397
- `create table ledger (id text not null);
1398
- insert into ledger (id) values (lower(hex(randomblob(16))));
1399
- create index usage_events_at on usage_events (at);`,
1400
- // Volumes (#91): a row per create, resize and rm, the size from that moment on. Its own table and
1401
- // ids, pulled by the control plane like usage_events, in the same ledger.
1402
- `create table volume_events (
1403
- id integer primary key,
1404
- volume_id text not null,
1405
- owner text not null,
1406
- name text not null,
1407
- at text not null,
1408
- size_gib integer not null,
1409
- by text not null
1410
- );
1411
- create index volume_events_volume_at on volume_events (volume_id, at);`
1412
- ];
1413
- var handles = /* @__PURE__ */ new Map();
1414
- function openDb(p = paths()) {
1415
- const have = handles.get(p.db);
1416
- if (have !== void 0) return have;
1417
- mkdirSync(dirname(p.db), { recursive: true, mode: 448 });
1418
- closeSync(openSync(p.db, "a", 384));
1419
- chmodSync(p.db, 384);
1420
- const db = new DatabaseSync(p.db);
1421
- db.exec("pragma journal_mode = wal");
1422
- db.exec("pragma busy_timeout = 5000");
1423
- migrate(db);
1424
- handles.set(p.db, db);
1425
- return db;
1426
- }
1427
- function migrate(db) {
1428
- db.exec("create table if not exists schema_version (version integer not null)");
1429
- const row = db.prepare("select version from schema_version").get();
1430
- let version = row?.version ?? 0;
1431
- if (row === void 0) db.prepare("insert into schema_version (version) values (0)").run();
1432
- while (version < MIGRATIONS.length) {
1433
- db.exec("begin");
1434
- try {
1435
- db.exec(MIGRATIONS[version]);
1436
- version += 1;
1437
- db.prepare("update schema_version set version = ?").run(version);
1438
- db.exec("commit");
1439
- } catch (err) {
1440
- db.exec("rollback");
1441
- throw err;
1442
- }
849
+ var DNS_PORT = 10053;
850
+ var DNS_SUFFIX = ".kvbox";
851
+ var DNS_RETRY_MS = 1e4;
852
+ var TTL_SEC = 5;
853
+ var BOXES_FRESH_MS = 6e4;
854
+ var TYPE_A = 1;
855
+ var CLASS_IN = 1;
856
+ var RCODE = { ok: 0, nxDomain: 3, refused: 5 };
857
+ function parseQuery(msg) {
858
+ if (msg.length < 12) return null;
859
+ const flags = msg.readUInt16BE(2);
860
+ const isResponse = flags & 32768;
861
+ const opcode = flags >> 11 & 15;
862
+ if (isResponse || opcode !== 0 || msg.readUInt16BE(4) < 1) return null;
863
+ const labels = [];
864
+ let at = 12;
865
+ for (; ; ) {
866
+ if (at >= msg.length) return null;
867
+ const len = msg[at];
868
+ at += 1;
869
+ if (len === 0) break;
870
+ if (len > 63 || at + len > msg.length) return null;
871
+ labels.push(msg.subarray(at, at + len).toString("latin1"));
872
+ at += len;
1443
873
  }
874
+ if (at + 4 > msg.length) return null;
875
+ return {
876
+ id: msg.readUInt16BE(0),
877
+ rd: Boolean(flags & 256),
878
+ name: labels.join(".").toLowerCase(),
879
+ type: msg.readUInt16BE(at),
880
+ class: msg.readUInt16BE(at + 2),
881
+ question: msg.subarray(12, at + 4)
882
+ };
1444
883
  }
1445
- var LIVE_STATES = ["running", "standby"];
1446
- function fromRaw(r) {
1447
- return { boxId: r.box_id, owner: r.owner, name: r.name, at: r.at, state: r.state, vcpu: r.vcpu, memMib: r.mem_mib, diskGib: r.disk_gib, by: r.by };
1448
- }
1449
- function lastEvent(boxId, db) {
1450
- const raw = db.prepare("select * from usage_events where box_id = ? order by at desc, id desc limit 1").get(boxId);
1451
- return raw === void 0 ? void 0 : fromRaw(raw);
1452
- }
1453
- function insertRaw(e, db) {
1454
- db.prepare(
1455
- "insert into usage_events (box_id, owner, name, at, state, vcpu, mem_mib, disk_gib, by) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"
1456
- ).run(e.boxId, e.owner, e.name, e.at, e.state, e.vcpu, e.memMib, e.diskGib, e.by);
1457
- }
1458
- function insertUsageEvent(e, p = paths()) {
1459
- const db = openDb(p);
1460
- if (e.state === "running" && e.by !== "resume") closeOpenRun(e.boxId, e.at, p);
1461
- insertRaw(e, db);
1462
- }
1463
- function closeOpenRun(boxId, at, p = paths()) {
1464
- const db = openDb(p);
1465
- const last = lastEvent(boxId, db);
1466
- if (last === void 0 || !LIVE_STATES.includes(last.state)) return false;
1467
- insertRaw({ ...last, at, state: "stopped", by: "server" }, db);
1468
- return true;
1469
- }
1470
- function closeRunCutByBoot(boxId, bootAt, now, p = paths()) {
1471
- const last = lastEvent(boxId, openDb(p));
1472
- return closeOpenRun(boxId, last !== void 0 && last.at < bootAt ? bootAt : now, p);
1473
- }
1474
- function usageEventsFor(boxId, since, p = paths()) {
1475
- const rows = openDb(p).prepare("select * from usage_events where box_id = ? and at >= ? order by at, id").all(boxId, since);
1476
- return rows.map(fromRaw);
1477
- }
1478
- var withId = (r) => ({ ...fromRaw(r), id: r.id });
1479
- function ledgerId(p = paths()) {
1480
- return openDb(p).prepare("select id from ledger").get().id;
884
+ function buildAnswer(q, rcode, ip) {
885
+ const header = Buffer.alloc(12);
886
+ header.writeUInt16BE(q.id, 0);
887
+ header.writeUInt16BE(32768 | 1024 | (q.rd ? 256 : 0) | rcode, 2);
888
+ header.writeUInt16BE(1, 4);
889
+ header.writeUInt16BE(ip ? 1 : 0, 6);
890
+ if (!ip) return Buffer.concat([header, q.question]);
891
+ const rr = Buffer.alloc(16);
892
+ rr.writeUInt16BE(49164, 0);
893
+ rr.writeUInt16BE(TYPE_A, 2);
894
+ rr.writeUInt16BE(CLASS_IN, 4);
895
+ rr.writeUInt32BE(TTL_SEC, 6);
896
+ rr.writeUInt16BE(4, 10);
897
+ ip.split(".").forEach((o, i) => rr.writeUInt8(Number(o), 12 + i));
898
+ return Buffer.concat([header, q.question, rr]);
1481
899
  }
1482
- function usageEventsAfter(after, limit, scope, p = paths()) {
1483
- const db = openDb(p);
1484
- const rows = scope === null ? db.prepare("select * from usage_events where id > ? order by id limit ?").all(after, limit) : typeof scope === "string" ? db.prepare("select * from usage_events where id > ? and owner = ? order by id limit ?").all(after, scope, limit) : db.prepare("select * from usage_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?").all(after, `@${scope.realm}`, `@${scope.realm}`, limit);
1485
- return rows.map(withId);
900
+ var slugOf = (owner) => owner.split("@")[0].toLowerCase();
901
+ var isOurs = (q) => q.class === CLASS_IN && q.name.endsWith(DNS_SUFFIX);
902
+ function answerFor(q, asker, boxes) {
903
+ if (!isOurs(q)) return { rcode: RCODE.refused };
904
+ const [name, slug, ...rest] = q.name.slice(0, -DNS_SUFFIX.length).split(".");
905
+ const from = boxes.find((b) => b.ip === asker);
906
+ let box;
907
+ if (from && rest.length === 0) {
908
+ 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));
909
+ }
910
+ if (!box) return { rcode: RCODE.nxDomain };
911
+ return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };
1486
912
  }
1487
- function usageEventsInScope(scope, window, p = paths()) {
1488
- const rows = openDb(p).prepare(
1489
- `select * from usage_events where at < ? and (at >= ? or id in (select max(id) from usage_events where at < ? group by box_id))
1490
- order by at, id`
1491
- ).all(window.to, window.from, window.from);
1492
- return rows.filter((r) => inScope(r.owner, scope)).map(withId);
913
+ async function boxAddresses(p) {
914
+ const out = [];
915
+ for (const ref of await listMachineRefs(p)) {
916
+ const meta = await readMachineMeta(ref, p).catch(() => null);
917
+ if (meta) out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {} });
918
+ }
919
+ return out;
1493
920
  }
1494
- var volumeWithId = (r) => ({ id: r.id, volumeId: r.volume_id, owner: r.owner, name: r.name, at: r.at, sizeGib: r.size_gib, by: r.by });
1495
- function insertVolumeEvent(e, p = paths()) {
1496
- openDb(p).prepare("insert into volume_events (volume_id, owner, name, at, size_gib, by) values (?, ?, ?, ?, ?, ?)").run(e.volumeId, e.owner, e.name, e.at, e.sizeGib, e.by);
921
+ function sharedBoxes(load, freshMs = BOXES_FRESH_MS, version = boxListVersionNow) {
922
+ let last = null;
923
+ return () => {
924
+ if (!last || last.version !== version() || Date.now() - last.at > freshMs) {
925
+ const entry = { at: Date.now(), version: version(), list: load() };
926
+ last = entry;
927
+ entry.list.catch(() => {
928
+ if (last === entry) last = null;
929
+ });
930
+ }
931
+ return last.list;
932
+ };
1497
933
  }
1498
- function volumeEventsAfter(after, limit, scope, p = paths()) {
1499
- const db = openDb(p);
1500
- const rows = scope === null ? db.prepare("select * from volume_events where id > ? order by id limit ?").all(after, limit) : typeof scope === "string" ? db.prepare("select * from volume_events where id > ? and owner = ? order by id limit ?").all(after, scope, limit) : db.prepare("select * from volume_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?").all(after, `@${scope.realm}`, `@${scope.realm}`, limit);
1501
- return rows.map(volumeWithId);
934
+ async function startDns(opts) {
935
+ const p = opts.p ?? paths();
936
+ const boxes = sharedBoxes(opts.boxes ?? (() => boxAddresses(p)));
937
+ const socket = createSocket("udp4");
938
+ socket.on("message", (msg, rinfo) => {
939
+ const q = parseQuery(msg);
940
+ if (!q) return;
941
+ const reply = (a) => socket.send(buildAnswer(q, a.rcode, a.ip), rinfo.port, rinfo.address);
942
+ if (!isOurs(q)) return reply({ rcode: RCODE.refused });
943
+ void boxes().then((list) => answerFor(q, rinfo.address, list)).catch(() => ({ rcode: RCODE.refused })).then(reply);
944
+ });
945
+ await new Promise((resolve2, reject) => {
946
+ socket.once("error", (err) => {
947
+ socket.close();
948
+ reject(err);
949
+ });
950
+ socket.bind(opts.port ?? DNS_PORT, opts.host, () => {
951
+ socket.removeAllListeners("error");
952
+ socket.on("error", () => {
953
+ });
954
+ resolve2();
955
+ });
956
+ });
957
+ return { socket, close: () => new Promise((resolve2) => socket.close(() => resolve2())) };
1502
958
  }
1503
- function volumeEventsInScope(scope, window, p = paths()) {
1504
- const rows = openDb(p).prepare(
1505
- `select * from volume_events where at < ? and (at >= ? or id in (select max(id) from volume_events where at < ? group by volume_id))
1506
- order by at, id`
1507
- ).all(window.to, window.from, window.from);
1508
- return rows.filter((r) => inScope(r.owner, scope)).map(volumeWithId);
959
+
960
+ // src/core/machines.ts
961
+ import { spawn } from "node:child_process";
962
+ import { closeSync as closeSync3, existsSync as existsSync6, openSync as openSync3, statSync as statSync2 } from "node:fs";
963
+ import { link as link2, mkdir as mkdir5, readFile as readFile5, rename as rename5, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
964
+ import { setTimeout as sleep } from "node:timers/promises";
965
+
966
+ // ../shared/src/duration.ts
967
+ var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
968
+ function parseDuration(text) {
969
+ const t = text.trim().toLowerCase();
970
+ if (!/^(\d+[mhd])+$/.test(t)) return void 0;
971
+ let sec = 0;
972
+ for (const [, n, unit] of t.matchAll(/(\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit];
973
+ return sec;
1509
974
  }
1510
975
 
1511
- // src/core/state.ts
1512
- var MachineMetaSchema = z4.object({
1513
- /** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */
976
+ // ../shared/src/api.ts
977
+ import { z as z4 } from "zod";
978
+ var SizeSchema = z4.enum(SIZE_NAMES);
979
+ var BoxStatusSchema = z4.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
980
+ var PortProtoSchema = z4.enum(["tcp", "udp"]);
981
+ var MAX_BOX_PORTS = 16;
982
+ var PortForwardSchema = z4.object({
983
+ guestPort: z4.number().int().min(1).max(65535),
984
+ hostPort: z4.number().int(),
985
+ proto: PortProtoSchema,
986
+ /** The host's public address; only the control plane fills it in, as for `ssh`. */
987
+ address: z4.string().optional()
988
+ });
989
+ var PortsRequest = z4.object({
990
+ ports: z4.array(z4.object({ guestPort: z4.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
991
+ });
992
+ var BoxPortSchema = z4.number().int().min(1).max(65535);
993
+ var MAX_BOX_LINKS = 32;
994
+ var BoxLinkSchema = z4.object({ from: z4.string(), port: BoxPortSchema });
995
+ var LinkRequest = z4.object({ from: z4.string().min(1), fromOwner: z4.string().optional(), port: BoxPortSchema });
996
+ var ClaimSubdomainRequest = z4.object({ name: z4.string(), port: BoxPortSchema });
997
+ var SubdomainPortRequest = z4.object({ port: BoxPortSchema });
998
+ var SubdomainRouteRequest = z4.object({ name: z4.string(), port: BoxPortSchema });
999
+ var SubdomainSchema = z4.object({
1000
+ owner: z4.string(),
1001
+ box: z4.string(),
1002
+ subdomain: z4.string(),
1003
+ port: BoxPortSchema,
1004
+ url: z4.string(),
1005
+ routes: z4.array(z4.object({ name: z4.string(), port: BoxPortSchema, url: z4.string() }))
1006
+ });
1007
+ var AddDomainRequest = z4.object({ domain: z4.string(), port: BoxPortSchema.optional() });
1008
+ var DomainSchema = z4.object({
1009
+ owner: z4.string(),
1010
+ box: z4.string(),
1011
+ domain: z4.string(),
1012
+ port: BoxPortSchema,
1013
+ status: z4.enum(["pending", "live"]),
1014
+ www: z4.boolean(),
1015
+ url: z4.string(),
1016
+ error: z4.string().nullable(),
1017
+ records: z4.array(z4.object({ type: z4.enum(["A", "TXT", "CNAME"]), name: z4.string(), value: z4.string() })),
1018
+ createdAt: z4.string()
1019
+ });
1020
+ var WakeHookSchema = z4.object({
1021
+ id: z4.string(),
1022
+ owner: z4.string(),
1023
+ box: z4.string(),
1024
+ url: z4.string(),
1025
+ createdBy: z4.string().nullable(),
1026
+ createdAt: z4.string(),
1027
+ lastCalledAt: z4.string().nullable()
1028
+ });
1029
+ var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z4.string() });
1030
+ var WakeHookCallSchema = z4.object({
1031
+ box: z4.string(),
1032
+ action: z4.enum(["wake", "resume", "none"]),
1033
+ reason: z4.string().optional()
1034
+ });
1035
+ var BACKUP_STATUSES = ["running", "ready", "failed"];
1036
+ var BackupSchema = z4.object({
1037
+ id: z4.string(),
1038
+ owner: z4.string(),
1039
+ box: z4.string(),
1040
+ status: z4.enum(BACKUP_STATUSES),
1041
+ /** Why it failed; null otherwise. */
1042
+ error: z4.string().nullable(),
1043
+ /** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
1044
+ base: z4.string().nullable(),
1045
+ image: z4.string().optional(),
1046
+ vcpu: z4.number().int().nullable(),
1047
+ memMib: z4.number().int().nullable(),
1048
+ /** The disk's size. */
1049
+ diskBytes: z4.number().int().nullable(),
1050
+ /** What it holds: the slots that are not all zeros. */
1051
+ dataBytes: z4.number().int().nullable(),
1052
+ /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
1053
+ uploadedBytes: z4.number().int().nullable(),
1054
+ createdBy: z4.string().nullable(),
1055
+ createdAt: z4.string(),
1056
+ finishedAt: z4.string().nullable()
1057
+ });
1058
+ var HostBackupRequest = z4.object({ id: z4.string(), key: z4.string() });
1059
+ var HostBackupManifestSchema = z4.object({
1060
+ id: z4.string(),
1061
+ sizeBytes: z4.number().int(),
1062
+ chunks: z4.array(z4.string().nullable()),
1063
+ env: z4.string().nullable(),
1064
+ base: z4.string(),
1065
+ image: z4.string().optional(),
1066
+ vcpu: z4.number().int(),
1067
+ memMib: z4.number().int()
1068
+ });
1069
+ var HostUploadRequest = z4.object({ key: z4.string(), urls: z4.record(z4.string(), z4.string()) });
1070
+ var HostUploadResultSchema = z4.object({ chunks: z4.number().int(), bytes: z4.number().int(), sizes: z4.record(z4.string(), z4.number().int()) });
1071
+ var HostRestoreRequest = z4.object({
1072
+ /** The backup's id: its variables were sealed under it. */
1073
+ id: z4.string(),
1074
+ key: z4.string(),
1075
+ sizeBytes: z4.number().int().positive(),
1076
+ base: z4.string(),
1077
+ image: z4.string().optional(),
1078
+ env: z4.string().nullable(),
1079
+ chunks: z4.array(z4.object({ index: z4.number().int().nonnegative(), hash: z4.string(), url: z4.string() }))
1080
+ });
1081
+ var MachineSchema = z4.object({
1082
+ /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
1514
1083
  id: z4.string(),
1515
1084
  name: z4.string(),
1516
- /** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */
1085
+ /** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */
1517
1086
  owner: z4.string(),
1518
1087
  ip: z4.string(),
1519
1088
  mac: z4.string(),
1520
1089
  pid: z4.number().int().nullable(),
1521
- // null: stopped on purpose, disk kept
1522
- /**
1523
- * The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot
1524
- * the number can name some other process; a pid from another boot is dead whatever `kill -0` says.
1525
- * Absent (boxes launched before #29): the pid alone decides.
1526
- */
1527
- bootId: z4.string().optional(),
1528
1090
  vcpu: z4.number().int(),
1529
1091
  memMib: z4.number().int(),
1530
- createdAt: z4.string(),
1531
- source: z4.string(),
1532
- /** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */
1092
+ diskBytes: z4.number().int(),
1093
+ // the box's own writable disk, as the guest sees it
1094
+ diskUsedBytes: z4.number().int(),
1095
+ // what the box uses of it: the filesystem's own count, like the guest's `df` (#115)
1096
+ /** What the disk's sparse file occupies on the host. Grows while the box runs, `kvbox stop` trims it back. Hosts before 0.5.42 do not send it. */
1097
+ diskHostBytes: z4.number().int().optional(),
1533
1098
  base: z4.string(),
1534
- /** The image (#87), when not the base one: assets/images/<image>/rootfs-<base>.ext4. `vm update` keeps it. */
1099
+ // version of the image the box's overlay stacks on
1100
+ /** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
1535
1101
  image: z4.string().optional(),
1536
- /** The image's connect line with its secrets masked and `${BOX}` unfilled (#87, `maskedUrl`). Absent: the image declares none. */
1102
+ createdAt: z4.string(),
1103
+ source: z4.string(),
1104
+ // "base", "snapshot:<owner/name>" or "fork:<owner/name>" (#79)
1105
+ status: BoxStatusSchema,
1106
+ /**
1107
+ * Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made
1108
+ * through a control plane have one; the control plane adds the host's address for `connect` (#21).
1109
+ */
1110
+ sshPort: z4.number().int().optional(),
1111
+ /**
1112
+ * Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only
1113
+ * the control plane fills it in (a host does not know its own public address); absent for a box
1114
+ * whose host reported no port or did not answer.
1115
+ */
1116
+ ssh: z4.object({ host: z4.string(), port: z4.number().int(), user: z4.string() }).optional(),
1117
+ /** Box ports published on the host (#30). Absent: none. */
1118
+ ports: z4.array(PortForwardSchema).optional(),
1119
+ /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
1120
+ ownerKind: z4.enum(["user", "org"]).optional(),
1121
+ /**
1122
+ * The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
1123
+ * links to, and a volume attaches to, only a box on the same host.
1124
+ */
1125
+ host: z4.string().optional(),
1126
+ /** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
1127
+ country: z4.string().optional(),
1128
+ /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
1129
+ autoHibernateSec: z4.number().int().positive().optional(),
1130
+ /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
1131
+ idleCheck: z4.string().optional(),
1132
+ /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
1133
+ volumes: z4.array(z4.object({ name: z4.string(), sizeGib: z4.number().int(), mountPath: z4.string() })).optional(),
1134
+ /** Boxes that may reach this one, each on one port (#98). Absent: none. */
1135
+ links: z4.array(BoxLinkSchema).optional(),
1136
+ /** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */
1537
1137
  url: z4.string().optional(),
1538
1138
  /**
1539
- * Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
1540
- * each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
1541
- * is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.
1139
+ * Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
1140
+ * serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
1542
1141
  */
1543
- memSnapshots: z4.number().int().optional(),
1544
- /** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */
1545
- paused: z4.boolean().optional(),
1142
+ connect: z4.string().optional()
1143
+ });
1144
+ var VolumeSchema = z4.object({
1145
+ /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
1146
+ id: z4.string(),
1147
+ name: z4.string(),
1148
+ owner: z4.string(),
1149
+ sizeGib: z4.number().int(),
1150
+ /** What the sparse file really occupies on the host. */
1151
+ usedBytes: z4.number().int(),
1152
+ attachedTo: z4.string().nullable(),
1153
+ createdAt: z4.string(),
1154
+ /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
1155
+ ownerKind: z4.enum(["user", "org"]).optional(),
1156
+ /** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
1157
+ host: z4.string().optional()
1158
+ });
1159
+ var MAX_VOLUME_GIB = 4096;
1160
+ var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
1161
+ var VOLUME_NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
1162
+ var CreateVolumeRequest = z4.object({
1163
+ name: z4.string(),
1164
+ sizeGib: z4.number().int().min(1).max(MAX_VOLUME_GIB),
1546
1165
  /**
1547
- * authorized_keys lines the box gets on top of the host's own key, as the control plane sent them
1548
- * at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so
1549
- * `start` has to send the same lines again. Absent: host key only.
1166
+ * Through a control plane (#91): the box this volume is for, so it is made on that box's host; the
1167
+ * control plane requires it (a volume attaches only to a box on its own host, so one made for no box
1168
+ * could never attach) and the CLI attaches right after. A host ignores it.
1169
+ */
1170
+ box: z4.string().optional()
1171
+ });
1172
+ var AttachVolumeRequest = z4.object({
1173
+ box: z4.string()
1174
+ });
1175
+ var EnvVarSchema = z4.object({
1176
+ name: z4.string(),
1177
+ value: z4.string().optional(),
1178
+ secret: z4.boolean(),
1179
+ updatedAt: z4.string()
1180
+ });
1181
+ var BoxEnvSchema = z4.object({
1182
+ box: z4.string(),
1183
+ vars: z4.array(EnvVarSchema)
1184
+ });
1185
+ var BoxEnvChangeSchema = z4.object({
1186
+ box: z4.string(),
1187
+ name: z4.string(),
1188
+ /** Whether the box is running now: the change waits for its next start. */
1189
+ running: z4.boolean()
1190
+ });
1191
+ var SetEnvRequest = z4.object({
1192
+ value: z4.string(),
1193
+ secret: z4.boolean().optional()
1194
+ });
1195
+ var EnvChangeSchema = z4.object({
1196
+ owner: z4.string(),
1197
+ name: z4.string(),
1198
+ boxes: z4.number().int()
1199
+ });
1200
+ var HostEnvRequest = z4.object({
1201
+ version: z4.number().int().min(0),
1202
+ vars: z4.array(z4.object({ name: z4.string(), value: z4.string() }))
1203
+ });
1204
+ var HostEnvVersionsSchema = z4.array(z4.object({ owner: z4.string(), version: z4.number().int() }));
1205
+ var CreateMachineRequest = z4.object({
1206
+ name: z4.string().optional(),
1207
+ /** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
1208
+ owner: z4.string().optional(),
1209
+ size: SizeSchema.optional(),
1210
+ from: z4.string().optional(),
1211
+ force: z4.boolean().optional(),
1212
+ /**
1213
+ * Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends
1214
+ * its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every
1215
+ * boot (#49); a host older than that ignores them.
1550
1216
  */
1551
1217
  sshKeys: z4.array(z4.string()).optional(),
1218
+ /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
1219
+ autoHibernateSec: z4.number().int().min(0).optional(),
1552
1220
  /**
1553
- * The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,
1554
- * or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.
1221
+ * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
1222
+ * control plane reads it; a host has one place to put a box.
1555
1223
  */
1556
- sshKeysStale: z4.boolean().optional(),
1557
- /** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */
1558
- sshPort: z4.number().int().optional(),
1224
+ near: z4.string().optional(),
1559
1225
  /**
1560
- * Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,
1561
- * each host port the box's for its life. DNATed while the box runs, rebuilt from here with its
1562
- * current IP every time it comes up. Absent: none.
1226
+ * Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
1227
+ * `@kvbox/shared/country`. Only the control plane reads it.
1563
1228
  */
1564
- ports: z4.array(z4.object({ guestPort: z4.number().int(), hostPort: z4.number().int(), proto: z4.enum(["tcp", "udp"]) })).optional(),
1565
- /** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
1566
- autoHibernateSec: z4.number().int().positive().optional(),
1229
+ country: z4.string().optional(),
1230
+ /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
1231
+ image: z4.string().optional(),
1232
+ /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
1233
+ env: z4.array(z4.object({ name: z4.string(), value: z4.string() })).optional()
1234
+ });
1235
+ var ForkMachineRequest = z4.object({
1236
+ name: z4.string().optional(),
1567
1237
  /**
1568
- * A script inside the box auto-hibernate asks instead of watching the tap (#102, core/idle.ts): run by
1569
- * kvbox-agent, exit 0 = idle. A new box gets its image's `idle` (image.json); `kvbox vm set --idle-check`
1570
- * changes it. The one place the host looks. Absent: the traffic rule.
1238
+ * The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host
1239
+ * qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.
1571
1240
  */
1572
- idleCheck: z4.string().optional(),
1241
+ owner: z4.string().optional(),
1242
+ /** A cold fork only: a warm one keeps the source's vCPU and memory. */
1243
+ size: SizeSchema.optional(),
1244
+ force: z4.boolean().optional(),
1245
+ /** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */
1246
+ sshKeys: z4.array(z4.string()).optional(),
1247
+ autoHibernateSec: z4.number().int().min(0).optional()
1248
+ });
1249
+ var SetSshKeysRequest = z4.object({
1250
+ sshKeys: z4.array(z4.string())
1251
+ });
1252
+ var RescaleMachineRequest = z4.object({
1253
+ size: SizeSchema.optional(),
1254
+ vcpu: z4.number().int().min(1).max(64).optional(),
1255
+ memMib: z4.number().int().min(256).optional(),
1256
+ diskGib: z4.number().int().min(1).optional(),
1257
+ /** Skip the capacity guard when a running box grows (#37). */
1258
+ force: z4.boolean().optional()
1259
+ });
1260
+ var StartMachineRequest = z4.object({
1261
+ force: z4.boolean().optional()
1262
+ });
1263
+ var SetMachineRequest = z4.object({
1264
+ /** Seconds without network traffic before the box is hibernated (#47); 0: never. */
1265
+ autoHibernateSec: z4.number().int().min(0).optional(),
1266
+ /** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
1267
+ idleCheck: z4.union([z4.literal(""), z4.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
1268
+ });
1269
+ var SnapshotSchema = z4.object({
1270
+ name: z4.string(),
1271
+ owner: z4.string(),
1272
+ source: z4.string(),
1273
+ // the box it was taken from, as owner/name
1274
+ base: z4.string(),
1275
+ // version of the image the overlay stacks on; a restore needs the same one
1276
+ /** As in MachineSchema: the image when it is not the base one (#87). */
1277
+ image: z4.string().optional(),
1278
+ vcpu: z4.number().int(),
1279
+ memMib: z4.number().int(),
1280
+ sizeBytes: z4.number().int(),
1281
+ // what vmstate + mem + overlay really occupy on the host
1282
+ createdAt: z4.string()
1283
+ });
1284
+ var CreateSnapshotRequest = z4.object({
1285
+ box: z4.string(),
1286
+ name: z4.string(),
1287
+ /** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
1288
+ replace: z4.boolean().optional()
1289
+ });
1290
+ var DiskCapacitySchema = z4.object({
1291
+ totalGib: z4.number().int(),
1292
+ freeGib: z4.number().int(),
1293
+ volumesGib: z4.number().int(),
1294
+ volumesUsedGib: z4.number().int(),
1295
+ headroomGib: z4.number().int()
1296
+ });
1297
+ var CapacitySchema = z4.object({
1298
+ hostMemMib: z4.number().int(),
1299
+ hostCores: z4.number().int(),
1300
+ reservedMemMib: z4.number().int(),
1301
+ reservedVcpu: z4.number().int(),
1302
+ running: z4.number().int(),
1303
+ /** Absent on a host from before volumes (#91): it cannot take one. */
1304
+ disk: DiskCapacitySchema.optional(),
1573
1305
  /**
1574
- * Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
1575
- * their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
1576
- * volume's meta.json does not say. Absent: none.
1306
+ * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
1307
+ * Absent on a host from before images: it has only the base.
1577
1308
  */
1578
- volumes: z4.array(z4.string()).optional(),
1309
+ images: z4.array(z4.object({ name: z4.string(), version: z4.string() })).optional()
1310
+ });
1311
+ var ImageSchema = z4.object({ name: z4.string(), version: z4.string().nullable() });
1312
+ var RecoveryReportSchema = z4.object({
1313
+ at: z4.string(),
1314
+ booted: z4.array(z4.string()),
1315
+ leftStopped: z4.array(z4.string()),
1316
+ failed: z4.array(z4.object({ box: z4.string(), error: z4.string() }))
1317
+ });
1318
+ var HealthSchema = z4.object({
1319
+ ok: z4.literal(true),
1320
+ version: z4.string(),
1321
+ pid: z4.number().int(),
1322
+ /** Base image version new boxes get (null when the host has no usable base image yet). */
1323
+ base: z4.string().nullable(),
1324
+ /** Owner that boxes made over the local socket get (the Unix user running the server). */
1325
+ owner: z4.string(),
1326
+ /** The control plane this host joined (null when none). */
1327
+ controlPlane: z4.object({
1328
+ /** Realm name, e.g. kvbox.sh. */
1329
+ name: z4.string(),
1330
+ url: z4.string(),
1331
+ /** Where this host answers the control plane. */
1332
+ hostUrl: z4.string()
1333
+ }).nullable(),
1334
+ /** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */
1335
+ relay: z4.object({
1336
+ name: z4.string(),
1337
+ /** The public IP the relay owns for this host. */
1338
+ publicIp: z4.string(),
1339
+ /** The relay's WireGuard endpoint the tunnel dials. */
1340
+ endpoint: z4.string(),
1341
+ /** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */
1342
+ restarts: z4.number().int().optional(),
1343
+ lastRestartAt: z4.string().nullable().optional()
1344
+ }).nullable().optional(),
1345
+ /** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */
1346
+ recovery: RecoveryReportSchema.nullable().optional()
1347
+ });
1348
+ var MachineUsageSchema = z4.object({
1349
+ name: z4.string(),
1350
+ owner: z4.string(),
1351
+ status: BoxStatusSchema,
1352
+ window: z4.object({ from: z4.string(), to: z4.string() }),
1353
+ seconds: z4.object({
1354
+ running: z4.number().int(),
1355
+ standby: z4.number().int(),
1356
+ hibernated: z4.number().int(),
1357
+ stopped: z4.number().int()
1358
+ }),
1359
+ vcpuHours: z4.number(),
1360
+ ramGibHours: z4.number(),
1361
+ diskGibHours: z4.number(),
1362
+ cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
1363
+ /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */
1364
+ estimatedStops: z4.number().int(),
1365
+ historyFrom: z4.string().nullable()
1366
+ });
1367
+ var GuestStatsSchema = z4.object({
1368
+ /** Load average over 1, 5 and 15 minutes. */
1369
+ load: z4.tuple([z4.number(), z4.number(), z4.number()]),
1370
+ cpus: z4.number().int(),
1371
+ memTotalMib: z4.number().int(),
1372
+ /** Total minus available: page cache counts as free. */
1373
+ memUsedMib: z4.number().int(),
1374
+ /** The box's root, which is its overlay disk: the box's own writes, not the shared base. */
1375
+ diskTotalBytes: z4.number().int(),
1376
+ diskUsedBytes: z4.number().int(),
1377
+ uptimeSec: z4.number().int()
1378
+ });
1379
+ var MachineStatsSchema = z4.object({
1380
+ name: z4.string(),
1381
+ owner: z4.string(),
1382
+ stats: GuestStatsSchema.nullable()
1383
+ });
1384
+ var UsageStatusSchema = z4.enum([...BoxStatusSchema.options, "removed"]);
1385
+ var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({
1386
+ /** The host's box id; a name removed and recreated appears twice, with two ids. */
1387
+ id: z4.string(),
1388
+ status: UsageStatusSchema,
1389
+ /** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */
1390
+ ownerKind: z4.enum(["user", "org"]).optional(),
1579
1391
  /**
1580
- * Links into this box (#98, `kvbox vm link`): box `owner/name`, at `ip`, may open TCP connections to
1581
- * `port`. The rule is open while this box runs, rebuilt from here at every boot; `ip` is the other
1582
- * box's, fixed for its life, and checked against its meta.json before a rule opens. `stale`: that box
1583
- * was removed but the rule would not close; kept only so this box's next stop closes it, never opened
1584
- * again, never listed (a new box of the same name may get the same IP). Absent: none.
1392
+ * Through a control plane: the username that made the box (#60), absent when the box is gone from
1393
+ * the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.
1585
1394
  */
1586
- links: z4.array(z4.object({ owner: z4.string(), name: z4.string(), ip: z4.string(), port: z4.number().int(), stale: z4.literal(true).optional() })).optional()
1395
+ createdBy: z4.string().optional()
1587
1396
  });
1588
- var VolumeMetaSchema = z4.object({
1589
- /** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
1397
+ var VolumeUsageSchema = z4.object({
1398
+ /** The host's volume id; a name removed and made again appears twice, with two ids. */
1590
1399
  id: z4.string(),
1591
1400
  name: z4.string(),
1592
1401
  owner: z4.string(),
1402
+ ownerKind: z4.enum(["user", "org"]).optional(),
1403
+ /** The size at the end of the window (or when removed). */
1593
1404
  sizeGib: z4.number().int(),
1594
- createdAt: z4.string()
1405
+ status: z4.enum(["present", "removed"]),
1406
+ volumeHours: z4.number(),
1407
+ volumeGibHours: z4.number(),
1408
+ cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
1409
+ historyFrom: z4.string().nullable()
1595
1410
  });
1596
- function newBoxId(taken) {
1597
- for (; ; ) {
1598
- const id = randomBytes(3).toString("hex");
1599
- if (!taken.has(id)) return id;
1600
- }
1601
- }
1602
- var SnapshotMetaSchema = z4.object({
1603
- name: z4.string(),
1411
+ var UsageReportSchema = z4.object({
1412
+ window: z4.object({ from: z4.string(), to: z4.string() }),
1413
+ boxes: z4.array(BoxUsageSchema),
1414
+ /** Absent from a side older than #91. */
1415
+ volumes: z4.array(VolumeUsageSchema).optional(),
1416
+ totals: z4.object({
1417
+ seconds: MachineUsageSchema.shape.seconds,
1418
+ vcpuHours: z4.number(),
1419
+ ramGibHours: z4.number(),
1420
+ diskGibHours: z4.number(),
1421
+ volumeHours: z4.number().optional(),
1422
+ volumeGibHours: z4.number().optional(),
1423
+ /** Boxes and volumes together. */
1424
+ cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional()
1425
+ })
1426
+ });
1427
+ var UsageEventRowSchema = z4.object({
1428
+ id: z4.number().int(),
1429
+ boxId: z4.string(),
1604
1430
  owner: z4.string(),
1605
- /** The box it was taken from, as owner/name. */
1606
- source: z4.string(),
1607
- base: z4.string(),
1608
- /** As in a box's meta.json (#87). */
1609
- image: z4.string().optional(),
1431
+ name: z4.string(),
1432
+ at: z4.string(),
1433
+ state: z4.enum(["running", "standby", "hibernated", "stopped"]),
1610
1434
  vcpu: z4.number().int(),
1611
1435
  memMib: z4.number().int(),
1612
- sizeBytes: z4.number().int(),
1436
+ diskGib: z4.number().int(),
1437
+ by: z4.string()
1438
+ });
1439
+ var UsageEventsResponseSchema = z4.object({
1440
+ ledger: z4.string().min(1),
1441
+ events: z4.array(UsageEventRowSchema),
1442
+ next: z4.number().int()
1443
+ });
1444
+ var VolumeEventRowSchema = z4.object({
1445
+ id: z4.number().int(),
1446
+ volumeId: z4.string(),
1447
+ owner: z4.string(),
1448
+ name: z4.string(),
1449
+ at: z4.string(),
1450
+ sizeGib: z4.number().int(),
1451
+ by: z4.enum(["create", "resize", "rm"])
1452
+ });
1453
+ var VolumeEventsResponseSchema = z4.object({
1454
+ ledger: z4.string().min(1),
1455
+ events: z4.array(VolumeEventRowSchema),
1456
+ next: z4.number().int()
1457
+ });
1458
+ var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
1459
+ var ApiErrorCodeSchema = z4.enum(API_ERROR_CODES);
1460
+ var ApiErrorSchema = z4.object({
1461
+ error: z4.string(),
1462
+ code: ApiErrorCodeSchema.optional()
1463
+ });
1464
+ var ACTIVATED_BY = ["card", "admin"];
1465
+ var ActivatedBySchema = z4.enum(ACTIVATED_BY);
1466
+ var CloudUserSchema = z4.object({
1467
+ /** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */
1468
+ username: z4.string(),
1469
+ /** Display name, free text ("Alexandru Ghiura"). */
1470
+ name: z4.string(),
1471
+ /** Login identity, unique. */
1472
+ email: z4.string(),
1473
+ role: z4.enum(["admin", "user"]),
1613
1474
  createdAt: z4.string(),
1614
1475
  /**
1615
- * The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
1616
- * and their mounts in the memory image, but their data is not here. A box restored from the snapshot
1617
- * gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
1476
+ * False until a card is on file or an admin activates the account (#74): then only `/me` and
1477
+ * `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and
1478
+ * gates nobody, hence the defaults: a newer CLI must still parse its answers.
1618
1479
  */
1619
- volumes: z4.array(z4.object({ name: z4.string(), sizeGib: z4.number().int() })).optional()
1480
+ active: z4.boolean().default(true),
1481
+ activatedBy: ActivatedBySchema.nullable().default(null)
1620
1482
  });
1621
- async function ensureLayout(p = paths()) {
1622
- for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
1623
- await mkdir2(dir, { recursive: true, mode: 448 });
1624
- }
1625
- return p;
1626
- }
1627
- async function readJson(file, schema) {
1628
- return schema.parse(JSON.parse(await readFile4(file, "utf8")));
1629
- }
1630
- async function listDirs(dir) {
1631
- try {
1632
- const entries = await readdir(dir, { withFileTypes: true });
1633
- return entries.filter((e) => e.isDirectory()).map((e) => e.name);
1634
- } catch (err) {
1635
- if (err.code === "ENOENT") return [];
1636
- throw err;
1637
- }
1638
- }
1639
- async function readMachineMeta(ref, p = paths()) {
1640
- return readJson(p.machine(ref.owner, ref.name).meta, MachineMetaSchema);
1641
- }
1642
- var boxListVersion = 0;
1643
- var boxListVersionNow = () => boxListVersion;
1644
- var boxListChanged = () => void (boxListVersion += 1);
1645
- async function writeMachineMeta(meta, p = paths()) {
1646
- const m = p.machine(meta.owner, meta.name);
1647
- await mkdir2(m.dir, { recursive: true });
1648
- const tmp = `${m.meta}.tmp`;
1649
- await writeFile2(tmp, JSON.stringify(meta, null, 2) + "\n");
1650
- await rename2(tmp, m.meta);
1651
- boxListChanged();
1652
- }
1653
- async function listMachineRefs(p = paths()) {
1654
- return listRefs(p.machines);
1655
- }
1656
- async function readSnapshotMeta(ref, p = paths()) {
1657
- return readJson(p.snapshot(ref.owner, ref.name).meta, SnapshotMetaSchema);
1658
- }
1659
- async function writeSnapshotMeta(meta, p = paths(), s = p.snapshot(meta.owner, meta.name)) {
1660
- await mkdir2(s.dir, { recursive: true });
1661
- await writeFile2(s.meta, JSON.stringify(meta, null, 2) + "\n");
1662
- }
1663
- async function listSnapshotRefs(p = paths()) {
1664
- return (await listRefs(p.snapshots)).filter((ref) => !ref.name.startsWith("."));
1665
- }
1666
- async function readVolumeMeta(ref, p = paths()) {
1667
- const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z4.string().optional() }));
1668
- if (raw.id !== void 0) return { ...raw, id: raw.id };
1669
- const taken = /* @__PURE__ */ new Set();
1670
- for (const other of await listVolumeRefs(p)) {
1671
- try {
1672
- const j = JSON.parse(await readFile4(p.volume(other.owner, other.name).meta, "utf8"));
1673
- if (typeof j.id === "string") taken.add(j.id);
1674
- } catch {
1675
- }
1676
- }
1677
- const meta = { ...raw, id: newBoxId(taken) };
1678
- await writeVolumeMeta(meta, p);
1679
- insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: meta.createdAt, sizeGib: meta.sizeGib, by: "create" }, p);
1680
- return meta;
1681
- }
1682
- async function writeVolumeMeta(meta, p = paths()) {
1683
- const v = p.volume(meta.owner, meta.name);
1684
- await mkdir2(v.dir, { recursive: true, mode: 448 });
1685
- await writeFile2(v.meta, JSON.stringify(meta, null, 2) + "\n");
1686
- }
1687
- async function listVolumeRefs(p = paths()) {
1688
- return listRefs(p.volumes);
1689
- }
1690
- async function listRefs(root) {
1691
- const out = [];
1692
- for (const owner of await listDirs(root)) {
1693
- for (const name of await listDirs(`${root}/${owner}`)) {
1694
- out.push({ owner, name });
1695
- }
1696
- }
1697
- return out;
1698
- }
1699
- function pidAlive(pid) {
1700
- if (pid === null || pid <= 0) return false;
1701
- try {
1702
- process.kill(pid, 0);
1703
- return true;
1704
- } catch (err) {
1705
- return err.code === "EPERM";
1706
- }
1707
- }
1708
- var bootId;
1709
- function currentBootId() {
1710
- if (bootId === void 0) {
1711
- try {
1712
- bootId = { id: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() };
1713
- } catch {
1714
- bootId = { id: void 0 };
1715
- }
1716
- }
1717
- return bootId.id;
1718
- }
1719
- function vmAlive(meta) {
1720
- if (meta.bootId !== void 0 && meta.bootId !== currentBootId()) return false;
1721
- return pidAlive(meta.pid);
1722
- }
1723
- function hostBootTime() {
1724
- try {
1725
- const m = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
1726
- return m ? new Date(Number(m[1]) * 1e3) : null;
1727
- } catch {
1728
- return null;
1729
- }
1730
- }
1731
-
1732
- // src/core/dns.ts
1733
- var DNS_PORT = 10053;
1734
- var DNS_SUFFIX = ".kvbox";
1735
- var DNS_RETRY_MS = 1e4;
1736
- var TTL_SEC = 5;
1737
- var BOXES_FRESH_MS = 6e4;
1738
- var TYPE_A = 1;
1739
- var CLASS_IN = 1;
1740
- var RCODE = { ok: 0, nxDomain: 3, refused: 5 };
1741
- function parseQuery(msg) {
1742
- if (msg.length < 12) return null;
1743
- const flags = msg.readUInt16BE(2);
1744
- const isResponse = flags & 32768;
1745
- const opcode = flags >> 11 & 15;
1746
- if (isResponse || opcode !== 0 || msg.readUInt16BE(4) < 1) return null;
1747
- const labels = [];
1748
- let at = 12;
1749
- for (; ; ) {
1750
- if (at >= msg.length) return null;
1751
- const len = msg[at];
1752
- at += 1;
1753
- if (len === 0) break;
1754
- if (len > 63 || at + len > msg.length) return null;
1755
- labels.push(msg.subarray(at, at + len).toString("latin1"));
1756
- at += len;
1757
- }
1758
- if (at + 4 > msg.length) return null;
1759
- return {
1760
- id: msg.readUInt16BE(0),
1761
- rd: Boolean(flags & 256),
1762
- name: labels.join(".").toLowerCase(),
1763
- type: msg.readUInt16BE(at),
1764
- class: msg.readUInt16BE(at + 2),
1765
- question: msg.subarray(12, at + 4)
1766
- };
1767
- }
1768
- function buildAnswer(q, rcode, ip) {
1769
- const header = Buffer.alloc(12);
1770
- header.writeUInt16BE(q.id, 0);
1771
- header.writeUInt16BE(32768 | 1024 | (q.rd ? 256 : 0) | rcode, 2);
1772
- header.writeUInt16BE(1, 4);
1773
- header.writeUInt16BE(ip ? 1 : 0, 6);
1774
- if (!ip) return Buffer.concat([header, q.question]);
1775
- const rr = Buffer.alloc(16);
1776
- rr.writeUInt16BE(49164, 0);
1777
- rr.writeUInt16BE(TYPE_A, 2);
1778
- rr.writeUInt16BE(CLASS_IN, 4);
1779
- rr.writeUInt32BE(TTL_SEC, 6);
1780
- rr.writeUInt16BE(4, 10);
1781
- ip.split(".").forEach((o, i) => rr.writeUInt8(Number(o), 12 + i));
1782
- return Buffer.concat([header, q.question, rr]);
1783
- }
1784
- var slugOf = (owner) => owner.split("@")[0].toLowerCase();
1785
- var isOurs = (q) => q.class === CLASS_IN && q.name.endsWith(DNS_SUFFIX);
1786
- function answerFor(q, asker, boxes) {
1787
- if (!isOurs(q)) return { rcode: RCODE.refused };
1788
- const [name, slug, ...rest] = q.name.slice(0, -DNS_SUFFIX.length).split(".");
1789
- const from = boxes.find((b) => b.ip === asker);
1790
- let box;
1791
- if (from && rest.length === 0) {
1792
- 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));
1793
- }
1794
- if (!box) return { rcode: RCODE.nxDomain };
1795
- return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };
1796
- }
1797
- async function boxAddresses(p) {
1798
- const out = [];
1799
- for (const ref of await listMachineRefs(p)) {
1800
- const meta = await readMachineMeta(ref, p).catch(() => null);
1801
- if (meta) out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {} });
1483
+ var ORG_ROLES = ["owner", "admin", "member"];
1484
+ var OrgRoleSchema = z4.enum(ORG_ROLES);
1485
+ var CloudOrgSchema = z4.object({
1486
+ slug: z4.string(),
1487
+ /** Display name; the slug never changes, this may. */
1488
+ name: z4.string(),
1489
+ createdAt: z4.string(),
1490
+ /** An org pays for itself (#74): off until it has a card or an admin activates it; its boxes are 402. Defaults as on CloudUser. */
1491
+ active: z4.boolean().default(true),
1492
+ activatedBy: ActivatedBySchema.nullable().default(null)
1493
+ });
1494
+ var OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });
1495
+ var OrgMemberSchema = z4.object({
1496
+ username: z4.string(),
1497
+ name: z4.string(),
1498
+ role: OrgRoleSchema,
1499
+ addedAt: z4.string()
1500
+ });
1501
+ var OrgDetailSchema = CloudOrgSchema.extend({ members: z4.array(OrgMemberSchema) });
1502
+ var CreateOrgRequestSchema = z4.object({
1503
+ slug: z4.string().min(1),
1504
+ name: z4.string().min(1)
1505
+ });
1506
+ var RenameOrgRequestSchema = z4.object({ name: z4.string().min(1) });
1507
+ var AddMemberRequestSchema = z4.object({
1508
+ username: z4.string().min(1),
1509
+ role: OrgRoleSchema.default("member")
1510
+ });
1511
+ var SetRoleRequestSchema = z4.object({ role: OrgRoleSchema });
1512
+ var MeResponseSchema = CloudUserSchema.extend({ orgs: z4.array(OrgMembershipSchema) });
1513
+ var BalanceSchema = z4.object({
1514
+ slug: z4.string(),
1515
+ balance: z4.number(),
1516
+ currency: z4.string(),
1517
+ topUps: z4.number(),
1518
+ spent: z4.number(),
1519
+ /** The first moment usage counts from: the slug's first top-up; null when it has none. */
1520
+ since: z4.string().nullable(),
1521
+ /** When the slug ran out and its boxes were hibernated (the `sweep-credit` job); null in good standing. Absent from a control plane older than this field. */
1522
+ suspendedAt: z4.string().nullable().default(null)
1523
+ });
1524
+ var TopUpRequestSchema = z4.object({
1525
+ slug: z4.string().min(1),
1526
+ /** In the control plane's currency; negative corrects a mistake. */
1527
+ amount: z4.number().finite(),
1528
+ note: z4.string().max(200).optional()
1529
+ });
1530
+ var TopUpSchema = z4.object({
1531
+ id: z4.string(),
1532
+ slug: z4.string(),
1533
+ amount: z4.number(),
1534
+ currency: z4.string(),
1535
+ /** `transfer` (#93): an owner moving credit to an org they own, a negative row on their slug and a positive one on the org's. */
1536
+ source: z4.enum(["admin", "card", "trial", "transfer"]),
1537
+ note: z4.string().nullable(),
1538
+ at: z4.string()
1539
+ });
1540
+ var TOP_UP_AMOUNTS = [10, 25, 50, 100];
1541
+ var BillingInfoSchema = z4.object({
1542
+ card: z4.object({ brand: z4.string(), last4: z4.string() }).nullable(),
1543
+ cardInUse: z4.boolean(),
1544
+ balance: BalanceSchema
1545
+ });
1546
+ var BillingRedirectSchema = z4.object({ url: z4.string() });
1547
+ var TopUpCheckoutRequestSchema = z4.object({
1548
+ amount: z4.literal(TOP_UP_AMOUNTS)
1549
+ });
1550
+ var TransferRequestSchema = z4.object({
1551
+ org: z4.string().min(1),
1552
+ amount: z4.number().positive().multipleOf(0.01, "amount is in cents at most")
1553
+ });
1554
+ var TransferResponseSchema = z4.object({ from: BalanceSchema, to: BalanceSchema, activated: z4.boolean() });
1555
+ var LoginRequestSchema = z4.object({
1556
+ email: z4.string().min(1),
1557
+ password: z4.string().min(1),
1558
+ publicKey: z4.string().optional()
1559
+ });
1560
+ var SignupRequestSchema = z4.object({
1561
+ username: z4.string().min(1),
1562
+ name: z4.string().min(1),
1563
+ email: z4.string().min(1),
1564
+ password: z4.string().min(1)
1565
+ });
1566
+ var LoginResponseSchema = z4.object({
1567
+ token: z4.string(),
1568
+ user: CloudUserSchema,
1569
+ sshCert: z4.string().optional(),
1570
+ sshCertExpires: z4.string().optional(),
1571
+ /** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
1572
+ sshCertPrincipals: z4.array(z4.string()).optional()
1573
+ });
1574
+ var SshCertRequestSchema = z4.object({
1575
+ publicKey: z4.string().min(1)
1576
+ });
1577
+ var SshCertResponseSchema = z4.object({
1578
+ cert: z4.string(),
1579
+ expires: z4.string(),
1580
+ principals: z4.array(z4.string())
1581
+ });
1582
+ var SshCaResponseSchema = z4.object({
1583
+ publicKey: z4.string(),
1584
+ /** CAs replaced by `ca rotate` (#55), newest first; a box still holding one of these has not had `kvbox-server trust-ca` run on its host. */
1585
+ retired: z4.array(z4.object({ publicKey: z4.string(), retiredAt: z4.string() })).optional()
1586
+ });
1587
+ var HostSshCaResponseSchema = z4.object({
1588
+ publicKey: z4.string()
1589
+ });
1590
+ var CloudCaSchema = z4.object({
1591
+ controlPlane: z4.string(),
1592
+ publicKey: z4.string(),
1593
+ fingerprint: z4.string()
1594
+ });
1595
+ var TrustCaRequestSchema = z4.object({
1596
+ publicKey: z4.string().min(1)
1597
+ });
1598
+ var SshKeysAppliedSchema = z4.enum(["now", "start", "wake", "resume", "later"]);
1599
+ var TrustCaReportSchema = z4.object({
1600
+ publicKey: z4.string(),
1601
+ fingerprint: z4.string(),
1602
+ /** The guest trusts the CA now. */
1603
+ updated: z4.array(z4.string()),
1604
+ /** meta.json has the line; the guest gets it at `when`. */
1605
+ pending: z4.array(z4.object({ box: z4.string(), when: SshKeysAppliedSchema, why: z4.string().optional() })),
1606
+ failed: z4.array(z4.object({ box: z4.string(), error: z4.string() })),
1607
+ /** Local boxes, untouched: they trust the host's key only. */
1608
+ local: z4.number().int()
1609
+ });
1610
+ var HostJoinRequestSchema = z4.object({
1611
+ token: z4.string().min(1),
1612
+ name: z4.string().min(1),
1613
+ url: z4.string().url(),
1614
+ fingerprint: z4.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
1615
+ publicAddress: z4.string().min(1),
1616
+ /** Where the host is (`kvbox-server join --country`): a code or an English name. */
1617
+ country: z4.string().optional()
1618
+ });
1619
+ var HostJoinResponseSchema = z4.object({
1620
+ hostSecret: z4.string(),
1621
+ controlPlane: z4.object({ name: z4.string() })
1622
+ });
1623
+ var CloudHostSchema = z4.object({
1624
+ name: z4.string(),
1625
+ url: z4.string(),
1626
+ publicAddress: z4.string(),
1627
+ joinedAt: z4.string(),
1628
+ lastSeenAt: z4.string().nullable(),
1629
+ capacity: CapacitySchema.nullable(),
1630
+ /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
1631
+ country: z4.string().nullable()
1632
+ });
1633
+ var HostPatchRequest = z4.object({ country: z4.string().nullable() });
1634
+ var CountrySchema = z4.object({ code: z4.string(), name: z4.string() });
1635
+
1636
+ // ../shared/src/ssh.ts
1637
+ import { createHash } from "node:crypto";
1638
+ var SSH_PUBLIC_KEY_RE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com) ([A-Za-z0-9+/]+=*)(?: [^\r\n]*)?$/;
1639
+ function parseSshPublicKey(text) {
1640
+ const key = text.trim().replace(/^cert-authority\s+/, "");
1641
+ if (!SSH_PUBLIC_KEY_RE.test(key)) {
1642
+ throw new KvboxError("that is not an SSH public key; expected one line like: ssh-ed25519 AAAA\u2026 kvbox-ca@kvbox.sh");
1802
1643
  }
1803
- return out;
1804
- }
1805
- function sharedBoxes(load, freshMs = BOXES_FRESH_MS, version = boxListVersionNow) {
1806
- let last = null;
1807
- return () => {
1808
- if (!last || last.version !== version() || Date.now() - last.at > freshMs) {
1809
- const entry = { at: Date.now(), version: version(), list: load() };
1810
- last = entry;
1811
- entry.list.catch(() => {
1812
- if (last === entry) last = null;
1813
- });
1814
- }
1815
- return last.list;
1816
- };
1644
+ return key;
1817
1645
  }
1818
- async function startDns(opts) {
1819
- const p = opts.p ?? paths();
1820
- const boxes = sharedBoxes(opts.boxes ?? (() => boxAddresses(p)));
1821
- const socket = createSocket("udp4");
1822
- socket.on("message", (msg, rinfo) => {
1823
- const q = parseQuery(msg);
1824
- if (!q) return;
1825
- const reply = (a) => socket.send(buildAnswer(q, a.rcode, a.ip), rinfo.port, rinfo.address);
1826
- if (!isOurs(q)) return reply({ rcode: RCODE.refused });
1827
- void boxes().then((list) => answerFor(q, rinfo.address, list)).catch(() => ({ rcode: RCODE.refused })).then(reply);
1828
- });
1829
- await new Promise((resolve, reject) => {
1830
- socket.once("error", (err) => {
1831
- socket.close();
1832
- reject(err);
1833
- });
1834
- socket.bind(opts.port ?? DNS_PORT, opts.host, () => {
1835
- socket.removeAllListeners("error");
1836
- socket.on("error", () => {
1837
- });
1838
- resolve();
1839
- });
1840
- });
1841
- return { socket, close: () => new Promise((resolve) => socket.close(() => resolve())) };
1646
+ function sshKeyFingerprint(publicKey) {
1647
+ const m = SSH_PUBLIC_KEY_RE.exec(publicKey.trim());
1648
+ if (!m) throw new KvboxError("cannot fingerprint: not an SSH public key");
1649
+ return `SHA256:${createHash("sha256").update(Buffer.from(m[2], "base64")).digest("base64").replace(/=+$/, "")}`;
1842
1650
  }
1843
-
1844
- // src/core/machines.ts
1845
- import { spawn } from "node:child_process";
1846
- import { closeSync as closeSync3, existsSync as existsSync6, openSync as openSync3, statSync as statSync2 } from "node:fs";
1847
- import { link as link2, mkdir as mkdir6, readFile as readFile6, rename as rename5, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1848
- import { setTimeout as sleep } from "node:timers/promises";
1849
-
1850
- // ../shared/src/duration.ts
1851
- var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
1852
- function parseDuration(text) {
1853
- const t = text.trim().toLowerCase();
1854
- if (!/^(\d+[mhd])+$/.test(t)) return void 0;
1855
- let sec = 0;
1856
- for (const [, n, unit] of t.matchAll(/(\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit];
1857
- return sec;
1651
+ function caLineFor(principal, caPublicKey) {
1652
+ return `cert-authority,principals="${principal}" ${caPublicKey}`;
1858
1653
  }
1654
+ var isCaLine = (line) => /^cert-authority(,|\s)/.test(line.trim());
1859
1655
 
1860
1656
  // src/core/agent.ts
1861
1657
  import { connect } from "node:net";
1862
1658
  var AGENT_PORT = 52;
1863
1659
  async function agentCall(udsPath, req, timeoutMs = 5e3) {
1864
- const reply = await new Promise((resolve, reject) => {
1660
+ const reply = await new Promise((resolve2, reject) => {
1865
1661
  const sock = connect(udsPath);
1866
1662
  let buf = "";
1867
1663
  let handshaken = false;
@@ -1885,7 +1681,7 @@ async function agentCall(udsPath, req, timeoutMs = 5e3) {
1885
1681
  sock.write(JSON.stringify(req) + "\n");
1886
1682
  } else {
1887
1683
  sock.end();
1888
- return resolve(line);
1684
+ return resolve2(line);
1889
1685
  }
1890
1686
  }
1891
1687
  });
@@ -1930,7 +1726,7 @@ var isNoAgent = (err) => /vsock connect refused|vsock connection closed before t
1930
1726
 
1931
1727
  // src/core/env.ts
1932
1728
  import { existsSync } from "node:fs";
1933
- import { copyFile, mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1729
+ import { copyFile, mkdir as mkdir2, readFile as readFile4, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1934
1730
  import { z as z5 } from "zod";
1935
1731
 
1936
1732
  // ../shared/src/env.ts
@@ -1968,7 +1764,7 @@ async function withLock(key, fn) {
1968
1764
  if (mine?.has(key)) return fn();
1969
1765
  const previous = tails.get(key);
1970
1766
  let release;
1971
- const tail = new Promise((resolve) => release = resolve);
1767
+ const tail = new Promise((resolve2) => release = resolve2);
1972
1768
  tails.set(key, tail);
1973
1769
  try {
1974
1770
  await previous;
@@ -1985,6 +1781,25 @@ function locked(fn) {
1985
1781
  return (...args) => withBoxLock(args[0], () => fn(...args));
1986
1782
  }
1987
1783
 
1784
+ // src/core/log.ts
1785
+ function formatLine(level, message, at = /* @__PURE__ */ new Date()) {
1786
+ return `[${at.toISOString()}][${level}]: ${message}`;
1787
+ }
1788
+ var log = {
1789
+ debug(message) {
1790
+ console.error(formatLine("debug", message));
1791
+ },
1792
+ info(message) {
1793
+ console.log(formatLine("info", message));
1794
+ },
1795
+ warn(message) {
1796
+ console.error(formatLine("warn", message));
1797
+ },
1798
+ error(message) {
1799
+ console.error(formatLine("error", message));
1800
+ }
1801
+ };
1802
+
1988
1803
  // src/core/env.ts
1989
1804
  var OwnerEnvSchema = z5.object({
1990
1805
  /** The control plane's counter for the list; only ever grows. */
@@ -1993,7 +1808,7 @@ var OwnerEnvSchema = z5.object({
1993
1808
  });
1994
1809
  async function readOwnerEnv(owner, p = paths()) {
1995
1810
  try {
1996
- return OwnerEnvSchema.parse(JSON.parse(await readFile5(p.ownerEnv(owner), "utf8")));
1811
+ return OwnerEnvSchema.parse(JSON.parse(await readFile4(p.ownerEnv(owner), "utf8")));
1997
1812
  } catch (err) {
1998
1813
  if (err.code === "ENOENT") return null;
1999
1814
  throw err;
@@ -2002,7 +1817,7 @@ async function readOwnerEnv(owner, p = paths()) {
2002
1817
  async function envForBoot(box, p = paths()) {
2003
1818
  const env = await readOwnerEnv(box.owner, p).catch(() => null);
2004
1819
  const own = await readBoxEnv(box, p).catch((err) => {
2005
- console.error(`warning: box ${shown(box)}: its own variables are unreadable, it boots without them: ${err.message}`);
1820
+ log.warn(`box ${shown(box)}: its own variables are unreadable, it boots without them: ${err.message}`);
2006
1821
  return [];
2007
1822
  });
2008
1823
  const slug = env?.vars ?? (realmOf(box.owner) !== null ? [] : null);
@@ -2018,7 +1833,7 @@ async function readBoxEnv(box, p = paths()) {
2018
1833
  }
2019
1834
  async function readBoxEnvFile(file) {
2020
1835
  try {
2021
- return BoxEnvFileSchema.parse(JSON.parse(await readFile5(file, "utf8"))).vars;
1836
+ return BoxEnvFileSchema.parse(JSON.parse(await readFile4(file, "utf8"))).vars;
2022
1837
  } catch (err) {
2023
1838
  if (err.code === "ENOENT") return [];
2024
1839
  throw err;
@@ -2083,7 +1898,7 @@ async function setOwnerEnv(owner, req, p = paths()) {
2083
1898
  const have = await readOwnerEnv(owner, p);
2084
1899
  if (have !== null && have.version > req.version) return { version: have.version };
2085
1900
  const file = p.ownerEnv(owner);
2086
- await mkdir3(p.env, { recursive: true, mode: 448 });
1901
+ await mkdir2(p.env, { recursive: true, mode: 448 });
2087
1902
  const tmp = `${file}.tmp`;
2088
1903
  await writeFile3(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
2089
1904
  await rename3(tmp, file);
@@ -2114,6 +1929,32 @@ import { existsSync as existsSync2 } from "node:fs";
2114
1929
  import { readdir as readdir3, realpath } from "node:fs/promises";
2115
1930
  import { basename } from "node:path";
2116
1931
  import { z as z6 } from "zod";
1932
+
1933
+ // src/core/exec.ts
1934
+ import { execFile } from "node:child_process";
1935
+ import { promisify } from "node:util";
1936
+ var execFileAsync = promisify(execFile);
1937
+ async function run(argv, opts = {}) {
1938
+ const [cmd, ...args] = opts.sudo ? ["sudo", "-n", ...argv] : argv;
1939
+ if (!cmd) throw new KvboxError("run: empty argv");
1940
+ if (process.env["KVBOX_DEBUG"]) log.debug(`exec ${[cmd, ...args].join(" ")}`);
1941
+ try {
1942
+ const { stdout, stderr } = await execFileAsync(cmd, args, {
1943
+ cwd: opts.cwd,
1944
+ env: opts.env ?? process.env,
1945
+ timeout: opts.timeoutMs ?? 3e4,
1946
+ maxBuffer: 8 * 1024 * 1024
1947
+ });
1948
+ return { stdout, stderr };
1949
+ } catch (err) {
1950
+ const e = err;
1951
+ if (typeof e.code === "number" && opts.okExitCodes?.includes(e.code)) return { stdout: e.stdout ?? "", stderr: e.stderr ?? "" };
1952
+ const detail = (e.stderr ?? e.message ?? "").trim();
1953
+ throw new KvboxError(`${[cmd, ...args].join(" ")} failed${detail ? `: ${detail}` : ""}`);
1954
+ }
1955
+ }
1956
+
1957
+ // src/core/images.ts
2117
1958
  var BASE_IMAGE = "base";
2118
1959
  var IMAGE_RE = /^[a-z][a-z0-9-]{0,30}$/;
2119
1960
  function baseVersionOf(file) {
@@ -2270,7 +2111,7 @@ function namesIn(text) {
2270
2111
 
2271
2112
  // src/core/volumes.ts
2272
2113
  import { existsSync as existsSync3, statSync } from "node:fs";
2273
- import { lstat, mkdir as mkdir4, readdir as readdir4, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
2114
+ import { lstat, mkdir as mkdir3, readdir as readdir4, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
2274
2115
 
2275
2116
  // ../shared/src/capacity.ts
2276
2117
  var MEM_HEADROOM_MIB = 2048;
@@ -2299,7 +2140,7 @@ function recordVolume(meta, by, p, at = (/* @__PURE__ */ new Date()).toISOString
2299
2140
  try {
2300
2141
  insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at, sizeGib: meta.sizeGib, by }, p);
2301
2142
  } catch (err) {
2302
- console.error(`warning: volume ledger: ${err.message}`);
2143
+ log.warn(`volume ledger: ${err.message}`);
2303
2144
  }
2304
2145
  }
2305
2146
  async function attachments(owner, p) {
@@ -2340,7 +2181,7 @@ async function listVolumes(scope, p = paths()) {
2340
2181
  }
2341
2182
  out.push(toVolume(meta, attached.get(meta.name) ?? null, p));
2342
2183
  } catch (err) {
2343
- console.error(`warning: skipping volumes/${ref.owner}/${ref.name}: ${err.message}`);
2184
+ log.warn(`skipping volumes/${ref.owner}/${ref.name}: ${err.message}`);
2344
2185
  }
2345
2186
  }
2346
2187
  return out.sort((a, b) => a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name));
@@ -2376,7 +2217,7 @@ async function createVolume(req, owner, p = paths()) {
2376
2217
  async function makeVolume(req, owner, p) {
2377
2218
  const v = p.volume(owner, req.name);
2378
2219
  if (existsSync3(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
2379
- await mkdir4(p.ownerVolumes(owner), { recursive: true, mode: 448 });
2220
+ await mkdir3(p.ownerVolumes(owner), { recursive: true, mode: 448 });
2380
2221
  const disk = await diskCapacity(p);
2381
2222
  if (!hasDiskRoom(disk, req.sizeGib)) {
2382
2223
  throw new KvboxError(
@@ -2391,7 +2232,7 @@ async function makeVolume(req, owner, p) {
2391
2232
  }
2392
2233
  }
2393
2234
  try {
2394
- await mkdir4(v.dir, { mode: 448 });
2235
+ await mkdir3(v.dir, { mode: 448 });
2395
2236
  } catch (err) {
2396
2237
  if (err.code === "EEXIST") throw new KvboxError(`volume ${req.name} already exists`);
2397
2238
  throw err;
@@ -2610,10 +2451,10 @@ function ext4Usage(file) {
2610
2451
 
2611
2452
  // src/core/snapshots.ts
2612
2453
  import { existsSync as existsSync4 } from "node:fs";
2613
- import { link, mkdir as mkdir5, readdir as readdir5, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
2454
+ import { link, mkdir as mkdir4, readdir as readdir5, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
2614
2455
 
2615
2456
  // src/core/firecracker.ts
2616
- import { Agent, request as request2 } from "undici";
2457
+ import { Agent, request } from "undici";
2617
2458
  var FirecrackerClient = class {
2618
2459
  constructor(socketPath) {
2619
2460
  this.socketPath = socketPath;
@@ -2622,7 +2463,7 @@ var FirecrackerClient = class {
2622
2463
  socketPath;
2623
2464
  agent;
2624
2465
  async call(method, path, body) {
2625
- const res = await request2(`http://localhost${path}`, {
2466
+ const res = await request(`http://localhost${path}`, {
2626
2467
  dispatcher: this.agent,
2627
2468
  method,
2628
2469
  headers: body === void 0 ? {} : { "content-type": "application/json" },
@@ -2747,7 +2588,7 @@ async function listSnapshots(scope, p = paths()) {
2747
2588
  try {
2748
2589
  out.push(toSnapshot(await readSnapshotMeta(ref, p)));
2749
2590
  } catch (err) {
2750
- console.error(`warning: skipping snapshots/${refKey(ref)}: ${err.message}`);
2591
+ log.warn(`skipping snapshots/${refKey(ref)}: ${err.message}`);
2751
2592
  }
2752
2593
  }
2753
2594
  return out;
@@ -2787,7 +2628,7 @@ async function snapshotBox(ref, req, owner, p) {
2787
2628
  const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
2788
2629
  const cfg = await loadConfig(p);
2789
2630
  if (s !== final) await rm2(s.dir, { recursive: true, force: true });
2790
- await mkdir5(s.dir, { recursive: true, mode: 448 });
2631
+ await mkdir4(s.dir, { recursive: true, mode: 448 });
2791
2632
  try {
2792
2633
  const volumes = await captureDrivesOf(box, p);
2793
2634
  await captureBox(box, s, cfg, p);
@@ -3026,15 +2867,15 @@ async function standingLinks(meta, p) {
3026
2867
  async function openPorts(meta, cfg, p) {
3027
2868
  for (const proxy of boxProxies(meta)) await openProxy(proxy, cfg);
3028
2869
  for (const link3 of await standingLinks(meta, p)) {
3029
- await openLink(link3, cfg).catch((err) => console.error(`warning: could not open the link from ${link3.fromIp}: ${err.message}`));
2870
+ await openLink(link3, cfg).catch((err) => log.warn(`could not open the link from ${link3.fromIp}: ${err.message}`));
3030
2871
  }
3031
2872
  }
3032
2873
  async function closePorts(meta, cfg) {
3033
2874
  for (const proxy of boxProxies(meta)) {
3034
- await closeProxy(proxy, cfg).catch((err) => console.error(`warning: could not close port ${proxy.hostPort}: ${err.message}`));
2875
+ await closeProxy(proxy, cfg).catch((err) => log.warn(`could not close port ${proxy.hostPort}: ${err.message}`));
3035
2876
  }
3036
2877
  for (const link3 of boxLinks(meta)) {
3037
- await closeLink(link3, cfg).catch((err) => console.error(`warning: could not close the link from ${link3.fromIp}: ${err.message}`));
2878
+ await closeLink(link3, cfg).catch((err) => log.warn(`could not close the link from ${link3.fromIp}: ${err.message}`));
3038
2879
  }
3039
2880
  }
3040
2881
  var reservedPorts = /* @__PURE__ */ new Set();
@@ -3076,7 +2917,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
3076
2917
  try {
3077
2918
  insertUsageEvent({ boxId: meta.id, owner: meta.owner, name: meta.name, at, state, by, vcpu: meta.vcpu, memMib: meta.memMib, diskGib: diskGibOf(meta, p) }, p);
3078
2919
  } catch (err) {
3079
- console.error(`warning: usage ledger: ${err.message}`);
2920
+ log.warn(`usage ledger: ${err.message}`);
3080
2921
  }
3081
2922
  }
3082
2923
  function isHibernated(meta, p) {
@@ -3090,12 +2931,12 @@ function stateMessage(ref, status) {
3090
2931
  return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
3091
2932
  }
3092
2933
  function toMachine(meta, p = paths()) {
3093
- const alive = vmAlive(meta);
3094
- if (!alive && meta.pid !== null) {
2934
+ const alive2 = vmAlive(meta);
2935
+ if (!alive2 && meta.pid !== null) {
3095
2936
  try {
3096
2937
  closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
3097
2938
  } catch (err) {
3098
- console.error(`warning: usage ledger: ${err.message}`);
2939
+ log.warn(`usage ledger: ${err.message}`);
3099
2940
  }
3100
2941
  }
3101
2942
  return {
@@ -3104,7 +2945,7 @@ function toMachine(meta, p = paths()) {
3104
2945
  owner: meta.owner,
3105
2946
  ip: meta.ip,
3106
2947
  mac: meta.mac,
3107
- pid: alive ? meta.pid : null,
2948
+ pid: alive2 ? meta.pid : null,
3108
2949
  vcpu: meta.vcpu,
3109
2950
  memMib: meta.memMib,
3110
2951
  ...diskStats(p.machine(meta.owner, meta.name).overlay),
@@ -3135,7 +2976,7 @@ async function readAllMeta(p) {
3135
2976
  try {
3136
2977
  metas.push(await readMachineMeta(ref, p));
3137
2978
  } catch (err) {
3138
- console.error(`warning: skipping machines/${refKey(ref)}: ${err.message}`);
2979
+ log.warn(`skipping machines/${refKey(ref)}: ${err.message}`);
3139
2980
  }
3140
2981
  }
3141
2982
  return metas;
@@ -3196,7 +3037,7 @@ async function waitFor(pred, timeoutMs, stepMs = 50) {
3196
3037
  }
3197
3038
  async function tailOf(file, lines = 5) {
3198
3039
  try {
3199
- return (await readFile6(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
3040
+ return (await readFile5(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
3200
3041
  } catch {
3201
3042
  return "";
3202
3043
  }
@@ -3285,7 +3126,7 @@ async function currentBaseVersion(p = paths()) {
3285
3126
  }
3286
3127
  async function readHostPubkey(p) {
3287
3128
  try {
3288
- return (await readFile6(`${p.sshKey}.pub`, "utf8")).trim();
3129
+ return (await readFile5(`${p.sshKey}.pub`, "utf8")).trim();
3289
3130
  } catch {
3290
3131
  throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);
3291
3132
  }
@@ -3335,7 +3176,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
3335
3176
  const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
3336
3177
  const m = p.machine(owner, name);
3337
3178
  await ensureHostNetwork(cfg);
3338
- await mkdir6(m.dir, { recursive: true, mode: 448 });
3179
+ await mkdir5(m.dir, { recursive: true, mode: 448 });
3339
3180
  let tapCreated = false;
3340
3181
  let pid;
3341
3182
  let sshPort;
@@ -3423,7 +3264,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
3423
3264
  const { id, ip, owner, name } = box;
3424
3265
  const m = p.machine(owner, name);
3425
3266
  await ensureHostNetwork(cfg);
3426
- await mkdir6(m.dir, { recursive: true, mode: 448 });
3267
+ await mkdir5(m.dir, { recursive: true, mode: 448 });
3427
3268
  let tapCreated = false;
3428
3269
  let pid;
3429
3270
  let sshPort;
@@ -3554,7 +3395,7 @@ async function pushAuthorizedKeys(box, vsock, p) {
3554
3395
  return void 0;
3555
3396
  } catch (err) {
3556
3397
  const why = isUnknownOp(err) ? `its image predates base v0.6.0, whose kvbox-agent can replace authorized_keys (kvbox vm update ${shown(box)} moves it onto the current base)` : err.message;
3557
- console.error(`warning: box ${shown(box)} keeps the authorized_keys it was frozen with: ${why}`);
3398
+ log.warn(`box ${shown(box)} keeps the authorized_keys it was frozen with: ${why}`);
3558
3399
  return why;
3559
3400
  }
3560
3401
  }
@@ -3563,7 +3404,7 @@ async function dropGuestVolumes(box, vsock) {
3563
3404
  await dropVolumes(vsock, AGENT_REPLY_MS);
3564
3405
  } catch (err) {
3565
3406
  const why = isUnknownOp(err) ? `its image predates base v0.9.0, whose kvbox-agent can unmount them (kvbox vm update ${shown(box)} moves it onto the current base)` : err.message;
3566
- console.error(`warning: box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);
3407
+ log.warn(`box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);
3567
3408
  }
3568
3409
  }
3569
3410
  async function pushEnv(box, vsock, p) {
@@ -3578,10 +3419,10 @@ async function pushEnv(box, vsock, p) {
3578
3419
  function warnEnv(box, vars, err) {
3579
3420
  if (isUnknownOp(err)) {
3580
3421
  if (vars.length === 0) return;
3581
- console.error(`warning: box ${shown(box)} did not get its environment variables: its image predates base v0.10.0, whose kvbox-agent takes them (kvbox vm update ${shown(box)} moves it onto the current base)`);
3422
+ log.warn(`box ${shown(box)} did not get its environment variables: its image predates base v0.10.0, whose kvbox-agent takes them (kvbox vm update ${shown(box)} moves it onto the current base)`);
3582
3423
  return;
3583
3424
  }
3584
- console.error(`warning: box ${shown(box)} did not get its environment variables: ${err.message}`);
3425
+ log.warn(`box ${shown(box)} did not get its environment variables: ${err.message}`);
3585
3426
  }
3586
3427
  var ENV_BOOT_WAIT_MS = 12e4;
3587
3428
  function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS, waitMs: ENV_BOOT_WAIT_MS }) {
@@ -3649,7 +3490,7 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
3649
3490
  const m = p.machine(ref.owner, ref.name);
3650
3491
  if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);
3651
3492
  await shutdown(meta, cfg, p, 1e4);
3652
- await compactDisk(m.overlay).catch((err) => console.error(`warning: box ${shown(ref)}: disk not compacted: ${err.message}`));
3493
+ await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
3653
3494
  await rm3(m.hibernateDir, { recursive: true, force: true });
3654
3495
  await rm3(m.memBase, { force: true });
3655
3496
  const stopped = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
@@ -3772,7 +3613,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
3772
3613
  if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
3773
3614
  const m = p.machine(ref.owner, ref.name);
3774
3615
  await rm3(m.hibernateDir, { recursive: true, force: true });
3775
- await mkdir6(m.hibernateDir, { recursive: true, mode: 448 });
3616
+ await mkdir5(m.hibernateDir, { recursive: true, mode: 448 });
3776
3617
  const fc = new FirecrackerClient(m.sock);
3777
3618
  try {
3778
3619
  try {
@@ -4083,12 +3924,12 @@ async function dropLinksFrom(gone, p) {
4083
3924
  for (const l of meta.links.filter(isGone)) {
4084
3925
  await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg).catch((err) => {
4085
3926
  stuck.add(l);
4086
- console.error(`warning: could not close the link from removed box ${gone.name} into ${meta.name}: ${err.message}`);
3927
+ log.warn(`could not close the link from removed box ${gone.name} into ${meta.name}: ${err.message}`);
4087
3928
  });
4088
3929
  }
4089
3930
  const kept = meta.links.filter((l) => !isGone(l) || stuck.has(l)).map((l) => stuck.has(l) ? { ...l, stale: true } : l);
4090
3931
  await writeMachineMeta({ ...meta, links: kept.length > 0 ? kept : void 0 }, p);
4091
- }).catch((err) => console.error(`warning: links of removed box ${gone.name}: ${err.message}`));
3932
+ }).catch((err) => log.warn(`links of removed box ${gone.name}: ${err.message}`));
4092
3933
  }
4093
3934
  }
4094
3935
  var RECOVERY_CONCURRENCY = 2;
@@ -4102,7 +3943,7 @@ async function settleDeadBoxes(p = paths()) {
4102
3943
  try {
4103
3944
  closeRunCutByBoot(meta.id, bootAt, now, p);
4104
3945
  } catch (err) {
4105
- console.error(`warning: usage ledger: ${err.message}`);
3946
+ log.warn(`usage ledger: ${err.message}`);
4106
3947
  }
4107
3948
  await rm3(p.machine(meta.owner, meta.name).memBase, { force: true });
4108
3949
  if (meta.paused) {
@@ -4123,7 +3964,7 @@ async function pinRunningTaps(p = paths()) {
4123
3964
  if (!bridgeExists(cfg.bridge)) return;
4124
3965
  for (const meta of await readAllMeta(p)) {
4125
3966
  if (!vmAlive(meta) || !existsSync6(`/sys/class/net/${tapName(meta.id)}`)) continue;
4126
- await pinTap(meta, cfg).catch((err) => console.error(`warning: could not pin box ${meta.name}'s tap: ${err.message}`));
3967
+ await pinTap(meta, cfg).catch((err) => log.warn(`could not pin box ${meta.name}'s tap: ${err.message}`));
4127
3968
  }
4128
3969
  }
4129
3970
  var recovery = null;
@@ -4163,7 +4004,7 @@ async function bootRecovered(settled, p = paths()) {
4163
4004
  // src/core/backups.ts
4164
4005
  import { randomBytes as randomBytes4 } from "node:crypto";
4165
4006
  import { existsSync as existsSync7 } from "node:fs";
4166
- import { mkdir as mkdir7, open, readdir as readdir6, readFile as readFile7, rm as rm4, stat as stat3, statfs as statfs2, writeFile as writeFile6 } from "node:fs/promises";
4007
+ import { mkdir as mkdir6, open, readdir as readdir6, readFile as readFile6, rm as rm4, stat as stat3, statfs as statfs2, writeFile as writeFile6 } from "node:fs/promises";
4167
4008
  import { basename as basename2, join as join2 } from "node:path";
4168
4009
  import { setTimeout as sleep2 } from "node:timers/promises";
4169
4010
 
@@ -4298,7 +4139,7 @@ async function stageBackup(ref, req, p = paths()) {
4298
4139
  const keys = backupKeys(req.key);
4299
4140
  const s = p.backup(req.id);
4300
4141
  await rm4(s.dir, { recursive: true, force: true });
4301
- await mkdir7(s.dir, { recursive: true, mode: 448 });
4142
+ await mkdir6(s.dir, { recursive: true, mode: 448 });
4302
4143
  try {
4303
4144
  const { meta, envText } = await withBoxLock(ref, async () => {
4304
4145
  const meta2 = await readBox2(ref, p);
@@ -4320,7 +4161,7 @@ async function stageBackup(ref, req, p = paths()) {
4320
4161
  } else {
4321
4162
  await copy();
4322
4163
  }
4323
- const envText2 = existsSync7(m.env) ? await readFile7(m.env, "utf8") : null;
4164
+ const envText2 = existsSync7(m.env) ? await readFile6(m.env, "utf8") : null;
4324
4165
  return { meta: meta2, envText: envText2 };
4325
4166
  });
4326
4167
  const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
@@ -4372,7 +4213,7 @@ async function uploadOnce(id, req, signal, p) {
4372
4213
  const s = p.backup(id);
4373
4214
  if (!existsSync7(s.chunks)) throw new NotFoundError(`backup ${id}`);
4374
4215
  const keys = backupKeys(req.key);
4375
- const { chunks } = JSON.parse(await readFile7(s.chunks, "utf8"));
4216
+ const { chunks } = JSON.parse(await readFile6(s.chunks, "utf8"));
4376
4217
  const slotOf = /* @__PURE__ */ new Map();
4377
4218
  chunks.forEach((name, i) => {
4378
4219
  if (name !== null && !slotOf.has(name)) slotOf.set(name, i);
@@ -4517,47 +4358,226 @@ async function withTries(what, fn, signal) {
4517
4358
  await sleep2(250 * 2 ** i);
4518
4359
  }
4519
4360
  }
4520
- throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
4361
+ throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
4362
+ }
4363
+
4364
+ // src/core/relay.ts
4365
+ import { access as access2, chmod as chmod3, mkdir as mkdir8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
4366
+
4367
+ // ../shared/src/relay.ts
4368
+ import { z as z7 } from "zod";
4369
+ var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
4370
+ var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
4371
+ var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
4372
+ var RelayJoinSchema = z7.object({
4373
+ v: z7.literal(1),
4374
+ /** How the relay lists this host. */
4375
+ name: z7.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
4376
+ /** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
4377
+ relay: z7.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
4378
+ /** The relay's WireGuard public key. */
4379
+ relayKey: z7.string().regex(WG_KEY_RE),
4380
+ /** This host's address inside the tunnel. */
4381
+ tunnelIp: z7.string().regex(IPV4_RE),
4382
+ /** This host's WireGuard private key, generated on the relay, kept nowhere else. */
4383
+ privateKey: z7.string().regex(WG_KEY_RE),
4384
+ /** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
4385
+ publicIp: z7.string().regex(IPV4_RE)
4386
+ });
4387
+ function decodeRelayJoin(text) {
4388
+ let parsed;
4389
+ try {
4390
+ parsed = JSON.parse(Buffer.from(text.trim(), "base64url").toString("utf8"));
4391
+ } catch {
4392
+ return null;
4393
+ }
4394
+ const res = RelayJoinSchema.safeParse(parsed);
4395
+ return res.success ? res.data : null;
4396
+ }
4397
+
4398
+ // src/core/controlPlane.ts
4399
+ import { X509Certificate } from "node:crypto";
4400
+ import { chmod as chmod2, mkdir as mkdir7, readFile as readFile7 } from "node:fs/promises";
4401
+ import { hostname as osHostname } from "node:os";
4402
+ import { request as request2 } from "undici";
4403
+
4404
+ // ../shared/src/country.ts
4405
+ var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
4406
+ var NOT_COUNTRIES = /* @__PURE__ */ new Set(["EU", "EZ", "UN", "QO", "XA", "XB", "ZZ"]);
4407
+ var ALIASES = { usa: "US", america: "US", uk: "GB", britain: "GB", england: "GB", holland: "NL" };
4408
+ var fold = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z]/g, "");
4409
+ var byName;
4410
+ function nameIndex() {
4411
+ if (byName) return byName;
4412
+ byName = new Map(Object.entries(ALIASES));
4413
+ for (let a = 65; a <= 90; a++) {
4414
+ for (let b = 65; b <= 90; b++) {
4415
+ const code = String.fromCharCode(a, b);
4416
+ const name = countryName(code);
4417
+ if (name !== void 0 && canonical(code) === code) byName.set(fold(name), code);
4418
+ }
4419
+ }
4420
+ return byName;
4421
+ }
4422
+ function canonical(code) {
4423
+ return /-([A-Z]{2})$/.exec(Intl.getCanonicalLocales(`und-${code}`)[0] ?? "")?.[1] ?? code;
4424
+ }
4425
+ function countryName(code) {
4426
+ if (!/^[A-Z]{2}$/.test(code) || NOT_COUNTRIES.has(code)) return void 0;
4427
+ return names.of(code);
4428
+ }
4429
+ function parseCountry(input) {
4430
+ const t = input.trim();
4431
+ const upper = t.toUpperCase();
4432
+ const code = countryName(upper) !== void 0 ? canonical(upper) : nameIndex().get(fold(t));
4433
+ if (code !== void 0) return code;
4434
+ throw new KvboxError(`unknown country "${input}": give its name or its two-letter code, e.g. RO or US`);
4435
+ }
4436
+
4437
+ // src/core/controlPlane.ts
4438
+ var DEFAULT_HTTPS_PORT = 7777;
4439
+ async function ensureTlsCert(p = paths()) {
4440
+ const have = await readFile7(p.tlsCert, "utf8").catch(() => null);
4441
+ const haveKey = await readFile7(p.tlsKey).then(() => true, () => false);
4442
+ if (have === null || !haveKey) {
4443
+ await mkdir7(p.tls, { recursive: true, mode: 448 });
4444
+ try {
4445
+ await run([
4446
+ "openssl",
4447
+ "req",
4448
+ "-x509",
4449
+ "-newkey",
4450
+ "ec",
4451
+ "-pkeyopt",
4452
+ "ec_paramgen_curve:prime256v1",
4453
+ "-nodes",
4454
+ "-keyout",
4455
+ p.tlsKey,
4456
+ "-out",
4457
+ p.tlsCert,
4458
+ "-subj",
4459
+ "/CN=kvbox-host",
4460
+ "-days",
4461
+ "3650"
4462
+ ]);
4463
+ } catch (err) {
4464
+ throw new KvboxError(`could not make the host's certificate (is openssl installed?): ${err.message}`);
4465
+ }
4466
+ await chmod2(p.tlsKey, 384);
4467
+ }
4468
+ const pem = await readFile7(p.tlsCert, "utf8");
4469
+ return { fingerprint: new X509Certificate(pem).fingerprint256 };
4470
+ }
4471
+ function isPrivateAddress(ip) {
4472
+ const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(ip);
4473
+ if (!m) return false;
4474
+ const [a, b] = [Number(m[1]), Number(m[2])];
4475
+ return a === 10 || a === 127 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127;
4476
+ }
4477
+ async function defaultAdvertise() {
4478
+ const { stdout } = await run(["ip", "-4", "route", "get", "1.1.1.1"]).catch((err) => {
4479
+ throw new KvboxError(`cannot tell this host's address (${err.message}); pass --advertise <host-or-ip>`);
4480
+ });
4481
+ const m = /\bsrc\s+(\S+)/.exec(stdout);
4482
+ if (!m) throw new KvboxError("cannot tell this host's address from its routes; pass --advertise <host-or-ip>");
4483
+ return m[1];
4484
+ }
4485
+ async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdvertise) {
4486
+ const url = opts.url.replace(/\/+$/, "");
4487
+ const port = opts.port ?? DEFAULT_HTTPS_PORT;
4488
+ const cfg = await loadConfig(p);
4489
+ if (cfg.controlPlane) throw new KvboxError(`this host has already joined ${cfg.controlPlane.name} (${cfg.controlPlane.url}); run kvbox-server leave first`);
4490
+ let advertise = opts.advertise;
4491
+ if (advertise === void 0 && cfg.relay) {
4492
+ advertise = cfg.relay.publicIp;
4493
+ } else if (advertise === void 0) {
4494
+ advertise = await guessAddress();
4495
+ if (isPrivateAddress(advertise)) {
4496
+ throw new KvboxError(
4497
+ `${advertise} is a private address: a control plane on the internet cannot reach this host there.
4498
+ Pass --advertise <public host or ip>, or --advertise ${advertise} if the control plane is on the same network.`
4499
+ );
4500
+ }
4501
+ }
4502
+ const name = opts.name ?? osHostname();
4503
+ const country = opts.country === void 0 ? void 0 : parseCountry(opts.country);
4504
+ const { fingerprint } = await ensureTlsCert(p);
4505
+ const hostUrl = `https://${advertise}:${port}`;
4506
+ const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
4507
+ const res = await request2(`${url}/hosts/join`, {
4508
+ method: "POST",
4509
+ headers: { "content-type": "application/json" },
4510
+ body: JSON.stringify(body),
4511
+ headersTimeout: 1e4,
4512
+ bodyTimeout: 1e4
4513
+ }).catch((err) => {
4514
+ throw new KvboxError(`cannot reach ${url} (${err.message})`);
4515
+ });
4516
+ const text = await res.body.text();
4517
+ if (res.statusCode < 200 || res.statusCode >= 300) {
4518
+ throw new KvboxError(errorIn(text) ?? `control plane answered ${res.statusCode}`);
4519
+ }
4520
+ const parsed = HostJoinResponseSchema.safeParse(jsonOrNull(text));
4521
+ if (!parsed.success) throw new KvboxError(`${url} did not answer like a kvbox control plane`);
4522
+ if (!REALM_RE.test(parsed.data.controlPlane.name)) {
4523
+ throw new KvboxError(`${url} calls itself "${parsed.data.controlPlane.name}", which cannot name a realm (letters, digits, '.', '-')`);
4524
+ }
4525
+ await saveConfig({ ...cfg, controlPlane: { url, name: parsed.data.controlPlane.name, secret: parsed.data.hostSecret, advertise, port } }, p);
4526
+ return { hostName: name, controlPlane: parsed.data.controlPlane.name, hostUrl };
4521
4527
  }
4522
-
4523
- // src/core/relay.ts
4524
- import { access as access2, chmod as chmod3, mkdir as mkdir8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
4525
-
4526
- // ../shared/src/relay.ts
4527
- import { z as z7 } from "zod";
4528
- var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
4529
- var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
4530
- var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
4531
- var RelayJoinSchema = z7.object({
4532
- v: z7.literal(1),
4533
- /** How the relay lists this host. */
4534
- name: z7.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
4535
- /** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
4536
- relay: z7.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
4537
- /** The relay's WireGuard public key. */
4538
- relayKey: z7.string().regex(WG_KEY_RE),
4539
- /** This host's address inside the tunnel. */
4540
- tunnelIp: z7.string().regex(IPV4_RE),
4541
- /** This host's WireGuard private key, generated on the relay, kept nowhere else. */
4542
- privateKey: z7.string().regex(WG_KEY_RE),
4543
- /** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
4544
- publicIp: z7.string().regex(IPV4_RE)
4545
- });
4546
- function decodeRelayJoin(text) {
4547
- let parsed;
4528
+ async function fetchCloudCa(p = paths()) {
4529
+ const cfg = await loadConfig(p);
4530
+ const cp = cfg.controlPlane;
4531
+ if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no CA to fetch; paste the key instead: kvbox-server trust-ca <public-key>");
4532
+ const res = await request2(`${cp.url}/hosts/self/ssh-ca`, {
4533
+ headers: { authorization: `Bearer ${cp.secret}` },
4534
+ headersTimeout: 1e4,
4535
+ bodyTimeout: 1e4
4536
+ }).catch((err) => {
4537
+ throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
4538
+ });
4539
+ const text = await res.body.text();
4540
+ if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not answer /hosts/self/ssh-ca: it is older than this host; paste the key instead`);
4541
+ if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(errorIn(text) ?? `${cp.name} answered ${res.statusCode}`);
4542
+ const parsed = HostSshCaResponseSchema.safeParse(jsonOrNull(text));
4543
+ if (!parsed.success) throw new KvboxError(`${cp.name} did not answer with a CA key`);
4544
+ const publicKey = parseSshPublicKey(parsed.data.publicKey);
4545
+ return { controlPlane: cp.name, publicKey, fingerprint: sshKeyFingerprint(publicKey) };
4546
+ }
4547
+ async function leaveControlPlane(p = paths()) {
4548
+ const cfg = await loadConfig(p);
4549
+ const cp = cfg.controlPlane;
4550
+ if (!cp) throw new KvboxError("this host has not joined a control plane");
4551
+ const told = await request2(`${cp.url}/hosts/self`, {
4552
+ method: "DELETE",
4553
+ headers: { authorization: `Bearer ${cp.secret}` },
4554
+ headersTimeout: 3e3,
4555
+ bodyTimeout: 3e3
4556
+ }).then(async (res) => {
4557
+ await res.body.dump();
4558
+ return res.statusCode >= 200 && res.statusCode < 300;
4559
+ }).catch(() => false);
4560
+ const { controlPlane: _gone, ...rest } = cfg;
4561
+ await saveConfig(rest, p);
4562
+ return { controlPlane: cp.name, told };
4563
+ }
4564
+ function jsonOrNull(text) {
4548
4565
  try {
4549
- parsed = JSON.parse(Buffer.from(text.trim(), "base64url").toString("utf8"));
4566
+ return JSON.parse(text);
4550
4567
  } catch {
4551
4568
  return null;
4552
4569
  }
4553
- const res = RelayJoinSchema.safeParse(parsed);
4554
- return res.success ? res.data : null;
4570
+ }
4571
+ function errorIn(text) {
4572
+ const v = jsonOrNull(text);
4573
+ if (v && typeof v === "object" && typeof v.error === "string") return v.error;
4574
+ return void 0;
4555
4575
  }
4556
4576
 
4557
4577
  // src/core/relay.ts
4558
4578
  function relayConf(join3) {
4559
4579
  return [
4560
- "# kvbox relay tunnel: made by `kvbox server relay`, installed by net-setup.sh. Do not edit.",
4580
+ "# kvbox relay tunnel: made by `kvbox-server relay`, installed by net-setup.sh. Do not edit.",
4561
4581
  "[Interface]",
4562
4582
  `PrivateKey = ${join3.privateKey}`,
4563
4583
  `Address = ${join3.tunnelIp}/32`,
@@ -4578,11 +4598,11 @@ async function useRelay(joinString, p = paths()) {
4578
4598
  if (!join3) throw new KvboxError("that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay");
4579
4599
  const cfg = await loadConfig(p);
4580
4600
  if (cfg.relay && cfg.relay.name !== join3.name) {
4581
- throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox server relay off first`);
4601
+ throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox-server relay off first`);
4582
4602
  }
4583
4603
  if (cfg.relay && cfg.relay.publicIp !== join3.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {
4584
4604
  throw new KvboxError(
4585
- `${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join3.publicIp}; run kvbox server leave first, then join again`
4605
+ `${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join3.publicIp}; run kvbox-server leave first, then join again`
4586
4606
  );
4587
4607
  }
4588
4608
  await mkdir8(p.relay, { recursive: true, mode: 448 });
@@ -4605,7 +4625,7 @@ async function dropRelay(p = paths()) {
4605
4625
  const relay = cfg.relay;
4606
4626
  if (!relay) throw new KvboxError("this host does not go through a relay");
4607
4627
  if (cfg.controlPlane?.advertise === relay.publicIp) {
4608
- throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox server leave first`);
4628
+ throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
4609
4629
  }
4610
4630
  await netSetup(cfg, ["relay", "down"]);
4611
4631
  await rm5(p.relayConf, { force: true });
@@ -4647,7 +4667,7 @@ function startIdleWatch(opts = {}) {
4647
4667
  const hibernate = opts.hibernate ?? ((box) => hibernateIfRunning(box, p));
4648
4668
  const busy = opts.busy ?? ((box) => boxBusy(box) || restoreRunning(box));
4649
4669
  const now = opts.now ?? Date.now;
4650
- const log = opts.log ?? ((line) => console.log(line));
4670
+ const log2 = opts.log ?? ((line) => log.info(line));
4651
4671
  const seen = /* @__PURE__ */ new Map();
4652
4672
  const checkErrors = /* @__PURE__ */ new Map();
4653
4673
  let timer;
@@ -4657,10 +4677,10 @@ function startIdleWatch(opts = {}) {
4657
4677
  inflight.add(box.id);
4658
4678
  const byImage = bytes < 0;
4659
4679
  try {
4660
- if (await hibernate(box)) log(`box ${box.owner}/${box.name}: ${byImage ? "idle by its own check" : "no network traffic"} for ${quiet} min; hibernated it (kvbox connect wakes it)`);
4680
+ if (await hibernate(box)) log2(`box ${box.owner}/${box.name}: ${byImage ? "idle by its own check" : "no network traffic"} for ${quiet} min; hibernated it (kvbox connect wakes it)`);
4661
4681
  seen.delete(box.id);
4662
4682
  } catch (err) {
4663
- log(`warning: box ${box.owner}/${box.name}: could not hibernate it after ${quiet} min ${byImage ? "idle" : "without traffic"}: ${err.message}`);
4683
+ log2(`warning: box ${box.owner}/${box.name}: could not hibernate it after ${quiet} min ${byImage ? "idle" : "without traffic"}: ${err.message}`);
4664
4684
  seen.set(box.id, { bytes, since: t });
4665
4685
  } finally {
4666
4686
  inflight.delete(box.id);
@@ -4669,7 +4689,7 @@ function startIdleWatch(opts = {}) {
4669
4689
  const askIdle = (box) => guestIdle(box).then(
4670
4690
  (v) => (checkErrors.delete(box.id), v),
4671
4691
  (err) => {
4672
- if (checkErrors.get(box.id) !== err.message) log(`warning: box ${box.owner}/${box.name}: its idle check ${box.idleCheck ?? ""} failed, so it counts as busy and does not hibernate: ${err.message}`);
4692
+ if (checkErrors.get(box.id) !== err.message) log2(`warning: box ${box.owner}/${box.name}: its idle check ${box.idleCheck ?? ""} failed, so it counts as busy and does not hibernate: ${err.message}`);
4673
4693
  checkErrors.set(box.id, err.message);
4674
4694
  return false;
4675
4695
  }
@@ -4708,7 +4728,7 @@ function startIdleWatch(opts = {}) {
4708
4728
  };
4709
4729
  const schedule = () => {
4710
4730
  if (stopped) return;
4711
- timer = setTimeout(() => void check().catch((err) => log(`warning: idle watch: ${err.message}`)).finally(schedule), intervalMs);
4731
+ timer = setTimeout(() => void check().catch((err) => log2(`warning: idle watch: ${err.message}`)).finally(schedule), intervalMs);
4712
4732
  timer.unref();
4713
4733
  };
4714
4734
  schedule();
@@ -4739,7 +4759,7 @@ function startRelayWatch(opts = {}) {
4739
4759
  const misses = opts.misses ?? 3;
4740
4760
  const probe = opts.probe ?? pingRelay;
4741
4761
  const p = opts.p ?? paths();
4742
- const log = opts.log ?? ((line) => console.log(line));
4762
+ const log2 = opts.log ?? ((line) => log.info(line));
4743
4763
  const restart = opts.restart ?? (async () => netSetup(await loadConfig(p), ["relay", "restart"]));
4744
4764
  report = { restarts: 0, lastRestartAt: null };
4745
4765
  let missed = 0;
@@ -4753,25 +4773,25 @@ function startRelayWatch(opts = {}) {
4753
4773
  return;
4754
4774
  }
4755
4775
  if (await probe()) {
4756
- if (stuck) log(`relay ${cfg.relay.name}: the tunnel carries traffic again`);
4776
+ if (stuck) log2(`relay ${cfg.relay.name}: the tunnel carries traffic again`);
4757
4777
  missed = 0;
4758
4778
  stuck = false;
4759
4779
  return;
4760
4780
  }
4761
4781
  if (++missed < misses) return;
4762
4782
  missed = 0;
4763
- if (!stuck) log(`relay ${cfg.relay.name}: no answer through the tunnel for ${misses * intervalMs / 1e3} s; restarting it`);
4783
+ if (!stuck) log2(`relay ${cfg.relay.name}: no answer through the tunnel for ${misses * intervalMs / 1e3} s; restarting it`);
4764
4784
  try {
4765
4785
  await restart();
4766
4786
  report = { restarts: report.restarts + 1, lastRestartAt: (/* @__PURE__ */ new Date()).toISOString() };
4767
4787
  } catch (err) {
4768
- if (!stuck) console.error(`warning: relay ${cfg.relay.name}: could not restart the tunnel: ${err.message}`);
4788
+ if (!stuck) log.warn(`relay ${cfg.relay.name}: could not restart the tunnel: ${err.message}`);
4769
4789
  }
4770
4790
  stuck = true;
4771
4791
  };
4772
4792
  const schedule = () => {
4773
4793
  if (stopped) return;
4774
- timer = setTimeout(() => void round2().catch((err) => console.error(`warning: relay watch: ${err.message}`)).finally(schedule), intervalMs);
4794
+ timer = setTimeout(() => void round2().catch((err) => log.warn(`relay watch: ${err.message}`)).finally(schedule), intervalMs);
4775
4795
  timer.unref();
4776
4796
  };
4777
4797
  schedule();
@@ -4781,8 +4801,241 @@ function startRelayWatch(opts = {}) {
4781
4801
  };
4782
4802
  }
4783
4803
 
4804
+ // src/daemon.ts
4805
+ import { spawn as spawn2 } from "node:child_process";
4806
+ import { accessSync, constants as constants2, openSync as openSync4, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
4807
+ import { mkdir as mkdir9, readFile as readFile9, stat as stat4 } from "node:fs/promises";
4808
+ import { userInfo as userInfo2 } from "node:os";
4809
+ import { setTimeout as sleep3 } from "node:timers/promises";
4810
+
4811
+ // ../shared/src/systemd.ts
4812
+ import { spawnSync } from "node:child_process";
4813
+ import { readFileSync as readFileSync2 } from "node:fs";
4814
+ import { resolve } from "node:path";
4815
+ var UNIT = "kvbox-server";
4816
+ var UNIT_FILE = `/etc/systemd/system/${UNIT}.service`;
4817
+ function hasUnitFor(p, file = UNIT_FILE) {
4818
+ let text;
4819
+ try {
4820
+ text = readFileSync2(file, "utf8");
4821
+ } catch {
4822
+ return false;
4823
+ }
4824
+ const home = /^Environment="?KVBOX_HOME=([^"\n]+)"?$/m.exec(text)?.[1];
4825
+ return home !== void 0 && resolve(home) === resolve(p.home);
4826
+ }
4827
+ function startUnitProcess() {
4828
+ const res = spawnSync("sudo", ["-n", "systemctl", "start", UNIT], { encoding: "utf8" });
4829
+ return { ok: res.status === 0, out: `${res.stdout ?? ""}${res.stderr ?? ""}`.trim() };
4830
+ }
4831
+ function unitActive() {
4832
+ const res = spawnSync("systemctl", ["is-active", UNIT], { encoding: "utf8" });
4833
+ return (res.stdout ?? "").trim() === "active";
4834
+ }
4835
+ function startsAtBoot(p) {
4836
+ return hasUnitFor(p) && spawnSync("systemctl", ["is-enabled", "--quiet", UNIT]).status === 0;
4837
+ }
4838
+
4839
+ // src/socketClient.ts
4840
+ import { Agent as Agent2, request as request3 } from "undici";
4841
+ var SocketClient = class {
4842
+ agent;
4843
+ constructor(socketPath) {
4844
+ this.agent = new Agent2({ connect: { socketPath } });
4845
+ }
4846
+ health() {
4847
+ return this.call("GET", "/health", HealthSchema);
4848
+ }
4849
+ cloudCa() {
4850
+ return this.call("GET", "/ssh/cloud-ca", CloudCaSchema);
4851
+ }
4852
+ trustCa(req) {
4853
+ return this.call("POST", "/ssh/trust-ca", TrustCaReportSchema, req);
4854
+ }
4855
+ async close() {
4856
+ await this.agent.close();
4857
+ }
4858
+ async call(method, path, schema, body) {
4859
+ let res;
4860
+ try {
4861
+ res = await request3(`http://kvbox-server${path}`, {
4862
+ method,
4863
+ dispatcher: this.agent,
4864
+ ...body === void 0 ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }
4865
+ });
4866
+ } catch (err) {
4867
+ const code = err.code ?? "";
4868
+ if (code === "ENOENT" || code === "ECONNREFUSED") throw new KvboxError("kvbox-server is not running; start it with: kvbox-server start -d");
4869
+ throw new KvboxError(`cannot reach kvbox-server: ${err.message}`);
4870
+ }
4871
+ const text = await res.body.text();
4872
+ if (res.statusCode >= 300) {
4873
+ const parsed = ApiErrorSchema.safeParse(safeJson(text) ?? {});
4874
+ if (!parsed.success) throw new KvboxError(`kvbox-server answered ${res.statusCode}`);
4875
+ throw new KvboxError(parsed.data.error, res.statusCode === 501 ? 2 : 1);
4876
+ }
4877
+ const json = safeJson(text);
4878
+ if (json === void 0) throw new KvboxError(`kvbox-server answered ${res.statusCode} with something that is not JSON`);
4879
+ return schema.parse(json);
4880
+ }
4881
+ };
4882
+ function safeJson(text) {
4883
+ try {
4884
+ return JSON.parse(text);
4885
+ } catch {
4886
+ return void 0;
4887
+ }
4888
+ }
4889
+
4890
+ // src/daemon.ts
4891
+ async function runningPid(p = paths()) {
4892
+ let pid;
4893
+ try {
4894
+ pid = Number.parseInt(await readFile9(p.serverPid, "utf8"), 10);
4895
+ } catch {
4896
+ return null;
4897
+ }
4898
+ return Number.isInteger(pid) && alive(pid) ? pid : null;
4899
+ }
4900
+ function alive(pid) {
4901
+ try {
4902
+ process.kill(pid, 0);
4903
+ return true;
4904
+ } catch {
4905
+ return false;
4906
+ }
4907
+ }
4908
+ async function stopDaemon(pid, timeoutMs = 1e4) {
4909
+ process.kill(pid, "SIGTERM");
4910
+ const deadline = Date.now() + timeoutMs;
4911
+ while (alive(pid)) {
4912
+ if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1e3}s`);
4913
+ await sleep3(100);
4914
+ }
4915
+ }
4916
+ async function answering(p = paths()) {
4917
+ if (!await stat4(p.serverSock).then(() => true, () => false)) return null;
4918
+ const probe = new SocketClient(p.serverSock);
4919
+ try {
4920
+ const health = await probe.health();
4921
+ return { pid: health.pid, version: health.version };
4922
+ } catch {
4923
+ return null;
4924
+ } finally {
4925
+ await probe.close();
4926
+ }
4927
+ }
4928
+ async function startDetached(p = paths(), timeoutMs = 5e3) {
4929
+ await mkdir9(p.home, { recursive: true });
4930
+ const running = await answering(p);
4931
+ if (running) return { pid: running.pid, socketPath: p.serverSock, viaGroup: void 0, viaUnit: false, alreadyRunning: running.version };
4932
+ if (hasUnitFor(p)) return startUnit(p, timeoutMs);
4933
+ const log2 = openSync4(p.serverLog, "a");
4934
+ const launcher = selfLauncher();
4935
+ const child = spawn2(launcher.cmd, launcher.args, { detached: true, stdio: ["ignore", log2, log2], env: { ...process.env, KVBOX_HOME: p.home } });
4936
+ const failed = new Promise((_, reject) => {
4937
+ child.once("error", (err) => reject(new KvboxError(`could not start kvbox-server: ${err.message}`)));
4938
+ child.once("exit", (code) => {
4939
+ void lastErrorLine(p.serverLog).then((why) => {
4940
+ reject(new KvboxError(why === void 0 ? `kvbox-server exited with code ${String(code)} before listening; see ${p.serverLog}` : `kvbox-server could not start: ${why}`));
4941
+ });
4942
+ });
4943
+ });
4944
+ await Promise.race([serving(p, timeoutMs), failed]);
4945
+ child.removeAllListeners("exit");
4946
+ child.unref();
4947
+ return { pid: await pidFile(p, child.pid ?? -1), socketPath: p.serverSock, viaGroup: launcher.viaGroup, viaUnit: false };
4948
+ }
4949
+ async function restartDaemon(p = paths()) {
4950
+ const pid = await runningPid(p);
4951
+ if (pid !== null) await stopDaemon(pid);
4952
+ return startDetached(p);
4953
+ }
4954
+ async function startUnit(p, timeoutMs) {
4955
+ const logFrom = await stat4(p.serverLog).then((s) => s.size, () => 0);
4956
+ const res = startUnitProcess();
4957
+ if (!res.ok) {
4958
+ const why = res.out || await lastErrorLine(p.serverLog, logFrom) || "systemctl start failed";
4959
+ throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT}; rerun install-server.sh if sudo asked for a password)`);
4960
+ }
4961
+ await serving(p, timeoutMs, async () => {
4962
+ if (unitActive()) return;
4963
+ const why = await lastErrorLine(p.serverLog, logFrom) ?? "it exited right after starting";
4964
+ throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT})`);
4965
+ });
4966
+ return { pid: await pidFile(p, -1), socketPath: p.serverSock, viaGroup: void 0, viaUnit: true };
4967
+ }
4968
+ async function pidFile(p, fallback) {
4969
+ const pid = Number.parseInt(await readFile9(p.serverPid, "utf8").catch(() => ""), 10);
4970
+ return Number.isNaN(pid) ? fallback : pid;
4971
+ }
4972
+ async function serving(p, timeoutMs, check) {
4973
+ const deadline = Date.now() + timeoutMs;
4974
+ while (Date.now() < deadline) {
4975
+ await check?.();
4976
+ if (await stat4(p.serverSock).then(() => true, () => false)) {
4977
+ const probe = new SocketClient(p.serverSock);
4978
+ try {
4979
+ await probe.health();
4980
+ return;
4981
+ } catch {
4982
+ } finally {
4983
+ await probe.close();
4984
+ }
4985
+ }
4986
+ await sleep3(100);
4987
+ }
4988
+ throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
4989
+ }
4990
+ async function lastErrorLine(logPath, from = 0) {
4991
+ const text = (await readFile9(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
4992
+ for (const line of text.trimEnd().split("\n").slice(-20).reverse()) {
4993
+ const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
4994
+ if (m?.[1] !== void 0) return m[1];
4995
+ }
4996
+ return void 0;
4997
+ }
4998
+ function selfLauncher(opts = {}) {
4999
+ const device = opts.device ?? KVM_DEVICE;
5000
+ const argv = [process.execPath, ...process.execArgv, process.argv[1] ?? "kvbox-server", "start"];
5001
+ const plain = { cmd: argv[0], args: argv.slice(1) };
5002
+ try {
5003
+ accessSync(device, constants2.R_OK | constants2.W_OK);
5004
+ return plain;
5005
+ } catch (err) {
5006
+ const code = err.code;
5007
+ if (code !== "EACCES" && code !== "EPERM") return plain;
5008
+ }
5009
+ let gid;
5010
+ try {
5011
+ gid = statSync3(device).gid;
5012
+ } catch {
5013
+ return plain;
5014
+ }
5015
+ const group = groupWithMember(gid, opts.user ?? userInfo2().username, opts.groupFile ?? "/etc/group");
5016
+ if (group === void 0) return plain;
5017
+ return { cmd: "sg", args: [group, "-c", argv.map(shellQuote).join(" ")], viaGroup: group };
5018
+ }
5019
+ function shellQuote(word) {
5020
+ return `'${word.replaceAll("'", `'\\''`)}'`;
5021
+ }
5022
+ function groupWithMember(gid, user, groupFile) {
5023
+ let text;
5024
+ try {
5025
+ text = readFileSync3(groupFile, "utf8");
5026
+ } catch {
5027
+ return void 0;
5028
+ }
5029
+ for (const line of text.split("\n")) {
5030
+ const [name, , id, members = ""] = line.split(":");
5031
+ if (name === void 0 || id === void 0 || Number.parseInt(id, 10) !== gid) continue;
5032
+ return members.split(",").includes(user) ? name : void 0;
5033
+ }
5034
+ return void 0;
5035
+ }
5036
+
4784
5037
  // src/listen.ts
4785
- import { readFile as readFile9, rm as rm6, writeFile as writeFile8 } from "node:fs/promises";
5038
+ import { readFile as readFile10, rm as rm6, writeFile as writeFile8 } from "node:fs/promises";
4786
5039
  import { createServer as createHttpsServer } from "node:https";
4787
5040
  import { createAdaptorServer } from "@hono/node-server";
4788
5041
 
@@ -4802,7 +5055,7 @@ function versionOf(srcFileUrl, injected) {
4802
5055
  }
4803
5056
 
4804
5057
  // src/version.ts
4805
- var VERSION = versionOf(import.meta.url, true ? "0.5.42" : void 0);
5058
+ var VERSION = versionOf(import.meta.url, true ? "0.5.44" : void 0);
4806
5059
 
4807
5060
  // src/caller.ts
4808
5061
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";
@@ -4909,14 +5162,14 @@ function backupRoutes() {
4909
5162
  import { connect as connect2 } from "node:net";
4910
5163
  import { Readable } from "node:stream";
4911
5164
  import { Hono as Hono2 } from "hono";
4912
- import { request as request3 } from "undici";
5165
+ import { request as request4 } from "undici";
4913
5166
 
4914
5167
  // ../shared/src/httpHead.ts
4915
5168
  var END = "\r\n\r\n";
4916
5169
  var HeadTimeoutError = class extends Error {
4917
5170
  };
4918
5171
  function readHead(socket, opts) {
4919
- return new Promise((resolve, reject) => {
5172
+ return new Promise((resolve2, reject) => {
4920
5173
  let bytes = Buffer.alloc(0);
4921
5174
  const done = (err) => {
4922
5175
  clearTimeout(timer);
@@ -4925,7 +5178,7 @@ function readHead(socket, opts) {
4925
5178
  socket.pause();
4926
5179
  if (err) return reject(err);
4927
5180
  const end = bytes.indexOf(END);
4928
- resolve({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
5181
+ resolve2({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
4929
5182
  };
4930
5183
  const onData = (chunk) => {
4931
5184
  bytes = Buffer.concat([bytes, chunk]);
@@ -5051,7 +5304,7 @@ async function forward(c, wake) {
5051
5304
  raw.headers.forEach((value, name) => pairs.push([name, value]));
5052
5305
  let res;
5053
5306
  try {
5054
- res = await request3(`http://${target.ip}:${target.port}${target.path}`, {
5307
+ res = await request4(`http://${target.ip}:${target.port}${target.path}`, {
5055
5308
  method: raw.method,
5056
5309
  headers: boxHeaders(pairs, target).flat(),
5057
5310
  body: raw.body === null ? null : Readable.fromWeb(raw.body),
@@ -5326,7 +5579,7 @@ import { Hono as Hono7 } from "hono";
5326
5579
  function sshRoutes(opts = {}) {
5327
5580
  const r = new Hono7();
5328
5581
  if (opts.controlPlane) {
5329
- r.all("/*", (c) => c.json({ error: "trusting a CA is done on the host itself (kvbox server trust-ca there); the control plane cannot ask a host to" }, 403));
5582
+ r.all("/*", (c) => c.json({ error: "trusting a CA is done on the host itself (kvbox-server trust-ca there); the control plane cannot ask a host to" }, 403));
5330
5583
  return r;
5331
5584
  }
5332
5585
  r.get("/cloud-ca", async (c) => c.json(await fetchCloudCa()));
@@ -5437,7 +5690,7 @@ function createApp(opts = {}) {
5437
5690
  if (err instanceof KvboxError) {
5438
5691
  return c.json({ error: err.message }, err.exitCode === 2 ? 501 : 400);
5439
5692
  }
5440
- console.error(err);
5693
+ log.error(`${c.req.method} ${c.req.path}: ${err.stack ?? err.message}`);
5441
5694
  return c.json({ error: err.message }, 500);
5442
5695
  });
5443
5696
  return app;
@@ -5453,9 +5706,9 @@ async function listen(opts = {}) {
5453
5706
  }
5454
5707
  await rm6(socketPath, { force: true });
5455
5708
  const server = createAdaptorServer({ fetch: createApp().fetch });
5456
- await new Promise((resolve, reject) => {
5709
+ await new Promise((resolve2, reject) => {
5457
5710
  server.once("error", reject);
5458
- server.listen(socketPath, () => resolve());
5711
+ server.listen(socketPath, () => resolve2());
5459
5712
  });
5460
5713
  await writeFile8(p.serverPid, `${process.pid}
5461
5714
  `);
@@ -5463,7 +5716,7 @@ async function listen(opts = {}) {
5463
5716
  let httpsServer;
5464
5717
  const cp = cfg.controlPlane;
5465
5718
  if (cp) {
5466
- const [key, cert] = await Promise.all([readFile9(p.tlsKey), readFile9(p.tlsCert)]).catch((err) => {
5719
+ const [key, cert] = await Promise.all([readFile10(p.tlsKey), readFile10(p.tlsCert)]).catch((err) => {
5467
5720
  throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
5468
5721
  });
5469
5722
  httpsServer = createAdaptorServer({
@@ -5473,9 +5726,9 @@ async function listen(opts = {}) {
5473
5726
  });
5474
5727
  httpsServer.on("upgrade", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));
5475
5728
  const port = opts.httpsPort ?? cp.port;
5476
- await new Promise((resolve, reject) => {
5729
+ await new Promise((resolve2, reject) => {
5477
5730
  httpsServer.once("error", reject);
5478
- httpsServer.listen(port, "0.0.0.0", () => resolve());
5731
+ httpsServer.listen(port, "0.0.0.0", () => resolve2());
5479
5732
  }).catch(async (err) => {
5480
5733
  server.close();
5481
5734
  await rm6(socketPath, { force: true });
@@ -5487,8 +5740,8 @@ async function listen(opts = {}) {
5487
5740
  }
5488
5741
  const close = async () => {
5489
5742
  await Promise.all([
5490
- new Promise((resolve) => server.close(() => resolve())),
5491
- httpsServer ? new Promise((resolve) => httpsServer.close(() => resolve())) : void 0
5743
+ new Promise((resolve2) => server.close(() => resolve2())),
5744
+ httpsServer ? new Promise((resolve2) => httpsServer.close(() => resolve2())) : void 0
5492
5745
  ]);
5493
5746
  await rm6(socketPath, { force: true });
5494
5747
  await rm6(p.serverPid, { force: true });
@@ -5506,39 +5759,51 @@ async function listen(opts = {}) {
5506
5759
  return https ? { socketPath, server, https, close } : { socketPath, server, close };
5507
5760
  }
5508
5761
 
5509
- // src/index.ts
5510
- var program = new Command("kvbox-server").description("kvbox host daemon: owns Firecracker and ~/.kvbox, serves the kvbox API").version(VERSION, "-v, --version").showHelpAfterError();
5511
- program.command("start", { isDefault: true }).description("serve the API on the local Unix socket (foreground)").option("--socket <path>", "socket to listen on (default: $KVBOX_HOME/server.sock)").action(async (opts) => {
5762
+ // src/commands/start.ts
5763
+ var daemon = false;
5764
+ var isDaemon = () => daemon;
5765
+ var startCommand = new Command("start").description("run the daemon in the foreground; -d starts it in the background and returns").option("-d, --detach", "start the daemon in the background (through systemd when install-server.sh set it up) and return once it answers").option("--socket <path>", "socket to listen on (default: $KVBOX_HOME/server.sock)").action(async (opts) => {
5766
+ if (opts.detach) {
5767
+ const started = await startDetached(paths());
5768
+ if (started.alreadyRunning !== void 0) {
5769
+ console.log(`kvbox-server ${started.alreadyRunning} is already running (pid ${started.pid})`);
5770
+ return;
5771
+ }
5772
+ console.log(`kvbox-server started (pid ${started.pid}), listening on ${started.socketPath}${started.viaUnit ? " (through systemd)" : ""}`);
5773
+ if (started.viaGroup !== void 0) console.log(`started through the ${started.viaGroup} group, which this shell does not have yet (log out and back in to get it)`);
5774
+ return;
5775
+ }
5776
+ daemon = true;
5512
5777
  await requireKvm();
5513
5778
  const settled = await settleDeadBoxes(paths());
5514
- await clearStagedBackups(paths()).catch((err) => console.error(`warning: ${err.message}`));
5779
+ await clearStagedBackups(paths()).catch((err) => log.warn(`staged backups not cleared: ${err.message}`));
5515
5780
  const { socketPath, https } = await listen(opts.socket ? { socketPath: opts.socket } : {});
5516
- console.log(`kvbox-server ${VERSION} listening on ${socketPath} (pid ${process.pid})`);
5781
+ log.info(`kvbox-server ${VERSION} listening on ${socketPath} (pid ${process.pid})`);
5517
5782
  if (https) {
5518
5783
  const cfg = await loadConfig(paths());
5519
- console.log(`control plane ${cfg.controlPlane?.name}: answering on ${https.url}`);
5784
+ log.info(`control plane ${cfg.controlPlane?.name}: answering on ${https.url}`);
5520
5785
  }
5521
5786
  try {
5522
5787
  const cfg = await loadConfig(paths());
5523
5788
  const state = await ensureHostNetwork(cfg);
5524
- console.log(`host network: bridge ${cfg.bridge} ${state}`);
5789
+ log.info(`host network: bridge ${cfg.bridge} ${state}`);
5525
5790
  await pinRunningTaps(paths());
5526
5791
  } catch (err) {
5527
- console.error(`warning: host network not ready (${err.message}); run: kvbox-server net up`);
5792
+ log.warn(`host network not ready (${err.message}); run: kvbox-server net up`);
5528
5793
  }
5529
5794
  try {
5530
5795
  const relay = await restoreRelay(paths());
5531
- if (relay) console.log(`relay ${relay.name}: the control plane may reach this host through the tunnel again`);
5796
+ if (relay) log.info(`relay ${relay.name}: the control plane may reach this host through the tunnel again`);
5532
5797
  } catch (err) {
5533
- console.error(`warning: the control plane may not reach this host through its relay (${err.message}); run: kvbox server relay <join string>`);
5798
+ log.warn(`the control plane may not reach this host through its relay (${err.message}); run: kvbox-server relay <join string>`);
5534
5799
  }
5535
5800
  let dnsWarned = false;
5536
5801
  const bindDns = () => {
5537
5802
  loadConfig(paths()).then(async (cfg) => {
5538
5803
  await startDns({ host: cfg.gateway });
5539
- console.log(`box names: <name>.kvbox answered on ${cfg.gateway}`);
5804
+ log.info(`box names: <name>.kvbox answered on ${cfg.gateway}`);
5540
5805
  }).catch((err) => {
5541
- if (!dnsWarned) console.error(`warning: box names (<name>.kvbox) do not resolve yet (${err.message}); retrying`);
5806
+ if (!dnsWarned) log.warn(`box names (<name>.kvbox) do not resolve yet (${err.message}); retrying`);
5542
5807
  dnsWarned = true;
5543
5808
  setTimeout(bindDns, DNS_RETRY_MS).unref();
5544
5809
  });
@@ -5548,48 +5813,244 @@ program.command("start", { isDefault: true }).description("serve the API on the
5548
5813
  startIdleWatch();
5549
5814
  const recovery2 = await bootRecovered(settled, paths());
5550
5815
  if (recovery2) {
5551
- for (const box of recovery2.booted) console.log(`box ${box} was running when it went down; booted it again`);
5552
- for (const box of recovery2.leftStopped) console.log(`box ${box} was in standby when it went down; its memory is gone, left stopped`);
5553
- for (const f of recovery2.failed) console.error(`warning: box ${f.box} was running when it went down and did not come back: ${f.error}`);
5816
+ for (const box of recovery2.booted) log.info(`box ${box} was running when it went down; booted it again`);
5817
+ for (const box of recovery2.leftStopped) log.info(`box ${box} was in standby when it went down; its memory is gone, left stopped`);
5818
+ for (const f of recovery2.failed) log.warn(`box ${f.box} was running when it went down and did not come back: ${f.error}`);
5554
5819
  }
5555
5820
  });
5556
- program.command("join <control-plane-url>").description("register this host with a control plane (needs a one-time token minted there); it answers the control plane from its next start").requiredOption("--token <token>", "one-time join token from the control plane").option("--advertise <host-or-ip>", "address the control plane reaches this host at (default: this host's default-route address)").option("--name <name>", "how the control plane lists this host (default: hostname)").option("--country <country>", "where this host is, a name or a code (romania, US); kvbox new --country places boxes by it").action(async (url, opts) => {
5557
- const joined = await joinControlPlane({ url, ...opts }, paths());
5821
+
5822
+ // src/program.ts
5823
+ import { Command as Command10 } from "commander";
5824
+
5825
+ // src/commands/join.ts
5826
+ import { Command as Command2 } from "commander";
5827
+ var joinCommand = new Command2("join").description("put this host behind a control plane (needs a one-time token minted there) and restart the daemon").argument("<control-plane-url>", "the control plane, e.g. https://api.kvbox.sh").requiredOption("--token <token>", "one-time join token from the control plane").option("--advertise <host-or-ip>", "address the control plane reaches this host at (default: this host's default-route address)").option("--name <name>", "how the control plane lists this host (default: hostname)").option("--country <country>", "where this host is, a name or a code (romania, US); kvbox new --country places boxes by it").action(async (url, opts) => {
5828
+ const p = paths();
5829
+ const joined = await joinControlPlane({ url, ...opts }, p);
5558
5830
  console.log(`joined ${joined.controlPlane} as host ${joined.hostName}`);
5559
- console.log(`it answers the control plane on ${joined.hostUrl} once its server restarts`);
5560
5831
  console.log(`make sure port ${new URL(joined.hostUrl).port} is reachable from the control plane`);
5832
+ if (await runningPid(p) === null) {
5833
+ console.log(`it answers the control plane on ${joined.hostUrl} once the daemon starts (kvbox-server start -d)`);
5834
+ return;
5835
+ }
5836
+ const started = await restartDaemon(p);
5837
+ console.log(`kvbox-server restarted (pid ${started.pid}); it answers the control plane on ${joined.hostUrl} now`);
5561
5838
  });
5562
- program.command("leave").description("forget the control plane this host joined; the HTTPS port closes at the next start").action(async () => {
5563
- const left = await leaveControlPlane(paths());
5564
- console.log(`left ${left.controlPlane}; the HTTPS port closes once its server restarts`);
5839
+
5840
+ // src/commands/leave.ts
5841
+ import { Command as Command3 } from "commander";
5842
+ var leaveCommand = new Command3("leave").description("take this host out from behind its control plane and restart the daemon").action(async () => {
5843
+ const p = paths();
5844
+ const left = await leaveControlPlane(p);
5845
+ console.log(`left ${left.controlPlane}`);
5565
5846
  if (!left.told) console.log(`(the control plane could not be told; remove this host there)`);
5566
- });
5567
- program.command("relay <join-string>").description("reach the internet through a relay (paste what `kvbox-relay add` printed there); `off` takes the tunnel down").action(async (joinString) => {
5568
- if (joinString === "off") {
5569
- const relay2 = await dropRelay(paths());
5570
- console.log(`tunnel to relay ${relay2.name} is down; this host no longer answers at ${relay2.publicIp}`);
5847
+ if (await runningPid(p) === null) {
5848
+ console.log("the HTTPS port stays closed from the daemon's next start");
5571
5849
  return;
5572
5850
  }
5573
- const relay = await useRelay(joinString, paths());
5574
- console.log(`tunnel to relay ${relay.name} (${relay.endpoint}) is up`);
5575
- console.log(`this host is reachable at ${relay.publicIp}; kvbox server join advertises it by default`);
5851
+ const started = await restartDaemon(p);
5852
+ console.log(`kvbox-server restarted (pid ${started.pid}); only this machine talks to it now`);
5853
+ });
5854
+
5855
+ // src/commands/logs.ts
5856
+ import { open as open2, readFile as readFile11, stat as stat5 } from "node:fs/promises";
5857
+ import { setTimeout as sleep4 } from "node:timers/promises";
5858
+ import { Command as Command4 } from "commander";
5859
+ var logsCommand = new Command4("logs").description("show the daemon's log ($KVBOX_HOME/server.log); -f keeps printing as it grows").option("-n, --lines <n>", "how many lines to show from the end", "50").option("-f, --follow", "keep printing new lines until Ctrl-C").action(async (opts) => {
5860
+ const n = Number.parseInt(opts.lines, 10);
5861
+ if (!Number.isInteger(n) || n < 0) throw new KvboxError(`--lines: expected a number, got ${opts.lines}`);
5862
+ const p = paths();
5863
+ const text = await readFile11(p.serverLog, "utf8").catch((err) => {
5864
+ if (err.code === "ENOENT") throw new KvboxError(`no log yet at ${p.serverLog} (the daemon writes it once it has run)`);
5865
+ throw err;
5866
+ });
5867
+ const tail = tailLines(text, n);
5868
+ if (tail !== "") process.stdout.write(`${tail}
5869
+ `);
5870
+ if (!opts.follow) return;
5871
+ const ac = new AbortController();
5872
+ process.once("SIGINT", () => ac.abort());
5873
+ process.once("SIGTERM", () => ac.abort());
5874
+ await follow(p.serverLog, (chunk) => process.stdout.write(chunk), { from: Buffer.byteLength(text), signal: ac.signal });
5576
5875
  });
5577
- program.command("net <action>").description("host network: up | down | status (bridge, forwarding, NAT; uses sudo)").action(async (action) => {
5876
+ function tailLines(text, n) {
5877
+ if (n === 0) return "";
5878
+ const lines = text.endsWith("\n") ? text.slice(0, -1).split("\n") : text.split("\n");
5879
+ return lines.slice(-n).join("\n");
5880
+ }
5881
+ async function follow(path, write, opts = {}) {
5882
+ const intervalMs = opts.intervalMs ?? 250;
5883
+ let offset = opts.from ?? await stat5(path).then((s) => s.size, () => 0);
5884
+ while (!opts.signal?.aborted) {
5885
+ const size = await stat5(path).then((s) => s.size, () => 0);
5886
+ if (size < offset) offset = 0;
5887
+ if (size > offset) {
5888
+ const fh = await open2(path, "r");
5889
+ try {
5890
+ const buf = Buffer.alloc(size - offset);
5891
+ const { bytesRead } = await fh.read(buf, 0, buf.length, offset);
5892
+ write(buf.subarray(0, bytesRead).toString("utf8"));
5893
+ offset += bytesRead;
5894
+ } finally {
5895
+ await fh.close();
5896
+ }
5897
+ }
5898
+ await sleep4(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
5899
+ }
5900
+ }
5901
+
5902
+ // src/commands/net.ts
5903
+ import { spawnSync as spawnSync2 } from "node:child_process";
5904
+ import { Command as Command5 } from "commander";
5905
+ var netCommand = new Command5("net").description("host network: up | down | status (bridge, forwarding, NAT; uses sudo)").argument("<action>", "up, down or status").action(async (action) => {
5578
5906
  if (!["up", "down", "status"].includes(action)) throw new KvboxError("net: expected up, down or status");
5579
5907
  const cfg = await loadConfig(paths());
5580
- const res = spawnSync(netSetupScript(), [action], {
5908
+ const res = spawnSync2(netSetupScript(), [action], {
5581
5909
  stdio: "inherit",
5582
5910
  env: { ...process.env, KVBOX_BRIDGE: cfg.bridge, KVBOX_SUBNET: cfg.subnet, KVBOX_GATEWAY: cfg.gateway }
5583
5911
  });
5584
5912
  process.exit(res.status ?? 1);
5585
5913
  });
5914
+
5915
+ // src/commands/relay.ts
5916
+ import { Command as Command6 } from "commander";
5917
+ var relayCommand = new Command6("relay").description("reach the internet through a relay (paste what `kvbox-relay add` printed on the relay VM); `off` takes the tunnel down").argument("<join-string>", "the line `kvbox-relay add` printed, or `off`").action(async (joinString) => {
5918
+ if (joinString === "off") {
5919
+ const relay2 = await dropRelay(paths());
5920
+ console.log(`tunnel to relay ${relay2.name} is down; this host no longer answers at ${relay2.publicIp}`);
5921
+ return;
5922
+ }
5923
+ const relay = await useRelay(joinString, paths());
5924
+ console.log(`tunnel to relay ${relay.name} (${relay.endpoint}) is up`);
5925
+ console.log(`this host is reachable at ${relay.publicIp}; kvbox-server join advertises it by default`);
5926
+ });
5927
+
5928
+ // src/commands/status.ts
5929
+ import { Command as Command7 } from "commander";
5930
+ var statusCommand = new Command7("status").description("show whether the daemon is running, its control plane and which base image new boxes get").option("--json", "print as JSON").action(async (opts) => {
5931
+ const p = paths();
5932
+ const atBoot = startsAtBoot(p);
5933
+ const pid = await runningPid(p);
5934
+ if (pid === null) {
5935
+ if (opts.json) {
5936
+ console.log(JSON.stringify({ running: false, startsAtBoot: atBoot }, null, 2));
5937
+ process.exitCode = 1;
5938
+ return;
5939
+ }
5940
+ throw new KvboxError(`kvbox-server is not running (start it with: kvbox-server start -d)${atBoot ? "; it starts at boot" : ""}`);
5941
+ }
5942
+ const client = new SocketClient(p.serverSock);
5943
+ try {
5944
+ const health = await client.health();
5945
+ if (opts.json) {
5946
+ console.log(JSON.stringify({ running: true, ...health, startsAtBoot: atBoot }, null, 2));
5947
+ return;
5948
+ }
5949
+ console.log(`kvbox-server ${health.version} running, pid ${health.pid}`);
5950
+ console.log(atBoot ? "starts at boot: yes, and brings back the boxes that were running" : "starts at boot: no (install-server.sh sets that up)");
5951
+ const r = health.recovery;
5952
+ if (r) {
5953
+ if (r.booted.length > 0) console.log(`after the last restart it booted again: ${r.booted.join(", ")}`);
5954
+ if (r.leftStopped.length > 0) console.log(`left stopped (were in standby, their memory was lost): ${r.leftStopped.join(", ")}`);
5955
+ for (const f of r.failed) console.log(`did not come back: ${f.box} (${f.error})`);
5956
+ }
5957
+ if (health.controlPlane) console.log(`control plane: ${health.controlPlane.name} at ${health.controlPlane.url}, this host answers it on ${health.controlPlane.hostUrl}`);
5958
+ else console.log("control plane: none (kvbox-server join <url> --token <token> puts this host behind one)");
5959
+ if (health.relay) {
5960
+ console.log(`relay: ${health.relay.name} lends this host ${health.relay.publicIp} (tunnel to ${health.relay.endpoint})`);
5961
+ if (health.relay.restarts && health.relay.lastRestartAt) {
5962
+ console.log(`the tunnel stopped carrying traffic and was redialed ${health.relay.restarts} time(s) since the server started, last at ${health.relay.lastRestartAt}`);
5963
+ }
5964
+ }
5965
+ if (health.base === null) console.log("base image: none usable yet (run install-server.sh)");
5966
+ else console.log(`base image: ${health.base} (what kvbox new uses; kvbox vm update <box> moves an older box onto it)`);
5967
+ console.log(`log: ${p.serverLog} (kvbox-server logs -f)`);
5968
+ } finally {
5969
+ await client.close();
5970
+ }
5971
+ });
5972
+
5973
+ // src/commands/stop.ts
5974
+ import { Command as Command8 } from "commander";
5975
+ var stopCommand = new Command8("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
5976
+ const pid = await runningPid(paths());
5977
+ if (pid === null) throw new KvboxError("kvbox-server is not running");
5978
+ await stopDaemon(pid);
5979
+ console.log(`kvbox-server stopped (pid ${pid}); boxes keep running`);
5980
+ });
5981
+
5982
+ // src/commands/trust-ca.ts
5983
+ import { Command as Command9 } from "commander";
5984
+ var trustCaCommand = new Command9("trust-ca").description("make every cloud box on this host trust a new SSH CA (after `ca rotate` on the control plane)").argument("[public-key]", "the CA public key (or its cert-authority line); or --from-cloud").option("--from-cloud", "ask the control plane this host joined for its current CA, show the fingerprint, then ask").option("-y, --yes", "do not ask for confirmation").option("--json", "print the report as JSON").action(async (publicKey, opts) => {
5985
+ if (publicKey === void 0 && !opts.fromCloud) throw new KvboxError("give the CA public key, or --from-cloud to fetch it from the control plane this host joined");
5986
+ if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
5987
+ const client = new SocketClient(paths().serverSock);
5988
+ try {
5989
+ let key = publicKey;
5990
+ if (key === void 0) {
5991
+ const ca = await client.cloudCa();
5992
+ console.log(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);
5993
+ if (!await confirm("make every cloud box on this host trust it (in place of the CA it trusts now)?", opts.yes ?? false)) {
5994
+ throw new KvboxError("cancelled", 130);
5995
+ }
5996
+ key = ca.publicKey;
5997
+ }
5998
+ const report2 = await client.trustCa({ publicKey: key });
5999
+ if (opts.json) console.log(JSON.stringify(report2, null, 2));
6000
+ else describeReport(report2);
6001
+ } finally {
6002
+ await client.close();
6003
+ }
6004
+ });
6005
+ async function confirm(question, yes) {
6006
+ if (yes) return true;
6007
+ if (!process.stdin.isTTY) {
6008
+ console.error("refusing without -y when stdin is not a terminal");
6009
+ return false;
6010
+ }
6011
+ const { createInterface } = await import("node:readline/promises");
6012
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
6013
+ try {
6014
+ const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
6015
+ return answer === "y" || answer === "yes";
6016
+ } finally {
6017
+ rl.close();
6018
+ }
6019
+ }
6020
+ var WHEN = {
6021
+ start: "is stopped: it trusts the CA from its next start",
6022
+ wake: "is hibernated: it trusts the CA from its next wake",
6023
+ resume: "is in standby: it trusts the CA from its next resume",
6024
+ later: "is running but could not take it now; it trusts the CA from its next stop and start"
6025
+ };
6026
+ function describeReport(report2) {
6027
+ console.log(`CA ${report2.fingerprint}`);
6028
+ for (const box of report2.updated) console.log(`box ${box} now trusts the CA`);
6029
+ for (const p of report2.pending) console.log(`box ${p.box} ${WHEN[p.when]}${p.why ? ` (${p.why})` : ""}`);
6030
+ for (const f of report2.failed) console.error(`box ${f.box}: ${f.error}`);
6031
+ const parts = [`${report2.updated.length} box(es) updated now`, `${report2.pending.length} pending`, `${report2.failed.length} failed`];
6032
+ if (report2.local > 0) parts.push(`${report2.local} local box(es) untouched (they trust this host's key only)`);
6033
+ console.log(parts.join(", "));
6034
+ }
6035
+
6036
+ // src/program.ts
6037
+ function buildProgram() {
6038
+ return new Command10("kvbox-server").description("kvbox host daemon: owns Firecracker and $KVBOX_HOME (~/.kvbox), serves the kvbox API").version(VERSION, "-v, --version").showHelpAfterError().addCommand(startCommand, { isDefault: true }).addCommand(stopCommand).addCommand(statusCommand).addCommand(logsCommand).addCommand(joinCommand).addCommand(leaveCommand).addCommand(relayCommand).addCommand(trustCaCommand).addCommand(netCommand);
6039
+ }
6040
+
6041
+ // src/index.ts
5586
6042
  try {
5587
- await program.parseAsync(process.argv);
6043
+ await buildProgram().parseAsync(process.argv);
5588
6044
  } catch (err) {
5589
6045
  if (err instanceof KvboxError) {
5590
- console.error(`error: ${err.message}`);
6046
+ if (isDaemon()) log.error(err.message);
6047
+ else console.error(`error: ${err.message}`);
5591
6048
  process.exit(err.exitCode);
5592
6049
  }
6050
+ if (isDaemon()) {
6051
+ log.error(err.stack ?? String(err));
6052
+ process.exit(1);
6053
+ }
5593
6054
  throw err;
5594
6055
  }
5595
6056
  //# sourceMappingURL=kvbox-server.js.map