@kvbox/server 0.6.0 → 0.6.1

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.
@@ -135,7 +135,9 @@ function paths(home = kvboxHome()) {
135
135
  dir,
136
136
  meta: join(dir, "meta.json"),
137
137
  /** The volume itself: a sparse ext4 the guest sees as a whole disk. */
138
- disk: join(dir, "disk.ext4")
138
+ disk: join(dir, "disk.ext4"),
139
+ /** A restore's disk while it downloads (a backup's chunks), renamed over `disk` once complete. */
140
+ restoring: join(dir, "disk.ext4.restore")
139
141
  };
140
142
  },
141
143
  /** Each owner's environment variables as the control plane last sent them (#88): env/<owner>.json, mode 600. */
@@ -579,6 +581,12 @@ function openDb(p = paths()) {
579
581
  handles.set(p.db, db);
580
582
  return db;
581
583
  }
584
+ function closeDb(p = paths()) {
585
+ const db = handles.get(p.db);
586
+ if (db === void 0) return;
587
+ db.close();
588
+ handles.delete(p.db);
589
+ }
582
590
  function migrate(db) {
583
591
  db.exec("create table if not exists schema_version (version integer not null)");
584
592
  const row = db.prepare("select version from schema_version").get();
@@ -597,6 +605,22 @@ function migrate(db) {
597
605
  }
598
606
  }
599
607
  }
608
+ function renameLedgerRealm(from, to, p = paths()) {
609
+ const db = openDb(p);
610
+ let rows = 0;
611
+ db.exec("begin");
612
+ try {
613
+ for (const table of ["usage_events", "volume_events"]) {
614
+ const res = db.prepare(`update ${table} set owner = substr(owner, 1, length(owner) - length(?)) || ? where substr(owner, -length(?)) = ?`).run(`@${from}`, `@${to}`, `@${from}`, `@${from}`);
615
+ rows += Number(res.changes);
616
+ }
617
+ db.exec("commit");
618
+ } catch (err) {
619
+ db.exec("rollback");
620
+ throw err;
621
+ }
622
+ return rows;
623
+ }
600
624
  var LIVE_STATES = ["running", "standby"];
601
625
  function fromRaw(r) {
602
626
  return { boxId: r.box_id, owner: r.owner, name: r.name, at: r.at, state: r.state, vcpu: r.vcpu, memMib: r.mem_mib, diskGib: r.disk_gib, by: r.by };
@@ -1079,6 +1103,7 @@ var WakeHookCallSchema = z4.object({
1079
1103
  reason: z4.string().optional()
1080
1104
  });
1081
1105
  var BACKUP_STATUSES = ["running", "ready", "failed"];
1106
+ var BACKUP_KINDS = ["box", "volume"];
1082
1107
  var BackupSchema = z4.object({
1083
1108
  id: z4.string(),
1084
1109
  owner: z4.string(),
@@ -1126,6 +1151,31 @@ var HostRestoreRequest = z4.object({
1126
1151
  /** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */
1127
1152
  pin: z4.string().optional()
1128
1153
  });
1154
+ var VolumeBackupSchema = z4.object({
1155
+ id: z4.string(),
1156
+ owner: z4.string(),
1157
+ volume: z4.string(),
1158
+ status: z4.enum(BACKUP_STATUSES),
1159
+ /** Why it failed; null otherwise. */
1160
+ error: z4.string().nullable(),
1161
+ /** The volume's size when taken. */
1162
+ diskBytes: z4.number().int().nullable(),
1163
+ /** What it holds: the slots that are not all zeros. */
1164
+ dataBytes: z4.number().int().nullable(),
1165
+ /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
1166
+ uploadedBytes: z4.number().int().nullable(),
1167
+ createdBy: z4.string().nullable(),
1168
+ createdAt: z4.string(),
1169
+ finishedAt: z4.string().nullable()
1170
+ });
1171
+ var HostVolumeBackupManifestSchema = z4.object({ id: z4.string(), sizeBytes: z4.number().int(), chunks: z4.array(z4.string().nullable()) });
1172
+ var HostVolumeRestoreRequest = z4.object({
1173
+ id: z4.string(),
1174
+ key: z4.string(),
1175
+ sizeBytes: z4.number().int().positive(),
1176
+ chunks: z4.array(z4.object({ index: z4.number().int().nonnegative(), hash: z4.string(), url: z4.string() })),
1177
+ pin: z4.string().optional()
1178
+ });
1129
1179
  var BACKUP_STORE_BUCKET = "kvbox-backups";
1130
1180
  var BACKUP_STORE_REGION = "kvbox";
1131
1181
  var BackupStoreSetupRequest = z4.object({ path: z4.string().min(1), force: z4.boolean().optional(), newStore: z4.boolean().optional() });
@@ -1160,7 +1210,38 @@ var CloudBackupStoreSchema = z4.object({
1160
1210
  freeBytes: z4.number().int().nullable(),
1161
1211
  /** Ready backups kept here, and what their chunks take (encrypted, compressed). */
1162
1212
  backups: z4.number().int(),
1163
- storedBytes: z4.number().int()
1213
+ storedBytes: z4.number().int(),
1214
+ /** How many boxes have a ready backup here (a box and an earlier one of the same name count once), and how many volumes (#168). */
1215
+ boxes: z4.number().int(),
1216
+ volumes: z4.number().int(),
1217
+ /** When the newest ready backup kept here finished; null when it keeps none. */
1218
+ lastBackupAt: z4.string().nullable()
1219
+ });
1220
+ var StoredItemSchema = z4.object({
1221
+ kind: z4.enum(BACKUP_KINDS),
1222
+ owner: z4.string(),
1223
+ name: z4.string(),
1224
+ /** The host the box (or volume) is on now; null when it is gone (its backups stay). */
1225
+ host: z4.string().nullable(),
1226
+ /** It is on the store's own host: losing that host loses it and its backups together. */
1227
+ sameHost: z4.boolean(),
1228
+ /** Ready backups kept here, and what they added to the store together (encrypted, compressed). */
1229
+ backups: z4.number().int(),
1230
+ uploadedBytes: z4.number().int(),
1231
+ /** The newest backup sent here, whatever became of it. */
1232
+ latest: z4.object({ id: z4.string(), status: z4.enum(BACKUP_STATUSES), error: z4.string().nullable(), createdAt: z4.string() })
1233
+ });
1234
+ var FailedBackupSchema = z4.object({
1235
+ id: z4.string(),
1236
+ owner: z4.string(),
1237
+ /** What it was a backup of: a box or a volume (#168), and its name. */
1238
+ kind: z4.enum(BACKUP_KINDS),
1239
+ name: z4.string(),
1240
+ error: z4.string().nullable(),
1241
+ /** The host that took it, and the host of the store it was going to; null when gone, or when it failed before a store was picked. */
1242
+ host: z4.string().nullable(),
1243
+ store: z4.string().nullable(),
1244
+ createdAt: z4.string()
1164
1245
  });
1165
1246
  var MachineSchema = z4.object({
1166
1247
  /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
@@ -3038,6 +3119,7 @@ import { link, mkdir as mkdir5, readdir as readdir5, rename as rename5, rm as rm
3038
3119
 
3039
3120
  // src/core/firecracker.ts
3040
3121
  import { Agent, request as request2 } from "undici";
3122
+ var syncFallbackLogged = false;
3041
3123
  var FirecrackerClient = class {
3042
3124
  constructor(socketPath) {
3043
3125
  this.socketPath = socketPath;
@@ -3063,15 +3145,35 @@ var FirecrackerClient = class {
3063
3145
  }
3064
3146
  /** /dev/vda: the shared base image, read-only. Firecracker adds `root=/dev/vda ro` to the boot args to match. */
3065
3147
  rootDrive(pathOnHost) {
3066
- return this.drive("rootfs", pathOnHost, { root: true, readOnly: true });
3148
+ return this.drive("rootfs", pathOnHost, { root: true, readOnly: true, engine: "Sync" });
3067
3149
  }
3068
3150
  /** The box's own writable disk, /dev/vdb: the guest stacks it on the base as an overlay. */
3069
3151
  overlayDrive(pathOnHost) {
3070
- return this.drive("overlay", pathOnHost, { root: false, readOnly: false });
3152
+ return this.writableDrive("overlay", pathOnHost);
3071
3153
  }
3072
3154
  /** A volume (#52): /dev/vdc and up, in the order they are added; the guest mounts it by label. */
3073
3155
  volumeDrive(id, pathOnHost) {
3074
- return this.drive(id, pathOnHost, { root: false, readOnly: false });
3156
+ return this.writableDrive(id, pathOnHost);
3157
+ }
3158
+ /**
3159
+ * A drive the guest writes to gets the Async engine (io_uring, #175): with Sync, Firecracker's one
3160
+ * VMM thread sits in the write or the fsync and the box's network waits behind it, seconds under a
3161
+ * heavy write. The base image stays on Sync, which is the faster of the two for reads the host has
3162
+ * cached. A host that cannot do Async (kernel before 5.10.51, io_uring turned off) keeps Sync.
3163
+ * The engine is part of a snapshot: a box frozen on Sync wakes on Sync, until its next cold boot.
3164
+ */
3165
+ async writableDrive(id, pathOnHost) {
3166
+ const opts = { root: false, readOnly: false };
3167
+ try {
3168
+ return await this.drive(id, pathOnHost, { ...opts, engine: "Async" });
3169
+ } catch (asyncErr) {
3170
+ const done = await this.drive(id, pathOnHost, { ...opts, engine: "Sync" });
3171
+ if (!syncFallbackLogged) {
3172
+ syncFallbackLogged = true;
3173
+ log.warn(`this host cannot give box disks the Async engine, they keep Sync (heavy writes in a box can stall its network): ${asyncErr.message}`);
3174
+ }
3175
+ return done;
3176
+ }
3075
3177
  }
3076
3178
  drive(id, pathOnHost, opts) {
3077
3179
  return this.call("PUT", `/drives/${id}`, {
@@ -3082,7 +3184,8 @@ var FirecrackerClient = class {
3082
3184
  // "Unsafe" (the default) acks guest flushes without doing anything, so the last journal
3083
3185
  // commit of a clean shutdown can be lost when the guest resets and Firecracker exits.
3084
3186
  // Writeback makes a guest flush a real fsync; a box's writes must survive `kvbox stop`.
3085
- cache_type: "Writeback"
3187
+ cache_type: "Writeback",
3188
+ io_engine: opts.engine
3086
3189
  });
3087
3190
  }
3088
3191
  /**
@@ -4391,6 +4494,34 @@ async function resizeVolume(volume, sizeGib, p = paths()) {
4391
4494
  return { ...grown, attachedTo: holder };
4392
4495
  });
4393
4496
  }
4497
+ async function replaceVolumeDisk(volume, file, p = paths()) {
4498
+ const grow = async () => {
4499
+ const meta = await readVolume(volume, p);
4500
+ if (meta.sizeGib * 1024 ** 3 > statSync2(file).size) await growDisk(file, meta.sizeGib);
4501
+ };
4502
+ await grow();
4503
+ const swap = async () => {
4504
+ await grow();
4505
+ await rename6(file, p.volume(volume.owner, volume.name).disk);
4506
+ };
4507
+ const holder = await attachedBox(volume, p);
4508
+ if (holder === null) {
4509
+ await withHostLock("volumes", async () => {
4510
+ const now = await attachedBox(volume, p);
4511
+ if (now !== null) throw new KvboxError(`volume ${shown(volume)} was just attached to box ${now}; try again`);
4512
+ await swap();
4513
+ });
4514
+ return getVolume(volume, p);
4515
+ }
4516
+ const box = { owner: volume.owner, name: holder };
4517
+ await withBoxLock(box, async () => {
4518
+ const meta = await readMeta(box, p);
4519
+ if (!meta.volumes?.includes(volume.name)) throw new KvboxError(`volume ${shown(volume)} was just detached from box ${holder}; try again`);
4520
+ assertNotHibernated(meta, p);
4521
+ await applyAtNextBoot(meta, {}, "restore", await loadConfig(p), p, swap);
4522
+ });
4523
+ return getVolume(volume, p);
4524
+ }
4394
4525
  var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
4395
4526
  const meta = await readMeta(ref, p);
4396
4527
  const next = { ...meta };
@@ -4632,7 +4763,7 @@ async function bootRecovered(settled, p = paths()) {
4632
4763
  // src/core/backups.ts
4633
4764
  import { randomBytes as randomBytes5 } from "node:crypto";
4634
4765
  import { existsSync as existsSync8 } from "node:fs";
4635
- 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";
4766
+ import { mkdir as mkdir7, open, readdir as readdir6, readFile as readFile7, rm as rm6, stat as stat4, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
4636
4767
  import { basename as basename2, join as join3 } from "node:path";
4637
4768
  import { setTimeout as sleep3 } from "node:timers/promises";
4638
4769
 
@@ -4713,6 +4844,26 @@ function chunkCount(bytes) {
4713
4844
  return Math.ceil(bytes / CHUNK_SIZE);
4714
4845
  }
4715
4846
 
4847
+ // src/core/clone.ts
4848
+ import { rm as rm5 } from "node:fs/promises";
4849
+ var CLONE_TIMEOUT_MS = 6e5;
4850
+ async function cloneDisk(from, to, timeoutMs = CLONE_TIMEOUT_MS) {
4851
+ const started = Date.now();
4852
+ try {
4853
+ await run(["cp", "--reflink=always", from, to], { timeoutMs });
4854
+ } catch (err) {
4855
+ await rm5(to, { force: true });
4856
+ if (Date.now() - started >= timeoutMs) {
4857
+ throw new KvboxError(`the instant copy of the disk took more than ${Math.round(timeoutMs / 1e3)} s and was stopped; the box was paused for that long. Try again; if it keeps happening, the host's operator should look at its disk`);
4858
+ }
4859
+ const why = err.message;
4860
+ if (/failed to clone|not supported|cross-device|Invalid cross/i.test(why)) {
4861
+ throw new KvboxError("this host cannot take backups: its disk cannot make an instant copy of a box's disk (kvbox hosts keep their boxes on XFS); the host's operator has to move it to XFS");
4862
+ }
4863
+ throw err;
4864
+ }
4865
+ }
4866
+
4716
4867
  // src/core/storeFetch.ts
4717
4868
  import { Agent as Agent2, buildConnector, fetch as pinnedFetch } from "undici";
4718
4869
  var dispatchers = /* @__PURE__ */ new Map();
@@ -4804,29 +4955,14 @@ async function stageBackup(ref, req, p = paths()) {
4804
4955
  checkId(req.id);
4805
4956
  const keys = backupKeys(req.key);
4806
4957
  const s = p.backup(req.id);
4807
- await rm5(s.dir, { recursive: true, force: true });
4958
+ await rm6(s.dir, { recursive: true, force: true });
4808
4959
  await mkdir7(s.dir, { recursive: true, mode: 448 });
4809
4960
  try {
4810
4961
  const { meta, envText } = await withBoxLock(ref, async () => {
4811
4962
  const meta2 = await readBox2(ref, p);
4812
4963
  const m = p.machine(meta2.owner, meta2.name);
4813
4964
  await assertRoom(s.dir, 0, `a backup of box ${shown(ref)}`, p);
4814
- const copy = () => run(["cp", "--sparse=always", "--reflink=auto", m.overlay, s.disk], { timeoutMs: 6e5 });
4815
- if (vmAlive(meta2) && !meta2.paused) {
4816
- const fc = new FirecrackerClient(m.sock);
4817
- try {
4818
- await fc.pause();
4819
- try {
4820
- await copy();
4821
- } finally {
4822
- await resumeAfterCopy(fc, meta2, p);
4823
- }
4824
- } finally {
4825
- await fc.close();
4826
- }
4827
- } else {
4828
- await copy();
4829
- }
4965
+ await frozenClone(meta2, m.overlay, s.disk, p);
4830
4966
  const envText2 = existsSync8(m.env) ? await readFile7(m.env, "utf8") : null;
4831
4967
  return { meta: meta2, envText: envText2 };
4832
4968
  });
@@ -4843,7 +4979,54 @@ async function stageBackup(ref, req, p = paths()) {
4843
4979
  memMib: meta.memMib
4844
4980
  };
4845
4981
  } catch (err) {
4846
- await rm5(s.dir, { recursive: true, force: true });
4982
+ await rm6(s.dir, { recursive: true, force: true });
4983
+ throw err;
4984
+ }
4985
+ }
4986
+ async function frozenClone(box, from, to, p) {
4987
+ if (!vmAlive(box) || box.paused) return cloneDisk(from, to);
4988
+ const fc = new FirecrackerClient(p.machine(box.owner, box.name).sock);
4989
+ try {
4990
+ await fc.pause();
4991
+ try {
4992
+ await cloneDisk(from, to);
4993
+ } finally {
4994
+ await resumeAfterCopy(fc, box, p);
4995
+ }
4996
+ } finally {
4997
+ await fc.close();
4998
+ }
4999
+ }
5000
+ async function stageVolumeBackup(ref, req, p = paths()) {
5001
+ checkId(req.id);
5002
+ const keys = backupKeys(req.key);
5003
+ await readVolume(ref, p);
5004
+ const from = p.volume(ref.owner, ref.name).disk;
5005
+ const s = p.backup(req.id);
5006
+ await rm6(s.dir, { recursive: true, force: true });
5007
+ await mkdir7(s.dir, { recursive: true, mode: 448 });
5008
+ try {
5009
+ await assertRoom(s.dir, 0, `a backup of volume ${shown(ref)}`, p);
5010
+ const holder = await attachedBox(ref, p);
5011
+ if (holder === null) {
5012
+ await withHostLock("volumes", async () => {
5013
+ const now = await attachedBox(ref, p);
5014
+ if (now !== null) throw new KvboxError(`volume ${shown(ref)} was just attached to box ${now}; try again`);
5015
+ await cloneDisk(from, s.disk);
5016
+ });
5017
+ } else {
5018
+ const box = { owner: ref.owner, name: holder };
5019
+ await withBoxLock(box, async () => {
5020
+ const meta = await readBox2(box, p);
5021
+ if (!meta.volumes?.includes(ref.name)) throw new KvboxError(`volume ${shown(ref)} was just detached from box ${holder}; try again`);
5022
+ await frozenClone(meta, from, s.disk, p);
5023
+ });
5024
+ }
5025
+ const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
5026
+ await writeFile7(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
5027
+ return { id: req.id, sizeBytes, chunks };
5028
+ } catch (err) {
5029
+ await rm6(s.dir, { recursive: true, force: true });
4847
5030
  throw err;
4848
5031
  }
4849
5032
  }
@@ -4908,20 +5091,25 @@ async function uploadOnce(id, req, signal, p) {
4908
5091
  } finally {
4909
5092
  await fh.close();
4910
5093
  }
4911
- await rm5(s.dir, { recursive: true, force: true });
5094
+ await rm6(s.dir, { recursive: true, force: true });
4912
5095
  return { chunks: work.length, bytes, sizes };
4913
5096
  }
4914
5097
  async function dropBackup(id, p = paths()) {
4915
5098
  checkId(id);
4916
5099
  uploads.get(id)?.abort();
4917
- await rm5(p.backup(id).dir, { recursive: true, force: true });
5100
+ await rm6(p.backup(id).dir, { recursive: true, force: true });
4918
5101
  }
4919
5102
  async function clearStagedBackups(p = paths()) {
4920
- await rm5(p.backups, { recursive: true, force: true });
5103
+ await rm6(p.backups, { recursive: true, force: true });
4921
5104
  const prefix = basename2(p.machine("x", "x").restoring);
4922
5105
  for (const ref of await listMachineRefs(p)) {
4923
5106
  const dir = p.machine(ref.owner, ref.name).dir;
4924
- for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm5(join3(dir, f), { force: true });
5107
+ for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm6(join3(dir, f), { force: true });
5108
+ }
5109
+ const volumePrefix = basename2(p.volume("x", "x").restoring);
5110
+ for (const ref of await listVolumeRefs(p)) {
5111
+ const dir = p.volume(ref.owner, ref.name).dir;
5112
+ for (const f of await readdir6(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await rm6(join3(dir, f), { force: true });
4925
5113
  }
4926
5114
  }
4927
5115
  async function downloadDisk(file, req, p = paths()) {
@@ -4952,8 +5140,9 @@ async function downloadDisk(file, req, p = paths()) {
4952
5140
  }
4953
5141
  }
4954
5142
  var restoring = /* @__PURE__ */ new Set();
5143
+ var holding = /* @__PURE__ */ new Map();
4955
5144
  function restoreRunning(ref) {
4956
- return restoring.has(refKey(ref));
5145
+ return restoring.has(refKey(ref)) || holding.has(refKey(ref));
4957
5146
  }
4958
5147
  async function restoreBackup(ref, req, p = paths()) {
4959
5148
  checkId(req.id);
@@ -4994,8 +5183,44 @@ async function restoreOnce(ref, req, p) {
4994
5183
  await downloadDisk(file, req, p);
4995
5184
  return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
4996
5185
  } finally {
4997
- await rm5(file, { force: true });
4998
- await rm5(envFile, { force: true });
5186
+ await rm6(file, { force: true });
5187
+ await rm6(envFile, { force: true });
5188
+ }
5189
+ }
5190
+ async function restoreVolumeBackup(ref, req, p = paths()) {
5191
+ checkId(req.id);
5192
+ const k = `volume:${refKey(ref)}`;
5193
+ if (restoring.has(k)) throw new KvboxError(`a restore of volume ${shown(ref)} is already running; wait for it to finish`);
5194
+ restoring.add(k);
5195
+ const v = p.volume(ref.owner, ref.name);
5196
+ const file = `${v.restoring}.${randomBytes5(4).toString("hex")}`;
5197
+ let held2 = null;
5198
+ try {
5199
+ const meta = await readVolume(ref, p);
5200
+ const holder = await attachedBox(ref, p);
5201
+ if (holder !== null) {
5202
+ held2 = refKey({ owner: ref.owner, name: holder });
5203
+ holding.set(held2, (holding.get(held2) ?? 0) + 1);
5204
+ const box = await readBox2({ owner: ref.owner, name: holder }, p);
5205
+ if (!vmAlive(box) && existsSync8(p.machine(box.owner, box.name).hibernateVmstate)) {
5206
+ throw new KvboxError(`volume ${shown(ref)} is attached to box ${shown(box)}, which is hibernated; its memory belongs to the disks it has: kvbox wake ${shown(box)} or kvbox stop ${shown(box)} first`);
5207
+ }
5208
+ }
5209
+ if (req.sizeBytes > meta.sizeGib * 1024 ** 3) {
5210
+ const gib = Math.ceil(req.sizeBytes / 1024 ** 3);
5211
+ throw new KvboxError(`this backup's volume was ${gib} GB and volume ${shown(ref)} is ${meta.sizeGib} GB: kvbox volume grow ${shown(ref)} ${gib} first`);
5212
+ }
5213
+ await assertRoom(v.dir, req.chunks.length * CHUNK_SIZE, `a restore of volume ${shown(ref)}`, p);
5214
+ await downloadDisk(file, req, p);
5215
+ return await replaceVolumeDisk(ref, file, p);
5216
+ } finally {
5217
+ restoring.delete(k);
5218
+ if (held2 !== null) {
5219
+ const n = (holding.get(held2) ?? 1) - 1;
5220
+ if (n > 0) holding.set(held2, n);
5221
+ else holding.delete(held2);
5222
+ }
5223
+ await rm6(file, { force: true });
4999
5224
  }
5000
5225
  }
5001
5226
  async function pool(items, fn) {
@@ -5030,7 +5255,7 @@ async function withTries(what, fn, signal) {
5030
5255
  }
5031
5256
 
5032
5257
  // src/core/relay.ts
5033
- import { access as access2, chmod as chmod4, mkdir as mkdir9, rm as rm6, writeFile as writeFile8 } from "node:fs/promises";
5258
+ import { access as access2, chmod as chmod4, mkdir as mkdir9, rm as rm7, writeFile as writeFile8 } from "node:fs/promises";
5034
5259
 
5035
5260
  // ../shared/src/relay.ts
5036
5261
  import { z as z7 } from "zod";
@@ -5212,6 +5437,19 @@ async function fetchCloudCa(p = paths()) {
5212
5437
  const publicKey = parseSshPublicKey(parsed.data.publicKey);
5213
5438
  return { controlPlane: cp.name, publicKey, fingerprint: sshKeyFingerprint(publicKey) };
5214
5439
  }
5440
+ async function fetchCloudName(p = paths()) {
5441
+ const cfg = await loadConfig(p);
5442
+ const cp = cfg.controlPlane;
5443
+ if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no name to ask for; give it: kvbox-server rename-realm <name>");
5444
+ const res = await request3(`${cp.url}/health`, { headersTimeout: 1e4, bodyTimeout: 1e4 }).catch((err) => {
5445
+ throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
5446
+ });
5447
+ const text = await res.body.text();
5448
+ if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(`${cp.url} answered ${res.statusCode}`);
5449
+ const name = jsonOrNull(text)?.name;
5450
+ if (typeof name !== "string" || !REALM_RE.test(name)) throw new KvboxError(`${cp.url} did not say its name; give it: kvbox-server rename-realm <name>`);
5451
+ return name;
5452
+ }
5215
5453
  async function leaveControlPlane(p = paths()) {
5216
5454
  const cfg = await loadConfig(p);
5217
5455
  const cp = cfg.controlPlane;
@@ -5296,7 +5534,7 @@ async function dropRelay(p = paths()) {
5296
5534
  throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
5297
5535
  }
5298
5536
  await netSetup(cfg, ["relay", "down"]);
5299
- await rm6(p.relayConf, { force: true });
5537
+ await rm7(p.relayConf, { force: true });
5300
5538
  const { relay: _gone, ...rest } = cfg;
5301
5539
  await saveConfig(rest, p);
5302
5540
  return relay;
@@ -5734,7 +5972,7 @@ function groupWithMember(gid, user, groupFile) {
5734
5972
  }
5735
5973
 
5736
5974
  // src/listen.ts
5737
- import { readFile as readFile12, rm as rm7, writeFile as writeFile10 } from "node:fs/promises";
5975
+ import { readFile as readFile12, rm as rm8, writeFile as writeFile10 } from "node:fs/promises";
5738
5976
  import { createServer as createHttpsServer } from "node:https";
5739
5977
  import { createAdaptorServer } from "@hono/node-server";
5740
5978
 
@@ -5771,7 +6009,7 @@ function versionOf(srcFileUrl, injected) {
5771
6009
  }
5772
6010
 
5773
6011
  // src/version.ts
5774
- var VERSION = versionOf(import.meta.url, true ? "0.6.0" : void 0);
6012
+ var VERSION = versionOf(import.meta.url, true ? "0.6.1" : void 0);
5775
6013
 
5776
6014
  // src/caller.ts
5777
6015
  import { createHash as createHash3, timingSafeEqual } from "node:crypto";
@@ -5889,6 +6127,20 @@ function backupMachineRoutes() {
5889
6127
  });
5890
6128
  return r;
5891
6129
  }
6130
+ function backupVolumeRoutes() {
6131
+ const r = new Hono();
6132
+ r.post("/:name/backup", async (c) => {
6133
+ const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));
6134
+ if (!body.success) throw new KvboxError("backup: expected {id, key}");
6135
+ return c.json(await stageVolumeBackup(parseRef(c.req.param("name"), c.get("owner")), body.data));
6136
+ });
6137
+ r.post("/:name/restore", async (c) => {
6138
+ const body = HostVolumeRestoreRequest.safeParse(await c.req.json().catch(() => ({})));
6139
+ if (!body.success) throw new KvboxError("restore: expected {id, key, sizeBytes, chunks}");
6140
+ return c.json(await restoreVolumeBackup(parseRef(c.req.param("name"), c.get("owner")), body.data));
6141
+ });
6142
+ return r;
6143
+ }
5892
6144
  function backupRoutes() {
5893
6145
  const r = new Hono();
5894
6146
  r.post("/:id/upload", async (c) => {
@@ -6468,6 +6720,7 @@ function createApp(opts = {}) {
6468
6720
  if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
6469
6721
  if (opts.controlPlane) {
6470
6722
  app.route("/machines", backupMachineRoutes());
6723
+ app.route("/volumes", backupVolumeRoutes());
6471
6724
  app.route("/backups", backupRoutes());
6472
6725
  }
6473
6726
  app.route("/machines", machineRoutes());
@@ -6499,7 +6752,7 @@ async function listen(opts = {}) {
6499
6752
  throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
6500
6753
  }
6501
6754
  if (socketPath === p.serverSock) await refuseSecondDaemon(p);
6502
- await rm7(socketPath, { force: true });
6755
+ await rm8(socketPath, { force: true });
6503
6756
  const server = createAdaptorServer({ fetch: createApp().fetch });
6504
6757
  await new Promise((resolve3, reject) => {
6505
6758
  server.once("error", reject);
@@ -6536,8 +6789,8 @@ async function listen(opts = {}) {
6536
6789
  httpsServer.listen(port, "0.0.0.0", () => resolve3());
6537
6790
  }).catch(async (err) => {
6538
6791
  server.close();
6539
- await rm7(socketPath, { force: true });
6540
- await rm7(p.serverPid, { force: true });
6792
+ await rm8(socketPath, { force: true });
6793
+ await rm8(p.serverPid, { force: true });
6541
6794
  throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
6542
6795
  });
6543
6796
  const bound = httpsServer.address().port;
@@ -6548,15 +6801,15 @@ async function listen(opts = {}) {
6548
6801
  new Promise((resolve3) => server.close(() => resolve3())),
6549
6802
  httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
6550
6803
  ]);
6551
- await rm7(socketPath, { force: true });
6552
- await rm7(p.serverPid, { force: true });
6804
+ await rm8(socketPath, { force: true });
6805
+ await rm8(p.serverPid, { force: true });
6553
6806
  };
6554
6807
  const shutdown2 = async () => {
6555
6808
  server.close();
6556
6809
  httpsServer?.close();
6557
6810
  await stopRecovery();
6558
- await rm7(socketPath, { force: true });
6559
- await rm7(p.serverPid, { force: true });
6811
+ await rm8(socketPath, { force: true });
6812
+ await rm8(p.serverPid, { force: true });
6560
6813
  process.exit(0);
6561
6814
  };
6562
6815
  process.once("SIGINT", () => void shutdown2());
@@ -6638,7 +6891,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
6638
6891
  });
6639
6892
 
6640
6893
  // src/program.ts
6641
- import { Command as Command13 } from "commander";
6894
+ import { Command as Command14 } from "commander";
6642
6895
 
6643
6896
  // src/commands/backup/index.ts
6644
6897
  import { Command as Command4 } from "commander";
@@ -6798,11 +7051,241 @@ var relayCommand = new Command9("relay").description("reach the internet through
6798
7051
  console.log(`this host is reachable at ${relay.publicIp}; kvbox-server join advertises it by default`);
6799
7052
  });
6800
7053
 
7054
+ // src/commands/rename-realm.ts
7055
+ import { Command as Command11 } from "commander";
7056
+
7057
+ // src/core/realm.ts
7058
+ import { lstat as lstat2, readFile as readFile14, readdir as readdir7, readlink, rename as rename7, rm as rm9, symlink as symlink2, writeFile as writeFile11 } from "node:fs/promises";
7059
+ import { z as z8 } from "zod";
7060
+ var esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7061
+ async function ownersIn(root, from, suffix = "") {
7062
+ const entries = await readdir7(root).catch((err) => {
7063
+ if (err.code === "ENOENT") return [];
7064
+ throw err;
7065
+ });
7066
+ const tail = `@${from}${suffix}`;
7067
+ return entries.filter((e) => e.endsWith(tail)).map((e) => e.slice(0, e.length - suffix.length));
7068
+ }
7069
+ async function namesIn2(dir) {
7070
+ return (await readdir7(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
7071
+ }
7072
+ async function plan(from, to, p) {
7073
+ if (!REALM_RE.test(to)) throw new KvboxError(`"${to}" cannot name a realm (letters, digits, '.', '-')`);
7074
+ if (from === to) throw new KvboxError(`this host's cloud boxes are already under ${to}`);
7075
+ const tail = new RegExp(`@${esc(from)}$`);
7076
+ const owner = (o) => o.replace(tail, `@${to}`);
7077
+ const source = (s) => s.replace(new RegExp(`^((?:[a-z]+:)?[^/@]+)@${esc(from)}/`), `$1@${to}/`);
7078
+ const caLine = (line) => isCaLine(line) ? line.replace(/principals="([^"]*)"/, (_, list) => `principals="${list.split(",").map(owner).join(",")}"`) : line;
7079
+ const out = { boxes: [], snapshots: [], volumes: [], envOwners: await ownersIn(p.env, from, ".json") };
7080
+ const clash = async (path, what) => {
7081
+ if (await lstat2(path).then(() => true, () => false)) throw new KvboxError(`${what} already exists under ${to} (${path}); nothing was changed`);
7082
+ };
7083
+ const read = async (file, schema, what) => {
7084
+ try {
7085
+ return schema.parse(JSON.parse(await readFile14(file, "utf8")));
7086
+ } catch (err) {
7087
+ throw new KvboxError(`${what} cannot be read (${file}: ${err.message}); nothing was changed`);
7088
+ }
7089
+ };
7090
+ for (const oldOwner of await ownersIn(p.machines, from)) {
7091
+ await clash(p.ownerMachines(owner(oldOwner)), `boxes of ${owner(oldOwner)}`);
7092
+ for (const name of await namesIn2(p.ownerMachines(oldOwner))) {
7093
+ const meta = await read(p.machine(oldOwner, name).meta, MachineMetaSchema, `box ${oldOwner}/${name}`);
7094
+ const status = statusOf({ ...meta, owner: oldOwner, name }, p);
7095
+ const sshKeys = meta.sshKeys?.map(caLine);
7096
+ const keysChanged = sshKeys !== void 0 && sshKeys.some((l, i) => l !== meta.sshKeys[i]);
7097
+ out.boxes.push({
7098
+ oldOwner,
7099
+ name,
7100
+ status,
7101
+ meta: {
7102
+ ...meta,
7103
+ owner: owner(meta.owner),
7104
+ source: source(meta.source),
7105
+ ...sshKeys !== void 0 ? { sshKeys } : {},
7106
+ // A stopped box reads its lines at boot; any other guest still holds the old ones.
7107
+ ...keysChanged ? { sshKeysStale: status === "stopped" ? void 0 : true } : {},
7108
+ ...meta.links !== void 0 ? { links: meta.links.map((l) => ({ ...l, owner: owner(l.owner) })) } : {}
7109
+ }
7110
+ });
7111
+ }
7112
+ }
7113
+ for (const oldOwner of await ownersIn(p.snapshots, from)) {
7114
+ await clash(p.ownerSnapshots(owner(oldOwner)), `snapshots of ${owner(oldOwner)}`);
7115
+ for (const name of (await namesIn2(p.ownerSnapshots(oldOwner))).filter((n) => !n.startsWith("."))) {
7116
+ const meta = await read(p.snapshot(oldOwner, name).meta, SnapshotMetaSchema, `snapshot ${oldOwner}/${name}`);
7117
+ out.snapshots.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner), source: source(meta.source) } });
7118
+ }
7119
+ }
7120
+ for (const oldOwner of await ownersIn(p.volumes, from)) {
7121
+ await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);
7122
+ for (const name of await namesIn2(p.ownerVolumes(oldOwner))) {
7123
+ const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z8.string().optional() }), `volume ${oldOwner}/${name}`);
7124
+ out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });
7125
+ }
7126
+ }
7127
+ for (const oldOwner of out.envOwners) await clash(p.ownerEnv(owner(oldOwner)), `the variables of ${owner(oldOwner)}`);
7128
+ return out;
7129
+ }
7130
+ async function countRealm(from, to, p = paths()) {
7131
+ const planned = await plan(from, to, p);
7132
+ return { boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length };
7133
+ }
7134
+ async function writeJson(file, value) {
7135
+ const tmp = `${file}.tmp`;
7136
+ await writeFile11(tmp, JSON.stringify(value, null, 2) + "\n");
7137
+ await rename7(tmp, file);
7138
+ }
7139
+ async function move(entries, metaOf, ownerDir, owners, to) {
7140
+ for (const e of entries) await writeJson(metaOf(e.oldOwner, e.name), e.meta);
7141
+ for (const o of owners) await rename7(ownerDir(o), ownerDir(to(o)));
7142
+ }
7143
+ async function renameRealm(from, to, p = paths()) {
7144
+ const planned = await plan(from, to, p);
7145
+ const tail = new RegExp(`@${esc(from)}$`);
7146
+ const owner = (o) => o.replace(tail, `@${to}`);
7147
+ await move(planned.volumes, (o, n) => p.volume(o, n).meta, p.ownerVolumes, await ownersIn(p.volumes, from), owner);
7148
+ await move(planned.snapshots, (o, n) => p.snapshot(o, n).meta, p.ownerSnapshots, await ownersIn(p.snapshots, from), owner);
7149
+ await move(planned.boxes, (o, n) => p.machine(o, n).meta, p.ownerMachines, await ownersIn(p.machines, from), owner);
7150
+ for (const box of planned.boxes) {
7151
+ const m = p.machine(box.meta.owner, box.name);
7152
+ for (const volume of box.meta.volumes ?? []) {
7153
+ const link3 = m.volumeDrive(volume);
7154
+ const target = await readlink(link3).catch(() => null);
7155
+ if (target !== p.volume(box.oldOwner, volume).disk) continue;
7156
+ await rm9(link3, { force: true });
7157
+ await symlink2(p.volume(box.meta.owner, volume).disk, link3);
7158
+ }
7159
+ }
7160
+ for (const o of planned.envOwners) await rename7(p.ownerEnv(o), p.ownerEnv(owner(o)));
7161
+ renameLedgerRealm(from, to, p);
7162
+ closeDb(p);
7163
+ const cfg = await loadConfig(p);
7164
+ if (cfg.controlPlane?.name === from) await saveConfig({ ...cfg, controlPlane: { ...cfg.controlPlane, name: to } }, p);
7165
+ const report2 = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [] };
7166
+ for (const box of planned.boxes) {
7167
+ const { meta, status } = box;
7168
+ if (!(meta.sshKeys ?? []).some(isCaLine)) continue;
7169
+ const key = `${meta.owner}/${meta.name}`;
7170
+ if (status === "stopped") report2.keysPending.push({ box: key, when: "start" });
7171
+ else if (status === "hibernated") report2.keysPending.push({ box: key, when: "wake" });
7172
+ else if (status === "standby") report2.keysPending.push({ box: key, when: "resume" });
7173
+ else if (!meta.sshKeysStale) report2.keysUpdated.push(key);
7174
+ else {
7175
+ const why = await pushAuthorizedKeys(meta, p.machine(meta.owner, meta.name).vsock, p);
7176
+ if (why === void 0) {
7177
+ await writeJson(p.machine(meta.owner, meta.name).meta, { ...meta, sshKeysStale: void 0 });
7178
+ report2.keysUpdated.push(key);
7179
+ } else report2.keysPending.push({ box: key, when: "later", why });
7180
+ }
7181
+ }
7182
+ return report2;
7183
+ }
7184
+
7185
+ // src/commands/trust-ca.ts
7186
+ import { Command as Command10 } from "commander";
7187
+ var trustCaCommand = new Command10("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) => {
7188
+ 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");
7189
+ if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
7190
+ const client = new SocketClient(paths().serverSock);
7191
+ try {
7192
+ let key = publicKey;
7193
+ if (key === void 0) {
7194
+ const ca = await client.cloudCa();
7195
+ console.log(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);
7196
+ if (!await confirm("make every cloud box on this host trust it (in place of the CA it trusts now)?", opts.yes ?? false)) {
7197
+ throw new KvboxError("cancelled", 130);
7198
+ }
7199
+ key = ca.publicKey;
7200
+ }
7201
+ const report2 = await client.trustCa({ publicKey: key });
7202
+ if (opts.json) console.log(JSON.stringify(report2, null, 2));
7203
+ else describeReport(report2);
7204
+ } finally {
7205
+ await client.close();
7206
+ }
7207
+ });
7208
+ async function confirm(question, yes) {
7209
+ if (yes) return true;
7210
+ if (!process.stdin.isTTY) {
7211
+ console.error("refusing without -y when stdin is not a terminal");
7212
+ return false;
7213
+ }
7214
+ const { createInterface } = await import("node:readline/promises");
7215
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
7216
+ try {
7217
+ const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
7218
+ return answer === "y" || answer === "yes";
7219
+ } finally {
7220
+ rl.close();
7221
+ }
7222
+ }
7223
+ var WHEN = {
7224
+ start: "is stopped: it trusts the CA from its next start",
7225
+ wake: "is hibernated: it trusts the CA from its next wake",
7226
+ resume: "is in standby: it trusts the CA from its next resume",
7227
+ later: "is running but could not take it now; it trusts the CA from its next stop and start"
7228
+ };
7229
+ function describeReport(report2) {
7230
+ console.log(`CA ${report2.fingerprint}`);
7231
+ for (const box of report2.updated) console.log(`box ${box} now trusts the CA`);
7232
+ for (const p of report2.pending) console.log(`box ${p.box} ${WHEN[p.when]}${p.why ? ` (${p.why})` : ""}`);
7233
+ for (const f of report2.failed) console.error(`box ${f.box}: ${f.error}`);
7234
+ const parts = [`${report2.updated.length} box(es) updated now`, `${report2.pending.length} pending`, `${report2.failed.length} failed`];
7235
+ const skipped = report2.skipped ?? [];
7236
+ if (skipped.length > 0) parts.push(`${skipped.length} cloud box(es) without a CA line untouched (managed services: no certificate opens them)`);
7237
+ if (report2.local > 0) parts.push(`${report2.local} local box(es) untouched (they trust this host's key only)`);
7238
+ console.log(parts.join(", "));
7239
+ }
7240
+
7241
+ // src/commands/rename-realm.ts
7242
+ var renameRealmCommand = new Command11("rename-realm").description("move this host's cloud boxes to the control plane's new name (after KVBOX_CLOUD_NAME changed there)").argument("[name]", "the new name; without it the control plane is asked").option("--from <old>", "the name the boxes are under now (default: the one this host joined under)").option("-y, --yes", "do not ask for confirmation").option("--json", "print the report as JSON").action(async (name, opts) => {
7243
+ const p = paths();
7244
+ const cp = (await loadConfig(p)).controlPlane;
7245
+ const from = opts.from ?? cp?.name;
7246
+ if (from === void 0) throw new KvboxError("this host has not joined a control plane; say which name the boxes are under: --from <old>");
7247
+ const to = name ?? await fetchCloudName(p);
7248
+ if (from === to) {
7249
+ if (!opts.json) console.log(`nothing to do: the control plane is called ${to} and this host's boxes are already under that name`);
7250
+ else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [] }, null, 2));
7251
+ return;
7252
+ }
7253
+ const count = await countRealm(from, to, p);
7254
+ if (!opts.json) {
7255
+ console.log(`${name === void 0 ? `the control plane is now called ${to}; ` : ""}this host has ${count.boxes} box(es), ${count.snapshots} snapshot(s) and ${count.volumes} volume(s) under ${from}`);
7256
+ }
7257
+ if (!await confirm(`move them to ${to}? (kvbox-server restarts; boxes keep running, a backup in progress is lost)`, opts.yes ?? false)) {
7258
+ throw new KvboxError("cancelled", 130);
7259
+ }
7260
+ const pid = await daemonPid(p);
7261
+ if (pid !== null) await stopDaemon(pid);
7262
+ let report2;
7263
+ try {
7264
+ report2 = await renameRealm(from, to, p);
7265
+ } finally {
7266
+ if (pid !== null) await startDetached(p);
7267
+ }
7268
+ if (opts.json) console.log(JSON.stringify(report2, null, 2));
7269
+ else describe(report2, pid !== null);
7270
+ });
7271
+ var WHEN2 = {
7272
+ start: "is stopped: it accepts them from its next start",
7273
+ wake: "is hibernated: it accepts them from its next wake",
7274
+ resume: "is in standby: it accepts them from its next resume",
7275
+ later: "is running but could not take the change now; it accepts them from its next stop and start"
7276
+ };
7277
+ function describe(report2, restarted) {
7278
+ console.log(`moved ${report2.boxes} box(es), ${report2.snapshots} snapshot(s) and ${report2.volumes} volume(s) from ${report2.from} to ${report2.to}`);
7279
+ for (const box of report2.keysUpdated) console.log(`box ${box} accepts SSH certificates for ${report2.to} now`);
7280
+ for (const k of report2.keysPending) console.log(`box ${k.box} ${WHEN2[k.when]}${k.why ? ` (${k.why})` : ""}`);
7281
+ console.log(restarted ? "kvbox-server restarted" : "kvbox-server was not running; start it with kvbox-server start -d");
7282
+ }
7283
+
6801
7284
  // src/commands/status.ts
6802
7285
  import { homedir as homedir2 } from "node:os";
6803
7286
  import { styleText } from "node:util";
6804
- import { Command as Command10 } from "commander";
6805
- 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) => {
7287
+ import { Command as Command12 } from "commander";
7288
+ var statusCommand2 = new Command12("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) => {
6806
7289
  const p = paths();
6807
7290
  const atBoot = startsAtBoot(p);
6808
7291
  const pid = await daemonPid(p);
@@ -6874,73 +7357,17 @@ function printStatus(health, atBoot, logPath) {
6874
7357
  }
6875
7358
 
6876
7359
  // src/commands/stop.ts
6877
- import { Command as Command11 } from "commander";
6878
- var stopCommand = new Command11("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
7360
+ import { Command as Command13 } from "commander";
7361
+ var stopCommand = new Command13("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
6879
7362
  const pid = await daemonPid(paths());
6880
7363
  if (pid === null) throw new KvboxError("kvbox-server is not running");
6881
7364
  await stopDaemon(pid);
6882
7365
  console.log(`kvbox-server stopped (pid ${pid}); boxes keep running`);
6883
7366
  });
6884
7367
 
6885
- // src/commands/trust-ca.ts
6886
- import { Command as Command12 } from "commander";
6887
- 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) => {
6888
- 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");
6889
- if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
6890
- const client = new SocketClient(paths().serverSock);
6891
- try {
6892
- let key = publicKey;
6893
- if (key === void 0) {
6894
- const ca = await client.cloudCa();
6895
- console.log(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);
6896
- if (!await confirm("make every cloud box on this host trust it (in place of the CA it trusts now)?", opts.yes ?? false)) {
6897
- throw new KvboxError("cancelled", 130);
6898
- }
6899
- key = ca.publicKey;
6900
- }
6901
- const report2 = await client.trustCa({ publicKey: key });
6902
- if (opts.json) console.log(JSON.stringify(report2, null, 2));
6903
- else describeReport(report2);
6904
- } finally {
6905
- await client.close();
6906
- }
6907
- });
6908
- async function confirm(question, yes) {
6909
- if (yes) return true;
6910
- if (!process.stdin.isTTY) {
6911
- console.error("refusing without -y when stdin is not a terminal");
6912
- return false;
6913
- }
6914
- const { createInterface } = await import("node:readline/promises");
6915
- const rl = createInterface({ input: process.stdin, output: process.stderr });
6916
- try {
6917
- const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
6918
- return answer === "y" || answer === "yes";
6919
- } finally {
6920
- rl.close();
6921
- }
6922
- }
6923
- var WHEN = {
6924
- start: "is stopped: it trusts the CA from its next start",
6925
- wake: "is hibernated: it trusts the CA from its next wake",
6926
- resume: "is in standby: it trusts the CA from its next resume",
6927
- later: "is running but could not take it now; it trusts the CA from its next stop and start"
6928
- };
6929
- function describeReport(report2) {
6930
- console.log(`CA ${report2.fingerprint}`);
6931
- for (const box of report2.updated) console.log(`box ${box} now trusts the CA`);
6932
- for (const p of report2.pending) console.log(`box ${p.box} ${WHEN[p.when]}${p.why ? ` (${p.why})` : ""}`);
6933
- for (const f of report2.failed) console.error(`box ${f.box}: ${f.error}`);
6934
- const parts = [`${report2.updated.length} box(es) updated now`, `${report2.pending.length} pending`, `${report2.failed.length} failed`];
6935
- const skipped = report2.skipped ?? [];
6936
- if (skipped.length > 0) parts.push(`${skipped.length} cloud box(es) without a CA line untouched (managed services: no certificate opens them)`);
6937
- if (report2.local > 0) parts.push(`${report2.local} local box(es) untouched (they trust this host's key only)`);
6938
- console.log(parts.join(", "));
6939
- }
6940
-
6941
7368
  // src/program.ts
6942
7369
  function buildProgram() {
6943
- 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);
7370
+ return new Command14("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(renameRealmCommand).addCommand(backupCommand).addCommand(netCommand);
6944
7371
  }
6945
7372
 
6946
7373
  // src/index.ts