@kvbox/server 0.5.47 → 0.5.48

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.
@@ -225,7 +225,8 @@ function computeUsage(events, w) {
225
225
  vcpuHours: round(vcpuHours, 3),
226
226
  ramGibHours: round(ramGibHours, 3),
227
227
  diskGibHours: round(diskGibHours, 3),
228
- estimatedStops: sorted.filter((e) => e.state === "stopped" && e.by === "server" && e.at >= w.from).length,
228
+ // Inside the window only: rows may be dated after `to` (a ledger counted up to its last pull, #172).
229
+ estimatedStops: sorted.filter((e) => e.state === "stopped" && e.by === "server" && e.at >= w.from && e.at < w.to).length,
229
230
  historyFrom: sorted[0]?.at ?? null
230
231
  };
231
232
  if (w.pricing !== void 0) totals.cost = { amount: round(costOf(totals, w.pricing), 4), currency: w.pricing.currency };
@@ -338,6 +339,7 @@ function reportTotals(boxes, volumes, pricing) {
338
339
  if (pricing !== void 0) return { ...out, cost: { amount: round(costOf(sum, pricing) + volumeCostOf(vol, pricing), 4), currency: pricing.currency } };
339
340
  return out;
340
341
  }
342
+ var DAY_MS = 24 * HOUR_MS;
341
343
 
342
344
  // src/core/refs.ts
343
345
  import { userInfo } from "node:os";
@@ -685,7 +687,7 @@ var MachineMetaSchema = z3.object({
685
687
  * each host port the box's for its life. DNATed while the box runs, rebuilt from here with its
686
688
  * current IP every time it comes up. Absent: none.
687
689
  */
688
- ports: z3.array(z3.object({ guestPort: z3.number().int(), hostPort: z3.number().int(), proto: z3.enum(["tcp", "udp"]) })).optional(),
690
+ ports: z3.array(z3.object({ guestPort: z3.number().int(), hostPort: z3.number().int(), proto: z3.enum(["tcp", "udp"]), closed: z3.literal(true).optional() })).optional(),
689
691
  /** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
690
692
  autoHibernateSec: z3.number().int().positive().optional(),
691
693
  /**
@@ -992,10 +994,17 @@ var PortForwardSchema = z4.object({
992
994
  hostPort: z4.number().int(),
993
995
  proto: PortProtoSchema,
994
996
  /** The host's public address; only the control plane fills it in, as for `ssh`. */
995
- address: z4.string().optional()
997
+ address: z4.string().optional(),
998
+ /**
999
+ * Closed but kept (#173): nothing reaches the box through it, and the host port stays the box's, so
1000
+ * publishing the same box port again opens the same number. Absent: open while the box runs.
1001
+ */
1002
+ closed: z4.literal(true).optional()
996
1003
  });
997
1004
  var PortsRequest = z4.object({
998
- ports: z4.array(z4.object({ guestPort: z4.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
1005
+ ports: z4.array(z4.object({ guestPort: z4.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),
1006
+ /** `DELETE` only (#173): close the ports but keep their host ports for the box (`closed`). */
1007
+ keep: z4.boolean().optional()
999
1008
  });
1000
1009
  var BoxPortSchema = z4.number().int().min(1).max(65535);
1001
1010
  var MAX_BOX_LINKS = 32;
@@ -1180,6 +1189,11 @@ var CreateVolumeRequest = z4.object({
1180
1189
  var AttachVolumeRequest = z4.object({
1181
1190
  box: z4.string()
1182
1191
  });
1192
+ var ResizeVolumeRequest = z4.object({
1193
+ sizeGib: z4.number().int().min(1).max(MAX_VOLUME_GIB)
1194
+ });
1195
+ var RunScriptRequest = z4.object({ input: z4.unknown().optional() });
1196
+ var ScriptOutputSchema = z4.object({ output: z4.unknown() });
1183
1197
  var EnvVarSchema = z4.object({
1184
1198
  name: z4.string(),
1185
1199
  value: z4.string().optional(),
@@ -1435,11 +1449,31 @@ var VolumeUsageSchema = z4.object({
1435
1449
  cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
1436
1450
  historyFrom: z4.string().nullable()
1437
1451
  });
1452
+ var UsageDayItemSchema = z4.object({
1453
+ id: z4.string(),
1454
+ name: z4.string(),
1455
+ owner: z4.string(),
1456
+ /** Removed by the end of the report's window. */
1457
+ removed: z4.boolean(),
1458
+ cost: z4.number()
1459
+ });
1460
+ var UsageDaySchema = z4.object({
1461
+ /** `YYYY-MM-DD`, UTC. */
1462
+ date: z4.string(),
1463
+ from: z4.string(),
1464
+ to: z4.string(),
1465
+ cost: z4.number(),
1466
+ currency: z4.string(),
1467
+ boxes: z4.array(UsageDayItemSchema),
1468
+ volumes: z4.array(UsageDayItemSchema)
1469
+ });
1438
1470
  var UsageReportSchema = z4.object({
1439
1471
  window: z4.object({ from: z4.string(), to: z4.string() }),
1440
1472
  boxes: z4.array(BoxUsageSchema),
1441
1473
  /** Absent from a side older than #91. */
1442
1474
  volumes: z4.array(VolumeUsageSchema).optional(),
1475
+ /** With `?by=day` only, oldest day first. */
1476
+ days: z4.array(UsageDaySchema).optional(),
1443
1477
  totals: z4.object({
1444
1478
  seconds: MachineUsageSchema.shape.seconds,
1445
1479
  vcpuHours: z4.number(),
@@ -1673,7 +1707,9 @@ var TrustCaReportSchema = z4.object({
1673
1707
  pending: z4.array(z4.object({ box: z4.string(), when: SshKeysAppliedSchema, why: z4.string().optional() })),
1674
1708
  failed: z4.array(z4.object({ box: z4.string(), error: z4.string() })),
1675
1709
  /** Local boxes, untouched: they trust the host's key only. */
1676
- local: z4.number().int()
1710
+ local: z4.number().int(),
1711
+ /** Cloud boxes made without a CA line (a managed service's, #173), untouched: no certificate opens them. Absent from older servers. */
1712
+ skipped: z4.array(z4.string()).optional()
1677
1713
  });
1678
1714
  var HostJoinRequestSchema = z4.object({
1679
1715
  token: z4.string().min(1),
@@ -1795,6 +1831,9 @@ function setEnv(udsPath, vars, timeoutMs) {
1795
1831
  async function idle(udsPath, script, timeoutMs = 15e3) {
1796
1832
  return (await agentCall(udsPath, { op: "idle", path: script }, timeoutMs))["idle"] === true;
1797
1833
  }
1834
+ async function runScript(udsPath, path, input, timeoutMs = 35e3) {
1835
+ return (await agentCall(udsPath, { op: "script", path, input: input ?? null }, timeoutMs))["output"];
1836
+ }
1798
1837
  var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
1799
1838
  var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
1800
1839
  var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
@@ -2131,7 +2170,12 @@ var ImageManifestSchema = z6.object({
2131
2170
  /** Variables the host fills with a random password when the caller gave none. */
2132
2171
  generate: z6.array(z6.string()).optional(),
2133
2172
  /** How to reach what the box serves, `${NAME}` taken from its variables and `${BOX}` its name. */
2134
- connect: z6.string().optional()
2173
+ connect: z6.string().optional(),
2174
+ /**
2175
+ * Scripts in the box the host may run by name through kvbox-agent (#173): `status`, `password`, …
2176
+ * The host knows the names only; what each does and answers is the image's.
2177
+ */
2178
+ scripts: z6.record(z6.string(), z6.string().startsWith("/")).optional()
2135
2179
  });
2136
2180
  var manifests = /* @__PURE__ */ new Map();
2137
2181
  async function imageManifest(file) {
@@ -2356,6 +2400,33 @@ async function deleteVolume(ref, p = paths()) {
2356
2400
  }
2357
2401
  });
2358
2402
  }
2403
+ async function assertCanGrow(ref, sizeGib, p = paths()) {
2404
+ const meta = await readVolume(ref, p);
2405
+ if (!Number.isInteger(sizeGib) || sizeGib > MAX_VOLUME_GIB) throw new KvboxError(`volume size: whole GB, at most ${MAX_VOLUME_GIB}`);
2406
+ if (sizeGib <= meta.sizeGib) {
2407
+ throw new KvboxError(`volume ${shown(ref)} is ${meta.sizeGib} GB and a volume only grows; ${sizeGib} GB is ${sizeGib === meta.sizeGib ? "what it has" : "smaller"}`);
2408
+ }
2409
+ const disk = await diskCapacity(p);
2410
+ const more = sizeGib - meta.sizeGib;
2411
+ if (!hasDiskRoom(disk, more)) {
2412
+ throw new KvboxError(`not enough disk on this host to grow volume ${shown(ref)} by ${more} GB: it can still promise ${volumeRoomGib(disk)} GB`);
2413
+ }
2414
+ return meta;
2415
+ }
2416
+ async function growVolume(ref, sizeGib, p = paths(), check) {
2417
+ return withHostLock("volumes", async () => {
2418
+ const meta = await assertCanGrow(ref, sizeGib, p);
2419
+ await check?.();
2420
+ const disk = p.volume(ref.owner, ref.name).disk;
2421
+ await truncate(disk, sizeGib * 1024 ** 3);
2422
+ await run(["e2fsck", "-f", "-p", disk], { okExitCodes: [1] });
2423
+ await run(["resize2fs", disk]);
2424
+ const grown = { ...meta, sizeGib };
2425
+ await writeVolumeMeta(grown, p);
2426
+ recordVolume(grown, "resize", p);
2427
+ return toVolume(grown, (await attachments(ref.owner, p)).get(ref.name) ?? null, p);
2428
+ });
2429
+ }
2359
2430
  function volumeRef(box, name) {
2360
2431
  return parseRef(name, box.owner);
2361
2432
  }
@@ -2941,7 +3012,7 @@ var publicPortsInUse = (metas) => metas.flatMap((m) => [...m.sshPort === void 0
2941
3012
  var isCloudBox = (owner) => realmOf(owner) !== null;
2942
3013
  function boxProxies(meta) {
2943
3014
  const ssh = meta.sshPort === void 0 ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];
2944
- return [...ssh, ...(meta.ports ?? []).map((f) => ({ box: meta.id, boxIp: meta.ip, hostPort: f.hostPort, guestPort: f.guestPort, proto: f.proto }))];
3015
+ return [...ssh, ...(meta.ports ?? []).filter((f) => !f.closed).map((f) => ({ box: meta.id, boxIp: meta.ip, hostPort: f.hostPort, guestPort: f.guestPort, proto: f.proto }))];
2945
3016
  }
2946
3017
  function boxLinks(meta) {
2947
3018
  return (meta.links ?? []).map((l) => ({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }));
@@ -3640,7 +3711,7 @@ async function applySshKeys(meta, sshKeys, p) {
3640
3711
  }
3641
3712
  async function trustCa(publicKeyText, p = paths()) {
3642
3713
  const publicKey = parseSshPublicKey(publicKeyText);
3643
- const report2 = { publicKey, fingerprint: sshKeyFingerprint(publicKey), updated: [], pending: [], failed: [], local: 0 };
3714
+ const report2 = { publicKey, fingerprint: sshKeyFingerprint(publicKey), updated: [], pending: [], failed: [], local: 0, skipped: [] };
3644
3715
  const hostKey = await readHostPubkey(p);
3645
3716
  for (const listed of await readAllMeta(p)) {
3646
3717
  if (!isCloudBox(listed.owner)) {
@@ -3651,6 +3722,10 @@ async function trustCa(publicKeyText, p = paths()) {
3651
3722
  try {
3652
3723
  await withBoxLock(listed, async () => {
3653
3724
  const meta = await readMeta(listed, p);
3725
+ if (!(meta.sshKeys ?? []).some(isCaLine)) {
3726
+ report2.skipped.push(box);
3727
+ return;
3728
+ }
3654
3729
  const sshKeys = [...(meta.sshKeys ?? []).filter((l) => !isCaLine(l)), caLineFor(meta.owner, publicKey)];
3655
3730
  authorizedKeysLines(hostKey, sshKeys);
3656
3731
  const { applied, why } = await applySshKeys(meta, sshKeys, p);
@@ -3775,7 +3850,21 @@ async function applyAtNextBoot(meta, changes, by, cfg, p, whileStopped) {
3775
3850
  }
3776
3851
  const updated = { ...meta, ...changes, pid: null, memSnapshots: void 0, paused: void 0 };
3777
3852
  await writeMachineMeta(updated, p);
3778
- if (whileStopped) await whileStopped();
3853
+ if (whileStopped) {
3854
+ try {
3855
+ await whileStopped();
3856
+ } catch (err) {
3857
+ const before = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
3858
+ await writeMachineMeta(before, p);
3859
+ if (wasRunning) {
3860
+ recordState(before, "stopped", by, p);
3861
+ await startMachine(meta, p, true).catch((e) => {
3862
+ throw new KvboxError(`${err.message}; and box ${shown(meta)} could not be started again: ${e.message}`);
3863
+ });
3864
+ }
3865
+ throw err;
3866
+ }
3867
+ }
3779
3868
  recordState(updated, "stopped", by, p);
3780
3869
  return wasRunning ? startMachine(meta, p, true) : toMachine(updated, p);
3781
3870
  }
@@ -3857,6 +3946,28 @@ var detachVolume = locked(async function detachVolume2(ref, volume, p = paths())
3857
3946
  const kept = meta.volumes.filter((v) => v !== volume.name);
3858
3947
  return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () => rm3(p.machine(ref.owner, ref.name).volumeDrive(volume.name), { force: true }));
3859
3948
  });
3949
+ async function resizeVolume(volume, sizeGib, p = paths()) {
3950
+ await assertCanGrow(volume, sizeGib, p);
3951
+ const holder = await attachedBox(volume, p);
3952
+ if (holder === null) {
3953
+ return growVolume(volume, sizeGib, p, async () => {
3954
+ const now = await attachedBox(volume, p);
3955
+ if (now !== null) throw new KvboxError(`volume ${shown(volume)} was just attached to box ${now}; try again`);
3956
+ });
3957
+ }
3958
+ const box = { owner: volume.owner, name: holder };
3959
+ return withBoxLock(box, async () => {
3960
+ const meta = await readMeta(box, p);
3961
+ if (!meta.volumes?.includes(volume.name)) throw new KvboxError(`volume ${shown(volume)} was just detached from box ${holder}; try again`);
3962
+ assertNotHibernated(meta, p);
3963
+ const cfg = await loadConfig(p);
3964
+ let grown;
3965
+ await applyAtNextBoot(meta, {}, "grow", cfg, p, async () => {
3966
+ grown = await growVolume(volume, sizeGib, p);
3967
+ });
3968
+ return { ...grown, attachedTo: holder };
3969
+ });
3970
+ }
3860
3971
  var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
3861
3972
  const meta = await readMeta(ref, p);
3862
3973
  const next = { ...meta };
@@ -3875,25 +3986,30 @@ var addPorts = locked(async function addPorts2(ref, req, p = paths()) {
3875
3986
  const cfg = await loadConfig(p);
3876
3987
  const current = meta.ports ?? [];
3877
3988
  const wanted = portKeys(req);
3878
- const already = wanted.find((w) => current.some(samePort(w)));
3989
+ const isClosed = (k) => current.some((f) => samePort(k)(f) && f.closed);
3990
+ const reopened = wanted.filter(isClosed);
3991
+ const fresh = wanted.filter((w) => !current.some(samePort(w)));
3992
+ const already = wanted.find((w) => current.some(samePort(w)) && !isClosed(w));
3879
3993
  if (already) throw new KvboxError(`box ${shown(ref)} already publishes port ${already.guestPort} (${already.proto})`);
3880
3994
  if (meta.sshPort !== void 0 && wanted.some(samePort({ guestPort: 22, proto: "tcp" }))) {
3881
3995
  throw new KvboxError(`box ${shown(ref)} already reaches port 22 from outside on port ${meta.sshPort} (kvbox connect)`);
3882
3996
  }
3883
- if (current.length + wanted.length > MAX_BOX_PORTS) {
3997
+ if (current.length + fresh.length > MAX_BOX_PORTS) {
3884
3998
  throw new KvboxError(`a box publishes at most ${MAX_BOX_PORTS} ports; box ${shown(ref)} has ${current.length}`);
3885
3999
  }
3886
- const drawn = await drawPorts(wanted.length, p);
4000
+ const drawn = await drawPorts(fresh.length, p);
3887
4001
  const opened = [];
3888
4002
  try {
3889
- const added = wanted.map((w, i) => ({ ...w, hostPort: drawn.ports[i] }));
4003
+ const added = fresh.map((w, i) => ({ ...w, hostPort: drawn.ports[i] }));
4004
+ const open3 = ({ closed: _closed, ...f }) => f;
4005
+ const again = current.filter((f) => reopened.some(samePort(f))).map(open3);
3890
4006
  if (vmAlive(meta)) {
3891
- for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: added })) {
4007
+ for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: [...again, ...added] })) {
3892
4008
  await openProxy(proxy, cfg);
3893
4009
  opened.push(proxy);
3894
4010
  }
3895
4011
  }
3896
- const next = { ...meta, ports: [...current, ...added] };
4012
+ const next = { ...meta, ports: [...current.map((f) => reopened.some(samePort(f)) ? open3(f) : f), ...added] };
3897
4013
  await writeMachineMeta(next, p);
3898
4014
  return toMachine(next, p);
3899
4015
  } catch (err) {
@@ -3912,7 +4028,7 @@ var removePorts = locked(async function removePorts2(ref, req, p = paths()) {
3912
4028
  if (missing) throw new KvboxError(`box ${shown(ref)} does not publish port ${missing.guestPort} (${missing.proto})`);
3913
4029
  const removed = current.filter((f) => gone.some(samePort(f)));
3914
4030
  for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: removed })) await closeProxy(proxy, cfg);
3915
- const kept = current.filter((f) => !gone.some(samePort(f)));
4031
+ const kept = req.keep ? current.map((f) => gone.some(samePort(f)) ? { ...f, closed: true } : f) : current.filter((f) => !gone.some(samePort(f)));
3916
4032
  const next = { ...meta, ports: kept.length > 0 ? kept : void 0 };
3917
4033
  await writeMachineMeta(next, p);
3918
4034
  return toMachine(next, p);
@@ -5167,7 +5283,7 @@ function versionOf(srcFileUrl, injected) {
5167
5283
  }
5168
5284
 
5169
5285
  // src/version.ts
5170
- var VERSION = versionOf(import.meta.url, true ? "0.5.47" : void 0);
5286
+ var VERSION = versionOf(import.meta.url, true ? "0.5.48" : void 0);
5171
5287
 
5172
5288
  // src/caller.ts
5173
5289
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";
@@ -5601,6 +5717,27 @@ async function machineStats(ref, p = paths(), replyMs = STATS_REPLY_MS) {
5601
5717
  }
5602
5718
  }
5603
5719
 
5720
+ // src/core/scripts.ts
5721
+ async function runBoxScript(ref, script, input, p = paths()) {
5722
+ const meta = await readMachineMeta(ref, p).catch((err) => {
5723
+ if (err.code === "ENOENT") throw new NotFoundError(`box ${shown(ref)}`);
5724
+ throw err;
5725
+ });
5726
+ const manifest = await imageManifest(imageFileFor(meta, p));
5727
+ const path = Object.hasOwn(manifest.scripts ?? {}, script) ? manifest.scripts[script] : void 0;
5728
+ if (path === void 0) throw new KvboxError(`box ${shown(ref)} runs on ${imageLabel(meta.image)} ${meta.base}, which has no "${script}" script`);
5729
+ const status = statusOf(meta, p);
5730
+ if (status !== "running") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be asked`);
5731
+ try {
5732
+ return { output: await runScript(p.machine(meta.owner, meta.name).vsock, path, input) };
5733
+ } catch (err) {
5734
+ if (isUnknownOp(err) || isNoAgent(err)) {
5735
+ throw new KvboxError(`box ${shown(ref)} did not take the request: its image's kvbox-agent is too old or still starting (${err.message})`);
5736
+ }
5737
+ throw err;
5738
+ }
5739
+ }
5740
+
5604
5741
  // src/core/usage.ts
5605
5742
  async function machineUsage(ref, since, p = paths()) {
5606
5743
  const box = await getMachine(ref, p);
@@ -5709,6 +5846,10 @@ function machineRoutes() {
5709
5846
  const box = await getMachine(ref);
5710
5847
  return c.json({ box: ref.name, name, running: box.status !== "stopped" });
5711
5848
  });
5849
+ r.post("/:name/scripts/:script", async (c) => {
5850
+ const body = RunScriptRequest.parse(await c.req.json().catch(() => ({})));
5851
+ return c.json(await runBoxScript(parseRef(c.req.param("name"), c.get("owner")), c.req.param("script"), body.input));
5852
+ });
5712
5853
  r.get("/:name/stats", async (c) => c.json(await machineStats(parseRef(c.req.param("name"), c.get("owner")))));
5713
5854
  r.delete("/:name", async (c) => {
5714
5855
  await destroyMachine(parseRef(c.req.param("name"), c.get("owner")));
@@ -5810,6 +5951,10 @@ function volumeRoutes() {
5810
5951
  const owner = c.get("owner");
5811
5952
  return c.json(await detachVolume(parseRef(body.box, owner), parseRef(c.req.param("name"), owner)));
5812
5953
  });
5954
+ r.post("/:name/resize", async (c) => {
5955
+ const body = ResizeVolumeRequest.parse(await c.req.json().catch(() => ({})));
5956
+ return c.json(await resizeVolume(parseRef(c.req.param("name"), c.get("owner")), body.sizeGib));
5957
+ });
5813
5958
  return r;
5814
5959
  }
5815
5960
 
@@ -6222,6 +6367,8 @@ function describeReport(report2) {
6222
6367
  for (const p of report2.pending) console.log(`box ${p.box} ${WHEN[p.when]}${p.why ? ` (${p.why})` : ""}`);
6223
6368
  for (const f of report2.failed) console.error(`box ${f.box}: ${f.error}`);
6224
6369
  const parts = [`${report2.updated.length} box(es) updated now`, `${report2.pending.length} pending`, `${report2.failed.length} failed`];
6370
+ const skipped = report2.skipped ?? [];
6371
+ if (skipped.length > 0) parts.push(`${skipped.length} cloud box(es) without a CA line untouched (managed services: no certificate opens them)`);
6225
6372
  if (report2.local > 0) parts.push(`${report2.local} local box(es) untouched (they trust this host's key only)`);
6226
6373
  console.log(parts.join(", "));
6227
6374
  }