@kvbox/server 0.6.1 → 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.
@@ -209,7 +209,9 @@ var PricingSchema = z.object({
209
209
  */
210
210
  storageHour: z.number().nonnegative().default(0),
211
211
  storageGibHour: z.number().nonnegative().default(0),
212
- 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)
213
215
  });
214
216
  var PriceListSchema = PricingSchema.extend({ welcomeCredit: z.number().nonnegative() });
215
217
  var HOUR_MS = 36e5;
@@ -1347,6 +1349,28 @@ var ResizeVolumeRequest = z4.object({
1347
1349
  });
1348
1350
  var RunScriptRequest = z4.object({ input: z4.unknown().optional() });
1349
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() });
1350
1374
  var EnvVarSchema = z4.object({
1351
1375
  name: z4.string(),
1352
1376
  value: z4.string().optional(),
@@ -1615,6 +1639,17 @@ var VolumeUsageSchema = z4.object({
1615
1639
  cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
1616
1640
  historyFrom: z4.string().nullable()
1617
1641
  });
1642
+ var CronUsageSchema = z4.object({
1643
+ id: z4.string(),
1644
+ name: z4.string(),
1645
+ owner: z4.string(),
1646
+ ownerKind: z4.enum(["user", "org"]).optional(),
1647
+ status: z4.enum(["present", "removed"]),
1648
+ hours: z4.number(),
1649
+ cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
1650
+ /** When it was made. */
1651
+ historyFrom: z4.string().nullable()
1652
+ });
1618
1653
  var UsageDayItemSchema = z4.object({
1619
1654
  id: z4.string(),
1620
1655
  name: z4.string(),
@@ -1633,7 +1668,9 @@ var UsageDaySchema = z4.object({
1633
1668
  boxes: z4.array(UsageDayItemSchema),
1634
1669
  volumes: z4.array(UsageDayItemSchema),
1635
1670
  /** Object storage that existed that day (#182); absent on a day without any. */
1636
- storage: z4.array(UsageDayItemSchema).optional()
1671
+ storage: z4.array(UsageDayItemSchema).optional(),
1672
+ /** Cron services that existed that day (#190); absent on a day without any. */
1673
+ cron: z4.array(UsageDayItemSchema).optional()
1637
1674
  });
1638
1675
  var UsageReportSchema = z4.object({
1639
1676
  window: z4.object({ from: z4.string(), to: z4.string() }),
@@ -1646,6 +1683,8 @@ var UsageReportSchema = z4.object({
1646
1683
  * included ones, `sizeGib` its whole size. Absent when there is none.
1647
1684
  */
1648
1685
  storage: z4.array(VolumeUsageSchema).optional(),
1686
+ /** Cron services (#190, control plane only): one row per service a slug has or had. Absent when there is none. */
1687
+ cron: z4.array(CronUsageSchema).optional(),
1649
1688
  /** With `?by=day` only, oldest day first. */
1650
1689
  days: z4.array(UsageDaySchema).optional(),
1651
1690
  totals: z4.object({
@@ -1655,7 +1694,7 @@ var UsageReportSchema = z4.object({
1655
1694
  diskGibHours: z4.number(),
1656
1695
  volumeHours: z4.number().optional(),
1657
1696
  volumeGibHours: z4.number().optional(),
1658
- /** Boxes, volumes and object storage together. */
1697
+ /** Boxes, volumes, object storage and cron services together. */
1659
1698
  cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional()
1660
1699
  })
1661
1700
  });
@@ -2010,6 +2049,15 @@ async function idle(udsPath, script, timeoutMs = 15e3) {
2010
2049
  async function runScript(udsPath, path, input, timeoutMs = 35e3) {
2011
2050
  return (await agentCall(udsPath, { op: "script", path, input: input ?? null }, timeoutMs))["output"];
2012
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
+ }
2013
2061
  var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
2014
2062
  var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
2015
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 ?? "");
@@ -5542,6 +5590,62 @@ async function dropRelay(p = paths()) {
5542
5590
 
5543
5591
  // src/core/idle.ts
5544
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
5545
5649
  var HIBERNATE_CONCURRENCY = 2;
5546
5650
  async function tapTraffic(id) {
5547
5651
  const dir = `/sys/class/net/${tapName(id)}/statistics`;
@@ -5559,7 +5663,7 @@ async function boxIdle(box, p) {
5559
5663
  async function hibernateIfRunning(box, p) {
5560
5664
  const ref = { owner: box.owner, name: box.name };
5561
5665
  return withBoxLock(ref, async () => {
5562
- 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;
5563
5667
  await hibernateMachine(ref, p, "auto-hibernate");
5564
5668
  return true;
5565
5669
  });
@@ -5571,7 +5675,7 @@ function startIdleWatch(opts = {}) {
5571
5675
  const traffic = opts.traffic ?? tapTraffic;
5572
5676
  const guestIdle = opts.guestIdle ?? ((box) => boxIdle(box, p));
5573
5677
  const hibernate = opts.hibernate ?? ((box) => hibernateIfRunning(box, p));
5574
- const busy = opts.busy ?? ((box) => boxBusy(box) || restoreRunning(box));
5678
+ const busy = opts.busy ?? ((box) => boxBusy(box) || restoreRunning(box) || boxHasRun(box));
5575
5679
  const now = opts.now ?? Date.now;
5576
5680
  const log2 = opts.log ?? ((line) => log.info(line));
5577
5681
  const seen = /* @__PURE__ */ new Map();
@@ -5992,9 +6096,13 @@ var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
5992
6096
  function edgeCredential(hostSecret) {
5993
6097
  return createHmac2("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
5994
6098
  }
6099
+ var BOX_RUN_PATH_RE = /^\/machines\/([^/]+)\/runs(\/[A-Za-z0-9_-]{1,64})?\/?$/;
6100
+ function cronCredential(hostSecret) {
6101
+ return createHmac2("sha256", hostSecret).update("kvbox-cron-v1").digest("base64url");
6102
+ }
5995
6103
 
5996
6104
  // src/app.ts
5997
- import { Hono as Hono11 } from "hono";
6105
+ import { Hono as Hono12 } from "hono";
5998
6106
 
5999
6107
  // ../shared/src/version.ts
6000
6108
  import { createRequire } from "node:module";
@@ -6009,7 +6117,7 @@ function versionOf(srcFileUrl, injected) {
6009
6117
  }
6010
6118
 
6011
6119
  // src/version.ts
6012
- var VERSION = versionOf(import.meta.url, true ? "0.6.1" : void 0);
6120
+ var VERSION = versionOf(import.meta.url, true ? "0.6.3" : void 0);
6013
6121
 
6014
6122
  // src/caller.ts
6015
6123
  import { createHash as createHash3, timingSafeEqual } from "node:crypto";
@@ -6026,9 +6134,11 @@ function resolveCaller(opts = {}) {
6026
6134
  }
6027
6135
  const authorized = secretCheck(cp);
6028
6136
  const edge = edgeCheck(cp);
6137
+ const cron = cronCheck(cp);
6029
6138
  return async (c, next) => {
6030
6139
  const auth = c.req.header("authorization");
6031
- if (!authorized(auth) && !(edge(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);
6032
6142
  const user = c.req.header(OWNER_HEADER);
6033
6143
  if (user === void 0) {
6034
6144
  const path = c.req.path.replace(/\/$/, "");
@@ -6053,6 +6163,9 @@ function secretCheck(cp) {
6053
6163
  function edgeCheck(cp) {
6054
6164
  return bearerCheck(edgeCredential(cp.secret));
6055
6165
  }
6166
+ function cronCheck(cp) {
6167
+ return bearerCheck(cronCredential(cp.secret));
6168
+ }
6056
6169
  function bearerCheck(token) {
6057
6170
  const expected = digest(token);
6058
6171
  return (authorization) => {
@@ -6261,7 +6374,10 @@ async function targetOf(url, owner, path, wake) {
6261
6374
  const m = BOX_HTTP_PATH_RE.exec(url.pathname);
6262
6375
  const port = Number(m?.[2]);
6263
6376
  if (!m || port < 1 || port > 65535) throw new ProxyFailure(404, "not-found", `no route: ${url.pathname}`);
6264
- 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) {
6265
6381
  const ref = parseRef(name, owner);
6266
6382
  let box;
6267
6383
  try {
@@ -6283,7 +6399,7 @@ async function targetOf(url, owner, path, wake) {
6283
6399
  if (woke) box = await getMachine(ref);
6284
6400
  }
6285
6401
  if (box.status !== "running") throw new ProxyFailure(409, notRunning(box.status), `box ${name} is ${box.status}`);
6286
- return { ip: box.ip, port, path, woke };
6402
+ return { ref, box, woke };
6287
6403
  }
6288
6404
  function boxHeaders(incoming, target, upgrade = false) {
6289
6405
  const out = [];
@@ -6597,10 +6713,41 @@ function machineRoutes() {
6597
6713
  return r;
6598
6714
  }
6599
6715
 
6600
- // src/routes/snapshots.ts
6716
+ // src/routes/runs.ts
6601
6717
  import { Hono as Hono7 } from "hono";
6602
- 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) {
6603
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();
6604
6751
  r.get("/", async (c) => c.json(await listSnapshots(c.get("listScope"))));
6605
6752
  r.post("/", async (c) => {
6606
6753
  const body = CreateSnapshotRequest.parse(await c.req.json());
@@ -6614,9 +6761,9 @@ function snapshotRoutes() {
6614
6761
  }
6615
6762
 
6616
6763
  // src/routes/ssh.ts
6617
- import { Hono as Hono8 } from "hono";
6764
+ import { Hono as Hono9 } from "hono";
6618
6765
  function sshRoutes(opts = {}) {
6619
- const r = new Hono8();
6766
+ const r = new Hono9();
6620
6767
  if (opts.controlPlane) {
6621
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));
6622
6769
  return r;
@@ -6631,10 +6778,10 @@ function sshRoutes(opts = {}) {
6631
6778
  }
6632
6779
 
6633
6780
  // src/routes/usage.ts
6634
- import { Hono as Hono9 } from "hono";
6781
+ import { Hono as Hono10 } from "hono";
6635
6782
  var PULL_LIMIT = 1e3;
6636
6783
  function usageRoutes(opts = {}) {
6637
- const r = new Hono9();
6784
+ const r = new Hono10();
6638
6785
  r.get("/", async (c) => {
6639
6786
  let window;
6640
6787
  try {
@@ -6667,9 +6814,9 @@ function whole(value, name) {
6667
6814
  }
6668
6815
 
6669
6816
  // src/routes/volumes.ts
6670
- import { Hono as Hono10 } from "hono";
6817
+ import { Hono as Hono11 } from "hono";
6671
6818
  function volumeRoutes() {
6672
- const r = new Hono10();
6819
+ const r = new Hono11();
6673
6820
  r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
6674
6821
  r.post("/", async (c) => {
6675
6822
  const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
@@ -6699,7 +6846,7 @@ function volumeRoutes() {
6699
6846
 
6700
6847
  // src/app.ts
6701
6848
  function createApp(opts = {}) {
6702
- const app = new Hono11();
6849
+ const app = new Hono12();
6703
6850
  app.use(resolveCaller(opts));
6704
6851
  app.get("/health", async (c) => {
6705
6852
  const cfg = await loadConfig();
@@ -6718,6 +6865,7 @@ function createApp(opts = {}) {
6718
6865
  });
6719
6866
  if (opts.controlPlane) app.post("/update", async (c) => c.json(await startUpdate(VERSION), 202));
6720
6867
  if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
6868
+ if (opts.controlPlane) app.route("/machines", runRoutes());
6721
6869
  if (opts.controlPlane) {
6722
6870
  app.route("/machines", backupMachineRoutes());
6723
6871
  app.route("/volumes", backupVolumeRoutes());
@@ -6781,7 +6929,8 @@ async function listen(opts = {}) {
6781
6929
  });
6782
6930
  const secret = secretCheck(cp);
6783
6931
  const edge = edgeCheck(cp);
6784
- limitUntrusted(httpsServer, (req) => secret(req.headers.authorization) || edge(req.headers.authorization));
6932
+ const cron = cronCheck(cp);
6933
+ limitUntrusted(httpsServer, (req) => secret(req.headers.authorization) || edge(req.headers.authorization) || cron(req.headers.authorization));
6785
6934
  httpsServer.on("upgrade", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));
6786
6935
  const port = opts.httpsPort ?? cp.port;
6787
6936
  await new Promise((resolve3, reject) => {