@kvbox/server 0.6.2 → 0.6.4

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(),
@@ -1864,6 +1886,45 @@ var LoginResponseSchema = z4.object({
1864
1886
  /** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
1865
1887
  sshCertPrincipals: z4.array(z4.string()).optional()
1866
1888
  });
1889
+ var DeviceLoginRequestSchema = z4.object({
1890
+ // Capped: anyone may open a login, and the key is stored until it expires (an RSA-16384 key is ~2.8 KB).
1891
+ publicKey: z4.string().max(16384).optional(),
1892
+ hostname: z4.string().max(255).optional()
1893
+ });
1894
+ var DeviceLoginStartSchema = z4.object({
1895
+ deviceCode: z4.string(),
1896
+ userCode: z4.string(),
1897
+ verifyUrl: z4.string(),
1898
+ expiresIn: z4.number(),
1899
+ interval: z4.number()
1900
+ });
1901
+ var DeviceLoginPollRequestSchema = z4.object({ deviceCode: z4.string().min(1) });
1902
+ var DeviceLoginPollSchema = z4.union([
1903
+ z4.object({ status: z4.enum(["pending", "slow_down", "refused", "expired"]) }),
1904
+ LoginResponseSchema.extend({ status: z4.literal("approved") })
1905
+ ]);
1906
+ var DeviceLoginInfoSchema = z4.object({
1907
+ userCode: z4.string(),
1908
+ hostname: z4.string(),
1909
+ /** The address the request came from; null when the control plane could not tell. */
1910
+ ip: z4.string().nullable(),
1911
+ createdAt: z4.string(),
1912
+ expiresAt: z4.string()
1913
+ });
1914
+ var API_KEY_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
1915
+ var ApiKeySchema = z4.object({
1916
+ name: z4.string(),
1917
+ createdAt: z4.string(),
1918
+ /** Last request made with it (ISO); null: never used. */
1919
+ lastUsedAt: z4.string().nullable(),
1920
+ /** When it stops working (ISO); null: never. */
1921
+ expiresAt: z4.string().nullable()
1922
+ });
1923
+ var CreateApiKeyRequestSchema = z4.object({
1924
+ name: z4.string().regex(API_KEY_NAME_RE, "a key's name is lowercase letters, digits, '.', '_' or '-' (up to 32 characters)"),
1925
+ expiresAt: z4.iso.datetime({ offset: true }).nullable().optional()
1926
+ });
1927
+ var CreatedApiKeySchema = ApiKeySchema.extend({ key: z4.string() });
1867
1928
  var SshCertRequestSchema = z4.object({
1868
1929
  publicKey: z4.string().min(1)
1869
1930
  });
@@ -2027,6 +2088,15 @@ async function idle(udsPath, script, timeoutMs = 15e3) {
2027
2088
  async function runScript(udsPath, path, input, timeoutMs = 35e3) {
2028
2089
  return (await agentCall(udsPath, { op: "script", path, input: input ?? null }, timeoutMs))["output"];
2029
2090
  }
2091
+ async function startRun(udsPath, id, command, timeoutSec, timeoutMs = 15e3) {
2092
+ return (await agentCall(udsPath, { op: "run", id, command, timeoutSec }, timeoutMs))["started"] === true;
2093
+ }
2094
+ async function runStatus(udsPath, id, timeoutMs) {
2095
+ const reply = await agentCall(udsPath, { op: "runStatus", id }, timeoutMs);
2096
+ const state = reply["state"];
2097
+ if (state !== "running" && state !== "exited" && state !== "timeout" && state !== "unknown") throw new KvboxError("kvbox-agent sent a run state this server does not know");
2098
+ return { state, ...typeof reply["exitCode"] === "number" ? { exitCode: reply["exitCode"] } : {} };
2099
+ }
2030
2100
  var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
2031
2101
  var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
2032
2102
  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 +5629,62 @@ async function dropRelay(p = paths()) {
5559
5629
 
5560
5630
  // src/core/idle.ts
5561
5631
  import { readFile as readFile9 } from "node:fs/promises";
5632
+
5633
+ // src/core/runs.ts
5634
+ var BoxOutdatedError = class extends KvboxError {
5635
+ };
5636
+ var SEEN_RUNNING_MS = 3 * 6e4;
5637
+ var going = /* @__PURE__ */ new Map();
5638
+ var keyOf = (ref) => `${ref.owner}/${ref.name}`;
5639
+ function note(ref, id, until) {
5640
+ const key = keyOf(ref);
5641
+ const runs = going.get(key);
5642
+ if (until === null) {
5643
+ runs?.delete(id);
5644
+ if (runs?.size === 0) going.delete(key);
5645
+ return;
5646
+ }
5647
+ if (runs) runs.set(id, Math.max(until, runs.get(id) ?? 0));
5648
+ else going.set(key, /* @__PURE__ */ new Map([[id, until]]));
5649
+ }
5650
+ function boxHasRun(ref, now = Date.now()) {
5651
+ const runs = going.get(keyOf(ref));
5652
+ if (!runs) return false;
5653
+ for (const [id, until] of runs) if (until <= now) runs.delete(id);
5654
+ if (runs.size === 0) going.delete(keyOf(ref));
5655
+ return runs.size > 0;
5656
+ }
5657
+ async function socketOf(ref, p) {
5658
+ const meta = await readMachineMeta(ref, p).catch((err) => {
5659
+ if (err.code === "ENOENT") throw new NotFoundError(`box ${shown(ref)}`);
5660
+ throw err;
5661
+ });
5662
+ const status = statusOf(meta, p);
5663
+ if (status !== "running") throw new KvboxError(`${stateMessage(ref, status)}; only a running box runs a command`);
5664
+ return p.machine(meta.owner, meta.name).vsock;
5665
+ }
5666
+ var outdated = (ref, err) => {
5667
+ if (isUnknownOp(err)) throw new BoxOutdatedError(`box ${shown(ref)} runs on an image from before commands (it needs base v0.15.0 or later)`);
5668
+ if (isNoAgent(err)) throw new KvboxError(`box ${shown(ref)} did not take the request: its kvbox-agent is not answering (${err.message})`);
5669
+ throw err;
5670
+ };
5671
+ async function startBoxRun(ref, req, p = paths()) {
5672
+ const vsock = await socketOf(ref, p);
5673
+ const had = going.get(keyOf(ref))?.has(req.id) ?? false;
5674
+ note(ref, req.id, Date.now() + req.timeoutSec * 1e3 + 6e4);
5675
+ return startRun(vsock, req.id, req.command, req.timeoutSec).catch((err) => {
5676
+ if (!had) note(ref, req.id, null);
5677
+ return outdated(ref, err);
5678
+ });
5679
+ }
5680
+ async function boxRunStatus(ref, id, p = paths()) {
5681
+ const vsock = await socketOf(ref, p);
5682
+ const run2 = await runStatus(vsock, id).catch((err) => outdated(ref, err));
5683
+ note(ref, id, run2.state === "running" ? Date.now() + SEEN_RUNNING_MS : null);
5684
+ return { id, ...run2 };
5685
+ }
5686
+
5687
+ // src/core/idle.ts
5562
5688
  var HIBERNATE_CONCURRENCY = 2;
5563
5689
  async function tapTraffic(id) {
5564
5690
  const dir = `/sys/class/net/${tapName(id)}/statistics`;
@@ -5576,7 +5702,7 @@ async function boxIdle(box, p) {
5576
5702
  async function hibernateIfRunning(box, p) {
5577
5703
  const ref = { owner: box.owner, name: box.name };
5578
5704
  return withBoxLock(ref, async () => {
5579
- if ((await getMachine(ref, p)).status !== "running" || restoreRunning(ref)) return false;
5705
+ if ((await getMachine(ref, p)).status !== "running" || restoreRunning(ref) || boxHasRun(ref)) return false;
5580
5706
  await hibernateMachine(ref, p, "auto-hibernate");
5581
5707
  return true;
5582
5708
  });
@@ -5588,7 +5714,7 @@ function startIdleWatch(opts = {}) {
5588
5714
  const traffic = opts.traffic ?? tapTraffic;
5589
5715
  const guestIdle = opts.guestIdle ?? ((box) => boxIdle(box, p));
5590
5716
  const hibernate = opts.hibernate ?? ((box) => hibernateIfRunning(box, p));
5591
- const busy = opts.busy ?? ((box) => boxBusy(box) || restoreRunning(box));
5717
+ const busy = opts.busy ?? ((box) => boxBusy(box) || restoreRunning(box) || boxHasRun(box));
5592
5718
  const now = opts.now ?? Date.now;
5593
5719
  const log2 = opts.log ?? ((line) => log.info(line));
5594
5720
  const seen = /* @__PURE__ */ new Map();
@@ -6009,12 +6135,13 @@ var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
6009
6135
  function edgeCredential(hostSecret) {
6010
6136
  return createHmac2("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
6011
6137
  }
6138
+ var BOX_RUN_PATH_RE = /^\/machines\/([^/]+)\/runs(\/[A-Za-z0-9_-]{1,64})?\/?$/;
6012
6139
  function cronCredential(hostSecret) {
6013
6140
  return createHmac2("sha256", hostSecret).update("kvbox-cron-v1").digest("base64url");
6014
6141
  }
6015
6142
 
6016
6143
  // src/app.ts
6017
- import { Hono as Hono11 } from "hono";
6144
+ import { Hono as Hono12 } from "hono";
6018
6145
 
6019
6146
  // ../shared/src/version.ts
6020
6147
  import { createRequire } from "node:module";
@@ -6029,7 +6156,7 @@ function versionOf(srcFileUrl, injected) {
6029
6156
  }
6030
6157
 
6031
6158
  // src/version.ts
6032
- var VERSION = versionOf(import.meta.url, true ? "0.6.2" : void 0);
6159
+ var VERSION = versionOf(import.meta.url, true ? "0.6.4" : void 0);
6033
6160
 
6034
6161
  // src/caller.ts
6035
6162
  import { createHash as createHash3, timingSafeEqual } from "node:crypto";
@@ -6049,7 +6176,8 @@ function resolveCaller(opts = {}) {
6049
6176
  const cron = cronCheck(cp);
6050
6177
  return async (c, next) => {
6051
6178
  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);
6179
+ 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));
6180
+ if (!authorized(auth) && !narrow) return c.json({ error: "not authorized" }, 401);
6053
6181
  const user = c.req.header(OWNER_HEADER);
6054
6182
  if (user === void 0) {
6055
6183
  const path = c.req.path.replace(/\/$/, "");
@@ -6285,7 +6413,10 @@ async function targetOf(url, owner, path, wake) {
6285
6413
  const m = BOX_HTTP_PATH_RE.exec(url.pathname);
6286
6414
  const port = Number(m?.[2]);
6287
6415
  if (!m || port < 1 || port > 65535) throw new ProxyFailure(404, "not-found", `no route: ${url.pathname}`);
6288
- const name = decodeURIComponent(m[1]);
6416
+ const { box, woke } = await runningBox(decodeURIComponent(m[1]), owner, wake);
6417
+ return { ip: box.ip, port, path, woke };
6418
+ }
6419
+ async function runningBox(name, owner, wake) {
6289
6420
  const ref = parseRef(name, owner);
6290
6421
  let box;
6291
6422
  try {
@@ -6307,7 +6438,7 @@ async function targetOf(url, owner, path, wake) {
6307
6438
  if (woke) box = await getMachine(ref);
6308
6439
  }
6309
6440
  if (box.status !== "running") throw new ProxyFailure(409, notRunning(box.status), `box ${name} is ${box.status}`);
6310
- return { ip: box.ip, port, path, woke };
6441
+ return { ref, box, woke };
6311
6442
  }
6312
6443
  function boxHeaders(incoming, target, upgrade = false) {
6313
6444
  const out = [];
@@ -6621,10 +6752,41 @@ function machineRoutes() {
6621
6752
  return r;
6622
6753
  }
6623
6754
 
6624
- // src/routes/snapshots.ts
6755
+ // src/routes/runs.ts
6625
6756
  import { Hono as Hono7 } from "hono";
6626
- function snapshotRoutes() {
6757
+ var refusal = (c, err) => {
6758
+ if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
6759
+ if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
6760
+ if (err instanceof NotFoundError) return c.json({ error: err.message, code: "not-found" }, 404);
6761
+ throw err;
6762
+ };
6763
+ function runRoutes(wake = wakeBox) {
6627
6764
  const r = new Hono7();
6765
+ r.post("/:name/runs", async (c) => {
6766
+ const body = StartRunRequest.parse(await c.req.json().catch(() => ({})));
6767
+ try {
6768
+ const { ref, woke } = await runningBox(c.req.param("name"), c.get("owner"), wants(c.req.header(WAKE_HEADER)) ? wake : void 0);
6769
+ const started = await startBoxRun(ref, body);
6770
+ return c.json(StartRunAnswerSchema.parse({ id: body.id, started, woke }), 202);
6771
+ } catch (err) {
6772
+ return refusal(c, err);
6773
+ }
6774
+ });
6775
+ r.get("/:name/runs/:id", async (c) => {
6776
+ try {
6777
+ const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
6778
+ return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
6779
+ } catch (err) {
6780
+ return refusal(c, err);
6781
+ }
6782
+ });
6783
+ return r;
6784
+ }
6785
+
6786
+ // src/routes/snapshots.ts
6787
+ import { Hono as Hono8 } from "hono";
6788
+ function snapshotRoutes() {
6789
+ const r = new Hono8();
6628
6790
  r.get("/", async (c) => c.json(await listSnapshots(c.get("listScope"))));
6629
6791
  r.post("/", async (c) => {
6630
6792
  const body = CreateSnapshotRequest.parse(await c.req.json());
@@ -6638,9 +6800,9 @@ function snapshotRoutes() {
6638
6800
  }
6639
6801
 
6640
6802
  // src/routes/ssh.ts
6641
- import { Hono as Hono8 } from "hono";
6803
+ import { Hono as Hono9 } from "hono";
6642
6804
  function sshRoutes(opts = {}) {
6643
- const r = new Hono8();
6805
+ const r = new Hono9();
6644
6806
  if (opts.controlPlane) {
6645
6807
  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
6808
  return r;
@@ -6655,10 +6817,10 @@ function sshRoutes(opts = {}) {
6655
6817
  }
6656
6818
 
6657
6819
  // src/routes/usage.ts
6658
- import { Hono as Hono9 } from "hono";
6820
+ import { Hono as Hono10 } from "hono";
6659
6821
  var PULL_LIMIT = 1e3;
6660
6822
  function usageRoutes(opts = {}) {
6661
- const r = new Hono9();
6823
+ const r = new Hono10();
6662
6824
  r.get("/", async (c) => {
6663
6825
  let window;
6664
6826
  try {
@@ -6691,9 +6853,9 @@ function whole(value, name) {
6691
6853
  }
6692
6854
 
6693
6855
  // src/routes/volumes.ts
6694
- import { Hono as Hono10 } from "hono";
6856
+ import { Hono as Hono11 } from "hono";
6695
6857
  function volumeRoutes() {
6696
- const r = new Hono10();
6858
+ const r = new Hono11();
6697
6859
  r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
6698
6860
  r.post("/", async (c) => {
6699
6861
  const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
@@ -6723,7 +6885,7 @@ function volumeRoutes() {
6723
6885
 
6724
6886
  // src/app.ts
6725
6887
  function createApp(opts = {}) {
6726
- const app = new Hono11();
6888
+ const app = new Hono12();
6727
6889
  app.use(resolveCaller(opts));
6728
6890
  app.get("/health", async (c) => {
6729
6891
  const cfg = await loadConfig();
@@ -6742,6 +6904,7 @@ function createApp(opts = {}) {
6742
6904
  });
6743
6905
  if (opts.controlPlane) app.post("/update", async (c) => c.json(await startUpdate(VERSION), 202));
6744
6906
  if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
6907
+ if (opts.controlPlane) app.route("/machines", runRoutes());
6745
6908
  if (opts.controlPlane) {
6746
6909
  app.route("/machines", backupMachineRoutes());
6747
6910
  app.route("/volumes", backupVolumeRoutes());