@kvbox/server 0.5.49 → 0.5.51

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.
@@ -63,6 +63,15 @@ function paths(home = kvboxHome()) {
63
63
  firecracker: join(home, "bin", "firecracker"),
64
64
  /** Firecracker's snapshot-editor, from the same release: merges a diff snapshot onto a full memory image. */
65
65
  snapshotEditor: join(home, "bin", "snapshot-editor"),
66
+ /** Garage, on a host that is a backup store (`kvbox-server backup setup` downloads it). */
67
+ garage: join(home, "bin", "garage"),
68
+ /** The store's Garage as this host runs it: its configuration, pid and log. The data is on the disk the operator named. */
69
+ backupStore: {
70
+ dir: join(home, "backup-store"),
71
+ conf: join(home, "backup-store", "garage.toml"),
72
+ pid: join(home, "backup-store", "garage.pid"),
73
+ log: join(home, "backup-store", "garage.log")
74
+ },
66
75
  assets: join(home, "assets"),
67
76
  kernel: join(home, "assets", "vmlinux"),
68
77
  /** Symlink to the current base image, assets/rootfs-<version>.ext4; boxes keep using the version they were made from. */
@@ -190,7 +199,15 @@ var PricingSchema = z.object({
190
199
  diskGibHour: z.number().nonnegative(),
191
200
  volumeHour: z.number().nonnegative().default(0),
192
201
  volumeGibHour: z.number().nonnegative().default(0),
193
- diskIncludedGib: z.number().int().nonnegative().default(0)
202
+ diskIncludedGib: z.number().int().nonnegative().default(0),
203
+ /**
204
+ * Object storage (#182): an hour of a slug's storage existing, whatever it holds, which covers its
205
+ * hidden box and the first `storageIncludedGib` of its size; each GiB above that is `storageGibHour`.
206
+ * A price list from before object storage charges nothing for it.
207
+ */
208
+ storageHour: z.number().nonnegative().default(0),
209
+ storageGibHour: z.number().nonnegative().default(0),
210
+ storageIncludedGib: z.number().int().nonnegative().default(0)
194
211
  });
195
212
  var PriceListSchema = PricingSchema.extend({ welcomeCredit: z.number().nonnegative() });
196
213
  var HOUR_MS = 36e5;
@@ -408,6 +425,16 @@ var RelaySchema = z2.object({
408
425
  /** `<relay-ip>:<port>` the tunnel dials. */
409
426
  endpoint: z2.string().min(1)
410
427
  });
428
+ var BackupStoreSchema = z2.object({
429
+ /** A directory on the disk bought for backups. */
430
+ path: z2.string().min(1),
431
+ bucket: z2.string().min(1),
432
+ region: z2.string().min(1),
433
+ accessKey: z2.string().min(1),
434
+ secretKey: z2.string().min(1),
435
+ /** Whether the control plane took the store; false after a setup that could not reach it. */
436
+ registered: z2.boolean().default(false)
437
+ });
411
438
  var ConfigSchema = z2.object({
412
439
  kernel: z2.string(),
413
440
  rootfs: z2.string(),
@@ -431,7 +458,9 @@ var ConfigSchema = z2.object({
431
458
  /** Absent until the host joins a control plane; then the server also listens on HTTPS. */
432
459
  controlPlane: ControlPlaneSchema.optional(),
433
460
  /** Absent unless the host sits behind a relay. */
434
- relay: RelaySchema.optional()
461
+ relay: RelaySchema.optional(),
462
+ /** Absent unless the host is a backup store. */
463
+ backupStore: BackupStoreSchema.optional()
435
464
  });
436
465
  async function saveConfig(cfg, p = paths()) {
437
466
  const parsed = ConfigSchema.parse(cfg);
@@ -952,7 +981,7 @@ async function startDns(opts) {
952
981
  if (!isOurs(q)) return reply({ rcode: RCODE.refused });
953
982
  void boxes().then((list) => answerFor(q, rinfo.address, list)).catch(() => ({ rcode: RCODE.refused })).then(reply);
954
983
  });
955
- await new Promise((resolve2, reject) => {
984
+ await new Promise((resolve3, reject) => {
956
985
  socket.once("error", (err) => {
957
986
  socket.close();
958
987
  reject(err);
@@ -961,17 +990,17 @@ async function startDns(opts) {
961
990
  socket.removeAllListeners("error");
962
991
  socket.on("error", () => {
963
992
  });
964
- resolve2();
993
+ resolve3();
965
994
  });
966
995
  });
967
- return { socket, close: () => new Promise((resolve2) => socket.close(() => resolve2())) };
996
+ return { socket, close: () => new Promise((resolve3) => socket.close(() => resolve3())) };
968
997
  }
969
998
 
970
999
  // src/core/machines.ts
971
1000
  import { spawn as spawn2 } from "node:child_process";
972
- import { closeSync as closeSync3, existsSync as existsSync6, openSync as openSync4, statSync as statSync2 } from "node:fs";
973
- 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";
974
- import { setTimeout as sleep } from "node:timers/promises";
1001
+ import { closeSync as closeSync3, existsSync as existsSync7, openSync as openSync4, statSync as statSync2 } from "node:fs";
1002
+ import { link as link2, mkdir as mkdir6, readFile as readFile6, rename as rename6, rm as rm4, truncate as truncate2, writeFile as writeFile6 } from "node:fs/promises";
1003
+ import { setTimeout as sleep2 } from "node:timers/promises";
975
1004
 
976
1005
  // ../shared/src/duration.ts
977
1006
  var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
@@ -1083,7 +1112,7 @@ var HostBackupManifestSchema = z4.object({
1083
1112
  vcpu: z4.number().int(),
1084
1113
  memMib: z4.number().int()
1085
1114
  });
1086
- var HostUploadRequest = z4.object({ key: z4.string(), urls: z4.record(z4.string(), z4.string()) });
1115
+ var HostUploadRequest = z4.object({ key: z4.string(), urls: z4.record(z4.string(), z4.string()), pin: z4.string().optional() });
1087
1116
  var HostUploadResultSchema = z4.object({ chunks: z4.number().int(), bytes: z4.number().int(), sizes: z4.record(z4.string(), z4.number().int()) });
1088
1117
  var HostRestoreRequest = z4.object({
1089
1118
  /** The backup's id: its variables were sealed under it. */
@@ -1093,7 +1122,45 @@ var HostRestoreRequest = z4.object({
1093
1122
  base: z4.string(),
1094
1123
  image: z4.string().optional(),
1095
1124
  env: z4.string().nullable(),
1096
- chunks: z4.array(z4.object({ index: z4.number().int().nonnegative(), hash: z4.string(), url: z4.string() }))
1125
+ chunks: z4.array(z4.object({ index: z4.number().int().nonnegative(), hash: z4.string(), url: z4.string() })),
1126
+ /** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */
1127
+ pin: z4.string().optional()
1128
+ });
1129
+ var BACKUP_STORE_BUCKET = "kvbox-backups";
1130
+ var BACKUP_STORE_REGION = "kvbox";
1131
+ var BackupStoreSetupRequest = z4.object({ path: z4.string().min(1), force: z4.boolean().optional(), newStore: z4.boolean().optional() });
1132
+ var BackupStoreStatusSchema = z4.object({
1133
+ path: z4.string(),
1134
+ bucket: z4.string(),
1135
+ accessKey: z4.string(),
1136
+ /** Whether Garage is running and can store. */
1137
+ running: z4.boolean(),
1138
+ /** The filesystem the path is on. */
1139
+ totalBytes: z4.number().int(),
1140
+ freeBytes: z4.number().int(),
1141
+ /** What the bucket holds, when Garage answers. */
1142
+ objects: z4.number().int().optional(),
1143
+ storedBytes: z4.number().int().optional(),
1144
+ /** Whether the control plane took the store's registration at setup. */
1145
+ registered: z4.boolean().optional()
1146
+ });
1147
+ var BackupStoreRegistration = z4.object({ bucket: z4.string().min(1), region: z4.string().min(1), accessKey: z4.string().min(1), secretKey: z4.string().min(1) });
1148
+ var CloudBackupStoreSchema = z4.object({
1149
+ id: z4.string(),
1150
+ /** Null while no host serves it (its host left; it comes back when a host registers its key and secret again). */
1151
+ host: z4.string().nullable(),
1152
+ endpoint: z4.string().nullable(),
1153
+ bucket: z4.string(),
1154
+ accessKey: z4.string(),
1155
+ createdAt: z4.string(),
1156
+ /** The host answered a poll in the last minute and its Garage runs. */
1157
+ live: z4.boolean(),
1158
+ /** From the host's last poll; null when it never reported a store. */
1159
+ totalBytes: z4.number().int().nullable(),
1160
+ freeBytes: z4.number().int().nullable(),
1161
+ /** Ready backups kept here, and what their chunks take (encrypted, compressed). */
1162
+ backups: z4.number().int(),
1163
+ storedBytes: z4.number().int()
1097
1164
  });
1098
1165
  var MachineSchema = z4.object({
1099
1166
  /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
@@ -1335,7 +1402,11 @@ var CapacitySchema = z4.object({
1335
1402
  */
1336
1403
  images: z4.array(z4.object({ name: z4.string(), version: z4.string() })).optional(),
1337
1404
  /** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */
1338
- version: z4.string().optional()
1405
+ version: z4.string().optional(),
1406
+ /** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */
1407
+ backupStore: z4.object({ totalBytes: z4.number().int(), freeBytes: z4.number().int(), running: z4.boolean() }).optional(),
1408
+ /** True on a kvbox-server that reaches a backup store by its certificate's `pin`; older ones omit it and cannot back up to a store. */
1409
+ storeClient: z4.boolean().optional()
1339
1410
  });
1340
1411
  var ImageSchema = z4.object({ name: z4.string(), version: z4.string().nullable() });
1341
1412
  var ImageIndexSchema = z4.object({
@@ -1474,13 +1545,21 @@ var UsageDaySchema = z4.object({
1474
1545
  cost: z4.number(),
1475
1546
  currency: z4.string(),
1476
1547
  boxes: z4.array(UsageDayItemSchema),
1477
- volumes: z4.array(UsageDayItemSchema)
1548
+ volumes: z4.array(UsageDayItemSchema),
1549
+ /** Object storage that existed that day (#182); absent on a day without any. */
1550
+ storage: z4.array(UsageDayItemSchema).optional()
1478
1551
  });
1479
1552
  var UsageReportSchema = z4.object({
1480
1553
  window: z4.object({ from: z4.string(), to: z4.string() }),
1481
1554
  boxes: z4.array(BoxUsageSchema),
1482
1555
  /** Absent from a side older than #91. */
1483
1556
  volumes: z4.array(VolumeUsageSchema).optional(),
1557
+ /**
1558
+ * Object storage (#182, control plane only): one row per storage a slug has or had, shaped like a
1559
+ * volume's. `volumeHours` are the hours it existed, `volumeGibHours` those of the GiB beyond the
1560
+ * included ones, `sizeGib` its whole size. Absent when there is none.
1561
+ */
1562
+ storage: z4.array(VolumeUsageSchema).optional(),
1484
1563
  /** With `?by=day` only, oldest day first. */
1485
1564
  days: z4.array(UsageDaySchema).optional(),
1486
1565
  totals: z4.object({
@@ -1490,7 +1569,7 @@ var UsageReportSchema = z4.object({
1490
1569
  diskGibHours: z4.number(),
1491
1570
  volumeHours: z4.number().optional(),
1492
1571
  volumeGibHours: z4.number().optional(),
1493
- /** Boxes and volumes together. */
1572
+ /** Boxes, volumes and object storage together. */
1494
1573
  cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional()
1495
1574
  })
1496
1575
  });
@@ -1742,6 +1821,8 @@ var CloudHostSchema = z4.object({
1742
1821
  capacity: CapacitySchema.nullable(),
1743
1822
  /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
1744
1823
  country: z4.string().nullable(),
1824
+ /** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */
1825
+ region: z4.string().nullable(),
1745
1826
  /** kvbox-server's version as of the poller's last look (`capacity.version`); null before one, or for a server older than 0.5.45. */
1746
1827
  version: z4.string().nullable()
1747
1828
  });
@@ -1750,7 +1831,7 @@ var HostInfoSchema = z4.object({
1750
1831
  health: HealthSchema.nullable(),
1751
1832
  error: z4.string().nullable()
1752
1833
  });
1753
- var HostPatchRequest = z4.object({ country: z4.string().nullable() });
1834
+ var HostPatchRequest = z4.object({ country: z4.string().nullable().optional(), region: z4.string().nullable().optional() }).refine((b) => b.country !== void 0 || b.region !== void 0, { message: "give country, region or both" });
1754
1835
  var CountrySchema = z4.object({ code: z4.string(), name: z4.string() });
1755
1836
 
1756
1837
  // ../shared/src/ssh.ts
@@ -1777,7 +1858,7 @@ var isCaLine = (line) => /^cert-authority(,|\s)/.test(line.trim());
1777
1858
  import { connect } from "node:net";
1778
1859
  var AGENT_PORT = 52;
1779
1860
  async function agentCall(udsPath, req, timeoutMs = 5e3) {
1780
- const reply = await new Promise((resolve2, reject) => {
1861
+ const reply = await new Promise((resolve3, reject) => {
1781
1862
  const sock = connect(udsPath);
1782
1863
  let buf = "";
1783
1864
  let handshaken = false;
@@ -1801,7 +1882,7 @@ async function agentCall(udsPath, req, timeoutMs = 5e3) {
1801
1882
  sock.write(JSON.stringify(req) + "\n");
1802
1883
  } else {
1803
1884
  sock.end();
1804
- return resolve2(line);
1885
+ return resolve3(line);
1805
1886
  }
1806
1887
  }
1807
1888
  });
@@ -1887,7 +1968,7 @@ async function withLock(key, fn) {
1887
1968
  if (mine?.has(key)) return fn();
1888
1969
  const previous = tails.get(key);
1889
1970
  let release;
1890
- const tail = new Promise((resolve2) => release = resolve2);
1971
+ const tail = new Promise((resolve3) => release = resolve3);
1891
1972
  tails.set(key, tail);
1892
1973
  try {
1893
1974
  await previous;
@@ -2082,11 +2163,11 @@ function spawnDetached(argv, logFile, env = process.env) {
2082
2163
  if (!cmd) throw new KvboxError("spawnDetached: empty argv");
2083
2164
  const out = openSync2(logFile, "a");
2084
2165
  const child = spawn(cmd, args, { detached: true, stdio: ["ignore", out, out], env });
2085
- return new Promise((resolve2, reject) => {
2166
+ return new Promise((resolve3, reject) => {
2086
2167
  child.once("error", (err) => reject(new KvboxError(`${cmd} could not start: ${err.message}`)));
2087
2168
  child.once("spawn", () => {
2088
2169
  child.unref();
2089
- resolve2(child.pid ?? -1);
2170
+ resolve3(child.pid ?? -1);
2090
2171
  });
2091
2172
  });
2092
2173
  }
@@ -2510,6 +2591,331 @@ async function attachedBox(ref, p) {
2510
2591
 
2511
2592
  // src/core/capacity.ts
2512
2593
  import { cpus, totalmem } from "node:os";
2594
+
2595
+ // src/core/backupStore.ts
2596
+ import { createHash as createHash2, randomBytes as randomBytes3 } from "node:crypto";
2597
+ import { existsSync as existsSync4 } from "node:fs";
2598
+ import { chmod as chmod2, mkdir as mkdir4, readFile as readFile5, rename as rename4, rm as rm2, stat as stat2, statfs as statfs2, writeFile as writeFile5 } from "node:fs/promises";
2599
+ import { request as httpRequest } from "node:http";
2600
+ import { userInfo as userInfo2 } from "node:os";
2601
+ import { isAbsolute, join as join2 } from "node:path";
2602
+ import { pipeline } from "node:stream";
2603
+ import { setTimeout as sleep } from "node:timers/promises";
2604
+ import { request } from "undici";
2605
+ var GARAGE_VERSION = "2.5.0";
2606
+ var GARAGE_SHA256 = {
2607
+ x64: { arch: "x86_64", sha256: "2ff667286217cd73ebcb1c03af993822365000441dfe31a80cb64c5189a9dea8" },
2608
+ arm64: { arch: "aarch64", sha256: "69b6040cef428b993500c17dd0d0c1240acf2f3f667b9b05ceba4b9660db4e8c" }
2609
+ };
2610
+ var GARAGE_S3_PORT = 3900;
2611
+ var GARAGE_RPC_PORT = 3901;
2612
+ var KEY_NAME = "kvbox-control-plane";
2613
+ var START_WAIT_MS = 6e4;
2614
+ var WATCH_MS = 3e4;
2615
+ var garage = (p, args, timeoutMs = 2e4) => run([p.garage, "-c", p.backupStore.conf, ...args], { timeoutMs });
2616
+ var realDeps = {
2617
+ install: installGarage,
2618
+ start: (p) => spawnDetached([p.garage, "-c", p.backupStore.conf, "server"], p.backupStore.log),
2619
+ running: (p) => garageRunning(p),
2620
+ stop: stopGarage,
2621
+ api: async (p, operation, body) => {
2622
+ const { stdout } = await garage(p, ["json-api", operation, ...body === void 0 ? [] : [JSON.stringify(body)]]);
2623
+ const text = stdout.trim();
2624
+ return text === "" ? null : JSON.parse(text);
2625
+ },
2626
+ cli: async (p, args) => (await garage(p, args)).stdout,
2627
+ register: registerWithControlPlane,
2628
+ device: async (path) => (await stat2(path)).dev
2629
+ };
2630
+ var versionFile = (p) => `${p.garage}.version`;
2631
+ async function installGarage(p) {
2632
+ if (existsSync4(p.garage) && (await readFile5(versionFile(p), "utf8").catch(() => "")).trim() === GARAGE_VERSION) return false;
2633
+ const build = GARAGE_SHA256[process.arch];
2634
+ if (!build) throw new KvboxError(`there is no Garage build for this machine (${process.arch})`);
2635
+ const url = `https://garagehq.deuxfleurs.fr/_releases/v${GARAGE_VERSION}/${build.arch}-unknown-linux-musl/garage`;
2636
+ const res = await fetch(url, { signal: AbortSignal.timeout(3e5) }).catch((err) => {
2637
+ throw new KvboxError(`could not download Garage from ${url} (${err.message})`);
2638
+ });
2639
+ if (!res.ok) throw new KvboxError(`could not download Garage from ${url}: HTTP ${res.status}`);
2640
+ const bytes = Buffer.from(await res.arrayBuffer());
2641
+ const got = createHash2("sha256").update(bytes).digest("hex");
2642
+ if (got !== build.sha256) throw new KvboxError(`the Garage download is not the expected file (sha256 ${got}); nothing was installed`);
2643
+ await mkdir4(p.bin, { recursive: true });
2644
+ const tmp = `${p.garage}.tmp`;
2645
+ await writeFile5(tmp, bytes, { mode: 493 });
2646
+ await chmod2(tmp, 493);
2647
+ await rename4(tmp, p.garage);
2648
+ await writeFile5(versionFile(p), `${GARAGE_VERSION}
2649
+ `);
2650
+ return true;
2651
+ }
2652
+ async function registerWithControlPlane(cfg, body) {
2653
+ const cp = cfg.controlPlane;
2654
+ if (!cp) throw new KvboxError("this host has not joined a control plane");
2655
+ const res = await request(`${cp.url}/hosts/self/backup-store`, {
2656
+ method: "PUT",
2657
+ headers: { authorization: `Bearer ${cp.secret}`, "content-type": "application/json" },
2658
+ body: JSON.stringify(body),
2659
+ headersTimeout: 1e4,
2660
+ bodyTimeout: 1e4
2661
+ }).catch((err) => {
2662
+ throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
2663
+ });
2664
+ const text = await res.body.text();
2665
+ if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not know backup stores yet: it is older than this host`);
2666
+ if (res.statusCode < 200 || res.statusCode >= 300) {
2667
+ let error;
2668
+ try {
2669
+ error = JSON.parse(text).error;
2670
+ } catch {
2671
+ }
2672
+ throw new KvboxError(typeof error === "string" ? error : `${cp.name} answered ${res.statusCode}`);
2673
+ }
2674
+ }
2675
+ function garageToml(path) {
2676
+ const q = (s) => JSON.stringify(s);
2677
+ return [
2678
+ "# written by kvbox-server backup setup: this host's backup store",
2679
+ `metadata_dir = ${q(join2(path, "meta"))}`,
2680
+ `data_dir = ${q(join2(path, "data"))}`,
2681
+ 'db_engine = "lmdb"',
2682
+ "metadata_fsync = true",
2683
+ "data_fsync = true",
2684
+ "replication_factor = 1",
2685
+ `rpc_bind_addr = "127.0.0.1:${GARAGE_RPC_PORT}"`,
2686
+ `rpc_public_addr = "127.0.0.1:${GARAGE_RPC_PORT}"`,
2687
+ `rpc_secret_file = ${q(join2(path, "rpc_secret"))}`,
2688
+ "",
2689
+ "[s3_api]",
2690
+ `s3_region = ${q(BACKUP_STORE_REGION)}`,
2691
+ `api_bind_addr = "127.0.0.1:${GARAGE_S3_PORT}"`,
2692
+ ""
2693
+ ].join("\n");
2694
+ }
2695
+ async function readPid(p) {
2696
+ const n = Number((await readFile5(p.backupStore.pid, "utf8").catch(() => "")).trim());
2697
+ return Number.isInteger(n) && n > 0 ? n : null;
2698
+ }
2699
+ async function garageRunning(p = paths()) {
2700
+ const pid = await readPid(p);
2701
+ if (!pidAlive(pid)) return false;
2702
+ const cmdline = await readFile5(`/proc/${pid}/cmdline`, "utf8").catch(() => null);
2703
+ return cmdline === null || cmdline.split("\0")[0] === p.garage;
2704
+ }
2705
+ async function stopGarage(p) {
2706
+ const pid = await readPid(p);
2707
+ if (pid === null || !await garageRunning(p)) return;
2708
+ const cmdline = await readFile5(`/proc/${pid}/cmdline`, "utf8").catch(() => null);
2709
+ if (cmdline?.split("\0")[0] !== p.garage) throw new KvboxError(`cannot tell whether pid ${pid} is this host's Garage, so it was not stopped; stop Garage by hand and run this again`);
2710
+ process.kill(pid, "SIGTERM");
2711
+ const until = Date.now() + 15e3;
2712
+ while (pidAlive(pid)) {
2713
+ if (Date.now() > until) throw new KvboxError(`Garage (pid ${pid}) did not stop within 15s`);
2714
+ await sleep(200);
2715
+ }
2716
+ await rm2(p.backupStore.pid, { force: true });
2717
+ }
2718
+ async function ensureGarage(p, deps) {
2719
+ if (!await deps.running(p)) {
2720
+ const pid = await deps.start(p);
2721
+ await writeFile5(p.backupStore.pid, `${pid}
2722
+ `);
2723
+ }
2724
+ const until = Date.now() + START_WAIT_MS;
2725
+ for (; ; ) {
2726
+ try {
2727
+ await deps.cli(p, ["status"]);
2728
+ return;
2729
+ } catch (err) {
2730
+ if (Date.now() > until) throw new KvboxError(`Garage did not answer after ${START_WAIT_MS / 1e3}s (see ${p.backupStore.log}): ${err.message}`);
2731
+ await sleep(500);
2732
+ }
2733
+ }
2734
+ }
2735
+ function setupBackupStore(req, p = paths(), deps = realDeps) {
2736
+ return serial(() => setup(req, p, deps));
2737
+ }
2738
+ var turn = Promise.resolve();
2739
+ function serial(step) {
2740
+ const mine = turn.then(step, step);
2741
+ turn = mine.catch(() => void 0);
2742
+ return mine;
2743
+ }
2744
+ async function setup(req, p, deps) {
2745
+ const path = req.path.replace(/\/+$/, "") || "/";
2746
+ if (!isAbsolute(path) || /["\\\n\0]/.test(path)) throw new KvboxError(`${req.path} is not a path a store can use: give the full path of a directory on the backup disk`);
2747
+ const cfg = await loadConfig(p);
2748
+ if (!cfg.controlPlane) throw new KvboxError("this host has not joined a control plane, which is what takes backups; run kvbox-server join first");
2749
+ if (cfg.backupStore && cfg.backupStore.path !== path) {
2750
+ throw new KvboxError(`this host already is a backup store, with its data in ${cfg.backupStore.path}; a host has one store`);
2751
+ }
2752
+ const dir = await stat2(path).catch(() => null);
2753
+ if (!dir?.isDirectory()) throw new KvboxError(`${path} is not a directory: mount the backup disk and give a directory on it`);
2754
+ if (!req.force && await deps.device(path) === await deps.device(p.home)) {
2755
+ throw new KvboxError(`${path} is on the same disk as this host's boxes, so the backups would be lost with them; mount a disk for backups there, or pass --force to use it anyway`);
2756
+ }
2757
+ if (cfg.backupStore && !req.newStore && !existsSync4(join2(path, "rpc_secret"))) throw notTheStoreDisk(path);
2758
+ const newBinary = await deps.install(p);
2759
+ await mkdir4(p.backupStore.dir, { recursive: true, mode: 448 });
2760
+ try {
2761
+ for (const sub of ["meta", "data"]) await mkdir4(join2(path, sub), { recursive: true, mode: 448 });
2762
+ const rpcSecret = join2(path, "rpc_secret");
2763
+ if (!existsSync4(rpcSecret)) await writeFile5(rpcSecret, `${randomBytes3(32).toString("hex")}
2764
+ `, { mode: 384 });
2765
+ } catch (err) {
2766
+ const code = err.code;
2767
+ if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS") throw err;
2768
+ const user = userInfo2().username;
2769
+ throw new KvboxError(`kvbox-server (user ${user}) cannot write in ${path}: make the directory ${user}'s (sudo chown ${user} ${path}) and run this again`);
2770
+ }
2771
+ const conf = garageToml(path);
2772
+ const had = await readFile5(p.backupStore.conf, "utf8").catch(() => null);
2773
+ await writeFile5(p.backupStore.conf, conf, { mode: 384 });
2774
+ if ((newBinary || had !== null && had !== conf) && await deps.running(p)) await deps.stop(p);
2775
+ await ensureGarage(p, deps);
2776
+ const layout = await deps.api(p, "GetClusterLayout");
2777
+ if ((layout?.version ?? 0) === 0) {
2778
+ const node = (await deps.cli(p, ["node", "id", "-q"])).trim().split("@")[0];
2779
+ const fs = await statfs2(path);
2780
+ await deps.cli(p, ["layout", "assign", "-z", "kvbox", "-c", String(fs.blocks * fs.bsize), node]);
2781
+ await deps.cli(p, ["layout", "apply", "--version", "1"]);
2782
+ }
2783
+ const bucket = await bucketInfo(p, deps).then(async (info) => info ?? await deps.api(p, "CreateBucket", { globalAlias: BACKUP_STORE_BUCKET }));
2784
+ let store;
2785
+ if (cfg.backupStore && await hasKey(p, deps, cfg.backupStore.accessKey)) {
2786
+ store = cfg.backupStore;
2787
+ } else {
2788
+ if (cfg.backupStore && !req.newStore) {
2789
+ await deps.stop(p);
2790
+ throw notTheStoreDisk(path);
2791
+ }
2792
+ if (cfg.backupStore) log.warn(`backup store: a new store in ${path} replaces the one with key ${cfg.backupStore.accessKey}; the backups kept on the old disk are gone`);
2793
+ const key = await deps.api(p, "CreateKey", { name: KEY_NAME });
2794
+ store = { path, bucket: BACKUP_STORE_BUCKET, region: BACKUP_STORE_REGION, accessKey: key.accessKeyId, secretKey: key.secretAccessKey, registered: false };
2795
+ }
2796
+ await deps.api(p, "AllowBucketKey", { bucketId: bucket.id, accessKeyId: store.accessKey, permissions: { read: true, write: true, owner: false } });
2797
+ const now = await loadConfig(p);
2798
+ await saveConfig({ ...now, backupStore: { ...store, registered: false } }, p);
2799
+ log.info(`backup store: Garage keeps its data in ${path}`);
2800
+ try {
2801
+ await deps.register(now, { bucket: store.bucket, region: store.region, accessKey: store.accessKey, secretKey: store.secretKey });
2802
+ } catch (err) {
2803
+ throw new KvboxError(`the store is set up, but the control plane did not take it: ${err.message}. Run the same command again once that is solved`);
2804
+ }
2805
+ await saveConfig({ ...await loadConfig(p), backupStore: { ...store, registered: true } }, p);
2806
+ log.info(`backup store: registered with ${now.controlPlane?.name ?? cfg.controlPlane.name}`);
2807
+ return backupStoreStatus(p, deps);
2808
+ }
2809
+ var notTheStoreDisk = (path) => new KvboxError(
2810
+ `${path} does not hold this host's backup store: is its disk mounted there? Mount it and run this again. If that disk is gone for good, pass --new-store to start a new store here (the backups kept on the old disk can no longer be restored)`
2811
+ );
2812
+ async function hasKey(p, deps, id) {
2813
+ const keys = await deps.api(p, "ListKeys");
2814
+ return (keys ?? []).some((k) => k.id === id);
2815
+ }
2816
+ async function bucketInfo(p, deps) {
2817
+ try {
2818
+ return await deps.api(p, "GetBucketInfo", { globalAlias: BACKUP_STORE_BUCKET });
2819
+ } catch (err) {
2820
+ if (/not found|nosuchbucket/i.test(err.message)) return null;
2821
+ throw err;
2822
+ }
2823
+ }
2824
+ async function backupStoreStatus(p = paths(), deps = realDeps) {
2825
+ const store = (await loadConfig(p)).backupStore;
2826
+ if (!store) throw new KvboxError("this host is not a backup store; make it one with: kvbox-server backup setup --path <directory on the backup disk>");
2827
+ const fs = await statfs2(store.path).catch(() => null);
2828
+ const running = await deps.running(p);
2829
+ const info = running ? await bucketInfo(p, deps).catch(() => null) : null;
2830
+ return {
2831
+ path: store.path,
2832
+ bucket: store.bucket,
2833
+ accessKey: store.accessKey,
2834
+ running: running && info !== null,
2835
+ totalBytes: fs ? fs.blocks * fs.bsize : 0,
2836
+ freeBytes: fs ? fs.bavail * fs.bsize : 0,
2837
+ ...info ? { objects: info.objects ?? 0, storedBytes: info.bytes ?? 0 } : {},
2838
+ registered: store.registered
2839
+ };
2840
+ }
2841
+ async function backupStoreCapacity(p = paths(), deps = realDeps) {
2842
+ const store = (await loadConfig(p)).backupStore;
2843
+ if (!store) return void 0;
2844
+ const fs = await statfs2(store.path).catch(() => null);
2845
+ return { totalBytes: fs ? fs.blocks * fs.bsize : 0, freeBytes: fs ? fs.bavail * fs.bsize : 0, running: fs !== null && await deps.running(p) };
2846
+ }
2847
+ function reviveBackupStore(p = paths(), deps = realDeps) {
2848
+ return serial(() => revive(p, deps));
2849
+ }
2850
+ var upgraded = /* @__PURE__ */ new Set();
2851
+ var restartDue = /* @__PURE__ */ new Set();
2852
+ async function revive(p, deps) {
2853
+ const store = (await loadConfig(p)).backupStore;
2854
+ if (!store) return "none";
2855
+ if (!upgraded.has(p.home)) {
2856
+ upgraded.add(p.home);
2857
+ const fresh = await deps.install(p).catch((err) => {
2858
+ log.warn(`backup store: Garage ${GARAGE_VERSION} could not be installed, the one there keeps running (${err.message})`);
2859
+ return false;
2860
+ });
2861
+ if (fresh) restartDue.add(p.home);
2862
+ }
2863
+ if (restartDue.has(p.home) && existsSync4(join2(store.path, "rpc_secret"))) {
2864
+ if (await deps.running(p)) await deps.stop(p);
2865
+ const pid2 = await deps.start(p);
2866
+ await writeFile5(p.backupStore.pid, `${pid2}
2867
+ `);
2868
+ restartDue.delete(p.home);
2869
+ return "upgraded";
2870
+ }
2871
+ if (await deps.running(p)) return "running";
2872
+ if (!existsSync4(join2(store.path, "rpc_secret"))) return "no-disk";
2873
+ await rm2(p.backupStore.pid, { force: true });
2874
+ const pid = await deps.start(p);
2875
+ await writeFile5(p.backupStore.pid, `${pid}
2876
+ `);
2877
+ return "started";
2878
+ }
2879
+ var watch;
2880
+ function startBackupStoreWatch(p = paths()) {
2881
+ let warned = false;
2882
+ const tick = () => {
2883
+ reviveBackupStore(p).then((state) => {
2884
+ if (state === "started") log.info("backup store: Garage was not running; started it");
2885
+ if (state === "upgraded") log.info(`backup store: Garage ${GARAGE_VERSION} installed and started`);
2886
+ if (state === "no-disk" && !warned) log.warn("backup store: its disk is not mounted, so Garage is not started; backups to this host fail until it is back");
2887
+ warned = state === "no-disk";
2888
+ }).catch((err) => log.warn(`backup store: Garage did not start (${err.message})`));
2889
+ };
2890
+ tick();
2891
+ watch ??= setInterval(tick, WATCH_MS);
2892
+ watch.unref();
2893
+ }
2894
+ function isStoreRequest(url) {
2895
+ return url !== void 0 && (url.startsWith(`/${BACKUP_STORE_BUCKET}/`) || url.startsWith(`/${BACKUP_STORE_BUCKET}?`) || url === `/${BACKUP_STORE_BUCKET}`);
2896
+ }
2897
+ function forStore(url, p = paths()) {
2898
+ return isStoreRequest(url) && existsSync4(p.backupStore.conf);
2899
+ }
2900
+ function storeProxy(req, res, port = GARAGE_S3_PORT) {
2901
+ const up = httpRequest({ host: "127.0.0.1", port, method: req.method, path: req.url, headers: req.headers }, (answer) => {
2902
+ res.writeHead(answer.statusCode ?? 502, answer.headers);
2903
+ pipeline(answer, res, (err) => {
2904
+ if (err) res.destroy();
2905
+ });
2906
+ });
2907
+ up.on("error", () => {
2908
+ if (res.headersSent) return res.destroy();
2909
+ res.writeHead(503, { "content-type": "application/json" });
2910
+ res.end(JSON.stringify({ error: "this host's backup store is not running" }));
2911
+ });
2912
+ res.once("close", () => {
2913
+ if (!res.writableFinished) up.destroy();
2914
+ });
2915
+ req.pipe(up);
2916
+ }
2917
+
2918
+ // src/core/capacity.ts
2513
2919
  function hostResources() {
2514
2920
  return { memMib: Math.floor(totalmem() / 1024 ** 2), cores: cpus().length };
2515
2921
  }
@@ -2535,7 +2941,10 @@ async function capacity(p = paths()) {
2535
2941
  running: running.length,
2536
2942
  disk: await diskCapacity(p),
2537
2943
  // What a box can be made from here (#87): the control plane places `--base postgres` by it.
2538
- images: await listImages(await loadConfig(p), p)
2944
+ images: await listImages(await loadConfig(p), p),
2945
+ ...await backupStoreCapacity(p).then((store) => store ? { backupStore: store } : {}),
2946
+ // Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).
2947
+ storeClient: true
2539
2948
  };
2540
2949
  }
2541
2950
  function gb(mib) {
@@ -2619,11 +3028,11 @@ function ext4Usage(file) {
2619
3028
  }
2620
3029
 
2621
3030
  // src/core/snapshots.ts
2622
- import { existsSync as existsSync4 } from "node:fs";
2623
- import { link, mkdir as mkdir4, readdir as readdir5, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
3031
+ import { existsSync as existsSync5 } from "node:fs";
3032
+ import { link, mkdir as mkdir5, readdir as readdir5, rename as rename5, rm as rm3, stat as stat3 } from "node:fs/promises";
2624
3033
 
2625
3034
  // src/core/firecracker.ts
2626
- import { Agent, request } from "undici";
3035
+ import { Agent, request as request2 } from "undici";
2627
3036
  var FirecrackerClient = class {
2628
3037
  constructor(socketPath) {
2629
3038
  this.socketPath = socketPath;
@@ -2632,7 +3041,7 @@ var FirecrackerClient = class {
2632
3041
  socketPath;
2633
3042
  agent;
2634
3043
  async call(method, path, body) {
2635
- const res = await request(`http://localhost${path}`, {
3044
+ const res = await request2(`http://localhost${path}`, {
2636
3045
  dispatcher: this.agent,
2637
3046
  method,
2638
3047
  headers: body === void 0 ? {} : { "content-type": "application/json" },
@@ -2765,7 +3174,7 @@ async function listSnapshots(scope, p = paths()) {
2765
3174
  async function usedBytes(dir) {
2766
3175
  let total = 0;
2767
3176
  for (const entry of await readdir5(dir)) {
2768
- total += (await stat2(`${dir}/${entry}`)).blocks * 512;
3177
+ total += (await stat3(`${dir}/${entry}`)).blocks * 512;
2769
3178
  }
2770
3179
  return total;
2771
3180
  }
@@ -2787,17 +3196,17 @@ async function saveSnapshot(req, owner, p = paths()) {
2787
3196
  async function snapshotBox(ref, req, owner, p) {
2788
3197
  const box = await readBox(ref, p);
2789
3198
  if (!vmAlive(box)) {
2790
- if (existsSync4(p.machine(box.owner, box.name).hibernateVmstate)) {
3199
+ if (existsSync5(p.machine(box.owner, box.name).hibernateVmstate)) {
2791
3200
  throw new KvboxError(`box ${req.box} is hibernated; a snapshot freezes a running box (kvbox wake ${req.box} first)`);
2792
3201
  }
2793
3202
  throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);
2794
3203
  }
2795
3204
  const final = p.snapshot(owner, req.name);
2796
- if (existsSync4(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
3205
+ if (existsSync5(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
2797
3206
  const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
2798
3207
  const cfg = await loadConfig(p);
2799
- if (s !== final) await rm2(s.dir, { recursive: true, force: true });
2800
- await mkdir4(s.dir, { recursive: true, mode: 448 });
3208
+ if (s !== final) await rm3(s.dir, { recursive: true, force: true });
3209
+ await mkdir5(s.dir, { recursive: true, mode: 448 });
2801
3210
  try {
2802
3211
  const volumes = await captureDrivesOf(box, p);
2803
3212
  await captureBox(box, s, cfg, p);
@@ -2818,7 +3227,7 @@ async function snapshotBox(ref, req, owner, p) {
2818
3227
  if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);
2819
3228
  return toSnapshot(meta);
2820
3229
  } catch (err) {
2821
- await rm2(s.dir, { recursive: true, force: true });
3230
+ await rm3(s.dir, { recursive: true, force: true });
2822
3231
  throw err;
2823
3232
  }
2824
3233
  }
@@ -2826,17 +3235,17 @@ async function swapIn(ref, from, boxId, p) {
2826
3235
  const to = p.snapshot(ref.owner, ref.name).dir;
2827
3236
  const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
2828
3237
  await withSnapshotLock(ref, async () => {
2829
- await rm2(old, { recursive: true, force: true });
2830
- const hadOld = existsSync4(to);
2831
- if (hadOld) await rename4(to, old);
3238
+ await rm3(old, { recursive: true, force: true });
3239
+ const hadOld = existsSync5(to);
3240
+ if (hadOld) await rename5(to, old);
2832
3241
  try {
2833
- await rename4(from, to);
3242
+ await rename5(from, to);
2834
3243
  } catch (err) {
2835
- if (hadOld) await rename4(old, to);
3244
+ if (hadOld) await rename5(old, to);
2836
3245
  throw err;
2837
3246
  }
2838
3247
  });
2839
- await rm2(old, { recursive: true, force: true });
3248
+ await rm3(old, { recursive: true, force: true });
2840
3249
  }
2841
3250
  async function captureBox(box, to, cfg, p) {
2842
3251
  const m = p.machine(box.owner, box.name);
@@ -2844,7 +3253,7 @@ async function captureBox(box, to, cfg, p) {
2844
3253
  let lineageTouched = false;
2845
3254
  try {
2846
3255
  const since = box.memSnapshots ?? 0;
2847
- const mode = since === 0 || existsSync4(m.memBase) ? "Diff" : "Full";
3256
+ const mode = since === 0 || existsSync5(m.memBase) ? "Diff" : "Full";
2848
3257
  let failure2;
2849
3258
  await fc.pause();
2850
3259
  try {
@@ -2865,31 +3274,31 @@ async function captureBox(box, to, cfg, p) {
2865
3274
  } else if (since > 0) {
2866
3275
  await mergeOntoPrevious(m.memBase, to.mem, cfg.snapshotEditor ?? p.snapshotEditor);
2867
3276
  }
2868
- await rm2(m.memBase, { force: true });
3277
+ await rm3(m.memBase, { force: true });
2869
3278
  await link(to.mem, m.memBase);
2870
3279
  } catch (err) {
2871
- if (lineageTouched) await rm2(m.memBase, { force: true }).catch(() => void 0);
3280
+ if (lineageTouched) await rm3(m.memBase, { force: true }).catch(() => void 0);
2872
3281
  throw err;
2873
3282
  } finally {
2874
3283
  await fc.close();
2875
3284
  }
2876
3285
  }
2877
3286
  async function mergeOntoPrevious(previous, diffFile, editor) {
2878
- if (!existsSync4(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
3287
+ if (!existsSync5(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
2879
3288
  const merged = `${diffFile}.merged`;
2880
3289
  await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
2881
3290
  await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
2882
- await rename4(merged, diffFile);
3291
+ await rename5(merged, diffFile);
2883
3292
  }
2884
3293
  async function deleteSnapshot(ref, p = paths()) {
2885
3294
  const dir = p.snapshot(ref.owner, ref.name).dir;
2886
- if (ref.name.startsWith(".") || !existsSync4(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
2887
- await withSnapshotLock(ref, () => rm2(dir, { recursive: true, force: true }));
3295
+ if (ref.name.startsWith(".") || !existsSync5(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
3296
+ await withSnapshotLock(ref, () => rm3(dir, { recursive: true, force: true }));
2888
3297
  }
2889
3298
 
2890
3299
  // src/core/network.ts
2891
3300
  import { randomInt } from "node:crypto";
2892
- import { existsSync as existsSync5 } from "node:fs";
3301
+ import { existsSync as existsSync6 } from "node:fs";
2893
3302
  import { fileURLToPath } from "node:url";
2894
3303
  var TAP_PREFIX = "kv-";
2895
3304
  var PRIVILEGED_SCRIPT = "/usr/local/lib/kvbox/net-setup.sh";
@@ -2899,15 +3308,15 @@ function tapName(box) {
2899
3308
  function netSetupScript() {
2900
3309
  const override = process.env["KVBOX_NET_SETUP"];
2901
3310
  if (override) return override;
2902
- if (existsSync5(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
3311
+ if (existsSync6(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
2903
3312
  for (const rel of ["../scripts/net-setup.sh", "../../scripts/net-setup.sh"]) {
2904
3313
  const candidate = fileURLToPath(new URL(rel, import.meta.url));
2905
- if (existsSync5(candidate)) return candidate;
3314
+ if (existsSync6(candidate)) return candidate;
2906
3315
  }
2907
3316
  throw new KvboxError("net-setup.sh not found next to kvbox-server");
2908
3317
  }
2909
3318
  function bridgeExists(bridge) {
2910
- return existsSync5(`/sys/class/net/${bridge}`);
3319
+ return existsSync6(`/sys/class/net/${bridge}`);
2911
3320
  }
2912
3321
  function netRun(cfg, args) {
2913
3322
  return run([netSetupScript(), ...args], {
@@ -3090,7 +3499,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
3090
3499
  }
3091
3500
  }
3092
3501
  function isHibernated(meta, p) {
3093
- return !vmAlive(meta) && existsSync6(p.machine(meta.owner, meta.name).hibernateVmstate);
3502
+ return !vmAlive(meta) && existsSync7(p.machine(meta.owner, meta.name).hibernateVmstate);
3094
3503
  }
3095
3504
  function statusOf(meta, p = paths()) {
3096
3505
  if (vmAlive(meta)) return meta.paused ? "standby" : "running";
@@ -3192,7 +3601,7 @@ function bootArgs(name, ip, cfg, pubkeyB64) {
3192
3601
  return process.arch === "arm64" ? `keep_bootcon ${args}` : args;
3193
3602
  }
3194
3603
  async function createOverlay(file, gib) {
3195
- await writeFile5(file, "", { mode: 384 });
3604
+ await writeFile6(file, "", { mode: 384 });
3196
3605
  await truncate2(file, gib * 1024 ** 3);
3197
3606
  await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", "kvbox-box", "-E", "lazy_itable_init=1,lazy_journal_init=1", file]);
3198
3607
  }
@@ -3200,21 +3609,21 @@ async function waitFor(pred, timeoutMs, stepMs = 50) {
3200
3609
  const deadline = Date.now() + timeoutMs;
3201
3610
  while (Date.now() < deadline) {
3202
3611
  if (pred()) return true;
3203
- await sleep(stepMs);
3612
+ await sleep2(stepMs);
3204
3613
  }
3205
3614
  return pred();
3206
3615
  }
3207
3616
  async function tailOf(file, lines = 5) {
3208
3617
  try {
3209
- return (await readFile5(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
3618
+ return (await readFile6(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
3210
3619
  } catch {
3211
3620
  return "";
3212
3621
  }
3213
3622
  }
3214
3623
  async function spawnFirecracker(ref, cfg, p) {
3215
3624
  const m = p.machine(ref.owner, ref.name);
3216
- await rm3(m.sock, { force: true });
3217
- await rm3(m.vsock, { force: true });
3625
+ await rm4(m.sock, { force: true });
3626
+ await rm4(m.vsock, { force: true });
3218
3627
  const logFd = openSync4(m.log, "a");
3219
3628
  let child;
3220
3629
  try {
@@ -3229,7 +3638,7 @@ async function spawnFirecracker(ref, cfg, p) {
3229
3638
  child.unref();
3230
3639
  const pid = child.pid;
3231
3640
  if (pid === void 0) throw new KvboxError("could not start firecracker");
3232
- if (!await waitFor(() => existsSync6(m.sock), 3e3)) {
3641
+ if (!await waitFor(() => existsSync7(m.sock), 3e3)) {
3233
3642
  killQuietly(pid);
3234
3643
  throw new KvboxError(`firecracker did not open its API socket; last log lines:
3235
3644
  ${await tailOf(m.log)}`);
@@ -3295,14 +3704,14 @@ async function currentBaseVersion(p = paths()) {
3295
3704
  }
3296
3705
  async function readHostPubkey(p) {
3297
3706
  try {
3298
- return (await readFile5(`${p.sshKey}.pub`, "utf8")).trim();
3707
+ return (await readFile6(`${p.sshKey}.pub`, "utf8")).trim();
3299
3708
  } catch {
3300
3709
  throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);
3301
3710
  }
3302
3711
  }
3303
3712
  function assertAssets(cfg) {
3304
3713
  for (const [what, file] of [["kernel", cfg.kernel], ["base image", cfg.rootfs], ["firecracker", cfg.firecracker]]) {
3305
- if (!existsSync6(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
3714
+ if (!existsSync7(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
3306
3715
  }
3307
3716
  }
3308
3717
  async function createMachine(req, owner, p = paths()) {
@@ -3310,9 +3719,9 @@ async function createMachine(req, owner, p = paths()) {
3310
3719
  if (req.from !== void 0) return restoreMachine(req.from, owner, req, cfg, p);
3311
3720
  const sizeName = req.size ?? cfg.defaultSize;
3312
3721
  if (!isSizeName(sizeName)) throw new KvboxError(`unknown size "${sizeName}"; use one of ${Object.keys(SIZES).join(", ")}`);
3313
- const size = SIZES[sizeName];
3722
+ const size2 = SIZES[sizeName];
3314
3723
  assertAssets(cfg);
3315
- await assertRoomFor(size.vcpu, size.memMib, req.force ?? false, { owner }, "new", p);
3724
+ await assertRoomFor(size2.vcpu, size2.memMib, req.force ?? false, { owner }, "new", p);
3316
3725
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
3317
3726
  authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);
3318
3727
  const existing = await readAllMeta(p);
@@ -3328,10 +3737,10 @@ async function createMachine(req, owner, p = paths()) {
3328
3737
  const autoHibernateSec = autoHibernateFor(req, cfg, manifest);
3329
3738
  const vars = env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now }));
3330
3739
  const machine = await bootInto(
3331
- { id, name, owner, ip, mac: macFor(ip), vcpu: size.vcpu, memMib: size.memMib, base: base.version, image, sshKeys },
3740
+ { id, name, owner, ip, mac: macFor(ip), vcpu: size2.vcpu, memMib: size2.memMib, base: base.version, image, sshKeys },
3332
3741
  // The image is shared read-only by every box; only the box's own writes land in its overlay.
3333
3742
  async (m) => {
3334
- await createOverlay(m.overlay, size.diskGib);
3743
+ await createOverlay(m.overlay, size2.diskGib);
3335
3744
  if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);
3336
3745
  },
3337
3746
  { source: "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
@@ -3345,7 +3754,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
3345
3754
  const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
3346
3755
  const m = p.machine(owner, name);
3347
3756
  await ensureHostNetwork(cfg);
3348
- await mkdir5(m.dir, { recursive: true, mode: 448 });
3757
+ await mkdir6(m.dir, { recursive: true, mode: 448 });
3349
3758
  let tapCreated = false;
3350
3759
  let pid;
3351
3760
  let sshPort;
@@ -3368,7 +3777,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
3368
3777
  if (pid !== void 0) killQuietly(pid);
3369
3778
  await closePorts({ id, ip, sshPort }, cfg);
3370
3779
  if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
3371
- await rm3(m.dir, { recursive: true, force: true });
3780
+ await rm4(m.dir, { recursive: true, force: true });
3372
3781
  boxListChanged();
3373
3782
  throw err;
3374
3783
  } finally {
@@ -3397,7 +3806,7 @@ async function restoreFrom(from, owner, req, cfg, p) {
3397
3806
  throw new KvboxError(`--size cannot be combined with --from: a restored box has the snapshot's size (${shown(from)}: ${snap.vcpu} vCPU, ${snap.memMib} MiB)`);
3398
3807
  }
3399
3808
  assertAssets(cfg);
3400
- if (!existsSync6(imageFile(snap.image, snap.base, p))) {
3809
+ if (!existsSync7(imageFile(snap.image, snap.base, p))) {
3401
3810
  throw new KvboxError(`snapshot ${shown(from)} stacks on ${imageLabel(snap.image)} ${snap.base}, which is gone from ${p.assets}`);
3402
3811
  }
3403
3812
  const manifest = await imageManifest(imageFile(snap.image, snap.base, p));
@@ -3433,7 +3842,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
3433
3842
  const { id, ip, owner, name } = box;
3434
3843
  const m = p.machine(owner, name);
3435
3844
  await ensureHostNetwork(cfg);
3436
- await mkdir5(m.dir, { recursive: true, mode: 448 });
3845
+ await mkdir6(m.dir, { recursive: true, mode: 448 });
3437
3846
  let tapCreated = false;
3438
3847
  let pid;
3439
3848
  let sshPort;
@@ -3465,7 +3874,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
3465
3874
  if (pid !== void 0) killQuietly(pid);
3466
3875
  await closePorts({ id, ip, sshPort }, cfg);
3467
3876
  if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
3468
- await rm3(m.dir, { recursive: true, force: true });
3877
+ await rm4(m.dir, { recursive: true, force: true });
3469
3878
  boxListChanged();
3470
3879
  throw err;
3471
3880
  } finally {
@@ -3533,7 +3942,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
3533
3942
  // another slug. Such a fork is discarded rather than kept stale; a cold fork boots with the new line.
3534
3943
  owner === src.owner ? void 0 : `box ${shown(ref)} was not forked into ${owner}: the copy would still let ${src.owner} in (stop the box and fork it cold, which boots with ${owner}'s keys)`
3535
3944
  );
3536
- await rm3(p.machine(owner, name).forkVmstate, { force: true });
3945
+ await rm4(p.machine(owner, name).forkVmstate, { force: true });
3537
3946
  return machine;
3538
3947
  });
3539
3948
  var AGENT_REPLY_MS = 2e4;
@@ -3548,7 +3957,7 @@ async function introduce(spec, vsock, cfg, failure2) {
3548
3957
  const msg = err.message;
3549
3958
  const transient = /unreachable|refused|before the guest accepted/.test(msg);
3550
3959
  if (transient && Date.now() < deadline) {
3551
- await sleep(100);
3960
+ await sleep2(100);
3552
3961
  continue;
3553
3962
  }
3554
3963
  if (transient) throw new KvboxError(`${msg}
@@ -3607,7 +4016,7 @@ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS
3607
4016
  } catch (err) {
3608
4017
  if (!pidAlive(pid)) return;
3609
4018
  if (isNoAgent(err) && Date.now() < deadline) {
3610
- await sleep(500);
4019
+ await sleep2(500);
3611
4020
  continue;
3612
4021
  }
3613
4022
  warnEnv(box, vars, err);
@@ -3650,8 +4059,8 @@ async function cleanupProcess(meta, cfg, p) {
3650
4059
  await closePorts(meta, cfg);
3651
4060
  await deleteTap(meta.id, cfg);
3652
4061
  const m = p.machine(meta.owner, meta.name);
3653
- await rm3(m.sock, { force: true });
3654
- await rm3(m.vsock, { force: true });
4062
+ await rm4(m.sock, { force: true });
4063
+ await rm4(m.vsock, { force: true });
3655
4064
  }
3656
4065
  var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
3657
4066
  const meta = await readMeta(ref, p);
@@ -3660,8 +4069,8 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
3660
4069
  if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);
3661
4070
  await shutdown(meta, cfg, p, 1e4);
3662
4071
  await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
3663
- await rm3(m.hibernateDir, { recursive: true, force: true });
3664
- await rm3(m.memBase, { force: true });
4072
+ await rm4(m.hibernateDir, { recursive: true, force: true });
4073
+ await rm4(m.memBase, { force: true });
3665
4074
  const stopped = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
3666
4075
  await writeMachineMeta(stopped, p);
3667
4076
  recordState(stopped, "stopped", "stop", p);
@@ -3785,15 +4194,15 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
3785
4194
  if (status === "hibernated") throw new KvboxError(`${stateMessage(ref, status)} already`);
3786
4195
  if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
3787
4196
  const m = p.machine(ref.owner, ref.name);
3788
- await rm3(m.hibernateDir, { recursive: true, force: true });
3789
- await mkdir5(m.hibernateDir, { recursive: true, mode: 448 });
4197
+ await rm4(m.hibernateDir, { recursive: true, force: true });
4198
+ await mkdir6(m.hibernateDir, { recursive: true, mode: 448 });
3790
4199
  const fc = new FirecrackerClient(m.sock);
3791
4200
  try {
3792
4201
  try {
3793
4202
  await fc.pause();
3794
4203
  await fc.snapshotCreate(m.hibernateVmstate, m.hibernateMem, "Full");
3795
4204
  } catch (err) {
3796
- await rm3(m.hibernateDir, { recursive: true, force: true });
4205
+ await rm4(m.hibernateDir, { recursive: true, force: true });
3797
4206
  if (!meta.paused) await fc.resume().catch(() => void 0);
3798
4207
  throw err;
3799
4208
  }
@@ -3804,7 +4213,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
3804
4213
  await waitFor(() => !pidAlive(meta.pid), 5e3, 50);
3805
4214
  await cleanupProcess(meta, cfg, p);
3806
4215
  await run(["fallocate", "--dig-holes", m.hibernateMem]);
3807
- await rm3(m.memBase, { force: true });
4216
+ await rm4(m.memBase, { force: true });
3808
4217
  const hibernated = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
3809
4218
  await writeMachineMeta(hibernated, p);
3810
4219
  recordState(hibernated, "hibernated", by, p);
@@ -3817,7 +4226,7 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
3817
4226
  if (status === "running" || status === "standby") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated`);
3818
4227
  if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated; kvbox start ${shown(ref)} boots it`);
3819
4228
  assertAssets(cfg);
3820
- if (!existsSync6(imageFile(meta.image, meta.base, p))) {
4229
+ if (!existsSync7(imageFile(meta.image, meta.base, p))) {
3821
4230
  throw new KvboxError(`box ${shown(ref)} stacks on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);
3822
4231
  }
3823
4232
  await assertRoomFor(meta.vcpu, meta.memMib, force, meta, "start", p);
@@ -3843,9 +4252,9 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
3843
4252
  await deleteTap(meta.id, cfg).catch(() => void 0);
3844
4253
  throw err;
3845
4254
  }
3846
- await rm3(m.memBase, { force: true });
4255
+ await rm4(m.memBase, { force: true });
3847
4256
  await link2(m.hibernateMem, m.memBase);
3848
- await rm3(m.hibernateDir, { recursive: true, force: true });
4257
+ await rm4(m.hibernateDir, { recursive: true, force: true });
3849
4258
  const running = { ...meta, pid, bootId: currentBootId(), memSnapshots: 1, paused: void 0, sshKeysStale: stale ? true : void 0 };
3850
4259
  await writeMachineMeta(running, p);
3851
4260
  recordState(running, "running", "wake", p);
@@ -3855,7 +4264,7 @@ async function applyAtNextBoot(meta, changes, by, cfg, p, whileStopped) {
3855
4264
  const wasRunning = vmAlive(meta);
3856
4265
  if (wasRunning) {
3857
4266
  await shutdown(meta, cfg, p, 1e4);
3858
- await rm3(p.machine(meta.owner, meta.name).memBase, { force: true });
4267
+ await rm4(p.machine(meta.owner, meta.name).memBase, { force: true });
3859
4268
  }
3860
4269
  const updated = { ...meta, ...changes, pid: null, memSnapshots: void 0, paused: void 0 };
3861
4270
  await writeMachineMeta(updated, p);
@@ -3925,9 +4334,9 @@ var replaceDisk = locked(async function replaceDisk2(ref, file, disk, p = paths(
3925
4334
  const currentGib = Math.round(statSync2(m.overlay).size / 1024 ** 3);
3926
4335
  const restoredGib = Math.round(statSync2(file).size / 1024 ** 3);
3927
4336
  return applyAtNextBoot(meta, { base: disk.base, image: disk.image }, "restore", cfg, p, async () => {
3928
- if (disk.vars === null) await rm3(m.env, { force: true });
4337
+ if (disk.vars === null) await rm4(m.env, { force: true });
3929
4338
  else await writeBoxEnv(ref, disk.vars, p);
3930
- await rename5(file, m.overlay);
4339
+ await rename6(file, m.overlay);
3931
4340
  if (currentGib > restoredGib) await growDisk(m.overlay, currentGib);
3932
4341
  });
3933
4342
  });
@@ -3953,7 +4362,7 @@ var detachVolume = locked(async function detachVolume2(ref, volume, p = paths())
3953
4362
  if (!meta.volumes?.includes(volume.name) || volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is not attached to box ${shown(ref)}`);
3954
4363
  assertNotHibernated(meta, p);
3955
4364
  const kept = meta.volumes.filter((v) => v !== volume.name);
3956
- return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () => rm3(p.machine(ref.owner, ref.name).volumeDrive(volume.name), { force: true }));
4365
+ return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () => rm4(p.machine(ref.owner, ref.name).volumeDrive(volume.name), { force: true }));
3957
4366
  });
3958
4367
  async function resizeVolume(volume, sizeGib, p = paths()) {
3959
4368
  await assertCanGrow(volume, sizeGib, p);
@@ -4111,7 +4520,7 @@ var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
4111
4520
  throw err;
4112
4521
  });
4113
4522
  recordState(meta, "stopped", "rm", p);
4114
- await rm3(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
4523
+ await rm4(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
4115
4524
  boxListChanged();
4116
4525
  return meta;
4117
4526
  });
@@ -4159,7 +4568,7 @@ async function settleDeadBoxes(p = paths()) {
4159
4568
  } catch (err) {
4160
4569
  log.warn(`usage ledger: ${err.message}`);
4161
4570
  }
4162
- await rm3(p.machine(meta.owner, meta.name).memBase, { force: true });
4571
+ await rm4(p.machine(meta.owner, meta.name).memBase, { force: true });
4163
4572
  if (meta.paused) {
4164
4573
  await writeMachineMeta({ ...meta, pid: null, bootId: void 0, memSnapshots: void 0, paused: void 0 }, p);
4165
4574
  leftStopped.push(refKey(meta));
@@ -4177,7 +4586,7 @@ async function pinRunningTaps(p = paths()) {
4177
4586
  const cfg = await loadConfig(p);
4178
4587
  if (!bridgeExists(cfg.bridge)) return;
4179
4588
  for (const meta of await readAllMeta(p)) {
4180
- if (!vmAlive(meta) || !existsSync6(`/sys/class/net/${tapName(meta.id)}`)) continue;
4589
+ if (!vmAlive(meta) || !existsSync7(`/sys/class/net/${tapName(meta.id)}`)) continue;
4181
4590
  await pinTap(meta, cfg).catch((err) => log.warn(`could not pin box ${meta.name}'s tap: ${err.message}`));
4182
4591
  }
4183
4592
  }
@@ -4216,14 +4625,14 @@ async function bootRecovered(settled, p = paths()) {
4216
4625
  }
4217
4626
 
4218
4627
  // src/core/backups.ts
4219
- import { randomBytes as randomBytes4 } from "node:crypto";
4220
- import { existsSync as existsSync7 } from "node:fs";
4221
- 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";
4222
- import { basename as basename2, join as join2 } from "node:path";
4223
- import { setTimeout as sleep2 } from "node:timers/promises";
4628
+ import { randomBytes as randomBytes5 } from "node:crypto";
4629
+ import { existsSync as existsSync8 } from "node:fs";
4630
+ import { mkdir as mkdir7, open, readdir as readdir6, readFile as readFile7, rm as rm5, stat as stat4, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
4631
+ import { basename as basename2, join as join3 } from "node:path";
4632
+ import { setTimeout as sleep3 } from "node:timers/promises";
4224
4633
 
4225
4634
  // ../shared/src/backup.ts
4226
- import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes3 } from "node:crypto";
4635
+ import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes4 } from "node:crypto";
4227
4636
  import { promisify as promisify2 } from "node:util";
4228
4637
  import { deflateRaw as deflateRawCb, inflateRaw as inflateRawCb, constants as zlib } from "node:zlib";
4229
4638
  var deflateRaw = promisify2(deflateRawCb);
@@ -4275,7 +4684,7 @@ function openText(keys, sealedB64, label) {
4275
4684
  return unseal(keys.seal, Buffer.from(sealedB64, "base64"), label, label).toString("utf8");
4276
4685
  }
4277
4686
  function seal(key, prefix, plain, aad) {
4278
- const nonce = randomBytes3(NONCE);
4687
+ const nonce = randomBytes4(NONCE);
4279
4688
  const cipher = createCipheriv("aes-256-gcm", key, nonce);
4280
4689
  cipher.setAAD(Buffer.from(aad));
4281
4690
  const data = Buffer.concat([cipher.update(plain), cipher.final()]);
@@ -4299,12 +4708,49 @@ function chunkCount(bytes) {
4299
4708
  return Math.ceil(bytes / CHUNK_SIZE);
4300
4709
  }
4301
4710
 
4711
+ // src/core/storeFetch.ts
4712
+ import { Agent as Agent2, buildConnector, fetch as pinnedFetch } from "undici";
4713
+ var dispatchers = /* @__PURE__ */ new Map();
4714
+ function storeDispatcher(pin, local) {
4715
+ const id = `${pin}|${local}`;
4716
+ const have = dispatchers.get(id);
4717
+ if (have) return have;
4718
+ const plain = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0, timeout: 1e4 });
4719
+ const connect3 = (opts, cb) => {
4720
+ plain(local ? { ...opts, hostname: "127.0.0.1" } : opts, (err, socket) => {
4721
+ if (err || !socket) return cb(err ?? new Error("no socket"), null);
4722
+ const tls = socket;
4723
+ const got = typeof tls.getPeerCertificate === "function" ? tls.getPeerCertificate().fingerprint256 : void 0;
4724
+ if (got !== pin) {
4725
+ socket.destroy();
4726
+ return cb(new Error("the backup store's certificate is not the one the control plane knows (fingerprint mismatch)"), null);
4727
+ }
4728
+ cb(null, socket);
4729
+ });
4730
+ };
4731
+ const agent = new Agent2({ connect: connect3 });
4732
+ dispatchers.set(id, agent);
4733
+ return agent;
4734
+ }
4735
+ async function chunkFetcher(pin, sampleUrl, p = paths()) {
4736
+ if (pin === void 0) return (url, init) => fetch(url, init);
4737
+ const cfg = await loadConfig(p);
4738
+ const cp = cfg.controlPlane;
4739
+ let local = false;
4740
+ if (cfg.backupStore && cp && sampleUrl !== void 0) {
4741
+ const target = new URL(sampleUrl);
4742
+ local = target.hostname === cp.advertise && Number(target.port || 443) === cp.port;
4743
+ }
4744
+ const dispatcher = storeDispatcher(pin, local);
4745
+ return (url, init) => pinnedFetch(url, { ...init, dispatcher });
4746
+ }
4747
+
4302
4748
  // src/core/backups.ts
4303
4749
  var PARALLEL = 4;
4304
4750
  var TRIES = 4;
4305
4751
  var CHUNK_TIMEOUT_MS = 12e4;
4306
4752
  async function assertRoom(dir, bytes, what, p) {
4307
- const st = await statfs2(dir);
4753
+ const st = await statfs3(dir);
4308
4754
  const free = st.bavail * st.bsize;
4309
4755
  const headroom = (await loadConfig(p)).volumeHeadroomGib * 1024 ** 3;
4310
4756
  if (free - bytes < headroom) {
@@ -4324,22 +4770,22 @@ async function readBox2(ref, p) {
4324
4770
  }
4325
4771
  }
4326
4772
  async function chunkNames(file, keys) {
4327
- const { size } = await stat3(file);
4773
+ const { size: size2 } = await stat4(file);
4328
4774
  const chunks = [];
4329
4775
  const fh = await open(file, "r");
4330
4776
  try {
4331
4777
  const buf = Buffer.alloc(CHUNK_SIZE);
4332
- for (let i = 0; i < chunkCount(size); i++) {
4333
- const slot = await readSlot(fh, buf, i, size);
4778
+ for (let i = 0; i < chunkCount(size2); i++) {
4779
+ const slot = await readSlot(fh, buf, i, size2);
4334
4780
  chunks.push(isZero(slot) ? null : chunkName(keys, slot));
4335
4781
  }
4336
4782
  } finally {
4337
4783
  await fh.close();
4338
4784
  }
4339
- return { sizeBytes: size, chunks };
4785
+ return { sizeBytes: size2, chunks };
4340
4786
  }
4341
- async function readSlot(fh, buf, index, size) {
4342
- const length = Math.min(CHUNK_SIZE, size - index * CHUNK_SIZE);
4787
+ async function readSlot(fh, buf, index, size2) {
4788
+ const length = Math.min(CHUNK_SIZE, size2 - index * CHUNK_SIZE);
4343
4789
  let got = 0;
4344
4790
  while (got < length) {
4345
4791
  const { bytesRead } = await fh.read(buf, got, length - got, index * CHUNK_SIZE + got);
@@ -4352,13 +4798,13 @@ async function stageBackup(ref, req, p = paths()) {
4352
4798
  checkId(req.id);
4353
4799
  const keys = backupKeys(req.key);
4354
4800
  const s = p.backup(req.id);
4355
- await rm4(s.dir, { recursive: true, force: true });
4356
- await mkdir6(s.dir, { recursive: true, mode: 448 });
4801
+ await rm5(s.dir, { recursive: true, force: true });
4802
+ await mkdir7(s.dir, { recursive: true, mode: 448 });
4357
4803
  try {
4358
4804
  const { meta, envText } = await withBoxLock(ref, async () => {
4359
4805
  const meta2 = await readBox2(ref, p);
4360
4806
  const m = p.machine(meta2.owner, meta2.name);
4361
- await assertRoom(s.dir, (await stat3(m.overlay)).blocks * 512, `a backup of box ${shown(ref)}`, p);
4807
+ await assertRoom(s.dir, (await stat4(m.overlay)).blocks * 512, `a backup of box ${shown(ref)}`, p);
4362
4808
  const copy = () => run(["cp", "--sparse=always", "--reflink=auto", m.overlay, s.disk], { timeoutMs: 6e5 });
4363
4809
  if (vmAlive(meta2) && !meta2.paused) {
4364
4810
  const fc = new FirecrackerClient(m.sock);
@@ -4375,11 +4821,11 @@ async function stageBackup(ref, req, p = paths()) {
4375
4821
  } else {
4376
4822
  await copy();
4377
4823
  }
4378
- const envText2 = existsSync7(m.env) ? await readFile6(m.env, "utf8") : null;
4824
+ const envText2 = existsSync8(m.env) ? await readFile7(m.env, "utf8") : null;
4379
4825
  return { meta: meta2, envText: envText2 };
4380
4826
  });
4381
4827
  const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
4382
- await writeFile6(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
4828
+ await writeFile7(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
4383
4829
  return {
4384
4830
  id: req.id,
4385
4831
  sizeBytes,
@@ -4391,7 +4837,7 @@ async function stageBackup(ref, req, p = paths()) {
4391
4837
  memMib: meta.memMib
4392
4838
  };
4393
4839
  } catch (err) {
4394
- await rm4(s.dir, { recursive: true, force: true });
4840
+ await rm5(s.dir, { recursive: true, force: true });
4395
4841
  throw err;
4396
4842
  }
4397
4843
  }
@@ -4425,9 +4871,9 @@ async function uploadBackup(id, req, p = paths()) {
4425
4871
  }
4426
4872
  async function uploadOnce(id, req, signal, p) {
4427
4873
  const s = p.backup(id);
4428
- if (!existsSync7(s.chunks)) throw new NotFoundError(`backup ${id}`);
4874
+ if (!existsSync8(s.chunks)) throw new NotFoundError(`backup ${id}`);
4429
4875
  const keys = backupKeys(req.key);
4430
- const { chunks } = JSON.parse(await readFile6(s.chunks, "utf8"));
4876
+ const { chunks } = JSON.parse(await readFile7(s.chunks, "utf8"));
4431
4877
  const slotOf = /* @__PURE__ */ new Map();
4432
4878
  chunks.forEach((name, i) => {
4433
4879
  if (name !== null && !slotOf.has(name)) slotOf.set(name, i);
@@ -4437,16 +4883,17 @@ async function uploadOnce(id, req, signal, p) {
4437
4883
  if (index === void 0) throw new KvboxError(`backup ${id} has no chunk ${name.slice(0, 12)}`);
4438
4884
  return { name, url, index };
4439
4885
  });
4440
- const { size } = await stat3(s.disk);
4886
+ const { size: size2 } = await stat4(s.disk);
4887
+ const fetchChunk = await chunkFetcher(req.pin, work[0]?.url, p);
4441
4888
  const fh = await open(s.disk, "r");
4442
4889
  let bytes = 0;
4443
4890
  const sizes = {};
4444
4891
  try {
4445
4892
  await pool(work, async ({ name, url, index }) => {
4446
- const slot = Buffer.from(await readSlot(fh, Buffer.alloc(CHUNK_SIZE), index, size));
4893
+ const slot = Buffer.from(await readSlot(fh, Buffer.alloc(CHUNK_SIZE), index, size2));
4447
4894
  const sealed = await sealChunk(keys, name, slot);
4448
4895
  await withTries(`upload of chunk ${index}`, async () => {
4449
- const res = await fetch(url, { method: "PUT", body: sealed, signal: AbortSignal.any([signal, AbortSignal.timeout(CHUNK_TIMEOUT_MS)]) });
4896
+ const res = await fetchChunk(url, { method: "PUT", body: sealed, signal: AbortSignal.any([signal, AbortSignal.timeout(CHUNK_TIMEOUT_MS)]) });
4450
4897
  if (!res.ok) throw new Error(`storage answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
4451
4898
  }, signal);
4452
4899
  bytes += sealed.length;
@@ -4455,36 +4902,37 @@ async function uploadOnce(id, req, signal, p) {
4455
4902
  } finally {
4456
4903
  await fh.close();
4457
4904
  }
4458
- await rm4(s.dir, { recursive: true, force: true });
4905
+ await rm5(s.dir, { recursive: true, force: true });
4459
4906
  return { chunks: work.length, bytes, sizes };
4460
4907
  }
4461
4908
  async function dropBackup(id, p = paths()) {
4462
4909
  checkId(id);
4463
4910
  uploads.get(id)?.abort();
4464
- await rm4(p.backup(id).dir, { recursive: true, force: true });
4911
+ await rm5(p.backup(id).dir, { recursive: true, force: true });
4465
4912
  }
4466
4913
  async function clearStagedBackups(p = paths()) {
4467
- await rm4(p.backups, { recursive: true, force: true });
4914
+ await rm5(p.backups, { recursive: true, force: true });
4468
4915
  const prefix = basename2(p.machine("x", "x").restoring);
4469
4916
  for (const ref of await listMachineRefs(p)) {
4470
4917
  const dir = p.machine(ref.owner, ref.name).dir;
4471
- for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm4(join2(dir, f), { force: true });
4918
+ for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm5(join3(dir, f), { force: true });
4472
4919
  }
4473
4920
  }
4474
- async function downloadDisk(file, req) {
4921
+ async function downloadDisk(file, req, p = paths()) {
4475
4922
  const keys = backupKeys(req.key);
4476
4923
  const slots = chunkCount(req.sizeBytes);
4477
4924
  for (const c of req.chunks) {
4478
4925
  if (c.index >= slots) throw new KvboxError(`chunk ${c.index} is past the end of a ${req.sizeBytes}-byte disk`);
4479
4926
  if (!CHUNK_HASH_RE.test(c.hash)) throw new KvboxError(`chunk ${c.index}: not a chunk name`);
4480
4927
  }
4481
- await writeFile6(file, "", { mode: 384 });
4928
+ const fetchChunk = await chunkFetcher(req.pin, req.chunks[0]?.url, p);
4929
+ await writeFile7(file, "", { mode: 384 });
4482
4930
  const fh = await open(file, "r+");
4483
4931
  try {
4484
4932
  await fh.truncate(req.sizeBytes);
4485
4933
  await pool(req.chunks, async ({ index, hash, url }) => {
4486
4934
  const plain = await withTries(`download of chunk ${index}`, async () => {
4487
- const res = await fetch(url, { signal: AbortSignal.timeout(CHUNK_TIMEOUT_MS) });
4935
+ const res = await fetchChunk(url, { signal: AbortSignal.timeout(CHUNK_TIMEOUT_MS) });
4488
4936
  if (!res.ok) throw new Error(`storage answered ${res.status}`);
4489
4937
  return Buffer.from(await res.arrayBuffer());
4490
4938
  });
@@ -4514,34 +4962,34 @@ async function restoreBackup(ref, req, p = paths()) {
4514
4962
  }
4515
4963
  async function restoreOnce(ref, req, p) {
4516
4964
  const meta = await readBox2(ref, p);
4517
- if (!vmAlive(meta) && existsSync7(p.machine(ref.owner, ref.name).hibernateVmstate)) {
4965
+ if (!vmAlive(meta) && existsSync8(p.machine(ref.owner, ref.name).hibernateVmstate)) {
4518
4966
  throw new KvboxError(`box ${shown(ref)} is hibernated; its memory belongs to the disk it has: kvbox wake ${shown(ref)} or kvbox stop ${shown(ref)} first`);
4519
4967
  }
4520
- if (!existsSync7(imageFile(req.image, req.base, p))) {
4968
+ if (!existsSync8(imageFile(req.image, req.base, p))) {
4521
4969
  throw new KvboxError(`this backup stacks on ${imageLabel(req.image)} ${req.base}, which this host does not have`);
4522
4970
  }
4523
4971
  const keys = backupKeys(req.key);
4524
4972
  const m = p.machine(ref.owner, ref.name);
4525
- const current = (await stat3(m.overlay)).size;
4973
+ const current = (await stat4(m.overlay)).size;
4526
4974
  if (req.sizeBytes > current) {
4527
4975
  const gb2 = (n) => `${Math.ceil(n / 1024 ** 3)}GB`;
4528
4976
  throw new KvboxError(`this backup's disk is ${gb2(req.sizeBytes)} and box ${shown(ref)}'s is ${gb2(current)}: kvbox vm rescale ${shown(ref)} --disk ${gb2(req.sizeBytes)} first`);
4529
4977
  }
4530
- const file = `${m.restoring}.${randomBytes4(4).toString("hex")}`;
4978
+ const file = `${m.restoring}.${randomBytes5(4).toString("hex")}`;
4531
4979
  const envFile = `${file}.env`;
4532
4980
  try {
4533
4981
  let vars = null;
4534
4982
  if (req.env !== null) {
4535
- await writeFile6(envFile, openText(keys, req.env, `env:${req.id}`), { mode: 384 });
4983
+ await writeFile7(envFile, openText(keys, req.env, `env:${req.id}`), { mode: 384 });
4536
4984
  vars = await readBoxEnvFile(envFile);
4537
4985
  checkBoxEnv(vars);
4538
4986
  }
4539
4987
  await assertRoom(m.dir, req.chunks.length * CHUNK_SIZE, `a restore of box ${shown(ref)}`, p);
4540
- await downloadDisk(file, req);
4988
+ await downloadDisk(file, req, p);
4541
4989
  return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
4542
4990
  } finally {
4543
- await rm4(file, { force: true });
4544
- await rm4(envFile, { force: true });
4991
+ await rm5(file, { force: true });
4992
+ await rm5(envFile, { force: true });
4545
4993
  }
4546
4994
  }
4547
4995
  async function pool(items, fn) {
@@ -4569,14 +5017,14 @@ async function withTries(what, fn, signal) {
4569
5017
  } catch (err) {
4570
5018
  if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
4571
5019
  last = err;
4572
- await sleep2(250 * 2 ** i);
5020
+ await sleep3(250 * 2 ** i);
4573
5021
  }
4574
5022
  }
4575
5023
  throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
4576
5024
  }
4577
5025
 
4578
5026
  // src/core/relay.ts
4579
- import { access as access2, chmod as chmod3, mkdir as mkdir8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
5027
+ import { access as access2, chmod as chmod4, mkdir as mkdir9, rm as rm6, writeFile as writeFile8 } from "node:fs/promises";
4580
5028
 
4581
5029
  // ../shared/src/relay.ts
4582
5030
  import { z as z7 } from "zod";
@@ -4611,9 +5059,9 @@ function decodeRelayJoin(text) {
4611
5059
 
4612
5060
  // src/core/controlPlane.ts
4613
5061
  import { X509Certificate } from "node:crypto";
4614
- import { chmod as chmod2, mkdir as mkdir7, readFile as readFile7 } from "node:fs/promises";
5062
+ import { chmod as chmod3, mkdir as mkdir8, readFile as readFile8 } from "node:fs/promises";
4615
5063
  import { hostname as osHostname } from "node:os";
4616
- import { request as request2 } from "undici";
5064
+ import { request as request3 } from "undici";
4617
5065
 
4618
5066
  // ../shared/src/country.ts
4619
5067
  var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
@@ -4651,10 +5099,10 @@ function parseCountry(input) {
4651
5099
  // src/core/controlPlane.ts
4652
5100
  var DEFAULT_HTTPS_PORT = 7777;
4653
5101
  async function ensureTlsCert(p = paths()) {
4654
- const have = await readFile7(p.tlsCert, "utf8").catch(() => null);
4655
- const haveKey = await readFile7(p.tlsKey).then(() => true, () => false);
5102
+ const have = await readFile8(p.tlsCert, "utf8").catch(() => null);
5103
+ const haveKey = await readFile8(p.tlsKey).then(() => true, () => false);
4656
5104
  if (have === null || !haveKey) {
4657
- await mkdir7(p.tls, { recursive: true, mode: 448 });
5105
+ await mkdir8(p.tls, { recursive: true, mode: 448 });
4658
5106
  try {
4659
5107
  await run([
4660
5108
  "openssl",
@@ -4677,9 +5125,9 @@ async function ensureTlsCert(p = paths()) {
4677
5125
  } catch (err) {
4678
5126
  throw new KvboxError(`could not make the host's certificate (is openssl installed?): ${err.message}`);
4679
5127
  }
4680
- await chmod2(p.tlsKey, 384);
5128
+ await chmod3(p.tlsKey, 384);
4681
5129
  }
4682
- const pem = await readFile7(p.tlsCert, "utf8");
5130
+ const pem = await readFile8(p.tlsCert, "utf8");
4683
5131
  return { fingerprint: new X509Certificate(pem).fingerprint256 };
4684
5132
  }
4685
5133
  function isPrivateAddress(ip) {
@@ -4718,7 +5166,7 @@ async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdverti
4718
5166
  const { fingerprint } = await ensureTlsCert(p);
4719
5167
  const hostUrl = `https://${advertise}:${port}`;
4720
5168
  const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
4721
- const res = await request2(`${url}/hosts/join`, {
5169
+ const res = await request3(`${url}/hosts/join`, {
4722
5170
  method: "POST",
4723
5171
  headers: { "content-type": "application/json" },
4724
5172
  body: JSON.stringify(body),
@@ -4743,7 +5191,7 @@ async function fetchCloudCa(p = paths()) {
4743
5191
  const cfg = await loadConfig(p);
4744
5192
  const cp = cfg.controlPlane;
4745
5193
  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>");
4746
- const res = await request2(`${cp.url}/hosts/self/ssh-ca`, {
5194
+ const res = await request3(`${cp.url}/hosts/self/ssh-ca`, {
4747
5195
  headers: { authorization: `Bearer ${cp.secret}` },
4748
5196
  headersTimeout: 1e4,
4749
5197
  bodyTimeout: 1e4
@@ -4762,7 +5210,7 @@ async function leaveControlPlane(p = paths()) {
4762
5210
  const cfg = await loadConfig(p);
4763
5211
  const cp = cfg.controlPlane;
4764
5212
  if (!cp) throw new KvboxError("this host has not joined a control plane");
4765
- const told = await request2(`${cp.url}/hosts/self`, {
5213
+ const told = await request3(`${cp.url}/hosts/self`, {
4766
5214
  method: "DELETE",
4767
5215
  headers: { authorization: `Bearer ${cp.secret}` },
4768
5216
  headersTimeout: 3e3,
@@ -4772,7 +5220,7 @@ async function leaveControlPlane(p = paths()) {
4772
5220
  return res.statusCode >= 200 && res.statusCode < 300;
4773
5221
  }).catch(() => false);
4774
5222
  const { controlPlane: _gone, ...rest } = cfg;
4775
- await saveConfig(rest, p);
5223
+ await saveConfig({ ...rest, ...rest.backupStore ? { backupStore: { ...rest.backupStore, registered: false } } : {} }, p);
4776
5224
  return { controlPlane: cp.name, told };
4777
5225
  }
4778
5226
  function jsonOrNull(text) {
@@ -4789,16 +5237,16 @@ function errorIn(text) {
4789
5237
  }
4790
5238
 
4791
5239
  // src/core/relay.ts
4792
- function relayConf(join3) {
5240
+ function relayConf(join4) {
4793
5241
  return [
4794
5242
  "# kvbox relay tunnel: made by `kvbox-server relay`, installed by net-setup.sh. Do not edit.",
4795
5243
  "[Interface]",
4796
- `PrivateKey = ${join3.privateKey}`,
4797
- `Address = ${join3.tunnelIp}/32`,
5244
+ `PrivateKey = ${join4.privateKey}`,
5245
+ `Address = ${join4.tunnelIp}/32`,
4798
5246
  "",
4799
5247
  "[Peer]",
4800
- `PublicKey = ${join3.relayKey}`,
4801
- `Endpoint = ${join3.relay}`,
5248
+ `PublicKey = ${join4.relayKey}`,
5249
+ `Endpoint = ${join4.relay}`,
4802
5250
  // Only the relay's own tunnel address goes through the tunnel: the host keeps its normal internet
4803
5251
  // route, and the relay SNATs forwarded connections so their replies come back this way.
4804
5252
  `AllowedIPs = ${RELAY_TUNNEL_GATEWAY}/32`,
@@ -4808,22 +5256,22 @@ function relayConf(join3) {
4808
5256
  ].join("\n");
4809
5257
  }
4810
5258
  async function useRelay(joinString, p = paths()) {
4811
- const join3 = decodeRelayJoin(joinString);
4812
- if (!join3) throw new KvboxError("that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay");
5259
+ const join4 = decodeRelayJoin(joinString);
5260
+ if (!join4) throw new KvboxError("that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay");
4813
5261
  const cfg = await loadConfig(p);
4814
- if (cfg.relay && cfg.relay.name !== join3.name) {
5262
+ if (cfg.relay && cfg.relay.name !== join4.name) {
4815
5263
  throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox-server relay off first`);
4816
5264
  }
4817
- if (cfg.relay && cfg.relay.publicIp !== join3.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {
5265
+ if (cfg.relay && cfg.relay.publicIp !== join4.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {
4818
5266
  throw new KvboxError(
4819
- `${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join3.publicIp}; run kvbox-server leave first, then join again`
5267
+ `${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join4.publicIp}; run kvbox-server leave first, then join again`
4820
5268
  );
4821
5269
  }
4822
- await mkdir8(p.relay, { recursive: true, mode: 448 });
4823
- await writeFile7(p.relayConf, relayConf(join3), { mode: 384 });
4824
- await chmod3(p.relayConf, 384);
5270
+ await mkdir9(p.relay, { recursive: true, mode: 448 });
5271
+ await writeFile8(p.relayConf, relayConf(join4), { mode: 384 });
5272
+ await chmod4(p.relayConf, 384);
4825
5273
  await netSetup(cfg, ["relay", "up", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);
4826
- const relay = { name: join3.name, publicIp: join3.publicIp, tunnelIp: join3.tunnelIp, endpoint: join3.relay };
5274
+ const relay = { name: join4.name, publicIp: join4.publicIp, tunnelIp: join4.tunnelIp, endpoint: join4.relay };
4827
5275
  await saveConfig({ ...cfg, relay }, p);
4828
5276
  return relay;
4829
5277
  }
@@ -4842,19 +5290,19 @@ async function dropRelay(p = paths()) {
4842
5290
  throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
4843
5291
  }
4844
5292
  await netSetup(cfg, ["relay", "down"]);
4845
- await rm5(p.relayConf, { force: true });
5293
+ await rm6(p.relayConf, { force: true });
4846
5294
  const { relay: _gone, ...rest } = cfg;
4847
5295
  await saveConfig(rest, p);
4848
5296
  return relay;
4849
5297
  }
4850
5298
 
4851
5299
  // src/core/idle.ts
4852
- import { readFile as readFile8 } from "node:fs/promises";
5300
+ import { readFile as readFile9 } from "node:fs/promises";
4853
5301
  var HIBERNATE_CONCURRENCY = 2;
4854
5302
  async function tapTraffic(id) {
4855
5303
  const dir = `/sys/class/net/${tapName(id)}/statistics`;
4856
5304
  try {
4857
- const [rx, tx] = await Promise.all([readFile8(`${dir}/rx_bytes`, "utf8"), readFile8(`${dir}/tx_bytes`, "utf8")]);
5305
+ const [rx, tx] = await Promise.all([readFile9(`${dir}/rx_bytes`, "utf8"), readFile9(`${dir}/tx_bytes`, "utf8")]);
4858
5306
  return Number(rx) + Number(tx);
4859
5307
  } catch {
4860
5308
  return null;
@@ -5018,9 +5466,9 @@ function startRelayWatch(opts = {}) {
5018
5466
  // src/daemon.ts
5019
5467
  import { spawn as spawn3 } from "node:child_process";
5020
5468
  import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
5021
- import { mkdir as mkdir9, readFile as readFile9, stat as stat4 } from "node:fs/promises";
5022
- import { userInfo as userInfo2 } from "node:os";
5023
- import { setTimeout as sleep3 } from "node:timers/promises";
5469
+ import { mkdir as mkdir10, readFile as readFile10, stat as stat5 } from "node:fs/promises";
5470
+ import { userInfo as userInfo3 } from "node:os";
5471
+ import { setTimeout as sleep4 } from "node:timers/promises";
5024
5472
 
5025
5473
  // ../shared/src/systemd.ts
5026
5474
  import { spawnSync } from "node:child_process";
@@ -5056,11 +5504,11 @@ function startsAtBoot(p) {
5056
5504
  }
5057
5505
 
5058
5506
  // src/socketClient.ts
5059
- import { Agent as Agent2, request as request3 } from "undici";
5507
+ import { Agent as Agent3, request as request4 } from "undici";
5060
5508
  var SocketClient = class {
5061
5509
  agent;
5062
5510
  constructor(socketPath) {
5063
- this.agent = new Agent2({ connect: { socketPath } });
5511
+ this.agent = new Agent3({ connect: { socketPath } });
5064
5512
  }
5065
5513
  health() {
5066
5514
  return this.call("GET", "/health", HealthSchema);
@@ -5071,15 +5519,23 @@ var SocketClient = class {
5071
5519
  trustCa(req) {
5072
5520
  return this.call("POST", "/ssh/trust-ca", TrustCaReportSchema, req);
5073
5521
  }
5522
+ backupStore() {
5523
+ return this.call("GET", "/backup-store", BackupStoreStatusSchema);
5524
+ }
5525
+ /** Downloads Garage the first time, so it may take minutes. */
5526
+ setupBackupStore(req) {
5527
+ return this.call("POST", "/backup-store", BackupStoreStatusSchema, req, 15 * 6e4);
5528
+ }
5074
5529
  async close() {
5075
5530
  await this.agent.close();
5076
5531
  }
5077
- async call(method, path, schema, body) {
5532
+ async call(method, path, schema, body, timeoutMs) {
5078
5533
  let res;
5079
5534
  try {
5080
- res = await request3(`http://kvbox-server${path}`, {
5535
+ res = await request4(`http://kvbox-server${path}`, {
5081
5536
  method,
5082
5537
  dispatcher: this.agent,
5538
+ ...timeoutMs === void 0 ? {} : { headersTimeout: timeoutMs, bodyTimeout: timeoutMs },
5083
5539
  ...body === void 0 ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }
5084
5540
  });
5085
5541
  } catch (err) {
@@ -5110,7 +5566,7 @@ function safeJson(text) {
5110
5566
  async function runningPid(p = paths()) {
5111
5567
  let pid;
5112
5568
  try {
5113
- pid = Number.parseInt(await readFile9(p.serverPid, "utf8"), 10);
5569
+ pid = Number.parseInt(await readFile10(p.serverPid, "utf8"), 10);
5114
5570
  } catch {
5115
5571
  return null;
5116
5572
  }
@@ -5147,11 +5603,11 @@ async function stopDaemon(pid, timeoutMs = 1e4) {
5147
5603
  const deadline = Date.now() + timeoutMs;
5148
5604
  while (alive(pid)) {
5149
5605
  if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1e3}s`);
5150
- await sleep3(100);
5606
+ await sleep4(100);
5151
5607
  }
5152
5608
  }
5153
5609
  async function answering(p = paths()) {
5154
- if (!await stat4(p.serverSock).then(() => true, () => false)) return null;
5610
+ if (!await stat5(p.serverSock).then(() => true, () => false)) return null;
5155
5611
  const probe = new SocketClient(p.serverSock);
5156
5612
  try {
5157
5613
  const health = await probe.health();
@@ -5163,7 +5619,7 @@ async function answering(p = paths()) {
5163
5619
  }
5164
5620
  }
5165
5621
  async function startDetached(p = paths(), timeoutMs = 5e3) {
5166
- await mkdir9(p.home, { recursive: true });
5622
+ await mkdir10(p.home, { recursive: true });
5167
5623
  const running = await answering(p);
5168
5624
  if (running) return { pid: running.pid, socketPath: p.serverSock, viaGroup: void 0, viaUnit: false, alreadyRunning: running.version };
5169
5625
  if (hasUnitFor(p)) return startUnit(p, timeoutMs);
@@ -5189,7 +5645,7 @@ async function restartDaemon(p = paths()) {
5189
5645
  return startDetached(p);
5190
5646
  }
5191
5647
  async function startUnit(p, timeoutMs) {
5192
- const logFrom = await stat4(p.serverLog).then((s) => s.size, () => 0);
5648
+ const logFrom = await stat5(p.serverLog).then((s) => s.size, () => 0);
5193
5649
  const res = startUnitProcess();
5194
5650
  if (!res.ok) {
5195
5651
  const why = res.out || await lastErrorLine(p.serverLog, logFrom) || "systemctl start failed";
@@ -5203,14 +5659,14 @@ async function startUnit(p, timeoutMs) {
5203
5659
  return { pid: await pidFile(p, -1), socketPath: p.serverSock, viaGroup: void 0, viaUnit: true };
5204
5660
  }
5205
5661
  async function pidFile(p, fallback) {
5206
- const pid = Number.parseInt(await readFile9(p.serverPid, "utf8").catch(() => ""), 10);
5662
+ const pid = Number.parseInt(await readFile10(p.serverPid, "utf8").catch(() => ""), 10);
5207
5663
  return Number.isNaN(pid) ? fallback : pid;
5208
5664
  }
5209
5665
  async function serving(p, timeoutMs, check) {
5210
5666
  const deadline = Date.now() + timeoutMs;
5211
5667
  while (Date.now() < deadline) {
5212
5668
  await check?.();
5213
- if (await stat4(p.serverSock).then(() => true, () => false)) {
5669
+ if (await stat5(p.serverSock).then(() => true, () => false)) {
5214
5670
  const probe = new SocketClient(p.serverSock);
5215
5671
  try {
5216
5672
  await probe.health();
@@ -5220,12 +5676,12 @@ async function serving(p, timeoutMs, check) {
5220
5676
  await probe.close();
5221
5677
  }
5222
5678
  }
5223
- await sleep3(100);
5679
+ await sleep4(100);
5224
5680
  }
5225
5681
  throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
5226
5682
  }
5227
5683
  async function lastErrorLine(logPath, from = 0) {
5228
- const text = (await readFile9(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
5684
+ const text = (await readFile10(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
5229
5685
  for (const line of text.trimEnd().split("\n").slice(-20).reverse()) {
5230
5686
  const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
5231
5687
  if (m?.[1] !== void 0) return m[1];
@@ -5249,7 +5705,7 @@ function selfLauncher(opts = {}) {
5249
5705
  } catch {
5250
5706
  return plain;
5251
5707
  }
5252
- const group = groupWithMember(gid, opts.user ?? userInfo2().username, opts.groupFile ?? "/etc/group");
5708
+ const group = groupWithMember(gid, opts.user ?? userInfo3().username, opts.groupFile ?? "/etc/group");
5253
5709
  if (group === void 0) return plain;
5254
5710
  return { cmd: "sg", args: [group, "-c", argv.map(shellQuote).join(" ")], viaGroup: group };
5255
5711
  }
@@ -5272,31 +5728,10 @@ function groupWithMember(gid, user, groupFile) {
5272
5728
  }
5273
5729
 
5274
5730
  // src/listen.ts
5275
- import { readFile as readFile11, rm as rm6, writeFile as writeFile9 } from "node:fs/promises";
5731
+ import { readFile as readFile12, rm as rm7, writeFile as writeFile10 } from "node:fs/promises";
5276
5732
  import { createServer as createHttpsServer } from "node:https";
5277
5733
  import { createAdaptorServer } from "@hono/node-server";
5278
5734
 
5279
- // src/app.ts
5280
- import { Hono as Hono10 } from "hono";
5281
-
5282
- // ../shared/src/version.ts
5283
- import { createRequire } from "node:module";
5284
- function versionOf(srcFileUrl, injected) {
5285
- if (typeof injected === "string") return injected;
5286
- try {
5287
- const require2 = createRequire(srcFileUrl);
5288
- return require2("../package.json").version;
5289
- } catch {
5290
- return "0.0.0-dev";
5291
- }
5292
- }
5293
-
5294
- // src/version.ts
5295
- var VERSION = versionOf(import.meta.url, true ? "0.5.49" : void 0);
5296
-
5297
- // src/caller.ts
5298
- import { createHash as createHash2, timingSafeEqual } from "node:crypto";
5299
-
5300
5735
  // ../shared/src/names.ts
5301
5736
  import { createHmac as createHmac2 } from "node:crypto";
5302
5737
  var PROXY_ERROR_HEADER = "x-kvbox-proxy-error";
@@ -5304,6 +5739,7 @@ var PROXIED_HEADER = "x-kvbox-proxied";
5304
5739
  var VISITOR_PATH_HEADER = "x-kvbox-path";
5305
5740
  var WAKE_HEADER = "x-kvbox-wake";
5306
5741
  var WAKE_WAIT_MS = 3e4;
5742
+ var REQUEST_TIMEOUT_MS = 36e5;
5307
5743
  var WOKE_HEADER = "x-kvbox-woke";
5308
5744
  var VISITOR_AUTH_HEADER = "x-kvbox-authorization";
5309
5745
  var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
@@ -5313,7 +5749,26 @@ function edgeCredential(hostSecret) {
5313
5749
  return createHmac2("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
5314
5750
  }
5315
5751
 
5752
+ // src/app.ts
5753
+ import { Hono as Hono11 } from "hono";
5754
+
5755
+ // ../shared/src/version.ts
5756
+ import { createRequire } from "node:module";
5757
+ function versionOf(srcFileUrl, injected) {
5758
+ if (typeof injected === "string") return injected;
5759
+ try {
5760
+ const require2 = createRequire(srcFileUrl);
5761
+ return require2("../package.json").version;
5762
+ } catch {
5763
+ return "0.0.0-dev";
5764
+ }
5765
+ }
5766
+
5767
+ // src/version.ts
5768
+ var VERSION = versionOf(import.meta.url, true ? "0.5.51" : void 0);
5769
+
5316
5770
  // src/caller.ts
5771
+ import { createHash as createHash3, timingSafeEqual } from "node:crypto";
5317
5772
  var OWNER_HEADER = "x-kvbox-owner";
5318
5773
  function resolveCaller(opts = {}) {
5319
5774
  const cp = opts.controlPlane;
@@ -5362,17 +5817,17 @@ function bearerCheck(token) {
5362
5817
  };
5363
5818
  }
5364
5819
  function digest(secret) {
5365
- return createHash2("sha256").update(secret).digest();
5820
+ return createHash3("sha256").update(secret).digest();
5366
5821
  }
5367
5822
 
5368
5823
  // src/core/update.ts
5369
- import { mkdir as mkdir10, readFile as readFile10, writeFile as writeFile8 } from "node:fs/promises";
5824
+ import { mkdir as mkdir11, readFile as readFile11, writeFile as writeFile9 } from "node:fs/promises";
5370
5825
  var INSTALL_SERVER_URL = "https://kvbox.sh/install-server.sh";
5371
5826
  var UPDATE_STALE_MS = 60 * 6e4;
5372
5827
  async function readUpdateState(p = paths(), now = Date.now()) {
5373
5828
  let raw;
5374
5829
  try {
5375
- raw = JSON.parse(await readFile10(p.updateState, "utf8"));
5830
+ raw = JSON.parse(await readFile11(p.updateState, "utf8"));
5376
5831
  } catch {
5377
5832
  return null;
5378
5833
  }
@@ -5392,19 +5847,19 @@ async function startUpdate(version, p = paths(), deps = {}) {
5392
5847
  if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);
5393
5848
  const script = await res.text();
5394
5849
  if (!script.startsWith("#!") || !script.includes("--update")) throw new KvboxError(`${url} is not an install-server.sh that knows --update`);
5395
- await mkdir10(p.updateDir, { recursive: true });
5396
- await writeFile8(p.updateScript, script, { mode: 448 });
5850
+ await mkdir11(p.updateDir, { recursive: true });
5851
+ await writeFile9(p.updateScript, script, { mode: 448 });
5397
5852
  const state = { state: "running", startedAt: (/* @__PURE__ */ new Date()).toISOString(), finishedAt: null, from: version, to: null, error: null, needsManual: [] };
5398
- await writeFile8(p.updateState, `${JSON.stringify(state, null, 2)}
5853
+ await writeFile9(p.updateState, `${JSON.stringify(state, null, 2)}
5399
5854
  `);
5400
- await writeFile8(p.updateLog, `--- ${state.startedAt} update from ${version}, ${url}
5855
+ await writeFile9(p.updateLog, `--- ${state.startedAt} update from ${version}, ${url}
5401
5856
  `, { flag: "a" });
5402
5857
  const env = { ...process.env, KVBOX_HOME: p.home, KVBOX_YES: "1" };
5403
5858
  try {
5404
5859
  await (deps.spawn ?? spawnDetached)(["bash", p.updateScript, "--update"], p.updateLog, env);
5405
5860
  } catch (err) {
5406
5861
  const failed = { ...state, state: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error: err.message };
5407
- await writeFile8(p.updateState, `${JSON.stringify(failed, null, 2)}
5862
+ await writeFile9(p.updateState, `${JSON.stringify(failed, null, 2)}
5408
5863
  `);
5409
5864
  throw err;
5410
5865
  }
@@ -5442,18 +5897,35 @@ function backupRoutes() {
5442
5897
  return r;
5443
5898
  }
5444
5899
 
5900
+ // src/routes/backupStore.ts
5901
+ import { Hono as Hono2 } from "hono";
5902
+ function backupStoreRoutes(opts = {}) {
5903
+ const r = new Hono2();
5904
+ if (opts.controlPlane) {
5905
+ r.all("/*", (c) => c.json({ error: "a backup store is set up on the host itself (kvbox-server backup setup there)" }, 403));
5906
+ return r;
5907
+ }
5908
+ r.get("/", async (c) => c.json(await backupStoreStatus()));
5909
+ r.post("/", async (c) => {
5910
+ const body = BackupStoreSetupRequest.safeParse(await c.req.json().catch(() => ({})));
5911
+ if (!body.success) throw new KvboxError("backup setup: expected the directory as path");
5912
+ return c.json(await setupBackupStore(body.data));
5913
+ });
5914
+ return r;
5915
+ }
5916
+
5445
5917
  // src/routes/boxHttp.ts
5446
5918
  import { connect as connect2 } from "node:net";
5447
5919
  import { Readable } from "node:stream";
5448
- import { Hono as Hono2 } from "hono";
5449
- import { request as request4 } from "undici";
5920
+ import { Hono as Hono3 } from "hono";
5921
+ import { request as request5 } from "undici";
5450
5922
 
5451
5923
  // ../shared/src/httpHead.ts
5452
5924
  var END = "\r\n\r\n";
5453
5925
  var HeadTimeoutError = class extends Error {
5454
5926
  };
5455
5927
  function readHead(socket, opts) {
5456
- return new Promise((resolve2, reject) => {
5928
+ return new Promise((resolve3, reject) => {
5457
5929
  let bytes = Buffer.alloc(0);
5458
5930
  const done = (err) => {
5459
5931
  clearTimeout(timer);
@@ -5462,7 +5934,7 @@ function readHead(socket, opts) {
5462
5934
  socket.pause();
5463
5935
  if (err) return reject(err);
5464
5936
  const end = bytes.indexOf(END);
5465
- resolve2({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
5937
+ resolve3({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
5466
5938
  };
5467
5939
  const onData = (chunk) => {
5468
5940
  bytes = Buffer.concat([bytes, chunk]);
@@ -5571,7 +6043,7 @@ function boxHeaders(incoming, target, upgrade = false) {
5571
6043
  var failure = (err, woke = false) => new Response(JSON.stringify({ error: err.message }), { status: err.status, headers: { "content-type": "application/json", [PROXY_ERROR_HEADER]: err.code, ...woke ? { [WOKE_HEADER]: "1" } : {} } });
5572
6044
  var wants = (value) => value === "1";
5573
6045
  function boxHttpRoutes(wake = wakeBox) {
5574
- const r = new Hono2();
6046
+ const r = new Hono3();
5575
6047
  r.all("/:name/http/:port", (c) => forward(c, wake));
5576
6048
  return r;
5577
6049
  }
@@ -5588,7 +6060,7 @@ async function forward(c, wake) {
5588
6060
  raw.headers.forEach((value, name) => pairs.push([name, value]));
5589
6061
  let res;
5590
6062
  try {
5591
- res = await request4(`http://${target.ip}:${target.port}${target.path}`, {
6063
+ res = await request5(`http://${target.ip}:${target.port}${target.path}`, {
5592
6064
  method: raw.method,
5593
6065
  headers: boxHeaders(pairs, target).flat(),
5594
6066
  body: raw.body === null ? null : Readable.fromWeb(raw.body),
@@ -5690,17 +6162,17 @@ ${lines.join("")}\r
5690
6162
  }
5691
6163
 
5692
6164
  // src/routes/capacity.ts
5693
- import { Hono as Hono3 } from "hono";
6165
+ import { Hono as Hono4 } from "hono";
5694
6166
  function capacityRoutes() {
5695
- const r = new Hono3();
6167
+ const r = new Hono4();
5696
6168
  r.get("/", async (c) => c.json({ ...await capacity(), version: VERSION }));
5697
6169
  return r;
5698
6170
  }
5699
6171
 
5700
6172
  // src/routes/env.ts
5701
- import { Hono as Hono4 } from "hono";
6173
+ import { Hono as Hono5 } from "hono";
5702
6174
  function envRoutes() {
5703
- const r = new Hono4();
6175
+ const r = new Hono5();
5704
6176
  r.get("/", async (c) => c.json(await listEnvVersions(c.get("listScope"))));
5705
6177
  r.post("/", async (c) => {
5706
6178
  const body = HostEnvRequest.safeParse(await c.req.json().catch(() => ({})));
@@ -5711,7 +6183,7 @@ function envRoutes() {
5711
6183
  }
5712
6184
 
5713
6185
  // src/routes/machines.ts
5714
- import { Hono as Hono5 } from "hono";
6186
+ import { Hono as Hono6 } from "hono";
5715
6187
 
5716
6188
  // src/core/stats.ts
5717
6189
  var STATS_REPLY_MS = 3e3;
@@ -5766,7 +6238,7 @@ async function usageReport(scope, window, p = paths()) {
5766
6238
 
5767
6239
  // src/routes/machines.ts
5768
6240
  function machineRoutes() {
5769
- const r = new Hono5();
6241
+ const r = new Hono6();
5770
6242
  r.get("/", async (c) => c.json(await listMachines(c.get("listScope"))));
5771
6243
  r.post("/", async (c) => {
5772
6244
  const body = CreateMachineRequest.parse(await c.req.json().catch(() => ({})));
@@ -5868,9 +6340,9 @@ function machineRoutes() {
5868
6340
  }
5869
6341
 
5870
6342
  // src/routes/snapshots.ts
5871
- import { Hono as Hono6 } from "hono";
6343
+ import { Hono as Hono7 } from "hono";
5872
6344
  function snapshotRoutes() {
5873
- const r = new Hono6();
6345
+ const r = new Hono7();
5874
6346
  r.get("/", async (c) => c.json(await listSnapshots(c.get("listScope"))));
5875
6347
  r.post("/", async (c) => {
5876
6348
  const body = CreateSnapshotRequest.parse(await c.req.json());
@@ -5884,9 +6356,9 @@ function snapshotRoutes() {
5884
6356
  }
5885
6357
 
5886
6358
  // src/routes/ssh.ts
5887
- import { Hono as Hono7 } from "hono";
6359
+ import { Hono as Hono8 } from "hono";
5888
6360
  function sshRoutes(opts = {}) {
5889
- const r = new Hono7();
6361
+ const r = new Hono8();
5890
6362
  if (opts.controlPlane) {
5891
6363
  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));
5892
6364
  return r;
@@ -5901,10 +6373,10 @@ function sshRoutes(opts = {}) {
5901
6373
  }
5902
6374
 
5903
6375
  // src/routes/usage.ts
5904
- import { Hono as Hono8 } from "hono";
6376
+ import { Hono as Hono9 } from "hono";
5905
6377
  var PULL_LIMIT = 1e3;
5906
6378
  function usageRoutes(opts = {}) {
5907
- const r = new Hono8();
6379
+ const r = new Hono9();
5908
6380
  r.get("/", async (c) => {
5909
6381
  let window;
5910
6382
  try {
@@ -5937,9 +6409,9 @@ function whole(value, name) {
5937
6409
  }
5938
6410
 
5939
6411
  // src/routes/volumes.ts
5940
- import { Hono as Hono9 } from "hono";
6412
+ import { Hono as Hono10 } from "hono";
5941
6413
  function volumeRoutes() {
5942
- const r = new Hono9();
6414
+ const r = new Hono10();
5943
6415
  r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
5944
6416
  r.post("/", async (c) => {
5945
6417
  const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
@@ -5969,7 +6441,7 @@ function volumeRoutes() {
5969
6441
 
5970
6442
  // src/app.ts
5971
6443
  function createApp(opts = {}) {
5972
- const app = new Hono10();
6444
+ const app = new Hono11();
5973
6445
  app.use(resolveCaller(opts));
5974
6446
  app.get("/health", async (c) => {
5975
6447
  const cfg = await loadConfig();
@@ -5998,6 +6470,7 @@ function createApp(opts = {}) {
5998
6470
  app.route("/capacity", capacityRoutes());
5999
6471
  app.route("/env", envRoutes());
6000
6472
  app.route("/ssh", sshRoutes(opts));
6473
+ app.route("/backup-store", backupStoreRoutes(opts));
6001
6474
  app.route("/usage", usageRoutes(opts));
6002
6475
  app.notFound((c) => c.json({ error: `no route: ${c.req.method} ${c.req.path}` }, 404));
6003
6476
  app.onError((err, c) => {
@@ -6020,35 +6493,45 @@ async function listen(opts = {}) {
6020
6493
  throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
6021
6494
  }
6022
6495
  if (socketPath === p.serverSock) await refuseSecondDaemon(p);
6023
- await rm6(socketPath, { force: true });
6496
+ await rm7(socketPath, { force: true });
6024
6497
  const server = createAdaptorServer({ fetch: createApp().fetch });
6025
- await new Promise((resolve2, reject) => {
6498
+ await new Promise((resolve3, reject) => {
6026
6499
  server.once("error", reject);
6027
- server.listen(socketPath, () => resolve2());
6500
+ server.listen(socketPath, () => resolve3());
6028
6501
  });
6029
- await writeFile9(p.serverPid, `${process.pid}
6502
+ await writeFile10(p.serverPid, `${process.pid}
6030
6503
  `);
6031
6504
  let https;
6032
6505
  let httpsServer;
6033
6506
  const cp = cfg.controlPlane;
6034
6507
  if (cp) {
6035
- const [key, cert] = await Promise.all([readFile11(p.tlsKey), readFile11(p.tlsCert)]).catch((err) => {
6508
+ const [key, cert] = await Promise.all([readFile12(p.tlsKey), readFile12(p.tlsCert)]).catch((err) => {
6036
6509
  throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
6037
6510
  });
6038
6511
  httpsServer = createAdaptorServer({
6039
6512
  fetch: createApp({ controlPlane: { name: cp.name, secret: cp.secret } }).fetch,
6040
6513
  createServer: createHttpsServer,
6041
- serverOptions: { key, cert }
6514
+ // A body forwarded to a box may take long to arrive (a large upload through the edge, #182).
6515
+ serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS }
6516
+ });
6517
+ const appListeners = httpsServer.listeners("request");
6518
+ httpsServer.removeAllListeners("request");
6519
+ httpsServer.on("request", (req, res) => {
6520
+ if (forStore(req.url, p)) return storeProxy(req, res);
6521
+ for (const l of appListeners) l.call(httpsServer, req, res);
6042
6522
  });
6523
+ const secret = secretCheck(cp);
6524
+ const edge = edgeCheck(cp);
6525
+ limitUntrusted(httpsServer, (req) => secret(req.headers.authorization) || edge(req.headers.authorization));
6043
6526
  httpsServer.on("upgrade", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));
6044
6527
  const port = opts.httpsPort ?? cp.port;
6045
- await new Promise((resolve2, reject) => {
6528
+ await new Promise((resolve3, reject) => {
6046
6529
  httpsServer.once("error", reject);
6047
- httpsServer.listen(port, "0.0.0.0", () => resolve2());
6530
+ httpsServer.listen(port, "0.0.0.0", () => resolve3());
6048
6531
  }).catch(async (err) => {
6049
6532
  server.close();
6050
- await rm6(socketPath, { force: true });
6051
- await rm6(p.serverPid, { force: true });
6533
+ await rm7(socketPath, { force: true });
6534
+ await rm7(p.serverPid, { force: true });
6052
6535
  throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
6053
6536
  });
6054
6537
  const bound = httpsServer.address().port;
@@ -6056,24 +6539,35 @@ async function listen(opts = {}) {
6056
6539
  }
6057
6540
  const close = async () => {
6058
6541
  await Promise.all([
6059
- new Promise((resolve2) => server.close(() => resolve2())),
6060
- httpsServer ? new Promise((resolve2) => httpsServer.close(() => resolve2())) : void 0
6542
+ new Promise((resolve3) => server.close(() => resolve3())),
6543
+ httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
6061
6544
  ]);
6062
- await rm6(socketPath, { force: true });
6063
- await rm6(p.serverPid, { force: true });
6545
+ await rm7(socketPath, { force: true });
6546
+ await rm7(p.serverPid, { force: true });
6064
6547
  };
6065
6548
  const shutdown2 = async () => {
6066
6549
  server.close();
6067
6550
  httpsServer?.close();
6068
6551
  await stopRecovery();
6069
- await rm6(socketPath, { force: true });
6070
- await rm6(p.serverPid, { force: true });
6552
+ await rm7(socketPath, { force: true });
6553
+ await rm7(p.serverPid, { force: true });
6071
6554
  process.exit(0);
6072
6555
  };
6073
6556
  process.once("SIGINT", () => void shutdown2());
6074
6557
  process.once("SIGTERM", () => void shutdown2());
6075
6558
  return https ? { socketPath, server, https, close } : { socketPath, server, close };
6076
6559
  }
6560
+ var UNTRUSTED_REQUEST_MS = 3e5;
6561
+ function limitUntrusted(server, trusted, ms = UNTRUSTED_REQUEST_MS) {
6562
+ server.on("request", (req) => {
6563
+ if (trusted(req)) return;
6564
+ const timer = setTimeout(() => req.socket.destroy(), ms);
6565
+ timer.unref();
6566
+ const done = () => clearTimeout(timer);
6567
+ req.once("end", done);
6568
+ req.once("close", done);
6569
+ });
6570
+ }
6077
6571
 
6078
6572
  // src/commands/start.ts
6079
6573
  var daemon = false;
@@ -6128,6 +6622,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
6128
6622
  bindDns();
6129
6623
  startRelayWatch();
6130
6624
  startIdleWatch();
6625
+ startBackupStoreWatch();
6131
6626
  const recovery2 = await bootRecovered(settled, paths());
6132
6627
  if (recovery2) {
6133
6628
  for (const box of recovery2.booted) log.info(`box ${box} was running when it went down; booted it again`);
@@ -6137,11 +6632,66 @@ var startCommand = new Command("start").description("run the daemon in the foreg
6137
6632
  });
6138
6633
 
6139
6634
  // src/program.ts
6140
- import { Command as Command10 } from "commander";
6635
+ import { Command as Command13 } from "commander";
6141
6636
 
6142
- // src/commands/join.ts
6637
+ // src/commands/backup/index.ts
6638
+ import { Command as Command4 } from "commander";
6639
+
6640
+ // src/commands/backup/setup.ts
6641
+ import { resolve as resolve2 } from "node:path";
6143
6642
  import { Command as Command2 } from "commander";
6144
- 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) => {
6643
+
6644
+ // src/commands/backup/output.ts
6645
+ function size(bytes) {
6646
+ const gib = bytes / 1024 ** 3;
6647
+ return gib >= 1024 ? `${(gib / 1024).toFixed(1)} TB` : `${gib.toFixed(1)} GB`;
6648
+ }
6649
+ function printStore(s) {
6650
+ const rows = [
6651
+ ["path", s.path],
6652
+ ["storage", s.running ? "running" : "not running (the daemon starts it again within a minute; kvbox-server logs says why if it does not)"],
6653
+ ["disk", `${size(s.totalBytes - s.freeBytes)} used of ${size(s.totalBytes)}, ${size(s.freeBytes)} free`]
6654
+ ];
6655
+ if (s.storedBytes !== void 0) rows.push(["backups", `${size(s.storedBytes)} in ${s.objects ?? 0} chunks`]);
6656
+ rows.push(["key", s.accessKey]);
6657
+ rows.push(["control plane", s.registered ? "knows this store" : "does not know this store yet: run kvbox-server backup setup again with the same path"]);
6658
+ const width = Math.max(...rows.map(([label]) => label.length));
6659
+ for (const [label, value] of rows) console.log(`${label.padEnd(width)} ${value}`);
6660
+ }
6661
+
6662
+ // src/commands/backup/setup.ts
6663
+ var setupCommand = new Command2("setup").description("keep box backups on this host: run Garage with its data in a directory on the backup disk, and tell the control plane").requiredOption("--path <dir>", "a directory on the disk for backups (mounted already)").option("--force", "use the path even when it is on the same disk as this host's boxes").option("--new-store", "the store's disk is gone for good: start a new store at the path (the old backups are lost)").option("--json", "print the store as JSON").action(async (opts) => {
6664
+ const client = new SocketClient(paths().serverSock);
6665
+ try {
6666
+ if (!opts.json) console.log("setting up the backup store (the first time downloads Garage, which can take a minute)");
6667
+ const store = await client.setupBackupStore({ path: resolve2(opts.path), ...opts.force ? { force: true } : {}, ...opts.newStore ? { newStore: true } : {} });
6668
+ if (opts.json) return console.log(JSON.stringify(store, null, 2));
6669
+ console.log("this host is now a backup store; new backups can be kept here");
6670
+ printStore(store);
6671
+ } finally {
6672
+ await client.close();
6673
+ }
6674
+ });
6675
+
6676
+ // src/commands/backup/status.ts
6677
+ import { Command as Command3 } from "commander";
6678
+ var statusCommand = new Command3("status").description("show this host's backup store: its disk, whether it runs and what it holds").option("--json", "print as JSON").action(async (opts) => {
6679
+ const client = new SocketClient(paths().serverSock);
6680
+ try {
6681
+ const store = await client.backupStore();
6682
+ if (opts.json) console.log(JSON.stringify(store, null, 2));
6683
+ else printStore(store);
6684
+ } finally {
6685
+ await client.close();
6686
+ }
6687
+ });
6688
+
6689
+ // src/commands/backup/index.ts
6690
+ var backupCommand = new Command4("backup").description("make this host a backup store: box backups are kept on a disk of its own, in Garage").addCommand(setupCommand).addCommand(statusCommand);
6691
+
6692
+ // src/commands/join.ts
6693
+ import { Command as Command5 } from "commander";
6694
+ var joinCommand = new Command5("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) => {
6145
6695
  const p = paths();
6146
6696
  const joined = await joinControlPlane({ url, ...opts }, p);
6147
6697
  console.log(`joined ${joined.controlPlane} as host ${joined.hostName}`);
@@ -6155,8 +6705,8 @@ var joinCommand = new Command2("join").description("put this host behind a contr
6155
6705
  });
6156
6706
 
6157
6707
  // src/commands/leave.ts
6158
- import { Command as Command3 } from "commander";
6159
- var leaveCommand = new Command3("leave").description("take this host out from behind its control plane and restart the daemon").action(async () => {
6708
+ import { Command as Command6 } from "commander";
6709
+ var leaveCommand = new Command6("leave").description("take this host out from behind its control plane and restart the daemon").action(async () => {
6160
6710
  const p = paths();
6161
6711
  const left = await leaveControlPlane(p);
6162
6712
  console.log(`left ${left.controlPlane}`);
@@ -6170,14 +6720,14 @@ var leaveCommand = new Command3("leave").description("take this host out from be
6170
6720
  });
6171
6721
 
6172
6722
  // src/commands/logs.ts
6173
- import { open as open2, readFile as readFile12, stat as stat5 } from "node:fs/promises";
6174
- import { setTimeout as sleep4 } from "node:timers/promises";
6175
- import { Command as Command4 } from "commander";
6176
- 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) => {
6723
+ import { open as open2, readFile as readFile13, stat as stat6 } from "node:fs/promises";
6724
+ import { setTimeout as sleep5 } from "node:timers/promises";
6725
+ import { Command as Command7 } from "commander";
6726
+ var logsCommand = new Command7("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) => {
6177
6727
  const n = Number.parseInt(opts.lines, 10);
6178
6728
  if (!Number.isInteger(n) || n < 0) throw new KvboxError(`--lines: expected a number, got ${opts.lines}`);
6179
6729
  const p = paths();
6180
- const text = await readFile12(p.serverLog, "utf8").catch((err) => {
6730
+ const text = await readFile13(p.serverLog, "utf8").catch((err) => {
6181
6731
  if (err.code === "ENOENT") throw new KvboxError(`no log yet at ${p.serverLog} (the daemon writes it once it has run)`);
6182
6732
  throw err;
6183
6733
  });
@@ -6197,14 +6747,14 @@ function tailLines(text, n) {
6197
6747
  }
6198
6748
  async function follow(path, write, opts = {}) {
6199
6749
  const intervalMs = opts.intervalMs ?? 250;
6200
- let offset = opts.from ?? await stat5(path).then((s) => s.size, () => 0);
6750
+ let offset = opts.from ?? await stat6(path).then((s) => s.size, () => 0);
6201
6751
  while (!opts.signal?.aborted) {
6202
- const size = await stat5(path).then((s) => s.size, () => 0);
6203
- if (size < offset) offset = 0;
6204
- if (size > offset) {
6752
+ const size2 = await stat6(path).then((s) => s.size, () => 0);
6753
+ if (size2 < offset) offset = 0;
6754
+ if (size2 > offset) {
6205
6755
  const fh = await open2(path, "r");
6206
6756
  try {
6207
- const buf = Buffer.alloc(size - offset);
6757
+ const buf = Buffer.alloc(size2 - offset);
6208
6758
  const { bytesRead } = await fh.read(buf, 0, buf.length, offset);
6209
6759
  write(buf.subarray(0, bytesRead).toString("utf8"));
6210
6760
  offset += bytesRead;
@@ -6212,14 +6762,14 @@ async function follow(path, write, opts = {}) {
6212
6762
  await fh.close();
6213
6763
  }
6214
6764
  }
6215
- await sleep4(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
6765
+ await sleep5(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
6216
6766
  }
6217
6767
  }
6218
6768
 
6219
6769
  // src/commands/net.ts
6220
6770
  import { spawnSync as spawnSync2 } from "node:child_process";
6221
- import { Command as Command5 } from "commander";
6222
- 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) => {
6771
+ import { Command as Command8 } from "commander";
6772
+ var netCommand = new Command8("net").description("host network: up | down | status (bridge, forwarding, NAT; uses sudo)").argument("<action>", "up, down or status").action(async (action) => {
6223
6773
  if (!["up", "down", "status"].includes(action)) throw new KvboxError("net: expected up, down or status");
6224
6774
  const cfg = await loadConfig(paths());
6225
6775
  const res = spawnSync2(netSetupScript(), [action], {
@@ -6230,8 +6780,8 @@ var netCommand = new Command5("net").description("host network: up | down | stat
6230
6780
  });
6231
6781
 
6232
6782
  // src/commands/relay.ts
6233
- import { Command as Command6 } from "commander";
6234
- 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) => {
6783
+ import { Command as Command9 } from "commander";
6784
+ var relayCommand = new Command9("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) => {
6235
6785
  if (joinString === "off") {
6236
6786
  const relay2 = await dropRelay(paths());
6237
6787
  console.log(`tunnel to relay ${relay2.name} is down; this host no longer answers at ${relay2.publicIp}`);
@@ -6245,8 +6795,8 @@ var relayCommand = new Command6("relay").description("reach the internet through
6245
6795
  // src/commands/status.ts
6246
6796
  import { homedir as homedir2 } from "node:os";
6247
6797
  import { styleText } from "node:util";
6248
- import { Command as Command7 } from "commander";
6249
- 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) => {
6798
+ import { Command as Command10 } from "commander";
6799
+ var statusCommand2 = new Command10("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) => {
6250
6800
  const p = paths();
6251
6801
  const atBoot = startsAtBoot(p);
6252
6802
  const pid = await daemonPid(p);
@@ -6318,8 +6868,8 @@ function printStatus(health, atBoot, logPath) {
6318
6868
  }
6319
6869
 
6320
6870
  // src/commands/stop.ts
6321
- import { Command as Command8 } from "commander";
6322
- var stopCommand = new Command8("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
6871
+ import { Command as Command11 } from "commander";
6872
+ var stopCommand = new Command11("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
6323
6873
  const pid = await daemonPid(paths());
6324
6874
  if (pid === null) throw new KvboxError("kvbox-server is not running");
6325
6875
  await stopDaemon(pid);
@@ -6327,8 +6877,8 @@ var stopCommand = new Command8("stop").description("stop the daemon (running box
6327
6877
  });
6328
6878
 
6329
6879
  // src/commands/trust-ca.ts
6330
- import { Command as Command9 } from "commander";
6331
- 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) => {
6880
+ import { Command as Command12 } from "commander";
6881
+ var trustCaCommand = new Command12("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) => {
6332
6882
  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");
6333
6883
  if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
6334
6884
  const client = new SocketClient(paths().serverSock);
@@ -6384,7 +6934,7 @@ function describeReport(report2) {
6384
6934
 
6385
6935
  // src/program.ts
6386
6936
  function buildProgram() {
6387
- 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).addCommand(stopCommand).addCommand(statusCommand).addCommand(logsCommand).addCommand(joinCommand).addCommand(leaveCommand).addCommand(relayCommand).addCommand(trustCaCommand).addCommand(netCommand);
6937
+ return new Command13("kvbox-server").description("kvbox host daemon: owns Firecracker and $KVBOX_HOME (~/.kvbox), serves the kvbox API").version(VERSION, "-v, --version").showHelpAfterError().addCommand(startCommand).addCommand(stopCommand).addCommand(statusCommand2).addCommand(logsCommand).addCommand(joinCommand).addCommand(leaveCommand).addCommand(relayCommand).addCommand(trustCaCommand).addCommand(backupCommand).addCommand(netCommand);
6388
6938
  }
6389
6939
 
6390
6940
  // src/index.ts