@kvbox/server 0.6.2 → 0.6.3

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.
@@ -1349,6 +1349,28 @@ var ResizeVolumeRequest = z4.object({
1349
1349
  });
1350
1350
  var RunScriptRequest = z4.object({ input: z4.unknown().optional() });
1351
1351
  var ScriptOutputSchema = z4.object({ output: z4.unknown() });
1352
+ var BOX_RUN_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
1353
+ var StartRunRequest = z4.object({
1354
+ id: z4.string().regex(BOX_RUN_ID_RE),
1355
+ command: z4.string().min(1).max(8192),
1356
+ /** The command and everything it started are killed after this long. */
1357
+ timeoutSec: z4.number().int().min(1).max(86400)
1358
+ });
1359
+ var StartRunAnswerSchema = z4.object({
1360
+ id: z4.string(),
1361
+ /** False: a run of this id was already there. */
1362
+ started: z4.boolean(),
1363
+ /** The box was asleep and this request woke it. */
1364
+ woke: z4.boolean()
1365
+ });
1366
+ var BOX_RUN_STATES = ["running", "exited", "timeout", "unknown"];
1367
+ var BoxRunSchema = z4.object({
1368
+ id: z4.string(),
1369
+ state: z4.enum(BOX_RUN_STATES),
1370
+ /** With `exited`; 128 + the signal for a command a signal ended. */
1371
+ exitCode: z4.number().int().optional()
1372
+ });
1373
+ var RunRefusalSchema = z4.object({ error: z4.string(), code: z4.string().optional() });
1352
1374
  var EnvVarSchema = z4.object({
1353
1375
  name: z4.string(),
1354
1376
  value: z4.string().optional(),
@@ -2027,6 +2049,15 @@ async function idle(udsPath, script, timeoutMs = 15e3) {
2027
2049
  async function runScript(udsPath, path, input, timeoutMs = 35e3) {
2028
2050
  return (await agentCall(udsPath, { op: "script", path, input: input ?? null }, timeoutMs))["output"];
2029
2051
  }
2052
+ async function startRun(udsPath, id, command, timeoutSec, timeoutMs = 15e3) {
2053
+ return (await agentCall(udsPath, { op: "run", id, command, timeoutSec }, timeoutMs))["started"] === true;
2054
+ }
2055
+ async function runStatus(udsPath, id, timeoutMs) {
2056
+ const reply = await agentCall(udsPath, { op: "runStatus", id }, timeoutMs);
2057
+ const state = reply["state"];
2058
+ if (state !== "running" && state !== "exited" && state !== "timeout" && state !== "unknown") throw new KvboxError("kvbox-agent sent a run state this server does not know");
2059
+ return { state, ...typeof reply["exitCode"] === "number" ? { exitCode: reply["exitCode"] } : {} };
2060
+ }
2030
2061
  var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
2031
2062
  var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
2032
2063
  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 ?? "");
@@ -5559,6 +5590,62 @@ async function dropRelay(p = paths()) {
5559
5590
 
5560
5591
  // src/core/idle.ts
5561
5592
  import { readFile as readFile9 } from "node:fs/promises";
5593
+
5594
+ // src/core/runs.ts
5595
+ var BoxOutdatedError = class extends KvboxError {
5596
+ };
5597
+ var SEEN_RUNNING_MS = 3 * 6e4;
5598
+ var going = /* @__PURE__ */ new Map();
5599
+ var keyOf = (ref) => `${ref.owner}/${ref.name}`;
5600
+ function note(ref, id, until) {
5601
+ const key = keyOf(ref);
5602
+ const runs = going.get(key);
5603
+ if (until === null) {
5604
+ runs?.delete(id);
5605
+ if (runs?.size === 0) going.delete(key);
5606
+ return;
5607
+ }
5608
+ if (runs) runs.set(id, Math.max(until, runs.get(id) ?? 0));
5609
+ else going.set(key, /* @__PURE__ */ new Map([[id, until]]));
5610
+ }
5611
+ function boxHasRun(ref, now = Date.now()) {
5612
+ const runs = going.get(keyOf(ref));
5613
+ if (!runs) return false;
5614
+ for (const [id, until] of runs) if (until <= now) runs.delete(id);
5615
+ if (runs.size === 0) going.delete(keyOf(ref));
5616
+ return runs.size > 0;
5617
+ }
5618
+ async function socketOf(ref, p) {
5619
+ const meta = await readMachineMeta(ref, p).catch((err) => {
5620
+ if (err.code === "ENOENT") throw new NotFoundError(`box ${shown(ref)}`);
5621
+ throw err;
5622
+ });
5623
+ const status = statusOf(meta, p);
5624
+ if (status !== "running") throw new KvboxError(`${stateMessage(ref, status)}; only a running box runs a command`);
5625
+ return p.machine(meta.owner, meta.name).vsock;
5626
+ }
5627
+ var outdated = (ref, err) => {
5628
+ if (isUnknownOp(err)) throw new BoxOutdatedError(`box ${shown(ref)} runs on an image from before commands (it needs base v0.15.0 or later)`);
5629
+ if (isNoAgent(err)) throw new KvboxError(`box ${shown(ref)} did not take the request: its kvbox-agent is not answering (${err.message})`);
5630
+ throw err;
5631
+ };
5632
+ async function startBoxRun(ref, req, p = paths()) {
5633
+ const vsock = await socketOf(ref, p);
5634
+ const had = going.get(keyOf(ref))?.has(req.id) ?? false;
5635
+ note(ref, req.id, Date.now() + req.timeoutSec * 1e3 + 6e4);
5636
+ return startRun(vsock, req.id, req.command, req.timeoutSec).catch((err) => {
5637
+ if (!had) note(ref, req.id, null);
5638
+ return outdated(ref, err);
5639
+ });
5640
+ }
5641
+ async function boxRunStatus(ref, id, p = paths()) {
5642
+ const vsock = await socketOf(ref, p);
5643
+ const run2 = await runStatus(vsock, id).catch((err) => outdated(ref, err));
5644
+ note(ref, id, run2.state === "running" ? Date.now() + SEEN_RUNNING_MS : null);
5645
+ return { id, ...run2 };
5646
+ }
5647
+
5648
+ // src/core/idle.ts
5562
5649
  var HIBERNATE_CONCURRENCY = 2;
5563
5650
  async function tapTraffic(id) {
5564
5651
  const dir = `/sys/class/net/${tapName(id)}/statistics`;
@@ -5576,7 +5663,7 @@ async function boxIdle(box, p) {
5576
5663
  async function hibernateIfRunning(box, p) {
5577
5664
  const ref = { owner: box.owner, name: box.name };
5578
5665
  return withBoxLock(ref, async () => {
5579
- if ((await getMachine(ref, p)).status !== "running" || restoreRunning(ref)) return false;
5666
+ if ((await getMachine(ref, p)).status !== "running" || restoreRunning(ref) || boxHasRun(ref)) return false;
5580
5667
  await hibernateMachine(ref, p, "auto-hibernate");
5581
5668
  return true;
5582
5669
  });
@@ -5588,7 +5675,7 @@ function startIdleWatch(opts = {}) {
5588
5675
  const traffic = opts.traffic ?? tapTraffic;
5589
5676
  const guestIdle = opts.guestIdle ?? ((box) => boxIdle(box, p));
5590
5677
  const hibernate = opts.hibernate ?? ((box) => hibernateIfRunning(box, p));
5591
- const busy = opts.busy ?? ((box) => boxBusy(box) || restoreRunning(box));
5678
+ const busy = opts.busy ?? ((box) => boxBusy(box) || restoreRunning(box) || boxHasRun(box));
5592
5679
  const now = opts.now ?? Date.now;
5593
5680
  const log2 = opts.log ?? ((line) => log.info(line));
5594
5681
  const seen = /* @__PURE__ */ new Map();
@@ -6009,12 +6096,13 @@ var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
6009
6096
  function edgeCredential(hostSecret) {
6010
6097
  return createHmac2("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
6011
6098
  }
6099
+ var BOX_RUN_PATH_RE = /^\/machines\/([^/]+)\/runs(\/[A-Za-z0-9_-]{1,64})?\/?$/;
6012
6100
  function cronCredential(hostSecret) {
6013
6101
  return createHmac2("sha256", hostSecret).update("kvbox-cron-v1").digest("base64url");
6014
6102
  }
6015
6103
 
6016
6104
  // src/app.ts
6017
- import { Hono as Hono11 } from "hono";
6105
+ import { Hono as Hono12 } from "hono";
6018
6106
 
6019
6107
  // ../shared/src/version.ts
6020
6108
  import { createRequire } from "node:module";
@@ -6029,7 +6117,7 @@ function versionOf(srcFileUrl, injected) {
6029
6117
  }
6030
6118
 
6031
6119
  // src/version.ts
6032
- var VERSION = versionOf(import.meta.url, true ? "0.6.2" : void 0);
6120
+ var VERSION = versionOf(import.meta.url, true ? "0.6.3" : void 0);
6033
6121
 
6034
6122
  // src/caller.ts
6035
6123
  import { createHash as createHash3, timingSafeEqual } from "node:crypto";
@@ -6049,7 +6137,8 @@ function resolveCaller(opts = {}) {
6049
6137
  const cron = cronCheck(cp);
6050
6138
  return async (c, next) => {
6051
6139
  const auth = c.req.header("authorization");
6052
- if (!authorized(auth) && !((edge(auth) || cron(auth)) && BOX_HTTP_PATH_RE.test(c.req.path))) return c.json({ error: "not authorized" }, 401);
6140
+ const narrow = edge(auth) && BOX_HTTP_PATH_RE.test(c.req.path) || cron(auth) && (BOX_HTTP_PATH_RE.test(c.req.path) || BOX_RUN_PATH_RE.test(c.req.path));
6141
+ if (!authorized(auth) && !narrow) return c.json({ error: "not authorized" }, 401);
6053
6142
  const user = c.req.header(OWNER_HEADER);
6054
6143
  if (user === void 0) {
6055
6144
  const path = c.req.path.replace(/\/$/, "");
@@ -6285,7 +6374,10 @@ async function targetOf(url, owner, path, wake) {
6285
6374
  const m = BOX_HTTP_PATH_RE.exec(url.pathname);
6286
6375
  const port = Number(m?.[2]);
6287
6376
  if (!m || port < 1 || port > 65535) throw new ProxyFailure(404, "not-found", `no route: ${url.pathname}`);
6288
- const name = decodeURIComponent(m[1]);
6377
+ const { box, woke } = await runningBox(decodeURIComponent(m[1]), owner, wake);
6378
+ return { ip: box.ip, port, path, woke };
6379
+ }
6380
+ async function runningBox(name, owner, wake) {
6289
6381
  const ref = parseRef(name, owner);
6290
6382
  let box;
6291
6383
  try {
@@ -6307,7 +6399,7 @@ async function targetOf(url, owner, path, wake) {
6307
6399
  if (woke) box = await getMachine(ref);
6308
6400
  }
6309
6401
  if (box.status !== "running") throw new ProxyFailure(409, notRunning(box.status), `box ${name} is ${box.status}`);
6310
- return { ip: box.ip, port, path, woke };
6402
+ return { ref, box, woke };
6311
6403
  }
6312
6404
  function boxHeaders(incoming, target, upgrade = false) {
6313
6405
  const out = [];
@@ -6621,10 +6713,41 @@ function machineRoutes() {
6621
6713
  return r;
6622
6714
  }
6623
6715
 
6624
- // src/routes/snapshots.ts
6716
+ // src/routes/runs.ts
6625
6717
  import { Hono as Hono7 } from "hono";
6626
- function snapshotRoutes() {
6718
+ var refusal = (c, err) => {
6719
+ if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
6720
+ if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
6721
+ if (err instanceof NotFoundError) return c.json({ error: err.message, code: "not-found" }, 404);
6722
+ throw err;
6723
+ };
6724
+ function runRoutes(wake = wakeBox) {
6627
6725
  const r = new Hono7();
6726
+ r.post("/:name/runs", async (c) => {
6727
+ const body = StartRunRequest.parse(await c.req.json().catch(() => ({})));
6728
+ try {
6729
+ const { ref, woke } = await runningBox(c.req.param("name"), c.get("owner"), wants(c.req.header(WAKE_HEADER)) ? wake : void 0);
6730
+ const started = await startBoxRun(ref, body);
6731
+ return c.json(StartRunAnswerSchema.parse({ id: body.id, started, woke }), 202);
6732
+ } catch (err) {
6733
+ return refusal(c, err);
6734
+ }
6735
+ });
6736
+ r.get("/:name/runs/:id", async (c) => {
6737
+ try {
6738
+ const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
6739
+ return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
6740
+ } catch (err) {
6741
+ return refusal(c, err);
6742
+ }
6743
+ });
6744
+ return r;
6745
+ }
6746
+
6747
+ // src/routes/snapshots.ts
6748
+ import { Hono as Hono8 } from "hono";
6749
+ function snapshotRoutes() {
6750
+ const r = new Hono8();
6628
6751
  r.get("/", async (c) => c.json(await listSnapshots(c.get("listScope"))));
6629
6752
  r.post("/", async (c) => {
6630
6753
  const body = CreateSnapshotRequest.parse(await c.req.json());
@@ -6638,9 +6761,9 @@ function snapshotRoutes() {
6638
6761
  }
6639
6762
 
6640
6763
  // src/routes/ssh.ts
6641
- import { Hono as Hono8 } from "hono";
6764
+ import { Hono as Hono9 } from "hono";
6642
6765
  function sshRoutes(opts = {}) {
6643
- const r = new Hono8();
6766
+ const r = new Hono9();
6644
6767
  if (opts.controlPlane) {
6645
6768
  r.all("/*", (c) => c.json({ error: "trusting a CA is done on the host itself (kvbox-server trust-ca there); the control plane cannot ask a host to" }, 403));
6646
6769
  return r;
@@ -6655,10 +6778,10 @@ function sshRoutes(opts = {}) {
6655
6778
  }
6656
6779
 
6657
6780
  // src/routes/usage.ts
6658
- import { Hono as Hono9 } from "hono";
6781
+ import { Hono as Hono10 } from "hono";
6659
6782
  var PULL_LIMIT = 1e3;
6660
6783
  function usageRoutes(opts = {}) {
6661
- const r = new Hono9();
6784
+ const r = new Hono10();
6662
6785
  r.get("/", async (c) => {
6663
6786
  let window;
6664
6787
  try {
@@ -6691,9 +6814,9 @@ function whole(value, name) {
6691
6814
  }
6692
6815
 
6693
6816
  // src/routes/volumes.ts
6694
- import { Hono as Hono10 } from "hono";
6817
+ import { Hono as Hono11 } from "hono";
6695
6818
  function volumeRoutes() {
6696
- const r = new Hono10();
6819
+ const r = new Hono11();
6697
6820
  r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
6698
6821
  r.post("/", async (c) => {
6699
6822
  const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
@@ -6723,7 +6846,7 @@ function volumeRoutes() {
6723
6846
 
6724
6847
  // src/app.ts
6725
6848
  function createApp(opts = {}) {
6726
- const app = new Hono11();
6849
+ const app = new Hono12();
6727
6850
  app.use(resolveCaller(opts));
6728
6851
  app.get("/health", async (c) => {
6729
6852
  const cfg = await loadConfig();
@@ -6742,6 +6865,7 @@ function createApp(opts = {}) {
6742
6865
  });
6743
6866
  if (opts.controlPlane) app.post("/update", async (c) => c.json(await startUpdate(VERSION), 202));
6744
6867
  if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
6868
+ if (opts.controlPlane) app.route("/machines", runRoutes());
6745
6869
  if (opts.controlPlane) {
6746
6870
  app.route("/machines", backupMachineRoutes());
6747
6871
  app.route("/volumes", backupVolumeRoutes());