@kvbox/server 0.6.0 → 0.6.2

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. */
@@ -207,7 +209,9 @@ var PricingSchema = z.object({
207
209
  */
208
210
  storageHour: z.number().nonnegative().default(0),
209
211
  storageGibHour: z.number().nonnegative().default(0),
210
- storageIncludedGib: z.number().int().nonnegative().default(0)
212
+ storageIncludedGib: z.number().int().nonnegative().default(0),
213
+ /** The cron service (#190): an hour of one cron service existing, whatever it holds or fires. A price list from before it charges nothing. */
214
+ cronHour: z.number().nonnegative().default(0)
211
215
  });
212
216
  var PriceListSchema = PricingSchema.extend({ welcomeCredit: z.number().nonnegative() });
213
217
  var HOUR_MS = 36e5;
@@ -579,6 +583,12 @@ function openDb(p = paths()) {
579
583
  handles.set(p.db, db);
580
584
  return db;
581
585
  }
586
+ function closeDb(p = paths()) {
587
+ const db = handles.get(p.db);
588
+ if (db === void 0) return;
589
+ db.close();
590
+ handles.delete(p.db);
591
+ }
582
592
  function migrate(db) {
583
593
  db.exec("create table if not exists schema_version (version integer not null)");
584
594
  const row = db.prepare("select version from schema_version").get();
@@ -597,6 +607,22 @@ function migrate(db) {
597
607
  }
598
608
  }
599
609
  }
610
+ function renameLedgerRealm(from, to, p = paths()) {
611
+ const db = openDb(p);
612
+ let rows = 0;
613
+ db.exec("begin");
614
+ try {
615
+ for (const table of ["usage_events", "volume_events"]) {
616
+ const res = db.prepare(`update ${table} set owner = substr(owner, 1, length(owner) - length(?)) || ? where substr(owner, -length(?)) = ?`).run(`@${from}`, `@${to}`, `@${from}`, `@${from}`);
617
+ rows += Number(res.changes);
618
+ }
619
+ db.exec("commit");
620
+ } catch (err) {
621
+ db.exec("rollback");
622
+ throw err;
623
+ }
624
+ return rows;
625
+ }
600
626
  var LIVE_STATES = ["running", "standby"];
601
627
  function fromRaw(r) {
602
628
  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 +1105,7 @@ var WakeHookCallSchema = z4.object({
1079
1105
  reason: z4.string().optional()
1080
1106
  });
1081
1107
  var BACKUP_STATUSES = ["running", "ready", "failed"];
1108
+ var BACKUP_KINDS = ["box", "volume"];
1082
1109
  var BackupSchema = z4.object({
1083
1110
  id: z4.string(),
1084
1111
  owner: z4.string(),
@@ -1126,6 +1153,31 @@ var HostRestoreRequest = z4.object({
1126
1153
  /** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */
1127
1154
  pin: z4.string().optional()
1128
1155
  });
1156
+ var VolumeBackupSchema = z4.object({
1157
+ id: z4.string(),
1158
+ owner: z4.string(),
1159
+ volume: z4.string(),
1160
+ status: z4.enum(BACKUP_STATUSES),
1161
+ /** Why it failed; null otherwise. */
1162
+ error: z4.string().nullable(),
1163
+ /** The volume's size when taken. */
1164
+ diskBytes: z4.number().int().nullable(),
1165
+ /** What it holds: the slots that are not all zeros. */
1166
+ dataBytes: z4.number().int().nullable(),
1167
+ /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
1168
+ uploadedBytes: z4.number().int().nullable(),
1169
+ createdBy: z4.string().nullable(),
1170
+ createdAt: z4.string(),
1171
+ finishedAt: z4.string().nullable()
1172
+ });
1173
+ var HostVolumeBackupManifestSchema = z4.object({ id: z4.string(), sizeBytes: z4.number().int(), chunks: z4.array(z4.string().nullable()) });
1174
+ var HostVolumeRestoreRequest = z4.object({
1175
+ id: z4.string(),
1176
+ key: z4.string(),
1177
+ sizeBytes: z4.number().int().positive(),
1178
+ chunks: z4.array(z4.object({ index: z4.number().int().nonnegative(), hash: z4.string(), url: z4.string() })),
1179
+ pin: z4.string().optional()
1180
+ });
1129
1181
  var BACKUP_STORE_BUCKET = "kvbox-backups";
1130
1182
  var BACKUP_STORE_REGION = "kvbox";
1131
1183
  var BackupStoreSetupRequest = z4.object({ path: z4.string().min(1), force: z4.boolean().optional(), newStore: z4.boolean().optional() });
@@ -1160,7 +1212,38 @@ var CloudBackupStoreSchema = z4.object({
1160
1212
  freeBytes: z4.number().int().nullable(),
1161
1213
  /** Ready backups kept here, and what their chunks take (encrypted, compressed). */
1162
1214
  backups: z4.number().int(),
1163
- storedBytes: z4.number().int()
1215
+ storedBytes: z4.number().int(),
1216
+ /** 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). */
1217
+ boxes: z4.number().int(),
1218
+ volumes: z4.number().int(),
1219
+ /** When the newest ready backup kept here finished; null when it keeps none. */
1220
+ lastBackupAt: z4.string().nullable()
1221
+ });
1222
+ var StoredItemSchema = z4.object({
1223
+ kind: z4.enum(BACKUP_KINDS),
1224
+ owner: z4.string(),
1225
+ name: z4.string(),
1226
+ /** The host the box (or volume) is on now; null when it is gone (its backups stay). */
1227
+ host: z4.string().nullable(),
1228
+ /** It is on the store's own host: losing that host loses it and its backups together. */
1229
+ sameHost: z4.boolean(),
1230
+ /** Ready backups kept here, and what they added to the store together (encrypted, compressed). */
1231
+ backups: z4.number().int(),
1232
+ uploadedBytes: z4.number().int(),
1233
+ /** The newest backup sent here, whatever became of it. */
1234
+ latest: z4.object({ id: z4.string(), status: z4.enum(BACKUP_STATUSES), error: z4.string().nullable(), createdAt: z4.string() })
1235
+ });
1236
+ var FailedBackupSchema = z4.object({
1237
+ id: z4.string(),
1238
+ owner: z4.string(),
1239
+ /** What it was a backup of: a box or a volume (#168), and its name. */
1240
+ kind: z4.enum(BACKUP_KINDS),
1241
+ name: z4.string(),
1242
+ error: z4.string().nullable(),
1243
+ /** 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. */
1244
+ host: z4.string().nullable(),
1245
+ store: z4.string().nullable(),
1246
+ createdAt: z4.string()
1164
1247
  });
1165
1248
  var MachineSchema = z4.object({
1166
1249
  /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
@@ -1534,6 +1617,17 @@ var VolumeUsageSchema = z4.object({
1534
1617
  cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
1535
1618
  historyFrom: z4.string().nullable()
1536
1619
  });
1620
+ var CronUsageSchema = z4.object({
1621
+ id: z4.string(),
1622
+ name: z4.string(),
1623
+ owner: z4.string(),
1624
+ ownerKind: z4.enum(["user", "org"]).optional(),
1625
+ status: z4.enum(["present", "removed"]),
1626
+ hours: z4.number(),
1627
+ cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
1628
+ /** When it was made. */
1629
+ historyFrom: z4.string().nullable()
1630
+ });
1537
1631
  var UsageDayItemSchema = z4.object({
1538
1632
  id: z4.string(),
1539
1633
  name: z4.string(),
@@ -1552,7 +1646,9 @@ var UsageDaySchema = z4.object({
1552
1646
  boxes: z4.array(UsageDayItemSchema),
1553
1647
  volumes: z4.array(UsageDayItemSchema),
1554
1648
  /** Object storage that existed that day (#182); absent on a day without any. */
1555
- storage: z4.array(UsageDayItemSchema).optional()
1649
+ storage: z4.array(UsageDayItemSchema).optional(),
1650
+ /** Cron services that existed that day (#190); absent on a day without any. */
1651
+ cron: z4.array(UsageDayItemSchema).optional()
1556
1652
  });
1557
1653
  var UsageReportSchema = z4.object({
1558
1654
  window: z4.object({ from: z4.string(), to: z4.string() }),
@@ -1565,6 +1661,8 @@ var UsageReportSchema = z4.object({
1565
1661
  * included ones, `sizeGib` its whole size. Absent when there is none.
1566
1662
  */
1567
1663
  storage: z4.array(VolumeUsageSchema).optional(),
1664
+ /** Cron services (#190, control plane only): one row per service a slug has or had. Absent when there is none. */
1665
+ cron: z4.array(CronUsageSchema).optional(),
1568
1666
  /** With `?by=day` only, oldest day first. */
1569
1667
  days: z4.array(UsageDaySchema).optional(),
1570
1668
  totals: z4.object({
@@ -1574,7 +1672,7 @@ var UsageReportSchema = z4.object({
1574
1672
  diskGibHours: z4.number(),
1575
1673
  volumeHours: z4.number().optional(),
1576
1674
  volumeGibHours: z4.number().optional(),
1577
- /** Boxes, volumes and object storage together. */
1675
+ /** Boxes, volumes, object storage and cron services together. */
1578
1676
  cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional()
1579
1677
  })
1580
1678
  });
@@ -3038,6 +3136,7 @@ import { link, mkdir as mkdir5, readdir as readdir5, rename as rename5, rm as rm
3038
3136
 
3039
3137
  // src/core/firecracker.ts
3040
3138
  import { Agent, request as request2 } from "undici";
3139
+ var syncFallbackLogged = false;
3041
3140
  var FirecrackerClient = class {
3042
3141
  constructor(socketPath) {
3043
3142
  this.socketPath = socketPath;
@@ -3063,15 +3162,35 @@ var FirecrackerClient = class {
3063
3162
  }
3064
3163
  /** /dev/vda: the shared base image, read-only. Firecracker adds `root=/dev/vda ro` to the boot args to match. */
3065
3164
  rootDrive(pathOnHost) {
3066
- return this.drive("rootfs", pathOnHost, { root: true, readOnly: true });
3165
+ return this.drive("rootfs", pathOnHost, { root: true, readOnly: true, engine: "Sync" });
3067
3166
  }
3068
3167
  /** The box's own writable disk, /dev/vdb: the guest stacks it on the base as an overlay. */
3069
3168
  overlayDrive(pathOnHost) {
3070
- return this.drive("overlay", pathOnHost, { root: false, readOnly: false });
3169
+ return this.writableDrive("overlay", pathOnHost);
3071
3170
  }
3072
3171
  /** A volume (#52): /dev/vdc and up, in the order they are added; the guest mounts it by label. */
3073
3172
  volumeDrive(id, pathOnHost) {
3074
- return this.drive(id, pathOnHost, { root: false, readOnly: false });
3173
+ return this.writableDrive(id, pathOnHost);
3174
+ }
3175
+ /**
3176
+ * A drive the guest writes to gets the Async engine (io_uring, #175): with Sync, Firecracker's one
3177
+ * VMM thread sits in the write or the fsync and the box's network waits behind it, seconds under a
3178
+ * heavy write. The base image stays on Sync, which is the faster of the two for reads the host has
3179
+ * cached. A host that cannot do Async (kernel before 5.10.51, io_uring turned off) keeps Sync.
3180
+ * The engine is part of a snapshot: a box frozen on Sync wakes on Sync, until its next cold boot.
3181
+ */
3182
+ async writableDrive(id, pathOnHost) {
3183
+ const opts = { root: false, readOnly: false };
3184
+ try {
3185
+ return await this.drive(id, pathOnHost, { ...opts, engine: "Async" });
3186
+ } catch (asyncErr) {
3187
+ const done = await this.drive(id, pathOnHost, { ...opts, engine: "Sync" });
3188
+ if (!syncFallbackLogged) {
3189
+ syncFallbackLogged = true;
3190
+ 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}`);
3191
+ }
3192
+ return done;
3193
+ }
3075
3194
  }
3076
3195
  drive(id, pathOnHost, opts) {
3077
3196
  return this.call("PUT", `/drives/${id}`, {
@@ -3082,7 +3201,8 @@ var FirecrackerClient = class {
3082
3201
  // "Unsafe" (the default) acks guest flushes without doing anything, so the last journal
3083
3202
  // commit of a clean shutdown can be lost when the guest resets and Firecracker exits.
3084
3203
  // Writeback makes a guest flush a real fsync; a box's writes must survive `kvbox stop`.
3085
- cache_type: "Writeback"
3204
+ cache_type: "Writeback",
3205
+ io_engine: opts.engine
3086
3206
  });
3087
3207
  }
3088
3208
  /**
@@ -4391,6 +4511,34 @@ async function resizeVolume(volume, sizeGib, p = paths()) {
4391
4511
  return { ...grown, attachedTo: holder };
4392
4512
  });
4393
4513
  }
4514
+ async function replaceVolumeDisk(volume, file, p = paths()) {
4515
+ const grow = async () => {
4516
+ const meta = await readVolume(volume, p);
4517
+ if (meta.sizeGib * 1024 ** 3 > statSync2(file).size) await growDisk(file, meta.sizeGib);
4518
+ };
4519
+ await grow();
4520
+ const swap = async () => {
4521
+ await grow();
4522
+ await rename6(file, p.volume(volume.owner, volume.name).disk);
4523
+ };
4524
+ const holder = await attachedBox(volume, p);
4525
+ if (holder === null) {
4526
+ await withHostLock("volumes", async () => {
4527
+ const now = await attachedBox(volume, p);
4528
+ if (now !== null) throw new KvboxError(`volume ${shown(volume)} was just attached to box ${now}; try again`);
4529
+ await swap();
4530
+ });
4531
+ return getVolume(volume, p);
4532
+ }
4533
+ const box = { owner: volume.owner, name: holder };
4534
+ await withBoxLock(box, async () => {
4535
+ const meta = await readMeta(box, p);
4536
+ if (!meta.volumes?.includes(volume.name)) throw new KvboxError(`volume ${shown(volume)} was just detached from box ${holder}; try again`);
4537
+ assertNotHibernated(meta, p);
4538
+ await applyAtNextBoot(meta, {}, "restore", await loadConfig(p), p, swap);
4539
+ });
4540
+ return getVolume(volume, p);
4541
+ }
4394
4542
  var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
4395
4543
  const meta = await readMeta(ref, p);
4396
4544
  const next = { ...meta };
@@ -4632,7 +4780,7 @@ async function bootRecovered(settled, p = paths()) {
4632
4780
  // src/core/backups.ts
4633
4781
  import { randomBytes as randomBytes5 } from "node:crypto";
4634
4782
  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";
4783
+ 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
4784
  import { basename as basename2, join as join3 } from "node:path";
4637
4785
  import { setTimeout as sleep3 } from "node:timers/promises";
4638
4786
 
@@ -4713,6 +4861,26 @@ function chunkCount(bytes) {
4713
4861
  return Math.ceil(bytes / CHUNK_SIZE);
4714
4862
  }
4715
4863
 
4864
+ // src/core/clone.ts
4865
+ import { rm as rm5 } from "node:fs/promises";
4866
+ var CLONE_TIMEOUT_MS = 6e5;
4867
+ async function cloneDisk(from, to, timeoutMs = CLONE_TIMEOUT_MS) {
4868
+ const started = Date.now();
4869
+ try {
4870
+ await run(["cp", "--reflink=always", from, to], { timeoutMs });
4871
+ } catch (err) {
4872
+ await rm5(to, { force: true });
4873
+ if (Date.now() - started >= timeoutMs) {
4874
+ 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`);
4875
+ }
4876
+ const why = err.message;
4877
+ if (/failed to clone|not supported|cross-device|Invalid cross/i.test(why)) {
4878
+ 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");
4879
+ }
4880
+ throw err;
4881
+ }
4882
+ }
4883
+
4716
4884
  // src/core/storeFetch.ts
4717
4885
  import { Agent as Agent2, buildConnector, fetch as pinnedFetch } from "undici";
4718
4886
  var dispatchers = /* @__PURE__ */ new Map();
@@ -4804,29 +4972,14 @@ async function stageBackup(ref, req, p = paths()) {
4804
4972
  checkId(req.id);
4805
4973
  const keys = backupKeys(req.key);
4806
4974
  const s = p.backup(req.id);
4807
- await rm5(s.dir, { recursive: true, force: true });
4975
+ await rm6(s.dir, { recursive: true, force: true });
4808
4976
  await mkdir7(s.dir, { recursive: true, mode: 448 });
4809
4977
  try {
4810
4978
  const { meta, envText } = await withBoxLock(ref, async () => {
4811
4979
  const meta2 = await readBox2(ref, p);
4812
4980
  const m = p.machine(meta2.owner, meta2.name);
4813
4981
  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
- }
4982
+ await frozenClone(meta2, m.overlay, s.disk, p);
4830
4983
  const envText2 = existsSync8(m.env) ? await readFile7(m.env, "utf8") : null;
4831
4984
  return { meta: meta2, envText: envText2 };
4832
4985
  });
@@ -4843,7 +4996,54 @@ async function stageBackup(ref, req, p = paths()) {
4843
4996
  memMib: meta.memMib
4844
4997
  };
4845
4998
  } catch (err) {
4846
- await rm5(s.dir, { recursive: true, force: true });
4999
+ await rm6(s.dir, { recursive: true, force: true });
5000
+ throw err;
5001
+ }
5002
+ }
5003
+ async function frozenClone(box, from, to, p) {
5004
+ if (!vmAlive(box) || box.paused) return cloneDisk(from, to);
5005
+ const fc = new FirecrackerClient(p.machine(box.owner, box.name).sock);
5006
+ try {
5007
+ await fc.pause();
5008
+ try {
5009
+ await cloneDisk(from, to);
5010
+ } finally {
5011
+ await resumeAfterCopy(fc, box, p);
5012
+ }
5013
+ } finally {
5014
+ await fc.close();
5015
+ }
5016
+ }
5017
+ async function stageVolumeBackup(ref, req, p = paths()) {
5018
+ checkId(req.id);
5019
+ const keys = backupKeys(req.key);
5020
+ await readVolume(ref, p);
5021
+ const from = p.volume(ref.owner, ref.name).disk;
5022
+ const s = p.backup(req.id);
5023
+ await rm6(s.dir, { recursive: true, force: true });
5024
+ await mkdir7(s.dir, { recursive: true, mode: 448 });
5025
+ try {
5026
+ await assertRoom(s.dir, 0, `a backup of volume ${shown(ref)}`, p);
5027
+ const holder = await attachedBox(ref, p);
5028
+ if (holder === null) {
5029
+ await withHostLock("volumes", async () => {
5030
+ const now = await attachedBox(ref, p);
5031
+ if (now !== null) throw new KvboxError(`volume ${shown(ref)} was just attached to box ${now}; try again`);
5032
+ await cloneDisk(from, s.disk);
5033
+ });
5034
+ } else {
5035
+ const box = { owner: ref.owner, name: holder };
5036
+ await withBoxLock(box, async () => {
5037
+ const meta = await readBox2(box, p);
5038
+ if (!meta.volumes?.includes(ref.name)) throw new KvboxError(`volume ${shown(ref)} was just detached from box ${holder}; try again`);
5039
+ await frozenClone(meta, from, s.disk, p);
5040
+ });
5041
+ }
5042
+ const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
5043
+ await writeFile7(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
5044
+ return { id: req.id, sizeBytes, chunks };
5045
+ } catch (err) {
5046
+ await rm6(s.dir, { recursive: true, force: true });
4847
5047
  throw err;
4848
5048
  }
4849
5049
  }
@@ -4908,20 +5108,25 @@ async function uploadOnce(id, req, signal, p) {
4908
5108
  } finally {
4909
5109
  await fh.close();
4910
5110
  }
4911
- await rm5(s.dir, { recursive: true, force: true });
5111
+ await rm6(s.dir, { recursive: true, force: true });
4912
5112
  return { chunks: work.length, bytes, sizes };
4913
5113
  }
4914
5114
  async function dropBackup(id, p = paths()) {
4915
5115
  checkId(id);
4916
5116
  uploads.get(id)?.abort();
4917
- await rm5(p.backup(id).dir, { recursive: true, force: true });
5117
+ await rm6(p.backup(id).dir, { recursive: true, force: true });
4918
5118
  }
4919
5119
  async function clearStagedBackups(p = paths()) {
4920
- await rm5(p.backups, { recursive: true, force: true });
5120
+ await rm6(p.backups, { recursive: true, force: true });
4921
5121
  const prefix = basename2(p.machine("x", "x").restoring);
4922
5122
  for (const ref of await listMachineRefs(p)) {
4923
5123
  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 });
5124
+ for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm6(join3(dir, f), { force: true });
5125
+ }
5126
+ const volumePrefix = basename2(p.volume("x", "x").restoring);
5127
+ for (const ref of await listVolumeRefs(p)) {
5128
+ const dir = p.volume(ref.owner, ref.name).dir;
5129
+ for (const f of await readdir6(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await rm6(join3(dir, f), { force: true });
4925
5130
  }
4926
5131
  }
4927
5132
  async function downloadDisk(file, req, p = paths()) {
@@ -4952,8 +5157,9 @@ async function downloadDisk(file, req, p = paths()) {
4952
5157
  }
4953
5158
  }
4954
5159
  var restoring = /* @__PURE__ */ new Set();
5160
+ var holding = /* @__PURE__ */ new Map();
4955
5161
  function restoreRunning(ref) {
4956
- return restoring.has(refKey(ref));
5162
+ return restoring.has(refKey(ref)) || holding.has(refKey(ref));
4957
5163
  }
4958
5164
  async function restoreBackup(ref, req, p = paths()) {
4959
5165
  checkId(req.id);
@@ -4994,8 +5200,44 @@ async function restoreOnce(ref, req, p) {
4994
5200
  await downloadDisk(file, req, p);
4995
5201
  return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
4996
5202
  } finally {
4997
- await rm5(file, { force: true });
4998
- await rm5(envFile, { force: true });
5203
+ await rm6(file, { force: true });
5204
+ await rm6(envFile, { force: true });
5205
+ }
5206
+ }
5207
+ async function restoreVolumeBackup(ref, req, p = paths()) {
5208
+ checkId(req.id);
5209
+ const k = `volume:${refKey(ref)}`;
5210
+ if (restoring.has(k)) throw new KvboxError(`a restore of volume ${shown(ref)} is already running; wait for it to finish`);
5211
+ restoring.add(k);
5212
+ const v = p.volume(ref.owner, ref.name);
5213
+ const file = `${v.restoring}.${randomBytes5(4).toString("hex")}`;
5214
+ let held2 = null;
5215
+ try {
5216
+ const meta = await readVolume(ref, p);
5217
+ const holder = await attachedBox(ref, p);
5218
+ if (holder !== null) {
5219
+ held2 = refKey({ owner: ref.owner, name: holder });
5220
+ holding.set(held2, (holding.get(held2) ?? 0) + 1);
5221
+ const box = await readBox2({ owner: ref.owner, name: holder }, p);
5222
+ if (!vmAlive(box) && existsSync8(p.machine(box.owner, box.name).hibernateVmstate)) {
5223
+ 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`);
5224
+ }
5225
+ }
5226
+ if (req.sizeBytes > meta.sizeGib * 1024 ** 3) {
5227
+ const gib = Math.ceil(req.sizeBytes / 1024 ** 3);
5228
+ 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`);
5229
+ }
5230
+ await assertRoom(v.dir, req.chunks.length * CHUNK_SIZE, `a restore of volume ${shown(ref)}`, p);
5231
+ await downloadDisk(file, req, p);
5232
+ return await replaceVolumeDisk(ref, file, p);
5233
+ } finally {
5234
+ restoring.delete(k);
5235
+ if (held2 !== null) {
5236
+ const n = (holding.get(held2) ?? 1) - 1;
5237
+ if (n > 0) holding.set(held2, n);
5238
+ else holding.delete(held2);
5239
+ }
5240
+ await rm6(file, { force: true });
4999
5241
  }
5000
5242
  }
5001
5243
  async function pool(items, fn) {
@@ -5030,7 +5272,7 @@ async function withTries(what, fn, signal) {
5030
5272
  }
5031
5273
 
5032
5274
  // 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";
5275
+ import { access as access2, chmod as chmod4, mkdir as mkdir9, rm as rm7, writeFile as writeFile8 } from "node:fs/promises";
5034
5276
 
5035
5277
  // ../shared/src/relay.ts
5036
5278
  import { z as z7 } from "zod";
@@ -5212,6 +5454,19 @@ async function fetchCloudCa(p = paths()) {
5212
5454
  const publicKey = parseSshPublicKey(parsed.data.publicKey);
5213
5455
  return { controlPlane: cp.name, publicKey, fingerprint: sshKeyFingerprint(publicKey) };
5214
5456
  }
5457
+ async function fetchCloudName(p = paths()) {
5458
+ const cfg = await loadConfig(p);
5459
+ const cp = cfg.controlPlane;
5460
+ 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>");
5461
+ const res = await request3(`${cp.url}/health`, { headersTimeout: 1e4, bodyTimeout: 1e4 }).catch((err) => {
5462
+ throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
5463
+ });
5464
+ const text = await res.body.text();
5465
+ if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(`${cp.url} answered ${res.statusCode}`);
5466
+ const name = jsonOrNull(text)?.name;
5467
+ 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>`);
5468
+ return name;
5469
+ }
5215
5470
  async function leaveControlPlane(p = paths()) {
5216
5471
  const cfg = await loadConfig(p);
5217
5472
  const cp = cfg.controlPlane;
@@ -5296,7 +5551,7 @@ async function dropRelay(p = paths()) {
5296
5551
  throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
5297
5552
  }
5298
5553
  await netSetup(cfg, ["relay", "down"]);
5299
- await rm6(p.relayConf, { force: true });
5554
+ await rm7(p.relayConf, { force: true });
5300
5555
  const { relay: _gone, ...rest } = cfg;
5301
5556
  await saveConfig(rest, p);
5302
5557
  return relay;
@@ -5734,7 +5989,7 @@ function groupWithMember(gid, user, groupFile) {
5734
5989
  }
5735
5990
 
5736
5991
  // src/listen.ts
5737
- import { readFile as readFile12, rm as rm7, writeFile as writeFile10 } from "node:fs/promises";
5992
+ import { readFile as readFile12, rm as rm8, writeFile as writeFile10 } from "node:fs/promises";
5738
5993
  import { createServer as createHttpsServer } from "node:https";
5739
5994
  import { createAdaptorServer } from "@hono/node-server";
5740
5995
 
@@ -5754,6 +6009,9 @@ var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
5754
6009
  function edgeCredential(hostSecret) {
5755
6010
  return createHmac2("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
5756
6011
  }
6012
+ function cronCredential(hostSecret) {
6013
+ return createHmac2("sha256", hostSecret).update("kvbox-cron-v1").digest("base64url");
6014
+ }
5757
6015
 
5758
6016
  // src/app.ts
5759
6017
  import { Hono as Hono11 } from "hono";
@@ -5771,7 +6029,7 @@ function versionOf(srcFileUrl, injected) {
5771
6029
  }
5772
6030
 
5773
6031
  // src/version.ts
5774
- var VERSION = versionOf(import.meta.url, true ? "0.6.0" : void 0);
6032
+ var VERSION = versionOf(import.meta.url, true ? "0.6.2" : void 0);
5775
6033
 
5776
6034
  // src/caller.ts
5777
6035
  import { createHash as createHash3, timingSafeEqual } from "node:crypto";
@@ -5788,9 +6046,10 @@ function resolveCaller(opts = {}) {
5788
6046
  }
5789
6047
  const authorized = secretCheck(cp);
5790
6048
  const edge = edgeCheck(cp);
6049
+ const cron = cronCheck(cp);
5791
6050
  return async (c, next) => {
5792
6051
  const auth = c.req.header("authorization");
5793
- if (!authorized(auth) && !(edge(auth) && BOX_HTTP_PATH_RE.test(c.req.path))) return c.json({ error: "not authorized" }, 401);
6052
+ if (!authorized(auth) && !((edge(auth) || cron(auth)) && BOX_HTTP_PATH_RE.test(c.req.path))) return c.json({ error: "not authorized" }, 401);
5794
6053
  const user = c.req.header(OWNER_HEADER);
5795
6054
  if (user === void 0) {
5796
6055
  const path = c.req.path.replace(/\/$/, "");
@@ -5815,6 +6074,9 @@ function secretCheck(cp) {
5815
6074
  function edgeCheck(cp) {
5816
6075
  return bearerCheck(edgeCredential(cp.secret));
5817
6076
  }
6077
+ function cronCheck(cp) {
6078
+ return bearerCheck(cronCredential(cp.secret));
6079
+ }
5818
6080
  function bearerCheck(token) {
5819
6081
  const expected = digest(token);
5820
6082
  return (authorization) => {
@@ -5889,6 +6151,20 @@ function backupMachineRoutes() {
5889
6151
  });
5890
6152
  return r;
5891
6153
  }
6154
+ function backupVolumeRoutes() {
6155
+ const r = new Hono();
6156
+ r.post("/:name/backup", async (c) => {
6157
+ const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));
6158
+ if (!body.success) throw new KvboxError("backup: expected {id, key}");
6159
+ return c.json(await stageVolumeBackup(parseRef(c.req.param("name"), c.get("owner")), body.data));
6160
+ });
6161
+ r.post("/:name/restore", async (c) => {
6162
+ const body = HostVolumeRestoreRequest.safeParse(await c.req.json().catch(() => ({})));
6163
+ if (!body.success) throw new KvboxError("restore: expected {id, key, sizeBytes, chunks}");
6164
+ return c.json(await restoreVolumeBackup(parseRef(c.req.param("name"), c.get("owner")), body.data));
6165
+ });
6166
+ return r;
6167
+ }
5892
6168
  function backupRoutes() {
5893
6169
  const r = new Hono();
5894
6170
  r.post("/:id/upload", async (c) => {
@@ -6468,6 +6744,7 @@ function createApp(opts = {}) {
6468
6744
  if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
6469
6745
  if (opts.controlPlane) {
6470
6746
  app.route("/machines", backupMachineRoutes());
6747
+ app.route("/volumes", backupVolumeRoutes());
6471
6748
  app.route("/backups", backupRoutes());
6472
6749
  }
6473
6750
  app.route("/machines", machineRoutes());
@@ -6499,7 +6776,7 @@ async function listen(opts = {}) {
6499
6776
  throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
6500
6777
  }
6501
6778
  if (socketPath === p.serverSock) await refuseSecondDaemon(p);
6502
- await rm7(socketPath, { force: true });
6779
+ await rm8(socketPath, { force: true });
6503
6780
  const server = createAdaptorServer({ fetch: createApp().fetch });
6504
6781
  await new Promise((resolve3, reject) => {
6505
6782
  server.once("error", reject);
@@ -6528,7 +6805,8 @@ async function listen(opts = {}) {
6528
6805
  });
6529
6806
  const secret = secretCheck(cp);
6530
6807
  const edge = edgeCheck(cp);
6531
- limitUntrusted(httpsServer, (req) => secret(req.headers.authorization) || edge(req.headers.authorization));
6808
+ const cron = cronCheck(cp);
6809
+ limitUntrusted(httpsServer, (req) => secret(req.headers.authorization) || edge(req.headers.authorization) || cron(req.headers.authorization));
6532
6810
  httpsServer.on("upgrade", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));
6533
6811
  const port = opts.httpsPort ?? cp.port;
6534
6812
  await new Promise((resolve3, reject) => {
@@ -6536,8 +6814,8 @@ async function listen(opts = {}) {
6536
6814
  httpsServer.listen(port, "0.0.0.0", () => resolve3());
6537
6815
  }).catch(async (err) => {
6538
6816
  server.close();
6539
- await rm7(socketPath, { force: true });
6540
- await rm7(p.serverPid, { force: true });
6817
+ await rm8(socketPath, { force: true });
6818
+ await rm8(p.serverPid, { force: true });
6541
6819
  throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
6542
6820
  });
6543
6821
  const bound = httpsServer.address().port;
@@ -6548,15 +6826,15 @@ async function listen(opts = {}) {
6548
6826
  new Promise((resolve3) => server.close(() => resolve3())),
6549
6827
  httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
6550
6828
  ]);
6551
- await rm7(socketPath, { force: true });
6552
- await rm7(p.serverPid, { force: true });
6829
+ await rm8(socketPath, { force: true });
6830
+ await rm8(p.serverPid, { force: true });
6553
6831
  };
6554
6832
  const shutdown2 = async () => {
6555
6833
  server.close();
6556
6834
  httpsServer?.close();
6557
6835
  await stopRecovery();
6558
- await rm7(socketPath, { force: true });
6559
- await rm7(p.serverPid, { force: true });
6836
+ await rm8(socketPath, { force: true });
6837
+ await rm8(p.serverPid, { force: true });
6560
6838
  process.exit(0);
6561
6839
  };
6562
6840
  process.once("SIGINT", () => void shutdown2());
@@ -6638,7 +6916,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
6638
6916
  });
6639
6917
 
6640
6918
  // src/program.ts
6641
- import { Command as Command13 } from "commander";
6919
+ import { Command as Command14 } from "commander";
6642
6920
 
6643
6921
  // src/commands/backup/index.ts
6644
6922
  import { Command as Command4 } from "commander";
@@ -6798,11 +7076,241 @@ var relayCommand = new Command9("relay").description("reach the internet through
6798
7076
  console.log(`this host is reachable at ${relay.publicIp}; kvbox-server join advertises it by default`);
6799
7077
  });
6800
7078
 
7079
+ // src/commands/rename-realm.ts
7080
+ import { Command as Command11 } from "commander";
7081
+
7082
+ // src/core/realm.ts
7083
+ 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";
7084
+ import { z as z8 } from "zod";
7085
+ var esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7086
+ async function ownersIn(root, from, suffix = "") {
7087
+ const entries = await readdir7(root).catch((err) => {
7088
+ if (err.code === "ENOENT") return [];
7089
+ throw err;
7090
+ });
7091
+ const tail = `@${from}${suffix}`;
7092
+ return entries.filter((e) => e.endsWith(tail)).map((e) => e.slice(0, e.length - suffix.length));
7093
+ }
7094
+ async function namesIn2(dir) {
7095
+ return (await readdir7(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
7096
+ }
7097
+ async function plan(from, to, p) {
7098
+ if (!REALM_RE.test(to)) throw new KvboxError(`"${to}" cannot name a realm (letters, digits, '.', '-')`);
7099
+ if (from === to) throw new KvboxError(`this host's cloud boxes are already under ${to}`);
7100
+ const tail = new RegExp(`@${esc(from)}$`);
7101
+ const owner = (o) => o.replace(tail, `@${to}`);
7102
+ const source = (s) => s.replace(new RegExp(`^((?:[a-z]+:)?[^/@]+)@${esc(from)}/`), `$1@${to}/`);
7103
+ const caLine = (line) => isCaLine(line) ? line.replace(/principals="([^"]*)"/, (_, list) => `principals="${list.split(",").map(owner).join(",")}"`) : line;
7104
+ const out = { boxes: [], snapshots: [], volumes: [], envOwners: await ownersIn(p.env, from, ".json") };
7105
+ const clash = async (path, what) => {
7106
+ if (await lstat2(path).then(() => true, () => false)) throw new KvboxError(`${what} already exists under ${to} (${path}); nothing was changed`);
7107
+ };
7108
+ const read = async (file, schema, what) => {
7109
+ try {
7110
+ return schema.parse(JSON.parse(await readFile14(file, "utf8")));
7111
+ } catch (err) {
7112
+ throw new KvboxError(`${what} cannot be read (${file}: ${err.message}); nothing was changed`);
7113
+ }
7114
+ };
7115
+ for (const oldOwner of await ownersIn(p.machines, from)) {
7116
+ await clash(p.ownerMachines(owner(oldOwner)), `boxes of ${owner(oldOwner)}`);
7117
+ for (const name of await namesIn2(p.ownerMachines(oldOwner))) {
7118
+ const meta = await read(p.machine(oldOwner, name).meta, MachineMetaSchema, `box ${oldOwner}/${name}`);
7119
+ const status = statusOf({ ...meta, owner: oldOwner, name }, p);
7120
+ const sshKeys = meta.sshKeys?.map(caLine);
7121
+ const keysChanged = sshKeys !== void 0 && sshKeys.some((l, i) => l !== meta.sshKeys[i]);
7122
+ out.boxes.push({
7123
+ oldOwner,
7124
+ name,
7125
+ status,
7126
+ meta: {
7127
+ ...meta,
7128
+ owner: owner(meta.owner),
7129
+ source: source(meta.source),
7130
+ ...sshKeys !== void 0 ? { sshKeys } : {},
7131
+ // A stopped box reads its lines at boot; any other guest still holds the old ones.
7132
+ ...keysChanged ? { sshKeysStale: status === "stopped" ? void 0 : true } : {},
7133
+ ...meta.links !== void 0 ? { links: meta.links.map((l) => ({ ...l, owner: owner(l.owner) })) } : {}
7134
+ }
7135
+ });
7136
+ }
7137
+ }
7138
+ for (const oldOwner of await ownersIn(p.snapshots, from)) {
7139
+ await clash(p.ownerSnapshots(owner(oldOwner)), `snapshots of ${owner(oldOwner)}`);
7140
+ for (const name of (await namesIn2(p.ownerSnapshots(oldOwner))).filter((n) => !n.startsWith("."))) {
7141
+ const meta = await read(p.snapshot(oldOwner, name).meta, SnapshotMetaSchema, `snapshot ${oldOwner}/${name}`);
7142
+ out.snapshots.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner), source: source(meta.source) } });
7143
+ }
7144
+ }
7145
+ for (const oldOwner of await ownersIn(p.volumes, from)) {
7146
+ await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);
7147
+ for (const name of await namesIn2(p.ownerVolumes(oldOwner))) {
7148
+ const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z8.string().optional() }), `volume ${oldOwner}/${name}`);
7149
+ out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });
7150
+ }
7151
+ }
7152
+ for (const oldOwner of out.envOwners) await clash(p.ownerEnv(owner(oldOwner)), `the variables of ${owner(oldOwner)}`);
7153
+ return out;
7154
+ }
7155
+ async function countRealm(from, to, p = paths()) {
7156
+ const planned = await plan(from, to, p);
7157
+ return { boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length };
7158
+ }
7159
+ async function writeJson(file, value) {
7160
+ const tmp = `${file}.tmp`;
7161
+ await writeFile11(tmp, JSON.stringify(value, null, 2) + "\n");
7162
+ await rename7(tmp, file);
7163
+ }
7164
+ async function move(entries, metaOf, ownerDir, owners, to) {
7165
+ for (const e of entries) await writeJson(metaOf(e.oldOwner, e.name), e.meta);
7166
+ for (const o of owners) await rename7(ownerDir(o), ownerDir(to(o)));
7167
+ }
7168
+ async function renameRealm(from, to, p = paths()) {
7169
+ const planned = await plan(from, to, p);
7170
+ const tail = new RegExp(`@${esc(from)}$`);
7171
+ const owner = (o) => o.replace(tail, `@${to}`);
7172
+ await move(planned.volumes, (o, n) => p.volume(o, n).meta, p.ownerVolumes, await ownersIn(p.volumes, from), owner);
7173
+ await move(planned.snapshots, (o, n) => p.snapshot(o, n).meta, p.ownerSnapshots, await ownersIn(p.snapshots, from), owner);
7174
+ await move(planned.boxes, (o, n) => p.machine(o, n).meta, p.ownerMachines, await ownersIn(p.machines, from), owner);
7175
+ for (const box of planned.boxes) {
7176
+ const m = p.machine(box.meta.owner, box.name);
7177
+ for (const volume of box.meta.volumes ?? []) {
7178
+ const link3 = m.volumeDrive(volume);
7179
+ const target = await readlink(link3).catch(() => null);
7180
+ if (target !== p.volume(box.oldOwner, volume).disk) continue;
7181
+ await rm9(link3, { force: true });
7182
+ await symlink2(p.volume(box.meta.owner, volume).disk, link3);
7183
+ }
7184
+ }
7185
+ for (const o of planned.envOwners) await rename7(p.ownerEnv(o), p.ownerEnv(owner(o)));
7186
+ renameLedgerRealm(from, to, p);
7187
+ closeDb(p);
7188
+ const cfg = await loadConfig(p);
7189
+ if (cfg.controlPlane?.name === from) await saveConfig({ ...cfg, controlPlane: { ...cfg.controlPlane, name: to } }, p);
7190
+ const report2 = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [] };
7191
+ for (const box of planned.boxes) {
7192
+ const { meta, status } = box;
7193
+ if (!(meta.sshKeys ?? []).some(isCaLine)) continue;
7194
+ const key = `${meta.owner}/${meta.name}`;
7195
+ if (status === "stopped") report2.keysPending.push({ box: key, when: "start" });
7196
+ else if (status === "hibernated") report2.keysPending.push({ box: key, when: "wake" });
7197
+ else if (status === "standby") report2.keysPending.push({ box: key, when: "resume" });
7198
+ else if (!meta.sshKeysStale) report2.keysUpdated.push(key);
7199
+ else {
7200
+ const why = await pushAuthorizedKeys(meta, p.machine(meta.owner, meta.name).vsock, p);
7201
+ if (why === void 0) {
7202
+ await writeJson(p.machine(meta.owner, meta.name).meta, { ...meta, sshKeysStale: void 0 });
7203
+ report2.keysUpdated.push(key);
7204
+ } else report2.keysPending.push({ box: key, when: "later", why });
7205
+ }
7206
+ }
7207
+ return report2;
7208
+ }
7209
+
7210
+ // src/commands/trust-ca.ts
7211
+ import { Command as Command10 } from "commander";
7212
+ 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) => {
7213
+ 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");
7214
+ if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
7215
+ const client = new SocketClient(paths().serverSock);
7216
+ try {
7217
+ let key = publicKey;
7218
+ if (key === void 0) {
7219
+ const ca = await client.cloudCa();
7220
+ console.log(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);
7221
+ if (!await confirm("make every cloud box on this host trust it (in place of the CA it trusts now)?", opts.yes ?? false)) {
7222
+ throw new KvboxError("cancelled", 130);
7223
+ }
7224
+ key = ca.publicKey;
7225
+ }
7226
+ const report2 = await client.trustCa({ publicKey: key });
7227
+ if (opts.json) console.log(JSON.stringify(report2, null, 2));
7228
+ else describeReport(report2);
7229
+ } finally {
7230
+ await client.close();
7231
+ }
7232
+ });
7233
+ async function confirm(question, yes) {
7234
+ if (yes) return true;
7235
+ if (!process.stdin.isTTY) {
7236
+ console.error("refusing without -y when stdin is not a terminal");
7237
+ return false;
7238
+ }
7239
+ const { createInterface } = await import("node:readline/promises");
7240
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
7241
+ try {
7242
+ const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
7243
+ return answer === "y" || answer === "yes";
7244
+ } finally {
7245
+ rl.close();
7246
+ }
7247
+ }
7248
+ var WHEN = {
7249
+ start: "is stopped: it trusts the CA from its next start",
7250
+ wake: "is hibernated: it trusts the CA from its next wake",
7251
+ resume: "is in standby: it trusts the CA from its next resume",
7252
+ later: "is running but could not take it now; it trusts the CA from its next stop and start"
7253
+ };
7254
+ function describeReport(report2) {
7255
+ console.log(`CA ${report2.fingerprint}`);
7256
+ for (const box of report2.updated) console.log(`box ${box} now trusts the CA`);
7257
+ for (const p of report2.pending) console.log(`box ${p.box} ${WHEN[p.when]}${p.why ? ` (${p.why})` : ""}`);
7258
+ for (const f of report2.failed) console.error(`box ${f.box}: ${f.error}`);
7259
+ const parts = [`${report2.updated.length} box(es) updated now`, `${report2.pending.length} pending`, `${report2.failed.length} failed`];
7260
+ const skipped = report2.skipped ?? [];
7261
+ if (skipped.length > 0) parts.push(`${skipped.length} cloud box(es) without a CA line untouched (managed services: no certificate opens them)`);
7262
+ if (report2.local > 0) parts.push(`${report2.local} local box(es) untouched (they trust this host's key only)`);
7263
+ console.log(parts.join(", "));
7264
+ }
7265
+
7266
+ // src/commands/rename-realm.ts
7267
+ 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) => {
7268
+ const p = paths();
7269
+ const cp = (await loadConfig(p)).controlPlane;
7270
+ const from = opts.from ?? cp?.name;
7271
+ if (from === void 0) throw new KvboxError("this host has not joined a control plane; say which name the boxes are under: --from <old>");
7272
+ const to = name ?? await fetchCloudName(p);
7273
+ if (from === to) {
7274
+ if (!opts.json) console.log(`nothing to do: the control plane is called ${to} and this host's boxes are already under that name`);
7275
+ else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [] }, null, 2));
7276
+ return;
7277
+ }
7278
+ const count = await countRealm(from, to, p);
7279
+ if (!opts.json) {
7280
+ 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}`);
7281
+ }
7282
+ if (!await confirm(`move them to ${to}? (kvbox-server restarts; boxes keep running, a backup in progress is lost)`, opts.yes ?? false)) {
7283
+ throw new KvboxError("cancelled", 130);
7284
+ }
7285
+ const pid = await daemonPid(p);
7286
+ if (pid !== null) await stopDaemon(pid);
7287
+ let report2;
7288
+ try {
7289
+ report2 = await renameRealm(from, to, p);
7290
+ } finally {
7291
+ if (pid !== null) await startDetached(p);
7292
+ }
7293
+ if (opts.json) console.log(JSON.stringify(report2, null, 2));
7294
+ else describe(report2, pid !== null);
7295
+ });
7296
+ var WHEN2 = {
7297
+ start: "is stopped: it accepts them from its next start",
7298
+ wake: "is hibernated: it accepts them from its next wake",
7299
+ resume: "is in standby: it accepts them from its next resume",
7300
+ later: "is running but could not take the change now; it accepts them from its next stop and start"
7301
+ };
7302
+ function describe(report2, restarted) {
7303
+ console.log(`moved ${report2.boxes} box(es), ${report2.snapshots} snapshot(s) and ${report2.volumes} volume(s) from ${report2.from} to ${report2.to}`);
7304
+ for (const box of report2.keysUpdated) console.log(`box ${box} accepts SSH certificates for ${report2.to} now`);
7305
+ for (const k of report2.keysPending) console.log(`box ${k.box} ${WHEN2[k.when]}${k.why ? ` (${k.why})` : ""}`);
7306
+ console.log(restarted ? "kvbox-server restarted" : "kvbox-server was not running; start it with kvbox-server start -d");
7307
+ }
7308
+
6801
7309
  // src/commands/status.ts
6802
7310
  import { homedir as homedir2 } from "node:os";
6803
7311
  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) => {
7312
+ import { Command as Command12 } from "commander";
7313
+ 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
7314
  const p = paths();
6807
7315
  const atBoot = startsAtBoot(p);
6808
7316
  const pid = await daemonPid(p);
@@ -6874,73 +7382,17 @@ function printStatus(health, atBoot, logPath) {
6874
7382
  }
6875
7383
 
6876
7384
  // 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 () => {
7385
+ import { Command as Command13 } from "commander";
7386
+ var stopCommand = new Command13("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
6879
7387
  const pid = await daemonPid(paths());
6880
7388
  if (pid === null) throw new KvboxError("kvbox-server is not running");
6881
7389
  await stopDaemon(pid);
6882
7390
  console.log(`kvbox-server stopped (pid ${pid}); boxes keep running`);
6883
7391
  });
6884
7392
 
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
7393
  // src/program.ts
6942
7394
  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);
7395
+ 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
7396
  }
6945
7397
 
6946
7398
  // src/index.ts