@kvbox/server 0.5.35 → 0.5.37

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.
@@ -85,6 +85,8 @@ function paths(home = kvboxHome()) {
85
85
  env: join(dir, "env.json"),
86
86
  /** The box's writable layer, stacked on the read-only base image inside the guest. */
87
87
  overlay: join(dir, "overlay.ext4"),
88
+ /** A restore's disk while it downloads (a backup's chunks), renamed over `overlay` once complete. */
89
+ restoring: join(dir, "overlay.ext4.restore"),
88
90
  /**
89
91
  * The box's memory as of its last snapshot (a hard link to that snapshot's `mem`, never modified).
90
92
  * The next snapshot is a diff of the pages dirtied since, merged onto this. Absent after a boot.
@@ -123,6 +125,16 @@ function paths(home = kvboxHome()) {
123
125
  /** Each owner's environment variables as the control plane last sent them (#88): env/<owner>.json, mode 600. */
124
126
  env: join(home, "env"),
125
127
  ownerEnv: (owner) => join(home, "env", `${owner}.json`),
128
+ /**
129
+ * Backups in progress (decision "Backups: encrypted 4 MiB chunks in object storage"): backups/<id>/ holds the
130
+ * copy of the box's disk being uploaded and its chunk list, gone once the upload ends. Nothing here outlives
131
+ * a daemon restart.
132
+ */
133
+ backups: join(home, "backups"),
134
+ backup: (id) => {
135
+ const dir = join(home, "backups", id);
136
+ return { dir, disk: join(dir, "disk.ext4"), chunks: join(dir, "chunks.json") };
137
+ },
126
138
  snapshot: (owner, name) => {
127
139
  const dir = join(home, "snapshots", owner, name);
128
140
  return {
@@ -506,6 +518,52 @@ var WakeHookCallSchema = z3.object({
506
518
  action: z3.enum(["wake", "resume", "none"]),
507
519
  reason: z3.string().optional()
508
520
  });
521
+ var BACKUP_STATUSES = ["running", "ready", "failed"];
522
+ var BackupSchema = z3.object({
523
+ id: z3.string(),
524
+ owner: z3.string(),
525
+ box: z3.string(),
526
+ status: z3.enum(BACKUP_STATUSES),
527
+ /** Why it failed; null otherwise. */
528
+ error: z3.string().nullable(),
529
+ /** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
530
+ base: z3.string().nullable(),
531
+ image: z3.string().optional(),
532
+ vcpu: z3.number().int().nullable(),
533
+ memMib: z3.number().int().nullable(),
534
+ /** The disk's size. */
535
+ diskBytes: z3.number().int().nullable(),
536
+ /** What it holds: the slots that are not all zeros. */
537
+ dataBytes: z3.number().int().nullable(),
538
+ /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
539
+ uploadedBytes: z3.number().int().nullable(),
540
+ createdBy: z3.string().nullable(),
541
+ createdAt: z3.string(),
542
+ finishedAt: z3.string().nullable()
543
+ });
544
+ var HostBackupRequest = z3.object({ id: z3.string(), key: z3.string() });
545
+ var HostBackupManifestSchema = z3.object({
546
+ id: z3.string(),
547
+ sizeBytes: z3.number().int(),
548
+ chunks: z3.array(z3.string().nullable()),
549
+ env: z3.string().nullable(),
550
+ base: z3.string(),
551
+ image: z3.string().optional(),
552
+ vcpu: z3.number().int(),
553
+ memMib: z3.number().int()
554
+ });
555
+ var HostUploadRequest = z3.object({ key: z3.string(), urls: z3.record(z3.string(), z3.string()) });
556
+ var HostUploadResultSchema = z3.object({ chunks: z3.number().int(), bytes: z3.number().int(), sizes: z3.record(z3.string(), z3.number().int()) });
557
+ var HostRestoreRequest = z3.object({
558
+ /** The backup's id: its variables were sealed under it. */
559
+ id: z3.string(),
560
+ key: z3.string(),
561
+ sizeBytes: z3.number().int().positive(),
562
+ base: z3.string(),
563
+ image: z3.string().optional(),
564
+ env: z3.string().nullable(),
565
+ chunks: z3.array(z3.object({ index: z3.number().int().nonnegative(), hash: z3.string(), url: z3.string() }))
566
+ });
509
567
  var MachineSchema = z3.object({
510
568
  /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
511
569
  id: z3.string(),
@@ -1725,7 +1783,7 @@ async function startDns(opts) {
1725
1783
  // src/core/machines.ts
1726
1784
  import { spawn } from "node:child_process";
1727
1785
  import { closeSync as closeSync2, existsSync as existsSync6, openSync as openSync2, statSync as statSync2 } from "node:fs";
1728
- import { link as link2, mkdir as mkdir6, readFile as readFile6, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1786
+ import { link as link2, mkdir as mkdir6, readFile as readFile6, rename as rename5, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1729
1787
  import { setTimeout as sleep } from "node:timers/promises";
1730
1788
 
1731
1789
  // ../shared/src/duration.ts
@@ -1905,7 +1963,7 @@ async function readBoxEnvFile(file) {
1905
1963
  throw err;
1906
1964
  }
1907
1965
  }
1908
- async function writeBoxEnv(box, vars, p = paths()) {
1966
+ function checkBoxEnv(vars) {
1909
1967
  if (vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
1910
1968
  const seen = /* @__PURE__ */ new Set();
1911
1969
  for (const v of vars) {
@@ -1914,6 +1972,9 @@ async function writeBoxEnv(box, vars, p = paths()) {
1914
1972
  if (seen.has(v.name)) throw new KvboxError(`${v.name} is given twice`);
1915
1973
  seen.add(v.name);
1916
1974
  }
1975
+ }
1976
+ async function writeBoxEnv(box, vars, p = paths()) {
1977
+ checkBoxEnv(vars);
1917
1978
  const file = p.machine(box.owner, box.name).env;
1918
1979
  const tmp = `${file}.tmp`;
1919
1980
  await writeFile3(tmp, JSON.stringify({ vars }, null, 2) + "\n", { mode: 384 });
@@ -3508,7 +3569,7 @@ var startMachine = locked(async function startMachine2(ref, p = paths(), force =
3508
3569
  pid = await launch(meta, tap, cfg, keysB64, p);
3509
3570
  await openPorts(meta, cfg, p);
3510
3571
  void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);
3511
- const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0 };
3572
+ const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0, paused: void 0 };
3512
3573
  await writeMachineMeta(started, p);
3513
3574
  recordState(started, "running", "start", p);
3514
3575
  return toMachine(started, p);
@@ -3723,6 +3784,20 @@ var rescaleMachine = locked(async function rescaleMachine2(ref, req, p = paths()
3723
3784
  }
3724
3785
  return applyAtNextBoot(meta, changes, "rescale", cfg, p, growTo === void 0 ? void 0 : () => growDisk(disk, growTo));
3725
3786
  });
3787
+ var replaceDisk = locked(async function replaceDisk2(ref, file, disk, p = paths()) {
3788
+ const meta = await readMeta(ref, p);
3789
+ const cfg = await loadConfig(p);
3790
+ assertNotHibernated(meta, p);
3791
+ const m = p.machine(ref.owner, ref.name);
3792
+ const currentGib = Math.round(statSync2(m.overlay).size / 1024 ** 3);
3793
+ const restoredGib = Math.round(statSync2(file).size / 1024 ** 3);
3794
+ return applyAtNextBoot(meta, { base: disk.base, image: disk.image }, "restore", cfg, p, async () => {
3795
+ if (disk.vars === null) await rm3(m.env, { force: true });
3796
+ else await writeBoxEnv(ref, disk.vars, p);
3797
+ await rename5(file, m.overlay);
3798
+ if (currentGib > restoredGib) await growDisk(m.overlay, currentGib);
3799
+ });
3800
+ });
3726
3801
  var attachVolume = locked(async function attachVolume2(ref, volume, p = paths()) {
3727
3802
  const cfg = await loadConfig(p);
3728
3803
  const claimed = await withHostLock("volumes", async () => {
@@ -3980,8 +4055,368 @@ async function bootRecovered(settled, p = paths()) {
3980
4055
  return recovery;
3981
4056
  }
3982
4057
 
4058
+ // src/core/backups.ts
4059
+ import { randomBytes as randomBytes4 } from "node:crypto";
4060
+ import { existsSync as existsSync7 } from "node:fs";
4061
+ import { mkdir as mkdir7, open, readdir as readdir6, readFile as readFile7, rm as rm4, stat as stat3, statfs as statfs2, writeFile as writeFile6 } from "node:fs/promises";
4062
+ import { basename as basename2, join as join2 } from "node:path";
4063
+ import { setTimeout as sleep2 } from "node:timers/promises";
4064
+
4065
+ // ../shared/src/backup.ts
4066
+ import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes3 } from "node:crypto";
4067
+ import { promisify as promisify2 } from "node:util";
4068
+ import { deflateRaw as deflateRawCb, inflateRaw as inflateRawCb, constants as zlib } from "node:zlib";
4069
+ var deflateRaw = promisify2(deflateRawCb);
4070
+ var inflateRaw = promisify2(inflateRawCb);
4071
+ var CHUNK_SIZE = 4 * 1024 * 1024;
4072
+ var BACKUP_ID_RE = /^bk_[A-Za-z0-9_-]{12}$/;
4073
+ var CHUNK_HASH_RE = /^[0-9a-f]{64}$/;
4074
+ var FLAG_RAW = 1;
4075
+ var FLAG_DEFLATE = 2;
4076
+ var NONCE = 12;
4077
+ var TAG = 16;
4078
+ function backupKeys(dataKeyB64) {
4079
+ const dk = Buffer.from(dataKeyB64, "base64");
4080
+ if (dk.length !== 32) throw new Error("backup key: expected 32 bytes");
4081
+ return {
4082
+ name: createHmac("sha256", dk).update("kvbox-backup chunk-name v1").digest(),
4083
+ seal: createHmac("sha256", dk).update("kvbox-backup chunk-seal v1").digest()
4084
+ };
4085
+ }
4086
+ function isZero(buf) {
4087
+ return buf.equals(zeros(buf.length));
4088
+ }
4089
+ var zeroBuf = Buffer.alloc(0);
4090
+ function zeros(n) {
4091
+ if (zeroBuf.length < n) zeroBuf = Buffer.alloc(n);
4092
+ return zeroBuf.subarray(0, n);
4093
+ }
4094
+ function chunkName(keys, plain) {
4095
+ return createHmac("sha256", keys.name).update(plain).digest("hex");
4096
+ }
4097
+ async function sealChunk(keys, name, plain) {
4098
+ const packed = await deflateRaw(plain, { level: zlib.Z_BEST_SPEED });
4099
+ const [flag, body] = packed.length < plain.length ? [FLAG_DEFLATE, packed] : [FLAG_RAW, plain];
4100
+ return seal(keys.seal, Buffer.from([flag]), body, `${name}:${flag}`);
4101
+ }
4102
+ async function openChunk(keys, name, stored) {
4103
+ if (stored.length < 1 + NONCE + TAG) throw new Error(`chunk ${name.slice(0, 12)}: too short to be one`);
4104
+ const flag = stored[0];
4105
+ if (flag !== FLAG_RAW && flag !== FLAG_DEFLATE) throw new Error(`chunk ${name.slice(0, 12)}: unknown format ${flag}`);
4106
+ const body = unseal(keys.seal, stored.subarray(1), `${name}:${flag}`, `chunk ${name.slice(0, 12)}`);
4107
+ const plain = flag === FLAG_DEFLATE ? await inflateRaw(body, { maxOutputLength: CHUNK_SIZE }) : body;
4108
+ if (chunkName(keys, plain) !== name) throw new Error(`chunk ${name.slice(0, 12)}: contents do not match its name`);
4109
+ return plain;
4110
+ }
4111
+ function sealText(keys, text, label) {
4112
+ return seal(keys.seal, Buffer.alloc(0), Buffer.from(text, "utf8"), label).toString("base64");
4113
+ }
4114
+ function openText(keys, sealedB64, label) {
4115
+ return unseal(keys.seal, Buffer.from(sealedB64, "base64"), label, label).toString("utf8");
4116
+ }
4117
+ function seal(key, prefix, plain, aad) {
4118
+ const nonce = randomBytes3(NONCE);
4119
+ const cipher = createCipheriv("aes-256-gcm", key, nonce);
4120
+ cipher.setAAD(Buffer.from(aad));
4121
+ const data = Buffer.concat([cipher.update(plain), cipher.final()]);
4122
+ return Buffer.concat([prefix, nonce, data, cipher.getAuthTag()]);
4123
+ }
4124
+ function unseal(key, sealed, aad, what) {
4125
+ if (sealed.length < NONCE + TAG) throw new Error(`${what}: too short`);
4126
+ const nonce = sealed.subarray(0, NONCE);
4127
+ const tag = sealed.subarray(sealed.length - TAG);
4128
+ const data = sealed.subarray(NONCE, sealed.length - TAG);
4129
+ try {
4130
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce);
4131
+ decipher.setAAD(Buffer.from(aad));
4132
+ decipher.setAuthTag(tag);
4133
+ return Buffer.concat([decipher.update(data), decipher.final()]);
4134
+ } catch {
4135
+ throw new Error(`${what}: does not open with this slug's backup key (changed or not this slug's)`);
4136
+ }
4137
+ }
4138
+ function chunkCount(bytes) {
4139
+ return Math.ceil(bytes / CHUNK_SIZE);
4140
+ }
4141
+
4142
+ // src/core/backups.ts
4143
+ var PARALLEL = 4;
4144
+ var TRIES = 4;
4145
+ var CHUNK_TIMEOUT_MS = 12e4;
4146
+ async function assertRoom(dir, bytes, what, p) {
4147
+ const st = await statfs2(dir);
4148
+ const free = st.bavail * st.bsize;
4149
+ const headroom = (await loadConfig(p)).volumeHeadroomGib * 1024 ** 3;
4150
+ if (free - bytes < headroom) {
4151
+ const gib = (n) => (n / 1024 ** 3).toFixed(1);
4152
+ throw new KvboxError(`${what} needs ${gib(bytes)} GiB and this host has ${gib(free)} GiB free (keeping ${gib(headroom)} GiB spare); try again when it has room`);
4153
+ }
4154
+ }
4155
+ function checkId(id) {
4156
+ if (!BACKUP_ID_RE.test(id)) throw new KvboxError(`not a backup id: ${id}`);
4157
+ }
4158
+ async function readBox2(ref, p) {
4159
+ try {
4160
+ return await readMachineMeta(ref, p);
4161
+ } catch (err) {
4162
+ if (err.code === "ENOENT") throw new NotFoundError(`box ${shown(ref)}`);
4163
+ throw err;
4164
+ }
4165
+ }
4166
+ async function chunkNames(file, keys) {
4167
+ const { size } = await stat3(file);
4168
+ const chunks = [];
4169
+ const fh = await open(file, "r");
4170
+ try {
4171
+ const buf = Buffer.alloc(CHUNK_SIZE);
4172
+ for (let i = 0; i < chunkCount(size); i++) {
4173
+ const slot = await readSlot(fh, buf, i, size);
4174
+ chunks.push(isZero(slot) ? null : chunkName(keys, slot));
4175
+ }
4176
+ } finally {
4177
+ await fh.close();
4178
+ }
4179
+ return { sizeBytes: size, chunks };
4180
+ }
4181
+ async function readSlot(fh, buf, index, size) {
4182
+ const length = Math.min(CHUNK_SIZE, size - index * CHUNK_SIZE);
4183
+ let got = 0;
4184
+ while (got < length) {
4185
+ const { bytesRead } = await fh.read(buf, got, length - got, index * CHUNK_SIZE + got);
4186
+ if (bytesRead === 0) break;
4187
+ got += bytesRead;
4188
+ }
4189
+ return buf.subarray(0, length);
4190
+ }
4191
+ async function stageBackup(ref, req, p = paths()) {
4192
+ checkId(req.id);
4193
+ const keys = backupKeys(req.key);
4194
+ const s = p.backup(req.id);
4195
+ await rm4(s.dir, { recursive: true, force: true });
4196
+ await mkdir7(s.dir, { recursive: true, mode: 448 });
4197
+ try {
4198
+ const { meta, envText } = await withBoxLock(ref, async () => {
4199
+ const meta2 = await readBox2(ref, p);
4200
+ const m = p.machine(meta2.owner, meta2.name);
4201
+ await assertRoom(s.dir, (await stat3(m.overlay)).blocks * 512, `a backup of box ${shown(ref)}`, p);
4202
+ const copy = () => run(["cp", "--sparse=always", "--reflink=auto", m.overlay, s.disk], { timeoutMs: 6e5 });
4203
+ if (vmAlive(meta2) && !meta2.paused) {
4204
+ const fc = new FirecrackerClient(m.sock);
4205
+ try {
4206
+ await fc.pause();
4207
+ try {
4208
+ await copy();
4209
+ } finally {
4210
+ await resumeAfterCopy(fc, meta2, p);
4211
+ }
4212
+ } finally {
4213
+ await fc.close();
4214
+ }
4215
+ } else {
4216
+ await copy();
4217
+ }
4218
+ const envText2 = existsSync7(m.env) ? await readFile7(m.env, "utf8") : null;
4219
+ return { meta: meta2, envText: envText2 };
4220
+ });
4221
+ const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
4222
+ await writeFile6(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
4223
+ return {
4224
+ id: req.id,
4225
+ sizeBytes,
4226
+ chunks,
4227
+ env: envText === null ? null : sealText(keys, envText, `env:${req.id}`),
4228
+ base: meta.base,
4229
+ ...meta.image !== void 0 ? { image: meta.image } : {},
4230
+ vcpu: meta.vcpu,
4231
+ memMib: meta.memMib
4232
+ };
4233
+ } catch (err) {
4234
+ await rm4(s.dir, { recursive: true, force: true });
4235
+ throw err;
4236
+ }
4237
+ }
4238
+ async function resumeAfterCopy(fc, meta, p) {
4239
+ try {
4240
+ await fc.resume();
4241
+ } catch {
4242
+ try {
4243
+ await fc.resume();
4244
+ } catch (err) {
4245
+ const why = err.message;
4246
+ if (!vmAlive(meta)) throw new KvboxError(`box ${shown(meta)} stopped while its disk was copied for the backup (${why}); kvbox start ${shown(meta)}`);
4247
+ const paused = { ...meta, paused: true };
4248
+ await writeMachineMeta(paused, p);
4249
+ recordState(paused, "standby", "backup", p);
4250
+ throw new KvboxError(`box ${shown(meta)} was paused for its backup and did not resume (${why}); kvbox resume ${shown(meta)}`);
4251
+ }
4252
+ }
4253
+ }
4254
+ var uploads = /* @__PURE__ */ new Map();
4255
+ async function uploadBackup(id, req, p = paths()) {
4256
+ checkId(id);
4257
+ const abort = new AbortController();
4258
+ uploads.get(id)?.abort();
4259
+ uploads.set(id, abort);
4260
+ try {
4261
+ return await uploadOnce(id, req, abort.signal, p);
4262
+ } finally {
4263
+ if (uploads.get(id) === abort) uploads.delete(id);
4264
+ }
4265
+ }
4266
+ async function uploadOnce(id, req, signal, p) {
4267
+ const s = p.backup(id);
4268
+ if (!existsSync7(s.chunks)) throw new NotFoundError(`backup ${id}`);
4269
+ const keys = backupKeys(req.key);
4270
+ const { chunks } = JSON.parse(await readFile7(s.chunks, "utf8"));
4271
+ const slotOf = /* @__PURE__ */ new Map();
4272
+ chunks.forEach((name, i) => {
4273
+ if (name !== null && !slotOf.has(name)) slotOf.set(name, i);
4274
+ });
4275
+ const work = Object.entries(req.urls).map(([name, url]) => {
4276
+ const index = slotOf.get(name);
4277
+ if (index === void 0) throw new KvboxError(`backup ${id} has no chunk ${name.slice(0, 12)}`);
4278
+ return { name, url, index };
4279
+ });
4280
+ const { size } = await stat3(s.disk);
4281
+ const fh = await open(s.disk, "r");
4282
+ let bytes = 0;
4283
+ const sizes = {};
4284
+ try {
4285
+ await pool(work, async ({ name, url, index }) => {
4286
+ const slot = Buffer.from(await readSlot(fh, Buffer.alloc(CHUNK_SIZE), index, size));
4287
+ const sealed = await sealChunk(keys, name, slot);
4288
+ await withTries(`upload of chunk ${index}`, async () => {
4289
+ const res = await fetch(url, { method: "PUT", body: sealed, signal: AbortSignal.any([signal, AbortSignal.timeout(CHUNK_TIMEOUT_MS)]) });
4290
+ if (!res.ok) throw new Error(`storage answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
4291
+ }, signal);
4292
+ bytes += sealed.length;
4293
+ sizes[name] = sealed.length;
4294
+ });
4295
+ } finally {
4296
+ await fh.close();
4297
+ }
4298
+ await rm4(s.dir, { recursive: true, force: true });
4299
+ return { chunks: work.length, bytes, sizes };
4300
+ }
4301
+ async function dropBackup(id, p = paths()) {
4302
+ checkId(id);
4303
+ uploads.get(id)?.abort();
4304
+ await rm4(p.backup(id).dir, { recursive: true, force: true });
4305
+ }
4306
+ async function clearStagedBackups(p = paths()) {
4307
+ await rm4(p.backups, { recursive: true, force: true });
4308
+ const prefix = basename2(p.machine("x", "x").restoring);
4309
+ for (const ref of await listMachineRefs(p)) {
4310
+ const dir = p.machine(ref.owner, ref.name).dir;
4311
+ for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm4(join2(dir, f), { force: true });
4312
+ }
4313
+ }
4314
+ async function downloadDisk(file, req) {
4315
+ const keys = backupKeys(req.key);
4316
+ const slots = chunkCount(req.sizeBytes);
4317
+ for (const c of req.chunks) {
4318
+ if (c.index >= slots) throw new KvboxError(`chunk ${c.index} is past the end of a ${req.sizeBytes}-byte disk`);
4319
+ if (!CHUNK_HASH_RE.test(c.hash)) throw new KvboxError(`chunk ${c.index}: not a chunk name`);
4320
+ }
4321
+ await writeFile6(file, "", { mode: 384 });
4322
+ const fh = await open(file, "r+");
4323
+ try {
4324
+ await fh.truncate(req.sizeBytes);
4325
+ await pool(req.chunks, async ({ index, hash, url }) => {
4326
+ const plain = await withTries(`download of chunk ${index}`, async () => {
4327
+ const res = await fetch(url, { signal: AbortSignal.timeout(CHUNK_TIMEOUT_MS) });
4328
+ if (!res.ok) throw new Error(`storage answered ${res.status}`);
4329
+ return Buffer.from(await res.arrayBuffer());
4330
+ });
4331
+ const slot = await openChunk(keys, hash, plain);
4332
+ const want = Math.min(CHUNK_SIZE, req.sizeBytes - index * CHUNK_SIZE);
4333
+ if (slot.length !== want) throw new KvboxError(`chunk ${index}: ${slot.length} bytes where the disk has room for ${want}`);
4334
+ await fh.write(slot, 0, slot.length, index * CHUNK_SIZE);
4335
+ });
4336
+ } finally {
4337
+ await fh.close();
4338
+ }
4339
+ }
4340
+ var restoring = /* @__PURE__ */ new Set();
4341
+ function restoreRunning(ref) {
4342
+ return restoring.has(refKey(ref));
4343
+ }
4344
+ async function restoreBackup(ref, req, p = paths()) {
4345
+ checkId(req.id);
4346
+ const k = refKey(ref);
4347
+ if (restoring.has(k)) throw new KvboxError(`a restore of box ${shown(ref)} is already running; wait for it to finish`);
4348
+ restoring.add(k);
4349
+ try {
4350
+ return await restoreOnce(ref, req, p);
4351
+ } finally {
4352
+ restoring.delete(k);
4353
+ }
4354
+ }
4355
+ async function restoreOnce(ref, req, p) {
4356
+ const meta = await readBox2(ref, p);
4357
+ if (!vmAlive(meta) && existsSync7(p.machine(ref.owner, ref.name).hibernateVmstate)) {
4358
+ 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`);
4359
+ }
4360
+ if (!existsSync7(imageFile(req.image, req.base, p))) {
4361
+ throw new KvboxError(`this backup stacks on ${imageLabel(req.image)} ${req.base}, which this host does not have`);
4362
+ }
4363
+ const keys = backupKeys(req.key);
4364
+ const m = p.machine(ref.owner, ref.name);
4365
+ const current = (await stat3(m.overlay)).size;
4366
+ if (req.sizeBytes > current) {
4367
+ const gb2 = (n) => `${Math.ceil(n / 1024 ** 3)}GB`;
4368
+ 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`);
4369
+ }
4370
+ const file = `${m.restoring}.${randomBytes4(4).toString("hex")}`;
4371
+ const envFile = `${file}.env`;
4372
+ try {
4373
+ let vars = null;
4374
+ if (req.env !== null) {
4375
+ await writeFile6(envFile, openText(keys, req.env, `env:${req.id}`), { mode: 384 });
4376
+ vars = await readBoxEnvFile(envFile);
4377
+ checkBoxEnv(vars);
4378
+ }
4379
+ await assertRoom(m.dir, req.chunks.length * CHUNK_SIZE, `a restore of box ${shown(ref)}`, p);
4380
+ await downloadDisk(file, req);
4381
+ return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
4382
+ } finally {
4383
+ await rm4(file, { force: true });
4384
+ await rm4(envFile, { force: true });
4385
+ }
4386
+ }
4387
+ async function pool(items, fn) {
4388
+ let next = 0;
4389
+ let failed;
4390
+ const worker = async () => {
4391
+ while (failed === void 0 && next < items.length) {
4392
+ const item = items[next++];
4393
+ try {
4394
+ await fn(item);
4395
+ } catch (err) {
4396
+ failed ??= err;
4397
+ }
4398
+ }
4399
+ };
4400
+ await Promise.all(Array.from({ length: Math.min(PARALLEL, items.length) }, worker));
4401
+ if (failed !== void 0) throw failed;
4402
+ }
4403
+ async function withTries(what, fn, signal) {
4404
+ let last;
4405
+ for (let i = 0; i < TRIES; i++) {
4406
+ if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
4407
+ try {
4408
+ return await fn();
4409
+ } catch (err) {
4410
+ if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
4411
+ last = err;
4412
+ await sleep2(250 * 2 ** i);
4413
+ }
4414
+ }
4415
+ throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
4416
+ }
4417
+
3983
4418
  // src/core/relay.ts
3984
- import { chmod as chmod3, mkdir as mkdir7, rm as rm4, writeFile as writeFile6 } from "node:fs/promises";
4419
+ import { chmod as chmod3, mkdir as mkdir8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
3985
4420
 
3986
4421
  // ../shared/src/relay.ts
3987
4422
  import { z as z7 } from "zod";
@@ -4015,16 +4450,16 @@ function decodeRelayJoin(text) {
4015
4450
  }
4016
4451
 
4017
4452
  // src/core/relay.ts
4018
- function relayConf(join2) {
4453
+ function relayConf(join3) {
4019
4454
  return [
4020
4455
  "# kvbox relay tunnel: made by `kvbox server relay`, installed by net-setup.sh. Do not edit.",
4021
4456
  "[Interface]",
4022
- `PrivateKey = ${join2.privateKey}`,
4023
- `Address = ${join2.tunnelIp}/32`,
4457
+ `PrivateKey = ${join3.privateKey}`,
4458
+ `Address = ${join3.tunnelIp}/32`,
4024
4459
  "",
4025
4460
  "[Peer]",
4026
- `PublicKey = ${join2.relayKey}`,
4027
- `Endpoint = ${join2.relay}`,
4461
+ `PublicKey = ${join3.relayKey}`,
4462
+ `Endpoint = ${join3.relay}`,
4028
4463
  // Only the relay's own tunnel address goes through the tunnel: the host keeps its normal internet
4029
4464
  // route, and the relay SNATs forwarded connections so their replies come back this way.
4030
4465
  `AllowedIPs = ${RELAY_TUNNEL_GATEWAY}/32`,
@@ -4034,22 +4469,22 @@ function relayConf(join2) {
4034
4469
  ].join("\n");
4035
4470
  }
4036
4471
  async function useRelay(joinString, p = paths()) {
4037
- const join2 = decodeRelayJoin(joinString);
4038
- if (!join2) throw new KvboxError("that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay");
4472
+ const join3 = decodeRelayJoin(joinString);
4473
+ if (!join3) throw new KvboxError("that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay");
4039
4474
  const cfg = await loadConfig(p);
4040
- if (cfg.relay && cfg.relay.name !== join2.name) {
4475
+ if (cfg.relay && cfg.relay.name !== join3.name) {
4041
4476
  throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox server relay off first`);
4042
4477
  }
4043
- if (cfg.relay && cfg.relay.publicIp !== join2.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {
4478
+ if (cfg.relay && cfg.relay.publicIp !== join3.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {
4044
4479
  throw new KvboxError(
4045
- `${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join2.publicIp}; run kvbox server leave first, then join again`
4480
+ `${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join3.publicIp}; run kvbox server leave first, then join again`
4046
4481
  );
4047
4482
  }
4048
- await mkdir7(p.relay, { recursive: true, mode: 448 });
4049
- await writeFile6(p.relayConf, relayConf(join2), { mode: 384 });
4483
+ await mkdir8(p.relay, { recursive: true, mode: 448 });
4484
+ await writeFile7(p.relayConf, relayConf(join3), { mode: 384 });
4050
4485
  await chmod3(p.relayConf, 384);
4051
4486
  await netSetup(cfg, ["relay", "up", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);
4052
- const relay = { name: join2.name, publicIp: join2.publicIp, tunnelIp: join2.tunnelIp, endpoint: join2.relay };
4487
+ const relay = { name: join3.name, publicIp: join3.publicIp, tunnelIp: join3.tunnelIp, endpoint: join3.relay };
4053
4488
  await saveConfig({ ...cfg, relay }, p);
4054
4489
  return relay;
4055
4490
  }
@@ -4061,19 +4496,19 @@ async function dropRelay(p = paths()) {
4061
4496
  throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox server leave first`);
4062
4497
  }
4063
4498
  await netSetup(cfg, ["relay", "down"]);
4064
- await rm4(p.relayConf, { force: true });
4499
+ await rm5(p.relayConf, { force: true });
4065
4500
  const { relay: _gone, ...rest } = cfg;
4066
4501
  await saveConfig(rest, p);
4067
4502
  return relay;
4068
4503
  }
4069
4504
 
4070
4505
  // src/core/idle.ts
4071
- import { readFile as readFile7 } from "node:fs/promises";
4506
+ import { readFile as readFile8 } from "node:fs/promises";
4072
4507
  var HIBERNATE_CONCURRENCY = 2;
4073
4508
  async function tapTraffic(id) {
4074
4509
  const dir = `/sys/class/net/${tapName(id)}/statistics`;
4075
4510
  try {
4076
- const [rx, tx] = await Promise.all([readFile7(`${dir}/rx_bytes`, "utf8"), readFile7(`${dir}/tx_bytes`, "utf8")]);
4511
+ const [rx, tx] = await Promise.all([readFile8(`${dir}/rx_bytes`, "utf8"), readFile8(`${dir}/tx_bytes`, "utf8")]);
4077
4512
  return Number(rx) + Number(tx);
4078
4513
  } catch {
4079
4514
  return null;
@@ -4086,7 +4521,7 @@ async function boxIdle(box, p) {
4086
4521
  async function hibernateIfRunning(box, p) {
4087
4522
  const ref = { owner: box.owner, name: box.name };
4088
4523
  return withBoxLock(ref, async () => {
4089
- if ((await getMachine(ref, p)).status !== "running") return false;
4524
+ if ((await getMachine(ref, p)).status !== "running" || restoreRunning(ref)) return false;
4090
4525
  await hibernateMachine(ref, p, "auto-hibernate");
4091
4526
  return true;
4092
4527
  });
@@ -4098,7 +4533,7 @@ function startIdleWatch(opts = {}) {
4098
4533
  const traffic = opts.traffic ?? tapTraffic;
4099
4534
  const guestIdle = opts.guestIdle ?? ((box) => boxIdle(box, p));
4100
4535
  const hibernate = opts.hibernate ?? ((box) => hibernateIfRunning(box, p));
4101
- const busy = opts.busy ?? ((box) => boxBusy(box));
4536
+ const busy = opts.busy ?? ((box) => boxBusy(box) || restoreRunning(box));
4102
4537
  const now = opts.now ?? Date.now;
4103
4538
  const log = opts.log ?? ((line) => console.log(line));
4104
4539
  const seen = /* @__PURE__ */ new Map();
@@ -4235,12 +4670,12 @@ function startRelayWatch(opts = {}) {
4235
4670
  }
4236
4671
 
4237
4672
  // src/listen.ts
4238
- import { readFile as readFile8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
4673
+ import { readFile as readFile9, rm as rm6, writeFile as writeFile8 } from "node:fs/promises";
4239
4674
  import { createServer as createHttpsServer } from "node:https";
4240
4675
  import { createAdaptorServer } from "@hono/node-server";
4241
4676
 
4242
4677
  // src/app.ts
4243
- import { Hono as Hono9 } from "hono";
4678
+ import { Hono as Hono10 } from "hono";
4244
4679
 
4245
4680
  // ../shared/src/version.ts
4246
4681
  import { createRequire } from "node:module";
@@ -4255,13 +4690,13 @@ function versionOf(srcFileUrl, injected) {
4255
4690
  }
4256
4691
 
4257
4692
  // src/version.ts
4258
- var VERSION = versionOf(import.meta.url, true ? "0.5.35" : void 0);
4693
+ var VERSION = versionOf(import.meta.url, true ? "0.5.37" : void 0);
4259
4694
 
4260
4695
  // src/caller.ts
4261
4696
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";
4262
4697
 
4263
4698
  // ../shared/src/names.ts
4264
- import { createHmac } from "node:crypto";
4699
+ import { createHmac as createHmac2 } from "node:crypto";
4265
4700
  var PROXY_ERROR_HEADER = "x-kvbox-proxy-error";
4266
4701
  var PROXIED_HEADER = "x-kvbox-proxied";
4267
4702
  var VISITOR_PATH_HEADER = "x-kvbox-path";
@@ -4273,7 +4708,7 @@ var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
4273
4708
  var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
4274
4709
  var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
4275
4710
  function edgeCredential(hostSecret) {
4276
- return createHmac("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
4711
+ return createHmac2("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
4277
4712
  }
4278
4713
 
4279
4714
  // src/caller.ts
@@ -4328,10 +4763,40 @@ function digest(secret) {
4328
4763
  return createHash2("sha256").update(secret).digest();
4329
4764
  }
4330
4765
 
4766
+ // src/routes/backups.ts
4767
+ import { Hono } from "hono";
4768
+ function backupMachineRoutes() {
4769
+ const r = new Hono();
4770
+ r.post("/:name/backup", async (c) => {
4771
+ const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));
4772
+ if (!body.success) throw new KvboxError("backup: expected {id, key}");
4773
+ return c.json(await stageBackup(parseRef(c.req.param("name"), c.get("owner")), body.data));
4774
+ });
4775
+ r.post("/:name/restore", async (c) => {
4776
+ const body = HostRestoreRequest.safeParse(await c.req.json().catch(() => ({})));
4777
+ if (!body.success) throw new KvboxError("restore: expected {id, key, sizeBytes, base, env, chunks}");
4778
+ return c.json(await restoreBackup(parseRef(c.req.param("name"), c.get("owner")), body.data));
4779
+ });
4780
+ return r;
4781
+ }
4782
+ function backupRoutes() {
4783
+ const r = new Hono();
4784
+ r.post("/:id/upload", async (c) => {
4785
+ const body = HostUploadRequest.safeParse(await c.req.json().catch(() => ({})));
4786
+ if (!body.success) throw new KvboxError("upload: expected {key, urls}");
4787
+ return c.json(await uploadBackup(c.req.param("id"), body.data));
4788
+ });
4789
+ r.delete("/:id", async (c) => {
4790
+ await dropBackup(c.req.param("id"));
4791
+ return c.body(null, 204);
4792
+ });
4793
+ return r;
4794
+ }
4795
+
4331
4796
  // src/routes/boxHttp.ts
4332
4797
  import { connect as connect2 } from "node:net";
4333
4798
  import { Readable } from "node:stream";
4334
- import { Hono } from "hono";
4799
+ import { Hono as Hono2 } from "hono";
4335
4800
  import { request as request3 } from "undici";
4336
4801
 
4337
4802
  // ../shared/src/httpHead.ts
@@ -4457,7 +4922,7 @@ function boxHeaders(incoming, target, upgrade = false) {
4457
4922
  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" } : {} } });
4458
4923
  var wants = (value) => value === "1";
4459
4924
  function boxHttpRoutes(wake = wakeBox) {
4460
- const r = new Hono();
4925
+ const r = new Hono2();
4461
4926
  r.all("/:name/http/:port", (c) => forward(c, wake));
4462
4927
  return r;
4463
4928
  }
@@ -4576,17 +5041,17 @@ ${lines.join("")}\r
4576
5041
  }
4577
5042
 
4578
5043
  // src/routes/capacity.ts
4579
- import { Hono as Hono2 } from "hono";
5044
+ import { Hono as Hono3 } from "hono";
4580
5045
  function capacityRoutes() {
4581
- const r = new Hono2();
5046
+ const r = new Hono3();
4582
5047
  r.get("/", async (c) => c.json(await capacity()));
4583
5048
  return r;
4584
5049
  }
4585
5050
 
4586
5051
  // src/routes/env.ts
4587
- import { Hono as Hono3 } from "hono";
5052
+ import { Hono as Hono4 } from "hono";
4588
5053
  function envRoutes() {
4589
- const r = new Hono3();
5054
+ const r = new Hono4();
4590
5055
  r.get("/", async (c) => c.json(await listEnvVersions(c.get("listScope"))));
4591
5056
  r.post("/", async (c) => {
4592
5057
  const body = HostEnvRequest.safeParse(await c.req.json().catch(() => ({})));
@@ -4597,7 +5062,7 @@ function envRoutes() {
4597
5062
  }
4598
5063
 
4599
5064
  // src/routes/machines.ts
4600
- import { Hono as Hono4 } from "hono";
5065
+ import { Hono as Hono5 } from "hono";
4601
5066
 
4602
5067
  // src/core/stats.ts
4603
5068
  var STATS_REPLY_MS = 3e3;
@@ -4631,7 +5096,7 @@ async function usageReport(scope, window, p = paths()) {
4631
5096
 
4632
5097
  // src/routes/machines.ts
4633
5098
  function machineRoutes() {
4634
- const r = new Hono4();
5099
+ const r = new Hono5();
4635
5100
  r.get("/", async (c) => c.json(await listMachines(c.get("listScope"))));
4636
5101
  r.post("/", async (c) => {
4637
5102
  const body = CreateMachineRequest.parse(await c.req.json().catch(() => ({})));
@@ -4729,9 +5194,9 @@ function machineRoutes() {
4729
5194
  }
4730
5195
 
4731
5196
  // src/routes/snapshots.ts
4732
- import { Hono as Hono5 } from "hono";
5197
+ import { Hono as Hono6 } from "hono";
4733
5198
  function snapshotRoutes() {
4734
- const r = new Hono5();
5199
+ const r = new Hono6();
4735
5200
  r.get("/", async (c) => c.json(await listSnapshots(c.get("listScope"))));
4736
5201
  r.post("/", async (c) => {
4737
5202
  const body = CreateSnapshotRequest.parse(await c.req.json());
@@ -4745,9 +5210,9 @@ function snapshotRoutes() {
4745
5210
  }
4746
5211
 
4747
5212
  // src/routes/ssh.ts
4748
- import { Hono as Hono6 } from "hono";
5213
+ import { Hono as Hono7 } from "hono";
4749
5214
  function sshRoutes(opts = {}) {
4750
- const r = new Hono6();
5215
+ const r = new Hono7();
4751
5216
  if (opts.controlPlane) {
4752
5217
  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));
4753
5218
  return r;
@@ -4762,10 +5227,10 @@ function sshRoutes(opts = {}) {
4762
5227
  }
4763
5228
 
4764
5229
  // src/routes/usage.ts
4765
- import { Hono as Hono7 } from "hono";
5230
+ import { Hono as Hono8 } from "hono";
4766
5231
  var PULL_LIMIT = 1e3;
4767
5232
  function usageRoutes(opts = {}) {
4768
- const r = new Hono7();
5233
+ const r = new Hono8();
4769
5234
  r.get("/", async (c) => {
4770
5235
  let window;
4771
5236
  try {
@@ -4798,9 +5263,9 @@ function whole(value, name) {
4798
5263
  }
4799
5264
 
4800
5265
  // src/routes/volumes.ts
4801
- import { Hono as Hono8 } from "hono";
5266
+ import { Hono as Hono9 } from "hono";
4802
5267
  function volumeRoutes() {
4803
- const r = new Hono8();
5268
+ const r = new Hono9();
4804
5269
  r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
4805
5270
  r.post("/", async (c) => {
4806
5271
  const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
@@ -4826,7 +5291,7 @@ function volumeRoutes() {
4826
5291
 
4827
5292
  // src/app.ts
4828
5293
  function createApp(opts = {}) {
4829
- const app = new Hono9();
5294
+ const app = new Hono10();
4830
5295
  app.use(resolveCaller(opts));
4831
5296
  app.get("/health", async (c) => {
4832
5297
  const cfg = await loadConfig();
@@ -4843,6 +5308,10 @@ function createApp(opts = {}) {
4843
5308
  });
4844
5309
  });
4845
5310
  if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
5311
+ if (opts.controlPlane) {
5312
+ app.route("/machines", backupMachineRoutes());
5313
+ app.route("/backups", backupRoutes());
5314
+ }
4846
5315
  app.route("/machines", machineRoutes());
4847
5316
  app.route("/snapshots", snapshotRoutes());
4848
5317
  app.route("/volumes", volumeRoutes());
@@ -4870,19 +5339,19 @@ async function listen(opts = {}) {
4870
5339
  if (Buffer.byteLength(socketPath) > 100) {
4871
5340
  throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
4872
5341
  }
4873
- await rm5(socketPath, { force: true });
5342
+ await rm6(socketPath, { force: true });
4874
5343
  const server = createAdaptorServer({ fetch: createApp().fetch });
4875
5344
  await new Promise((resolve, reject) => {
4876
5345
  server.once("error", reject);
4877
5346
  server.listen(socketPath, () => resolve());
4878
5347
  });
4879
- await writeFile7(p.serverPid, `${process.pid}
5348
+ await writeFile8(p.serverPid, `${process.pid}
4880
5349
  `);
4881
5350
  let https;
4882
5351
  let httpsServer;
4883
5352
  const cp = cfg.controlPlane;
4884
5353
  if (cp) {
4885
- const [key, cert] = await Promise.all([readFile8(p.tlsKey), readFile8(p.tlsCert)]).catch((err) => {
5354
+ const [key, cert] = await Promise.all([readFile9(p.tlsKey), readFile9(p.tlsCert)]).catch((err) => {
4886
5355
  throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
4887
5356
  });
4888
5357
  httpsServer = createAdaptorServer({
@@ -4897,8 +5366,8 @@ async function listen(opts = {}) {
4897
5366
  httpsServer.listen(port, "0.0.0.0", () => resolve());
4898
5367
  }).catch(async (err) => {
4899
5368
  server.close();
4900
- await rm5(socketPath, { force: true });
4901
- await rm5(p.serverPid, { force: true });
5369
+ await rm6(socketPath, { force: true });
5370
+ await rm6(p.serverPid, { force: true });
4902
5371
  throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
4903
5372
  });
4904
5373
  const bound = httpsServer.address().port;
@@ -4909,15 +5378,15 @@ async function listen(opts = {}) {
4909
5378
  new Promise((resolve) => server.close(() => resolve())),
4910
5379
  httpsServer ? new Promise((resolve) => httpsServer.close(() => resolve())) : void 0
4911
5380
  ]);
4912
- await rm5(socketPath, { force: true });
4913
- await rm5(p.serverPid, { force: true });
5381
+ await rm6(socketPath, { force: true });
5382
+ await rm6(p.serverPid, { force: true });
4914
5383
  };
4915
5384
  const shutdown2 = async () => {
4916
5385
  server.close();
4917
5386
  httpsServer?.close();
4918
5387
  await stopRecovery();
4919
- await rm5(socketPath, { force: true });
4920
- await rm5(p.serverPid, { force: true });
5388
+ await rm6(socketPath, { force: true });
5389
+ await rm6(p.serverPid, { force: true });
4921
5390
  process.exit(0);
4922
5391
  };
4923
5392
  process.once("SIGINT", () => void shutdown2());
@@ -4930,6 +5399,7 @@ var program = new Command("kvbox-server").description("kvbox host daemon: owns F
4930
5399
  program.command("start", { isDefault: true }).description("serve the API on the local Unix socket (foreground)").option("--socket <path>", "socket to listen on (default: $KVBOX_HOME/server.sock)").action(async (opts) => {
4931
5400
  await requireKvm();
4932
5401
  const settled = await settleDeadBoxes(paths());
5402
+ await clearStagedBackups(paths()).catch((err) => console.error(`warning: ${err.message}`));
4933
5403
  const { socketPath, https } = await listen(opts.socket ? { socketPath: opts.socket } : {});
4934
5404
  console.log(`kvbox-server ${VERSION} listening on ${socketPath} (pid ${process.pid})`);
4935
5405
  if (https) {