@kvbox/server 0.6.25 → 0.6.26

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.
@@ -218,6 +218,14 @@ var PricingSchema = z.object({
218
218
  storageHour: z.number().nonnegative().default(0),
219
219
  storageGibHour: z.number().nonnegative().default(0),
220
220
  storageIncludedGib: z.number().int().nonnegative().default(0),
221
+ /**
222
+ * The container registry (#234): priced as object storage is. An hour of a slug's registry existing,
223
+ * whatever it holds, covers its hidden box and the first `registryIncludedGib` of its size; each GiB
224
+ * above that is `registryGibHour`. A price list from before the registry charges nothing for it.
225
+ */
226
+ registryHour: z.number().nonnegative().default(0),
227
+ registryGibHour: z.number().nonnegative().default(0),
228
+ registryIncludedGib: z.number().int().nonnegative().default(0),
221
229
  /** The cron service (#190): an hour of one cron service existing, whatever it holds or fires. A price list from before it charges nothing. */
222
230
  cronHour: z.number().nonnegative().default(0),
223
231
  /**
@@ -472,6 +480,12 @@ var ConfigSchema = z2.object({
472
480
  bridge: z2.string().default("kvbox0"),
473
481
  subnet: z2.string().default("172.30.0.0/24"),
474
482
  gateway: z2.string().default("172.30.0.1"),
483
+ /**
484
+ * The range this host gives its boxes inside `subnet` (#240, `172.30.4.0/24`), from its control plane
485
+ * (core/range.ts); `subnet` is then the wide network every box sees. Absent: boxes get addresses anywhere
486
+ * in `subnet`, as before ranges.
487
+ */
488
+ boxRange: z2.string().optional(),
475
489
  defaultSize: z2.enum(SIZE_NAMES).default(DEFAULT_SIZE),
476
490
  /** Who boxes made over the local socket belong to: the Unix user running the server unless set here. No `@`, no `/`. */
477
491
  owner: z2.string().regex(LOCAL_OWNER_RE, "owner: letters, digits, '.', '_', '-'; no '@' or '/'").default(localOwner),
@@ -678,6 +692,16 @@ async function ensureHostNetwork(cfg) {
678
692
  await netRun(cfg, ["up"]);
679
693
  return "created";
680
694
  }
695
+ function carriesRanges() {
696
+ try {
697
+ return readFileSync(netSetupScript(), "utf8").includes("drop_old_network");
698
+ } catch {
699
+ return false;
700
+ }
701
+ }
702
+ async function widenHostNetwork(cfg) {
703
+ await netRun(cfg, ["up"]);
704
+ }
681
705
  async function createTap(box, cfg, opts = {}) {
682
706
  const tap = tapName(box.id);
683
707
  await netRun(cfg, ["tap", "add", tap, box.ip, box.mac, ...opts.detached ? ["detached"] : []]);
@@ -761,7 +785,7 @@ async function closeProxy(proxy, cfg) {
761
785
  }
762
786
  var ipToInt = (ip) => ip.split(".").reduce((acc, o) => (acc << 8) + Number(o), 0) >>> 0;
763
787
  var intToIp = (n) => [24, 16, 8, 0].map((s) => n >>> s & 255).join(".");
764
- function nextFreeIp(subnet, inUse) {
788
+ function nextFreeIp(subnet, inUse, wholeRange = false) {
765
789
  const [base, lenStr] = subnet.split("/");
766
790
  const len = Number(lenStr);
767
791
  if (!base || !Number.isInteger(len) || len < 8 || len > 30) throw new KvboxError(`bad subnet: ${subnet}`);
@@ -769,10 +793,12 @@ function nextFreeIp(subnet, inUse) {
769
793
  const network = (ipToInt(base) & mask) >>> 0;
770
794
  const broadcast = (network | ~mask >>> 0) >>> 0;
771
795
  const used = new Set(inUse.map(ipToInt));
772
- for (let n = network + 2; n < broadcast; n++) {
796
+ for (let n = network + (wholeRange ? 1 : 2); n < broadcast; n++) {
773
797
  if (!used.has(n)) return intToIp(n);
774
798
  }
775
- throw new KvboxError(`no free IP left in ${subnet}`);
799
+ throw new KvboxError(
800
+ wholeRange ? `this host has no address left for a box: all ${broadcast - network - 1} of its range ${subnet} are taken (stopped and hibernated boxes keep theirs)` : `no free IP left in ${subnet}`
801
+ );
776
802
  }
777
803
  function standInIp(subnet, inUse) {
778
804
  const [a, b, c] = (subnet.split("/")[0] ?? "").split(".");
@@ -795,6 +821,37 @@ import { closeSync, existsSync as existsSync2, openSync as openSync2 } from "nod
795
821
  import { readFile as readFile3, rm as rm2 } from "node:fs/promises";
796
822
  import { relative } from "node:path";
797
823
 
824
+ // ../shared/src/ranges.ts
825
+ var BOX_NETWORK = "172.30.0.0/16";
826
+ var BOX_GATEWAY = "172.30.0.1";
827
+ var UNNUMBERED_RANGE = "172.30.0.0/24";
828
+ var FIRST_RANGE = 1;
829
+ var LAST_RANGE = 254;
830
+ var RANGE_RE = /^172\.30\.(\d{1,3})\.0\/24$/;
831
+ var ipToInt2 = (ip) => ip.split(".").reduce((acc, o) => (acc << 8) + Number(o), 0) >>> 0;
832
+ function hostRangeNumber(range) {
833
+ const n = Number(RANGE_RE.exec(range)?.[1] ?? NaN);
834
+ return Number.isInteger(n) && n >= FIRST_RANGE && n <= LAST_RANGE ? n : null;
835
+ }
836
+ var isHostRange = (range) => hostRangeNumber(range) !== null;
837
+ function inRange(ip, cidr) {
838
+ const [base, lenStr] = cidr.split("/");
839
+ const len = Number(lenStr);
840
+ if (!base || !Number.isInteger(len) || len < 0 || len > 32) return false;
841
+ const mask = len === 0 ? 0 : ~0 << 32 - len >>> 0;
842
+ return (ipToInt2(ip) & mask) >>> 0 === (ipToInt2(base) & mask) >>> 0;
843
+ }
844
+ function rangesOverlap(a, b) {
845
+ const lenOf = (cidr) => Number(cidr.split("/")[1]);
846
+ const [wide, narrow] = lenOf(a) <= lenOf(b) ? [a, b] : [b, a];
847
+ return inRange(narrow.split("/")[0] ?? "", wide);
848
+ }
849
+ function netmaskOf(cidr) {
850
+ const len = Number(cidr.split("/")[1]);
851
+ const mask = len === 0 ? 0 : ~0 << 32 - len >>> 0;
852
+ return [24, 16, 8, 0].map((s) => mask >>> s & 255).join(".");
853
+ }
854
+
798
855
  // src/core/proc.ts
799
856
  import { setTimeout as sleep } from "node:timers/promises";
800
857
  async function waitFor(pred, timeoutMs, stepMs = 50) {
@@ -952,7 +1009,7 @@ var GUEST_CID = 3;
952
1009
  var OVERLAY_REL = "overlay.ext4";
953
1010
  var vsockRel = (m) => relative(m.dir, m.vsock);
954
1011
  function bootArgs(name, ip, cfg, pubkeyB64) {
955
- const args = `console=ttyS0 reboot=k panic=1 init=/sbin/overlay-init kvbox.overlay=/dev/vdb ip=${ip}::${cfg.gateway}:255.255.255.0:${name}:eth0:off kvbox.name=${name} kvbox.sshkey=${pubkeyB64}`;
1012
+ const args = `console=ttyS0 reboot=k panic=1 init=/sbin/overlay-init kvbox.overlay=/dev/vdb ip=${ip}::${cfg.gateway}:${netmaskOf(cfg.subnet)}:${name}:eth0:off kvbox.name=${name} kvbox.sshkey=${pubkeyB64}`;
956
1013
  return process.arch === "arm64" ? `keep_bootcon ${args}` : args;
957
1014
  }
958
1015
  async function tailOf(file, lines = 5) {
@@ -1092,8 +1149,10 @@ var firecrackerDriver = {
1092
1149
  },
1093
1150
  net: {
1094
1151
  prepare: ensureHostNetwork,
1152
+ carriesRanges,
1153
+ widen: widenHostNetwork,
1095
1154
  allocate(cfg, inUse) {
1096
- const ip = nextFreeIp(cfg.subnet, [...inUse, cfg.gateway]);
1155
+ const ip = cfg.boxRange === void 0 ? nextFreeIp(cfg.subnet, [...inUse, cfg.gateway]) : nextFreeIp(cfg.boxRange, [...inUse, cfg.gateway], true);
1097
1156
  return { ip, mac: macFor(ip) };
1098
1157
  },
1099
1158
  create: createTap,
@@ -1345,6 +1404,11 @@ var MachineMetaSchema = z3.object({
1345
1404
  owner: z3.string(),
1346
1405
  ip: z3.string(),
1347
1406
  mac: z3.string(),
1407
+ /**
1408
+ * The address the box had before it moved into its host's range (#240), while a link from it into another
1409
+ * box may still name it (core/machines/address.ts `followMove`). Absent: it never moved, or all followed.
1410
+ */
1411
+ movedFrom: z3.string().optional(),
1348
1412
  pid: z3.number().int().nullable(),
1349
1413
  // null: stopped on purpose, disk kept
1350
1414
  /**
@@ -1893,24 +1957,166 @@ function namesIn(text) {
1893
1957
  return [...text.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g)].map((m) => m[1]);
1894
1958
  }
1895
1959
 
1896
- // src/core/machines/change.ts
1897
- import { statSync as statSync3 } from "node:fs";
1898
- import { rename as rename5, rm as rm8 } from "node:fs/promises";
1960
+ // src/core/locks.ts
1961
+ import { AsyncLocalStorage } from "node:async_hooks";
1962
+ var tails = /* @__PURE__ */ new Map();
1963
+ var held = new AsyncLocalStorage();
1964
+ function withBoxLock(ref, fn) {
1965
+ return withLock(refKey(ref), fn);
1966
+ }
1967
+ function withSnapshotLock(ref, fn) {
1968
+ return withLock(`snapshot:${refKey(ref)}`, fn);
1969
+ }
1970
+ function withHostLock(name, fn) {
1971
+ return withLock(`host:${name}`, fn);
1972
+ }
1973
+ async function withLock(key, fn) {
1974
+ const mine = held.getStore();
1975
+ if (mine?.has(key)) return fn();
1976
+ const previous = tails.get(key);
1977
+ let release;
1978
+ const tail = new Promise((resolve3) => release = resolve3);
1979
+ tails.set(key, tail);
1980
+ try {
1981
+ await previous;
1982
+ return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
1983
+ } finally {
1984
+ release();
1985
+ if (tails.get(key) === tail) tails.delete(key);
1986
+ }
1987
+ }
1988
+ function outsideLocks(fn) {
1989
+ return held.exit(fn);
1990
+ }
1991
+ function boxBusy(ref) {
1992
+ return tails.has(refKey(ref));
1993
+ }
1994
+ function locked(fn) {
1995
+ return (...args) => withBoxLock(args[0], () => fn(...args));
1996
+ }
1899
1997
 
1900
- // src/core/capacity.ts
1901
- import { cpus, totalmem } from "node:os";
1998
+ // src/core/machines/common.ts
1999
+ import { existsSync as existsSync5 } from "node:fs";
2000
+ import { readFile as readFile6 } from "node:fs/promises";
1902
2001
 
1903
- // ../shared/src/capacity.ts
1904
- function sellableGib(d) {
1905
- return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);
2002
+ // src/core/machines/disk.ts
2003
+ import { statSync } from "node:fs";
2004
+ import { truncate, writeFile as writeFile3 } from "node:fs/promises";
2005
+
2006
+ // src/core/ext4.ts
2007
+ import { closeSync as closeSync3, openSync as openSync4, readSync } from "node:fs";
2008
+ var SUPERBLOCK_OFFSET = 1024;
2009
+ var EXT4_MAGIC = 61267;
2010
+ var INCOMPAT_META_BG = 16;
2011
+ var INCOMPAT_64BIT = 128;
2012
+ function ext4Usage(file) {
2013
+ let fd;
2014
+ try {
2015
+ fd = openSync4(file, "r");
2016
+ const sb = Buffer.alloc(1024);
2017
+ if (readSync(fd, sb, 0, sb.length, SUPERBLOCK_OFFSET) !== sb.length) return null;
2018
+ if (sb.readUInt16LE(56) !== EXT4_MAGIC) return null;
2019
+ const incompat = sb.readUInt32LE(96);
2020
+ if (incompat & INCOMPAT_META_BG) return null;
2021
+ const is64 = (incompat & INCOMPAT_64BIT) !== 0;
2022
+ const blockSize = 1024 << sb.readUInt32LE(24);
2023
+ const blocks = sb.readUInt32LE(4) + (is64 ? sb.readUInt32LE(336) * 2 ** 32 : 0);
2024
+ const firstDataBlock = sb.readUInt32LE(20);
2025
+ const blocksPerGroup = sb.readUInt32LE(32);
2026
+ const descSize = is64 ? sb.readUInt16LE(254) : 32;
2027
+ if (blocksPerGroup === 0 || descSize < 32) return null;
2028
+ const groups = Math.ceil((blocks - firstDataBlock) / blocksPerGroup);
2029
+ const table = Buffer.alloc(groups * descSize);
2030
+ if (readSync(fd, table, 0, table.length, (firstDataBlock + 1) * blockSize) !== table.length) return null;
2031
+ let free = 0;
2032
+ for (let g = 0; g < groups; g++) {
2033
+ const at = g * descSize;
2034
+ free += table.readUInt16LE(at + 12) + (descSize >= 64 ? table.readUInt16LE(at + 44) * 65536 : 0);
2035
+ }
2036
+ return { sizeBytes: blocks * blockSize, usedBytes: (blocks - free) * blockSize };
2037
+ } catch {
2038
+ return null;
2039
+ } finally {
2040
+ if (fd !== void 0) closeSync3(fd);
2041
+ }
1906
2042
  }
1907
- function volumeRoomGib(d) {
1908
- return Math.max(0, sellableGib(d) - d.volumesGib);
2043
+
2044
+ // src/core/machines/disk.ts
2045
+ function diskStats(disk) {
2046
+ try {
2047
+ const st = statSync(disk);
2048
+ const diskHostBytes = st.blocks * 512;
2049
+ const fs = ext4Usage(disk);
2050
+ return { diskBytes: st.size, diskUsedBytes: fs ? Math.min(fs.usedBytes, st.size) : diskHostBytes, diskHostBytes };
2051
+ } catch {
2052
+ return { diskBytes: 0, diskUsedBytes: 0, diskHostBytes: 0 };
2053
+ }
1909
2054
  }
1910
- function hasDiskRoom(d, sizeGib) {
1911
- return sizeGib <= volumeRoomGib(d);
2055
+ async function compactDisk(file) {
2056
+ await run(["e2fsck", "-f", "-p", "-E", "discard", file], { okExitCodes: [1, 2], timeoutMs: 10 * 6e4 });
2057
+ }
2058
+ function diskGibOf(meta, p) {
2059
+ try {
2060
+ return Math.round(statSync(p.machine(meta.owner, meta.name).overlay).size / 1024 ** 3);
2061
+ } catch {
2062
+ return 0;
2063
+ }
2064
+ }
2065
+ async function createOverlay(file, gib) {
2066
+ await writeFile3(file, "", { mode: 384 });
2067
+ await truncate(file, gib * 1024 ** 3);
2068
+ await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", "kvbox-box", "-E", "lazy_itable_init=1,lazy_journal_init=1", file]);
2069
+ }
2070
+ async function growDisk(file, gib) {
2071
+ await truncate(file, gib * 1024 ** 3);
2072
+ await run(["e2fsck", "-f", "-p", file], { okExitCodes: [1] });
2073
+ await run(["resize2fs", file]);
2074
+ }
2075
+
2076
+ // src/core/machines/common.ts
2077
+ var idsInUse = (metas) => new Set(metas.map((m) => m.id));
2078
+ var isCloudBox = (owner) => realmOf(owner) !== null;
2079
+ async function readMeta(ref, p) {
2080
+ try {
2081
+ return await readMachineMeta(ref, p);
2082
+ } catch (err) {
2083
+ if (err.code === "ENOENT") throw new NotFoundError(`box ${shown(ref)}`);
2084
+ throw err;
2085
+ }
2086
+ }
2087
+ async function readAllMeta(p) {
2088
+ const metas = [];
2089
+ for (const ref of await listMachineRefs(p)) {
2090
+ try {
2091
+ metas.push(await readMachineMeta(ref, p));
2092
+ } catch (err) {
2093
+ log.warn(`skipping machines/${refKey(ref)}: ${err.message}`);
2094
+ }
2095
+ }
2096
+ return metas;
2097
+ }
2098
+ async function readHostPubkey(p) {
2099
+ try {
2100
+ return (await readFile6(`${p.sshKey}.pub`, "utf8")).trim();
2101
+ } catch {
2102
+ throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);
2103
+ }
2104
+ }
2105
+ function assertAssets(cfg) {
2106
+ for (const [what, file] of [["kernel", cfg.kernel], ["base image", cfg.rootfs], ["firecracker", cfg.firecracker]]) {
2107
+ if (!existsSync5(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
2108
+ }
2109
+ }
2110
+ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISOString()) {
2111
+ try {
2112
+ insertUsageEvent({ boxId: meta.id, owner: meta.owner, name: meta.name, at, state, by, vcpu: meta.vcpu, memMib: meta.memMib, diskGib: diskGibOf(meta, p) }, p);
2113
+ } catch (err) {
2114
+ log.warn(`usage ledger: ${err.message}`);
2115
+ }
1912
2116
  }
1913
- var VCPU_OVERSUBSCRIPTION = 2;
2117
+
2118
+ // ../shared/src/api.ts
2119
+ import { z as z6 } from "zod";
1914
2120
 
1915
2121
  // ../shared/src/integrations.ts
1916
2122
  import { z as z5 } from "zod";
@@ -2024,12 +2230,7 @@ function unusableOnBase(base, list) {
2024
2230
  }
2025
2231
  var GUEST_REQUESTS_PER_MINUTE = 60;
2026
2232
 
2027
- // src/core/volumes.ts
2028
- import { existsSync as existsSync5, statSync } from "node:fs";
2029
- import { lstat, mkdir as mkdir2, readdir as readdir3, rm as rm3, statfs, symlink, truncate, writeFile as writeFile3 } from "node:fs/promises";
2030
-
2031
2233
  // ../shared/src/api.ts
2032
- import { z as z6 } from "zod";
2033
2234
  var SizeSchema = z6.enum(SIZE_NAMES);
2034
2235
  var BoxStatusSchema = z6.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
2035
2236
  var PortProtoSchema = z6.enum(["tcp", "udp"]);
@@ -2669,7 +2870,13 @@ var CapacitySchema = z6.object({
2669
2870
  /** True on a host whose network puts the boxes of one cluster in reach of each other (#215); the control plane places a cluster's box only on such a host. */
2670
2871
  clusters: z6.boolean().optional(),
2671
2872
  /** The integrations this kvbox-server knows (`hostKnowsIntegrations`). Absent with `integrations`: the first one's, `github` alone. */
2672
- integrationIds: z6.array(z6.string()).optional()
2873
+ integrationIds: z6.array(z6.string()).optional(),
2874
+ /** True on a host that can take a box range of its own (#240): its privileged network script widens a network that is up. */
2875
+ ranges: z6.boolean().optional(),
2876
+ /** The range the host gives its boxes now (`172.30.4.0/24`, config.json `boxRange`); absent while it has none. */
2877
+ boxRange: z6.string().optional(),
2878
+ /** Boxes of the host whose address is still outside `boxRange`: each moves at its next cold start. Absent without a range. */
2879
+ offRange: z6.number().int().optional()
2673
2880
  });
2674
2881
  var ImageSchema = z6.object({ name: z6.string(), version: z6.string().nullable() });
2675
2882
  var ImageIndexSchema = z6.object({
@@ -2861,6 +3068,8 @@ var UsageDaySchema = z6.object({
2861
3068
  volumes: z6.array(UsageDayItemSchema),
2862
3069
  /** Object storage that existed that day (#182); absent on a day without any. */
2863
3070
  storage: z6.array(UsageDayItemSchema).optional(),
3071
+ /** A container registry that existed that day (#234); absent on a day without any. */
3072
+ registry: z6.array(UsageDayItemSchema).optional(),
2864
3073
  /** Cron services that existed that day (#190); absent on a day without any. */
2865
3074
  cron: z6.array(UsageDayItemSchema).optional(),
2866
3075
  /** Kubernetes clusters that existed that day (#222), each with its master and nodes together; absent on a day without any. */
@@ -2879,6 +3088,11 @@ var UsageReportSchema = z6.object({
2879
3088
  * included ones, `sizeGib` its whole size. Absent when there is none.
2880
3089
  */
2881
3090
  storage: z6.array(VolumeUsageSchema).optional(),
3091
+ /**
3092
+ * Container registries (#234, control plane only): one row per registry a slug has or had, shaped and
3093
+ * priced like `storage` with the registry's prices. Absent when there is none.
3094
+ */
3095
+ registry: z6.array(VolumeUsageSchema).optional(),
2882
3096
  /** Cron services (#190, control plane only): one row per service a slug has or had. Absent when there is none. */
2883
3097
  cron: z6.array(CronUsageSchema).optional(),
2884
3098
  /**
@@ -2897,7 +3111,7 @@ var UsageReportSchema = z6.object({
2897
3111
  diskGibHours: z6.number(),
2898
3112
  volumeHours: z6.number().optional(),
2899
3113
  volumeGibHours: z6.number().optional(),
2900
- /** Boxes, volumes, object storage, cron services, Kubernetes clusters and paid backups together; the hours above are those of `boxes` and `volumes` alone. */
3114
+ /** Boxes, volumes, object storage, container registries, cron services, Kubernetes clusters and paid backups together; the hours above are those of `boxes` and `volumes` alone. */
2901
3115
  cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional()
2902
3116
  })
2903
3117
  });
@@ -3166,6 +3380,9 @@ var SshCaResponseSchema = z6.object({
3166
3380
  var HostSshCaResponseSchema = z6.object({
3167
3381
  publicKey: z6.string()
3168
3382
  });
3383
+ var HostRangeResponseSchema = z6.object({
3384
+ range: z6.string().nullable()
3385
+ });
3169
3386
  var CloudCaSchema = z6.object({
3170
3387
  controlPlane: z6.string(),
3171
3388
  publicKey: z6.string(),
@@ -3195,7 +3412,12 @@ var HostJoinRequestSchema = z6.object({
3195
3412
  fingerprint: z6.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
3196
3413
  publicAddress: z6.string().min(1),
3197
3414
  /** Where the host is (`kvbox-server join --country`): a code or an English name. */
3198
- country: z6.string().optional()
3415
+ country: z6.string().optional(),
3416
+ /**
3417
+ * The box range this host already has boxes on (config.json `boxRange`, kept across a leave), which it
3418
+ * never gives up: the join gives it back, or is refused while it is another host's (#240).
3419
+ */
3420
+ boxRange: z6.string().optional()
3199
3421
  });
3200
3422
  var HostJoinResponseSchema = z6.object({
3201
3423
  hostSecret: z6.string(),
@@ -3213,60 +3435,307 @@ var CloudHostSchema = z6.object({
3213
3435
  /** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */
3214
3436
  region: z6.string().nullable(),
3215
3437
  /** kvbox-server's version as of the poller's last look (`capacity.version`); null before one, or for a server older than 0.5.45. */
3216
- version: z6.string().nullable()
3438
+ version: z6.string().nullable(),
3439
+ /**
3440
+ * The range of box addresses that is this host's alone (#240, `172.30.4.0/24`): the next free one at join,
3441
+ * or the admin's. Null: a host from before ranges that nobody gave one; its boxes are on `172.30.0.x` like
3442
+ * every such host's. What the host has taken of it is `capacity.boxRange`.
3443
+ */
3444
+ boxRange: z6.string().nullable()
3217
3445
  });
3218
3446
  var HostInfoSchema = z6.object({
3219
3447
  host: CloudHostSchema,
3220
3448
  health: HealthSchema.nullable(),
3221
3449
  error: z6.string().nullable()
3222
3450
  });
3223
- var HostPatchRequest = z6.object({ country: z6.string().nullable().optional(), region: z6.string().nullable().optional() }).refine((b) => b.country !== void 0 || b.region !== void 0, { message: "give country, region or both" });
3451
+ var HostPatchRequest = z6.object({ country: z6.string().nullable().optional(), region: z6.string().nullable().optional(), boxRange: z6.string().nullable().optional() }).refine((b) => b.country !== void 0 || b.region !== void 0 || b.boxRange !== void 0, { message: "give country, region or boxRange" });
3224
3452
  var CountrySchema = z6.object({ code: z6.string(), name: z6.string() });
3225
3453
 
3226
- // src/core/locks.ts
3227
- import { AsyncLocalStorage } from "node:async_hooks";
3228
- var tails = /* @__PURE__ */ new Map();
3229
- var held = new AsyncLocalStorage();
3230
- function withBoxLock(ref, fn) {
3231
- return withLock(refKey(ref), fn);
3232
- }
3233
- function withSnapshotLock(ref, fn) {
3234
- return withLock(`snapshot:${refKey(ref)}`, fn);
3235
- }
3236
- function withHostLock(name, fn) {
3237
- return withLock(`host:${name}`, fn);
3454
+ // src/core/publicPorts.ts
3455
+ import { randomInt } from "node:crypto";
3456
+ var SSH_PORT_MIN = 2e4;
3457
+ var SSH_PORT_MAX = 6e4;
3458
+ function pickSshPort(taken) {
3459
+ const span = SSH_PORT_MAX - SSH_PORT_MIN + 1;
3460
+ for (let i = 0; i < 32; i++) {
3461
+ const port = SSH_PORT_MIN + randomInt(span);
3462
+ if (!taken.has(port)) return port;
3463
+ }
3464
+ const start = randomInt(span);
3465
+ for (let i = 0; i < span; i++) {
3466
+ const port = SSH_PORT_MIN + (start + i) % span;
3467
+ if (!taken.has(port)) return port;
3468
+ }
3469
+ throw new KvboxError(`no free port left between ${SSH_PORT_MIN} and ${SSH_PORT_MAX} on this host`);
3238
3470
  }
3239
- async function withLock(key, fn) {
3240
- const mine = held.getStore();
3241
- if (mine?.has(key)) return fn();
3242
- const previous = tails.get(key);
3243
- let release;
3244
- const tail = new Promise((resolve3) => release = resolve3);
3245
- tails.set(key, tail);
3246
- try {
3247
- await previous;
3248
- return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
3249
- } finally {
3250
- release();
3251
- if (tails.get(key) === tail) tails.delete(key);
3471
+
3472
+ // src/core/machines/cluster.ts
3473
+ import { createHash } from "node:crypto";
3474
+ var clusterKey = (owner, cluster) => createHash("sha256").update(`${owner}
3475
+ ${cluster}`).digest("hex").slice(0, 16);
3476
+ function requestedCluster(req, owner, fromBackup = false) {
3477
+ if (req.cluster === void 0) return void 0;
3478
+ if (!isCloudBox(owner)) throw new KvboxError("a box is put in a cluster by a control plane; this host's own boxes have none");
3479
+ if (req.from !== void 0 || fromBackup) throw new KvboxError("a box of a cluster is made from its image, never from a snapshot or a backup");
3480
+ if (!driver().net.carriesClusters()) {
3481
+ throw new KvboxError("this host's network setup is from before clusters; its operator finishes the update by running install-server.sh on it (the root step)");
3252
3482
  }
3483
+ return req.cluster;
3253
3484
  }
3254
- function outsideLocks(fn) {
3255
- return held.exit(fn);
3485
+ async function joinCluster2(meta, cfg) {
3486
+ if (meta.cluster === void 0 || meta.owner === void 0) return;
3487
+ await driver().net.joinCluster({ box: meta.id, ip: meta.ip, cluster: clusterKey(meta.owner, meta.cluster) }, cfg);
3256
3488
  }
3257
- function boxBusy(ref) {
3258
- return tails.has(refKey(ref));
3489
+ async function leaveCluster2(meta, cfg) {
3490
+ await leftCluster(meta, cfg).catch((err) => log.warn(`could not take box ${meta.id} out of its cluster: ${err.message}`));
3259
3491
  }
3260
- function locked(fn) {
3261
- return (...args) => withBoxLock(args[0], () => fn(...args));
3492
+ async function leftCluster(meta, cfg) {
3493
+ if (meta.cluster === void 0) return;
3494
+ await driver().net.leaveCluster({ box: meta.id, ip: meta.ip }, cfg);
3262
3495
  }
3496
+ async function rejoinClusters(p = paths()) {
3497
+ const cfg = await loadConfig(p);
3498
+ for (const listed of await readAllMeta(p)) {
3499
+ if (!vmAlive(listed) || listed.cluster === void 0) continue;
3500
+ await withBoxLock(listed, async () => {
3501
+ const meta = await readMachineMeta(listed, p).catch(() => null);
3502
+ if (meta === null || !vmAlive(meta)) return;
3503
+ await joinCluster2(meta, cfg).catch((err) => log.warn(`box ${meta.name} is cut off from its cluster: ${err.message}`));
3504
+ });
3505
+ }
3506
+ }
3507
+
3508
+ // src/core/farTunnel.ts
3509
+ import { createServer } from "node:net";
3510
+ import { connect as tlsConnect } from "node:tls";
3511
+
3512
+ // ../shared/src/httpHead.ts
3513
+ var END = "\r\n\r\n";
3514
+ var HeadTimeoutError = class extends Error {
3515
+ };
3516
+ function readHead(socket, opts) {
3517
+ return new Promise((resolve3, reject) => {
3518
+ let bytes = Buffer.alloc(0);
3519
+ const done = (err) => {
3520
+ clearTimeout(timer);
3521
+ socket.off("data", onData);
3522
+ socket.off("close", onClose);
3523
+ socket.pause();
3524
+ if (err) return reject(err);
3525
+ const end = bytes.indexOf(END);
3526
+ resolve3({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
3527
+ };
3528
+ const onData = (chunk) => {
3529
+ bytes = Buffer.concat([bytes, chunk]);
3530
+ if (bytes.includes(END)) done();
3531
+ else if (bytes.length > opts.maxBytes) done(new Error("answer head too large"));
3532
+ };
3533
+ const onClose = () => done(new Error("closed before answering"));
3534
+ const timer = setTimeout(() => done(new HeadTimeoutError(`no answer within ${opts.timeoutMs / 1e3} s`)), opts.timeoutMs);
3535
+ socket.on("data", onData);
3536
+ socket.once("close", onClose);
3537
+ });
3538
+ }
3539
+ function headStatus(head) {
3540
+ const m = /^HTTP\/\d(?:\.\d)? (\d{3})(?: |\r|$)/.exec(head);
3541
+ return m ? Number(m[1]) : void 0;
3542
+ }
3543
+ function headHeader(head, name) {
3544
+ const line = head.split("\r\n").slice(1).find((l) => l.slice(0, l.indexOf(":")).trim().toLowerCase() === name);
3545
+ return line?.slice(line.indexOf(":") + 1).trim();
3546
+ }
3547
+ function rewriteHead(head, drop, add = {}) {
3548
+ const [status, ...lines] = head.split("\r\n");
3549
+ const kept = lines.filter((l) => !drop(l.slice(0, l.indexOf(":")).trim().toLowerCase()));
3550
+ const extra = Object.entries(add).map(([k, v]) => `${k}: ${v}`);
3551
+ return Buffer.from(`${[status, ...kept, ...extra].join("\r\n")}${END}`, "latin1");
3552
+ }
3553
+
3554
+ // ../shared/src/names.ts
3555
+ import { createHmac } from "node:crypto";
3556
+ var PROXY_ERROR_HEADER = "x-kvbox-proxy-error";
3557
+ var PROXIED_HEADER = "x-kvbox-proxied";
3558
+ var VISITOR_PATH_HEADER = "x-kvbox-path";
3559
+ var WAKE_HEADER = "x-kvbox-wake";
3560
+ var WAKE_WAIT_MS = 3e4;
3561
+ var REQUEST_TIMEOUT_MS = 36e5;
3562
+ var WOKE_HEADER = "x-kvbox-woke";
3563
+ var VISITOR_AUTH_HEADER = "x-kvbox-authorization";
3564
+ var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
3565
+ var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
3566
+ var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
3567
+ function edgeCredential(hostSecret) {
3568
+ return createHmac("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
3569
+ }
3570
+ var BOX_LINK_PATH_RE = /^\/machines\/([^/]+)\/link\/(\d{1,5})\/?$/;
3571
+ var LINK_PROTOCOL = "kvbox-link";
3572
+ var LINK_ERROR_HEADER = "x-kvbox-link-error";
3573
+ var BOX_RUN_PATH_RE = /^\/machines\/([^/]+)\/runs(\/[A-Za-z0-9_-]{1,64})?\/?$/;
3574
+ function cronCredential(hostSecret) {
3575
+ return createHmac("sha256", hostSecret).update("kvbox-cron-v1").digest("base64url");
3576
+ }
3577
+
3578
+ // src/core/farTunnel.ts
3579
+ var FarRefusal = class extends Error {
3580
+ constructor(code, message) {
3581
+ super(message);
3582
+ this.code = code;
3583
+ this.name = "FarRefusal";
3584
+ }
3585
+ code;
3586
+ };
3587
+ var DIAL_TIMEOUT_MS = 1e4;
3588
+ var MAX_HEAD_BYTES = 16 * 1024;
3589
+ var MAX_OPEN = 256;
3590
+ var WARN_EVERY_MS = 6e4;
3591
+ var KEEPALIVE_MS = 3e4;
3592
+ function splice(a, b) {
3593
+ for (const s of [a, b]) {
3594
+ s.allowHalfOpen = true;
3595
+ s.setKeepAlive(true, KEEPALIVE_MS);
3596
+ }
3597
+ a.pipe(b);
3598
+ b.pipe(a);
3599
+ const after = (gone, other) => (hadError) => {
3600
+ if (hadError || other.writableFinished || gone.errored) return void other.destroy();
3601
+ other.end(() => other.destroy());
3602
+ };
3603
+ a.once("close", after(a, b));
3604
+ b.once("close", after(b, a));
3605
+ }
3606
+ function connectPinned(url, pin, timeoutMs) {
3607
+ const target = new URL(url);
3608
+ return new Promise((resolve3, reject) => {
3609
+ const socket = tlsConnect({ host: target.hostname, port: Number(target.port || 443), rejectUnauthorized: false, timeout: timeoutMs });
3610
+ socket.allowHalfOpen = true;
3611
+ socket.once("timeout", () => socket.destroy(new Error(`no answer within ${timeoutMs / 1e3} s`)));
3612
+ socket.once("error", reject);
3613
+ socket.once("secureConnect", () => {
3614
+ if (socket.getPeerCertificate().fingerprint256 !== pin) {
3615
+ socket.destroy();
3616
+ return reject(new Error("its certificate is not the one the control plane named (fingerprint mismatch)"));
3617
+ }
3618
+ socket.setTimeout(0);
3619
+ socket.off("error", reject);
3620
+ socket.on("error", () => socket.destroy());
3621
+ resolve3(socket);
3622
+ });
3623
+ });
3624
+ }
3625
+ async function ask(t, method, timeoutMs) {
3626
+ const socket = await connectPinned(t.url, t.pin, timeoutMs);
3627
+ const slug = t.owner.split("@")[0];
3628
+ socket.write(
3629
+ `${method} /machines/${encodeURIComponent(t.name)}/link/${t.port} HTTP/1.1\r
3630
+ host: ${new URL(t.url).host}\r
3631
+ connection: Upgrade\r
3632
+ upgrade: ${LINK_PROTOCOL}\r
3633
+ authorization: Bearer ${t.key}\r
3634
+ x-kvbox-owner: ${slug}\r
3635
+ \r
3636
+ `
3637
+ );
3638
+ try {
3639
+ return { socket, ...await readHead(socket, { maxBytes: MAX_HEAD_BYTES, timeoutMs }) };
3640
+ } catch (err) {
3641
+ socket.destroy();
3642
+ throw err;
3643
+ }
3644
+ }
3645
+ var refusal = (head) => {
3646
+ const code = headHeader(head, LINK_ERROR_HEADER);
3647
+ return new FarRefusal(code === "gone" || code === "down" || code === "unreachable" ? code : "refused", `the other host answered ${headStatus(head) ?? "nothing it should"}${code ? ` (${code})` : ""}`);
3648
+ };
3649
+ async function dialFar(t, timeoutMs = DIAL_TIMEOUT_MS) {
3650
+ const { socket, head, rest } = await ask(t, "GET", timeoutMs);
3651
+ if (headStatus(head) === 101) return { socket, rest };
3652
+ socket.destroy();
3653
+ throw refusal(head);
3654
+ }
3655
+ async function dropFar(t, timeoutMs = DIAL_TIMEOUT_MS) {
3656
+ const { socket, head } = await ask(t, "DELETE", timeoutMs);
3657
+ socket.destroy();
3658
+ if (headStatus(head) === 200) return;
3659
+ const refused = refusal(head);
3660
+ if (refused.code !== "gone") throw refused;
3661
+ }
3662
+ var sameTarget = (a, b) => a.owner === b.owner && a.name === b.name && a.port === b.port && a.url === b.url && a.pin === b.pin && a.key === b.key;
3663
+ var listeners = /* @__PURE__ */ new Map();
3664
+ async function listenFar(id, opts) {
3665
+ const have = listeners.get(id);
3666
+ if (have && sameTarget(have.target, opts.target)) return have.port;
3667
+ if (have) await closeFar(id);
3668
+ const open4 = /* @__PURE__ */ new Set();
3669
+ const track = (s) => {
3670
+ open4.add(s);
3671
+ s.once("close", () => open4.delete(s));
3672
+ };
3673
+ let warnedAt = 0;
3674
+ const server = createServer({ allowHalfOpen: true }, (box) => {
3675
+ track(box);
3676
+ box.on("error", () => box.destroy());
3677
+ if (box.remoteAddress !== opts.fromIp) return void box.destroy();
3678
+ dialFar(opts.target, opts.dialTimeoutMs).then(
3679
+ ({ socket, rest }) => {
3680
+ if (box.destroyed) return void socket.destroy();
3681
+ track(socket);
3682
+ if (rest.length > 0) box.write(rest);
3683
+ splice(box, socket);
3684
+ },
3685
+ (err) => {
3686
+ box.destroy();
3687
+ if (err instanceof FarRefusal && err.code === "gone") return opts.onGone?.();
3688
+ if (err instanceof FarRefusal && err.code !== "refused") return;
3689
+ if (Date.now() - warnedAt < WARN_EVERY_MS) return;
3690
+ warnedAt = Date.now();
3691
+ log.warn(`link to ${opts.target.name} port ${opts.target.port} on another host: ${err.message}`);
3692
+ }
3693
+ );
3694
+ });
3695
+ server.maxConnections = MAX_OPEN;
3696
+ await new Promise((resolve3, reject) => {
3697
+ server.once("error", reject);
3698
+ server.listen(0, opts.host, () => {
3699
+ server.off("error", reject);
3700
+ resolve3();
3701
+ });
3702
+ });
3703
+ server.unref();
3704
+ server.on("error", () => void 0);
3705
+ const port = server.address().port;
3706
+ listeners.set(id, { server, open: open4, port, target: { ...opts.target } });
3707
+ return port;
3708
+ }
3709
+ async function closeFar(id) {
3710
+ const l = listeners.get(id);
3711
+ if (!l) return;
3712
+ listeners.delete(id);
3713
+ for (const sock of l.open) sock.destroy();
3714
+ await new Promise((resolve3) => l.server.close(() => resolve3()));
3715
+ }
3716
+
3717
+ // src/core/volumes.ts
3718
+ import { existsSync as existsSync6, statSync as statSync2 } from "node:fs";
3719
+ import { lstat, mkdir as mkdir2, readdir as readdir3, rm as rm3, statfs, symlink, truncate as truncate2, writeFile as writeFile4 } from "node:fs/promises";
3720
+
3721
+ // ../shared/src/capacity.ts
3722
+ function sellableGib(d) {
3723
+ return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);
3724
+ }
3725
+ function volumeRoomGib(d) {
3726
+ return Math.max(0, sellableGib(d) - d.volumesGib);
3727
+ }
3728
+ function hasDiskRoom(d, sizeGib) {
3729
+ return sizeGib <= volumeRoomGib(d);
3730
+ }
3731
+ var VCPU_OVERSUBSCRIPTION = 2;
3263
3732
 
3264
3733
  // src/core/volumes.ts
3265
3734
  var volumeLabel = (name) => `kv:${name}`;
3266
3735
  function toVolume(meta, attachedTo, p) {
3267
3736
  let usedBytes2 = 0;
3268
3737
  try {
3269
- usedBytes2 = statSync(p.volume(meta.owner, meta.name).disk).blocks * 512;
3738
+ usedBytes2 = statSync2(p.volume(meta.owner, meta.name).disk).blocks * 512;
3270
3739
  } catch {
3271
3740
  }
3272
3741
  return { id: meta.id, name: meta.name, owner: meta.owner, sizeGib: meta.sizeGib, usedBytes: usedBytes2, attachedTo, createdAt: meta.createdAt };
@@ -3322,13 +3791,13 @@ async function listVolumes(scope, p = paths()) {
3322
3791
  return out.sort((a, b) => a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name));
3323
3792
  }
3324
3793
  async function diskCapacity(p = paths()) {
3325
- const st = await statfs(existsSync5(p.volumes) ? p.volumes : p.home);
3794
+ const st = await statfs(existsSync6(p.volumes) ? p.volumes : p.home);
3326
3795
  let volumesGib = 0;
3327
3796
  let usedBytes2 = 0;
3328
3797
  for (const ref of await listVolumeRefs(p)) {
3329
3798
  try {
3330
3799
  volumesGib += (await readVolumeMeta(ref, p)).sizeGib;
3331
- usedBytes2 += statSync(p.volume(ref.owner, ref.name).disk).blocks * 512;
3800
+ usedBytes2 += statSync2(p.volume(ref.owner, ref.name).disk).blocks * 512;
3332
3801
  } catch {
3333
3802
  }
3334
3803
  }
@@ -3351,7 +3820,7 @@ async function createVolume(req, owner, p = paths()) {
3351
3820
  }
3352
3821
  async function makeVolume(req, owner, p) {
3353
3822
  const v = p.volume(owner, req.name);
3354
- if (existsSync5(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
3823
+ if (existsSync6(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
3355
3824
  await mkdir2(p.ownerVolumes(owner), { recursive: true, mode: 448 });
3356
3825
  const disk = await diskCapacity(p);
3357
3826
  if (!hasDiskRoom(disk, req.sizeGib)) {
@@ -3373,8 +3842,8 @@ async function makeVolume(req, owner, p) {
3373
3842
  throw err;
3374
3843
  }
3375
3844
  try {
3376
- await writeFile3(v.disk, "", { mode: 384 });
3377
- await truncate(v.disk, req.sizeGib * 1024 ** 3);
3845
+ await writeFile4(v.disk, "", { mode: 384 });
3846
+ await truncate2(v.disk, req.sizeGib * 1024 ** 3);
3378
3847
  await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", volumeLabel(req.name), "-E", "lazy_itable_init=1,lazy_journal_init=1", v.disk]);
3379
3848
  const meta = { id: newBoxId(taken), name: req.name, owner, sizeGib: req.sizeGib, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
3380
3849
  await writeVolumeMeta(meta, p);
@@ -3420,7 +3889,7 @@ async function growVolume(ref, sizeGib, p = paths(), check) {
3420
3889
  const meta = await assertCanGrow(ref, sizeGib, p);
3421
3890
  await check?.();
3422
3891
  const disk = p.volume(ref.owner, ref.name).disk;
3423
- await truncate(disk, sizeGib * 1024 ** 3);
3892
+ await truncate2(disk, sizeGib * 1024 ** 3);
3424
3893
  await run(["e2fsck", "-f", "-p", disk], { okExitCodes: [1] });
3425
3894
  await run(["resize2fs", disk]);
3426
3895
  const grown = { ...meta, sizeGib };
@@ -3465,7 +3934,7 @@ function volumeSummaries(box, p) {
3465
3934
  return box.volumes.map((name) => {
3466
3935
  let sizeGib = 0;
3467
3936
  try {
3468
- sizeGib = Math.round(statSync(p.volume(box.owner, name).disk).size / 1024 ** 3);
3937
+ sizeGib = Math.round(statSync2(p.volume(box.owner, name).disk).size / 1024 ** 3);
3469
3938
  } catch {
3470
3939
  }
3471
3940
  return { name, sizeGib, mountPath: volumeMountPath(name) };
@@ -3492,8 +3961,8 @@ async function placeholderDrives(boxDir, volumes) {
3492
3961
  for (const v of volumes) {
3493
3962
  const file = `${boxDir}/${volumeDriveRel(v.name)}`;
3494
3963
  await rm3(file, { force: true });
3495
- await writeFile3(file, "", { mode: 384 });
3496
- await truncate(file, v.sizeGib * 1024 ** 3);
3964
+ await writeFile4(file, "", { mode: 384 });
3965
+ await truncate2(file, v.sizeGib * 1024 ** 3);
3497
3966
  }
3498
3967
  }
3499
3968
  var volumeDriveId = (name) => `vol_${name.replace(/-/g, "_")}`;
@@ -3501,1858 +3970,1567 @@ async function attachedBox(ref, p) {
3501
3970
  return (await attachments(ref.owner, p)).get(ref.name) ?? null;
3502
3971
  }
3503
3972
 
3504
- // src/core/backupStore.ts
3505
- import { createHash, randomBytes as randomBytes3 } from "node:crypto";
3506
- import { existsSync as existsSync6 } from "node:fs";
3507
- import { chmod as chmod2, mkdir as mkdir3, readFile as readFile6, rename as rename3, rm as rm4, stat as stat2, statfs as statfs2, writeFile as writeFile4 } from "node:fs/promises";
3508
- import { request as httpRequest } from "node:http";
3509
- import { userInfo as userInfo2 } from "node:os";
3510
- import { isAbsolute, join as join2 } from "node:path";
3511
- import { pipeline } from "node:stream";
3512
- import { setTimeout as sleep2 } from "node:timers/promises";
3513
- import { request as request2 } from "undici";
3514
- var GARAGE_VERSION = "2.5.0";
3515
- var GARAGE_SHA256 = {
3516
- x64: { arch: "x86_64", sha256: "2ff667286217cd73ebcb1c03af993822365000441dfe31a80cb64c5189a9dea8" },
3517
- arm64: { arch: "aarch64", sha256: "69b6040cef428b993500c17dd0d0c1240acf2f3f667b9b05ceba4b9660db4e8c" }
3518
- };
3519
- var GARAGE_S3_PORT = 3900;
3520
- var GARAGE_RPC_PORT = 3901;
3521
- var KEY_NAME = "kvbox-control-plane";
3522
- var START_WAIT_MS = 6e4;
3523
- var WATCH_MS = 3e4;
3524
- var garage = (p, args, timeoutMs = 2e4) => run([p.garage, "-c", p.backupStore.conf, ...args], { timeoutMs });
3525
- var realDeps = {
3526
- install: installGarage,
3527
- start: (p) => spawnDetached([p.garage, "-c", p.backupStore.conf, "server"], p.backupStore.log),
3528
- running: (p) => garageRunning(p),
3529
- stop: stopGarage,
3530
- api: async (p, operation, body) => {
3531
- const { stdout } = await garage(p, ["json-api", operation, ...body === void 0 ? [] : [JSON.stringify(body)]]);
3532
- const text = stdout.trim();
3533
- return text === "" ? null : JSON.parse(text);
3534
- },
3535
- cli: async (p, args) => (await garage(p, args)).stdout,
3536
- register: registerWithControlPlane,
3537
- device: async (path) => (await stat2(path)).dev
3538
- };
3539
- var versionFile = (p) => `${p.garage}.version`;
3540
- async function installGarage(p) {
3541
- if (existsSync6(p.garage) && (await readFile6(versionFile(p), "utf8").catch(() => "")).trim() === GARAGE_VERSION) return false;
3542
- const build = GARAGE_SHA256[process.arch];
3543
- if (!build) throw new KvboxError(`there is no Garage build for this machine (${process.arch})`);
3544
- const url = `https://garagehq.deuxfleurs.fr/_releases/v${GARAGE_VERSION}/${build.arch}-unknown-linux-musl/garage`;
3545
- const res = await fetch(url, { signal: AbortSignal.timeout(3e5) }).catch((err) => {
3546
- throw new KvboxError(`could not download Garage from ${url} (${err.message})`);
3547
- });
3548
- if (!res.ok) throw new KvboxError(`could not download Garage from ${url}: HTTP ${res.status}`);
3549
- const bytes = Buffer.from(await res.arrayBuffer());
3550
- const got = createHash("sha256").update(bytes).digest("hex");
3551
- if (got !== build.sha256) throw new KvboxError(`the Garage download is not the expected file (sha256 ${got}); nothing was installed`);
3552
- await mkdir3(p.bin, { recursive: true });
3553
- const tmp = `${p.garage}.tmp`;
3554
- await writeFile4(tmp, bytes, { mode: 493 });
3555
- await chmod2(tmp, 493);
3556
- await rename3(tmp, p.garage);
3557
- await writeFile4(versionFile(p), `${GARAGE_VERSION}
3558
- `);
3559
- return true;
3560
- }
3561
- async function registerWithControlPlane(cfg, body) {
3562
- const cp = cfg.controlPlane;
3563
- if (!cp) throw new KvboxError("this host has not joined a control plane");
3564
- const res = await request2(`${cp.url}/hosts/self/backup-store`, {
3565
- method: "PUT",
3566
- headers: { authorization: `Bearer ${cp.secret}`, "content-type": "application/json" },
3567
- body: JSON.stringify(body),
3568
- headersTimeout: 1e4,
3569
- bodyTimeout: 1e4
3570
- }).catch((err) => {
3571
- throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
3572
- });
3573
- const text = await res.body.text();
3574
- if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not know backup stores yet: it is older than this host`);
3575
- if (res.statusCode < 200 || res.statusCode >= 300) {
3576
- let error;
3577
- try {
3578
- error = JSON.parse(text).error;
3579
- } catch {
3580
- }
3581
- throw new KvboxError(typeof error === "string" ? error : `${cp.name} answered ${res.statusCode}`);
3582
- }
3583
- }
3584
- function garageToml(path) {
3585
- const q = (s) => JSON.stringify(s);
3586
- return [
3587
- "# written by kvbox-server backup setup: this host's backup store",
3588
- `metadata_dir = ${q(join2(path, "meta"))}`,
3589
- `data_dir = ${q(join2(path, "data"))}`,
3590
- 'db_engine = "lmdb"',
3591
- "metadata_fsync = true",
3592
- "data_fsync = true",
3593
- "replication_factor = 1",
3594
- `rpc_bind_addr = "127.0.0.1:${GARAGE_RPC_PORT}"`,
3595
- `rpc_public_addr = "127.0.0.1:${GARAGE_RPC_PORT}"`,
3596
- `rpc_secret_file = ${q(join2(path, "rpc_secret"))}`,
3597
- "",
3598
- "[s3_api]",
3599
- `s3_region = ${q(BACKUP_STORE_REGION)}`,
3600
- `api_bind_addr = "127.0.0.1:${GARAGE_S3_PORT}"`,
3601
- ""
3602
- ].join("\n");
3973
+ // src/core/machines/status.ts
3974
+ import { existsSync as existsSync7 } from "node:fs";
3975
+ function isHibernated(meta, p) {
3976
+ return !vmAlive(meta) && existsSync7(p.machine(meta.owner, meta.name).hibernateVmstate);
3603
3977
  }
3604
- async function readPid(p) {
3605
- const n = Number((await readFile6(p.backupStore.pid, "utf8").catch(() => "")).trim());
3606
- return Number.isInteger(n) && n > 0 ? n : null;
3978
+ function statusOf(meta, p = paths()) {
3979
+ if (vmAlive(meta)) return meta.paused ? "standby" : "running";
3980
+ return isHibernated(meta, p) ? "hibernated" : "stopped";
3607
3981
  }
3608
- async function garageRunning(p = paths()) {
3609
- const pid = await readPid(p);
3610
- if (!pidAlive(pid)) return false;
3611
- const cmdline = await readFile6(`/proc/${pid}/cmdline`, "utf8").catch(() => null);
3612
- return cmdline === null || cmdline.split("\0")[0] === p.garage;
3982
+ function stateMessage(ref, status) {
3983
+ return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
3613
3984
  }
3614
- async function stopGarage(p) {
3615
- const pid = await readPid(p);
3616
- if (pid === null || !await garageRunning(p)) return;
3617
- const cmdline = await readFile6(`/proc/${pid}/cmdline`, "utf8").catch(() => null);
3618
- if (cmdline?.split("\0")[0] !== p.garage) throw new KvboxError(`cannot tell whether pid ${pid} is this host's Garage, so it was not stopped; stop Garage by hand and run this again`);
3619
- process.kill(pid, "SIGTERM");
3620
- const until = Date.now() + 15e3;
3621
- while (pidAlive(pid)) {
3622
- if (Date.now() > until) throw new KvboxError(`Garage (pid ${pid}) did not stop within 15s`);
3623
- await sleep2(200);
3985
+ function assertNotHibernated(meta, p) {
3986
+ if (isHibernated(meta, p)) {
3987
+ throw new KvboxError(`${stateMessage(meta, "hibernated")}; its memory image was made with its current shape and base: kvbox wake ${shown(meta)} first`);
3624
3988
  }
3625
- await rm4(p.backupStore.pid, { force: true });
3626
3989
  }
3627
- async function ensureGarage(p, deps) {
3628
- if (!await deps.running(p)) {
3629
- const pid = await deps.start(p);
3630
- await writeFile4(p.backupStore.pid, `${pid}
3631
- `);
3632
- }
3633
- const until = Date.now() + START_WAIT_MS;
3634
- for (; ; ) {
3990
+
3991
+ // src/core/machines/list.ts
3992
+ function toMachine(meta, p = paths()) {
3993
+ const alive2 = vmAlive(meta);
3994
+ if (!alive2 && meta.pid !== null) {
3635
3995
  try {
3636
- await deps.cli(p, ["status"]);
3637
- return;
3996
+ closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
3638
3997
  } catch (err) {
3639
- if (Date.now() > until) throw new KvboxError(`Garage did not answer after ${START_WAIT_MS / 1e3}s (see ${p.backupStore.log}): ${err.message}`);
3640
- await sleep2(500);
3998
+ log.warn(`usage ledger: ${err.message}`);
3641
3999
  }
3642
4000
  }
4001
+ return {
4002
+ id: meta.id,
4003
+ name: meta.name,
4004
+ owner: meta.owner,
4005
+ ip: meta.ip,
4006
+ mac: meta.mac,
4007
+ pid: alive2 ? meta.pid : null,
4008
+ vcpu: meta.vcpu,
4009
+ memMib: meta.memMib,
4010
+ ...diskStats(p.machine(meta.owner, meta.name).overlay),
4011
+ base: meta.base,
4012
+ ...meta.image !== void 0 ? { image: meta.image } : {},
4013
+ ...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
4014
+ createdAt: meta.createdAt,
4015
+ ...meta.bootedAt !== void 0 ? { bootedAt: meta.bootedAt } : {},
4016
+ source: meta.source,
4017
+ status: statusOf(meta, p),
4018
+ ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
4019
+ ...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
4020
+ ...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
4021
+ ...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
4022
+ ...meta.integrations?.length ? { integrations: [...meta.integrations] } : {},
4023
+ ...meta.cluster !== void 0 ? { clusterId: meta.cluster } : {},
4024
+ ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
4025
+ ...linksOf(meta)
4026
+ };
3643
4027
  }
3644
- function setupBackupStore(req, p = paths(), deps = realDeps) {
3645
- return serial(() => setup(req, p, deps));
4028
+ function linksOf(meta) {
4029
+ const all = [...(meta.links ?? []).filter((l) => !l.stale), ...meta.farLinks ?? []];
4030
+ return all.length > 0 ? { links: all.map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {};
3646
4031
  }
3647
- var turn = Promise.resolve();
3648
- function serial(step) {
3649
- const mine = turn.then(step, step);
3650
- turn = mine.catch(() => void 0);
3651
- return mine;
4032
+ var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
4033
+ async function listMachines(scope, p = paths()) {
4034
+ return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
3652
4035
  }
3653
- async function setup(req, p, deps) {
3654
- const path = req.path.replace(/\/+$/, "") || "/";
3655
- if (!isAbsolute(path) || /["\\\n\0]/.test(path)) throw new KvboxError(`${req.path} is not a path a store can use: give the full path of a directory on the backup disk`);
3656
- const cfg = await loadConfig(p);
3657
- if (!cfg.controlPlane) throw new KvboxError("this host has not joined a control plane, which is what takes backups; run kvbox-server join first");
3658
- if (cfg.backupStore && cfg.backupStore.path !== path) {
3659
- throw new KvboxError(`this host already is a backup store, with its data in ${cfg.backupStore.path}; a host has one store`);
3660
- }
3661
- const dir = await stat2(path).catch(() => null);
3662
- if (!dir?.isDirectory()) throw new KvboxError(`${path} is not a directory: mount the backup disk and give a directory on it`);
3663
- if (!req.force && await deps.device(path) === await deps.device(p.home)) {
3664
- throw new KvboxError(`${path} is on the same disk as this host's boxes, so the backups would be lost with them; mount a disk for backups there, or pass --force to use it anyway`);
3665
- }
3666
- if (cfg.backupStore && !req.newStore && !existsSync6(join2(path, "rpc_secret"))) throw notTheStoreDisk(path);
3667
- const newBinary = await deps.install(p);
3668
- await mkdir3(p.backupStore.dir, { recursive: true, mode: 448 });
4036
+ async function getMachine(ref, p = paths()) {
4037
+ return toMachine(await readMeta(ref, p), p);
4038
+ }
4039
+
4040
+ // src/core/machines/farTargets.ts
4041
+ var listenerId = (boxId, t) => `${boxId}|${t.owner}/${t.name}:${t.port}`;
4042
+ var sameTarget2 = (to, port) => (t) => t.owner === to.owner && t.name === to.name && t.port === port;
4043
+ function targetRef(req, caller) {
4044
+ if (req.toOwner !== void 0) return { owner: ownerFor(req.toOwner, caller), name: req.to, display: `${req.toOwner}/${req.to}` };
4045
+ return parseRef(req.to, caller);
4046
+ }
4047
+ async function open(meta, t, cfg, p) {
4048
+ const ref = { owner: meta.owner, name: meta.name };
4049
+ const via = await listenFar(listenerId(meta.id, t), {
4050
+ host: driver().net.farListenHost(cfg),
4051
+ fromIp: meta.ip,
4052
+ target: t,
4053
+ // The listener was made under the box's lock, and its connections would read as holding it: the forget
4054
+ // waits for the lock like any other change of the box.
4055
+ onGone: () => outsideLocks(() => void forgetFarTarget(ref, t, p).catch((err) => log.warn(`box ${meta.name}: could not forget its link to ${t.name}: ${err.message}`)))
4056
+ });
4057
+ await driver().net.openFarLink({ box: meta.id, fromIp: meta.ip, standIn: t.ip, port: t.port, via }, cfg);
4058
+ }
4059
+ async function close(meta, t, cfg) {
3669
4060
  try {
3670
- for (const sub of ["meta", "data"]) await mkdir3(join2(path, sub), { recursive: true, mode: 448 });
3671
- const rpcSecret = join2(path, "rpc_secret");
3672
- if (!existsSync6(rpcSecret)) await writeFile4(rpcSecret, `${randomBytes3(32).toString("hex")}
3673
- `, { mode: 384 });
3674
- } catch (err) {
3675
- const code = err.code;
3676
- if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS") throw err;
3677
- const user = userInfo2().username;
3678
- throw new KvboxError(`kvbox-server (user ${user}) cannot write in ${path}: make the directory ${user}'s (sudo chown ${user} ${path}) and run this again`);
3679
- }
3680
- const conf = garageToml(path);
3681
- const had = await readFile6(p.backupStore.conf, "utf8").catch(() => null);
3682
- await writeFile4(p.backupStore.conf, conf, { mode: 384 });
3683
- if ((newBinary || had !== null && had !== conf) && await deps.running(p)) await deps.stop(p);
3684
- await ensureGarage(p, deps);
3685
- const layout = await deps.api(p, "GetClusterLayout");
3686
- if ((layout?.version ?? 0) === 0) {
3687
- const node = (await deps.cli(p, ["node", "id", "-q"])).trim().split("@")[0];
3688
- const fs = await statfs2(path);
3689
- await deps.cli(p, ["layout", "assign", "-z", "kvbox", "-c", String(fs.blocks * fs.bsize), node]);
3690
- await deps.cli(p, ["layout", "apply", "--version", "1"]);
3691
- }
3692
- const bucket = await bucketInfo(p, deps).then(async (info) => info ?? await deps.api(p, "CreateBucket", { globalAlias: BACKUP_STORE_BUCKET }));
3693
- let store;
3694
- if (cfg.backupStore && await hasKey(p, deps, cfg.backupStore.accessKey)) {
3695
- store = cfg.backupStore;
3696
- } else {
3697
- if (cfg.backupStore && !req.newStore) {
3698
- await deps.stop(p);
3699
- throw notTheStoreDisk(path);
3700
- }
3701
- if (cfg.backupStore) log.warn(`backup store: a new store in ${path} replaces the one with key ${cfg.backupStore.accessKey}; the backups kept on the old disk are gone`);
3702
- const key = await deps.api(p, "CreateKey", { name: KEY_NAME });
3703
- store = { path, bucket: BACKUP_STORE_BUCKET, region: BACKUP_STORE_REGION, accessKey: key.accessKeyId, secretKey: key.secretAccessKey, registered: false };
4061
+ await driver().net.closeFarLink({ box: meta.id, fromIp: meta.ip, standIn: t.ip, port: t.port }, cfg);
4062
+ } finally {
4063
+ await closeFar(listenerId(meta.id, t));
3704
4064
  }
3705
- await deps.api(p, "AllowBucketKey", { bucketId: bucket.id, accessKeyId: store.accessKey, permissions: { read: true, write: true, owner: false } });
3706
- const now = await loadConfig(p);
3707
- await saveConfig({ ...now, backupStore: { ...store, registered: false } }, p);
3708
- log.info(`backup store: Garage keeps its data in ${path}`);
3709
- try {
3710
- await deps.register(now, { bucket: store.bucket, region: store.region, accessKey: store.accessKey, secretKey: store.secretKey });
3711
- } catch (err) {
3712
- throw new KvboxError(`the store is set up, but the control plane did not take it: ${err.message}. Run the same command again once that is solved`);
4065
+ }
4066
+ async function openFarTargets(meta, cfg, p) {
4067
+ for (const t of meta.farTargets ?? []) {
4068
+ await open(meta, t, cfg, p).catch((err) => log.warn(`box ${meta.name} cannot reach ${t.name} port ${t.port} on another host: ${err.message}`));
3713
4069
  }
3714
- await saveConfig({ ...await loadConfig(p), backupStore: { ...store, registered: true } }, p);
3715
- log.info(`backup store: registered with ${now.controlPlane?.name ?? cfg.controlPlane.name}`);
3716
- return backupStoreStatus(p, deps);
3717
4070
  }
3718
- var notTheStoreDisk = (path) => new KvboxError(
3719
- `${path} does not hold this host's backup store: is its disk mounted there? Mount it and run this again. If that disk is gone for good, pass --new-store to start a new store here (the backups kept on the old disk can no longer be restored)`
3720
- );
3721
- async function hasKey(p, deps, id) {
3722
- const keys = await deps.api(p, "ListKeys");
3723
- return (keys ?? []).some((k) => k.id === id);
4071
+ async function closeFarTargets(meta, cfg) {
4072
+ for (const t of meta.farTargets ?? []) {
4073
+ await close(meta, t, cfg).catch((err) => log.warn(`could not close box ${meta.name}'s link to ${t.name} on another host: ${err.message}`));
4074
+ }
3724
4075
  }
3725
- async function bucketInfo(p, deps) {
3726
- try {
3727
- return await deps.api(p, "GetBucketInfo", { globalAlias: BACKUP_STORE_BUCKET });
3728
- } catch (err) {
3729
- if (/not found|nosuchbucket/i.test(err.message)) return null;
3730
- throw err;
4076
+ async function reopenFarTargets(p = paths()) {
4077
+ const cfg = await loadConfig(p);
4078
+ for (const listed of await readAllMeta(p)) {
4079
+ if (!vmAlive(listed) || !listed.farTargets?.length) continue;
4080
+ await withBoxLock(listed, async () => {
4081
+ const meta = await readMachineMeta(listed, p).catch(() => null);
4082
+ if (meta !== null && vmAlive(meta)) await openFarTargets(meta, cfg, p);
4083
+ });
3731
4084
  }
3732
4085
  }
3733
- async function backupStoreStatus(p = paths(), deps = realDeps) {
3734
- const store = (await loadConfig(p)).backupStore;
3735
- if (!store) throw new KvboxError("this host is not a backup store; make it one with: kvbox-server backup setup --path <directory on the backup disk>");
3736
- const fs = await statfs2(store.path).catch(() => null);
3737
- const running = await deps.running(p);
3738
- const info = running ? await bucketInfo(p, deps).catch(() => null) : null;
3739
- return {
3740
- path: store.path,
3741
- bucket: store.bucket,
3742
- accessKey: store.accessKey,
3743
- running: running && info !== null,
3744
- totalBytes: fs ? fs.blocks * fs.bsize : 0,
3745
- freeBytes: fs ? fs.bavail * fs.bsize : 0,
3746
- ...info ? { objects: info.objects ?? 0, storedBytes: info.bytes ?? 0 } : {},
3747
- registered: store.registered
3748
- };
3749
- }
3750
- async function backupStoreCapacity(p = paths(), deps = realDeps) {
3751
- const store = (await loadConfig(p)).backupStore;
3752
- if (!store) return void 0;
3753
- const fs = await statfs2(store.path).catch(() => null);
3754
- return { totalBytes: fs ? fs.blocks * fs.bsize : 0, freeBytes: fs ? fs.bavail * fs.bsize : 0, running: fs !== null && await deps.running(p) };
3755
- }
3756
- function reviveBackupStore(p = paths(), deps = realDeps) {
3757
- return serial(() => revive(p, deps));
3758
- }
3759
- var upgraded = /* @__PURE__ */ new Set();
3760
- var restartDue = /* @__PURE__ */ new Set();
3761
- async function revive(p, deps) {
3762
- const store = (await loadConfig(p)).backupStore;
3763
- if (!store) return "none";
3764
- if (!upgraded.has(p.home)) {
3765
- upgraded.add(p.home);
3766
- const fresh = await deps.install(p).catch((err) => {
3767
- log.warn(`backup store: Garage ${GARAGE_VERSION} could not be installed, the one there keeps running (${err.message})`);
3768
- return false;
3769
- });
3770
- if (fresh) restartDue.add(p.home);
3771
- }
3772
- if (restartDue.has(p.home) && existsSync6(join2(store.path, "rpc_secret"))) {
3773
- if (await deps.running(p)) await deps.stop(p);
3774
- const pid2 = await deps.start(p);
3775
- await writeFile4(p.backupStore.pid, `${pid2}
3776
- `);
3777
- restartDue.delete(p.home);
3778
- return "upgraded";
3779
- }
3780
- if (await deps.running(p)) return "running";
3781
- if (!existsSync6(join2(store.path, "rpc_secret"))) return "no-disk";
3782
- await rm4(p.backupStore.pid, { force: true });
3783
- const pid = await deps.start(p);
3784
- await writeFile4(p.backupStore.pid, `${pid}
3785
- `);
3786
- return "started";
3787
- }
3788
- var watch;
3789
- function startBackupStoreWatch(p = paths()) {
3790
- let warned = false;
3791
- const tick = () => {
3792
- reviveBackupStore(p).then((state) => {
3793
- if (state === "started") log.info("backup store: Garage was not running; started it");
3794
- if (state === "upgraded") log.info(`backup store: Garage ${GARAGE_VERSION} installed and started`);
3795
- if (state === "no-disk" && !warned) log.warn("backup store: its disk is not mounted, so Garage is not started; backups to this host fail until it is back");
3796
- warned = state === "no-disk";
3797
- }).catch((err) => log.warn(`backup store: Garage did not start (${err.message})`));
3798
- };
3799
- tick();
3800
- watch ??= setInterval(tick, WATCH_MS);
3801
- watch.unref();
3802
- }
3803
- function isStoreRequest(url) {
3804
- return url !== void 0 && (url.startsWith(`/${BACKUP_STORE_BUCKET}/`) || url.startsWith(`/${BACKUP_STORE_BUCKET}?`) || url === `/${BACKUP_STORE_BUCKET}`);
3805
- }
3806
- function forStore(url, p = paths()) {
3807
- return isStoreRequest(url) && existsSync6(p.backupStore.conf);
3808
- }
3809
- function storeProxy(req, res, port = GARAGE_S3_PORT) {
3810
- const up = httpRequest({ host: "127.0.0.1", port, method: req.method, path: req.url, headers: req.headers }, (answer2) => {
3811
- res.writeHead(answer2.statusCode ?? 502, answer2.headers);
3812
- pipeline(answer2, res, (err) => {
3813
- if (err) res.destroy();
3814
- });
3815
- });
3816
- up.on("error", () => {
3817
- if (res.headersSent) return res.destroy();
3818
- res.writeHead(503, { "content-type": "application/json" });
3819
- res.end(JSON.stringify({ error: "this host's backup store is not running" }));
3820
- });
3821
- res.once("close", () => {
3822
- if (!res.writableFinished) up.destroy();
3823
- });
3824
- req.pipe(up);
3825
- }
3826
-
3827
- // src/core/capacity.ts
3828
- function hostResources() {
3829
- return { memMib: Math.floor(totalmem() / 1024 ** 2), cores: cpus().length };
3830
- }
3831
- async function runningReservations(p = paths()) {
3832
- const out = [];
3833
- for (const ref of await listMachineRefs(p)) {
3834
- try {
3835
- const meta = await readMachineMeta(ref, p);
3836
- if (vmAlive(meta)) out.push({ owner: meta.owner, name: meta.name, vcpu: meta.vcpu, memMib: meta.memMib });
3837
- } catch {
3838
- }
4086
+ var addFarTarget = locked(async function addFarTarget2(ref, req, caller, p = paths()) {
4087
+ const meta = await readMeta(ref, p);
4088
+ const to = targetRef(req, caller);
4089
+ if (realmOf(meta.owner) === null || realmOf(to.owner) !== realmOf(meta.owner)) {
4090
+ throw new KvboxError(`a link to a box on another host joins two boxes of one control plane; box ${shown(ref)} and box ${shown(to)} are not`);
3839
4091
  }
3840
- return out;
3841
- }
3842
- async function capacity(p = paths()) {
3843
- const host = hostResources();
3844
- const running = await runningReservations(p);
3845
4092
  const cfg = await loadConfig(p);
3846
- return {
3847
- hostMemMib: host.memMib,
3848
- memHeadroomMib: cfg.memHeadroomMib,
3849
- hostCores: host.cores,
3850
- reservedMemMib: running.reduce((n, r) => n + r.memMib, 0),
3851
- reservedVcpu: running.reduce((n, r) => n + r.vcpu, 0),
3852
- running: running.length,
3853
- disk: await diskCapacity(p),
3854
- // What a box can be made from here (#87): the control plane places `--base postgres` by it.
3855
- images: await listImages(cfg, p),
3856
- ...await backupStoreCapacity(p).then((store) => store ? { backupStore: store } : {}),
3857
- // Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).
3858
- storeClient: true,
3859
- // A new box on a backup's disk (#141): the control plane places `new --from-backup` only here.
3860
- fromBackup: true,
3861
- // A link to a box on another host is carried here (#207): the control plane links across hosts only between two such.
3862
- // Only once the host's privileged network script knows them: an update without its root step does not.
3863
- farLinks: driver().net.carriesFarLinks(),
3864
- // The boxes of a cluster reach each other here (#215), on the same condition: the control plane places a cluster's box only on such a host.
3865
- clusters: driver().net.carriesClusters(),
3866
- // A box's integrations are kept here (#205): the control plane sends a list only to such a host.
3867
- integrations: true,
3868
- // ...and which (the control plane places a box with `claude` only on a host that names it).
3869
- integrationIds: [...INTEGRATION_IDS]
3870
- };
3871
- }
3872
- function gb(mib) {
3873
- const g = mib / 1024;
3874
- return `${Number.isInteger(g) ? g : g.toFixed(1)} GB`;
3875
- }
3876
- function describeRunning(running, viewer) {
3877
- if (running.length === 0) return "no box is running";
3878
- const own = viewer === void 0 ? running : running.filter((r) => r.owner === viewer);
3879
- const others = running.length - own.length;
3880
- const named = own.map((r) => `${r.name} ${r.vcpu} vCPU/${gb(r.memMib)}`);
3881
- if (others > 0) named.push(`${others} ${others === 1 ? "box" : "boxes"} of other users`);
3882
- const list = named.join(", ");
3883
- const vcpu = running.reduce((n, r) => n + r.vcpu, 0);
3884
- const mem = running.reduce((n, r) => n + r.memMib, 0);
3885
- return `${running.length} running ${running.length === 1 ? "box reserves" : "boxes reserve"} ${vcpu} vCPU and ${gb(mem)} (${list})`;
3886
- }
3887
- var HINTS = {
3888
- new: "stop or remove a box (kvbox stop, kvbox rm), pick a smaller --size, or pass --force to start it anyway",
3889
- start: "stop or remove a box (kvbox stop, kvbox rm), or pass --force to start it anyway",
3890
- rescale: "stop or remove a box (kvbox stop, kvbox rm), ask for less, or pass --force to rescale it anyway"
3891
- };
3892
- function roomFor(host, running, want, opts = {}) {
3893
- const { viewer, by = "new" } = opts;
3894
- const reservedMem = running.reduce((n, r) => n + r.memMib, 0);
3895
- const reservedVcpu = running.reduce((n, r) => n + r.vcpu, 0);
3896
- const headroom = host.headroomMib ?? 0;
3897
- const memLimit = host.memMib - headroom;
3898
- const vcpuLimit = host.cores * VCPU_OVERSUBSCRIPTION;
3899
- const hint = HINTS[by];
3900
- if (reservedMem + want.memMib > memLimit) {
3901
- return `not enough memory for a ${gb(want.memMib)} box: ${describeRunning(running, viewer)}; ` + (headroom > 0 ? `this host has ${gb(host.memMib)} and keeps ${gb(headroom)} for itself, so boxes may reserve ${gb(memLimit)} in total. ` : `this host has ${gb(host.memMib)}, all of it for its boxes. `) + hint;
3902
- }
3903
- if (reservedVcpu + want.vcpu > vcpuLimit) {
3904
- return `too many vCPUs for a ${want.vcpu} vCPU box: ${describeRunning(running, viewer)}; this host has ${host.cores} cores and allows ${vcpuLimit} vCPUs in total (${VCPU_OVERSUBSCRIPTION}x). ` + hint;
3905
- }
3906
- return void 0;
3907
- }
3908
- async function assertRoomFor(vcpu, memMib, force, box, by, p = paths()) {
3909
- if (force) return;
3910
- const running = (await runningReservations(p)).filter((r) => box.name === void 0 || !(r.owner === box.owner && r.name === box.name));
3911
- const host = { ...hostResources(), headroomMib: (await loadConfig(p)).memHeadroomMib };
3912
- const reason = roomFor(host, running, { vcpu, memMib }, { viewer: box.owner, by });
3913
- if (reason !== void 0) throw new KvboxError(reason);
3914
- }
3915
-
3916
- // src/core/env.ts
3917
- import { existsSync as existsSync7 } from "node:fs";
3918
- import { copyFile, mkdir as mkdir4, readFile as readFile7, readdir as readdir4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
3919
- import { z as z7 } from "zod";
3920
-
3921
- // ../shared/src/env.ts
3922
- var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
3923
- var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
3924
- var ENV_MAX_VALUE_BYTES = 4096;
3925
- var ENV_MAX_VARS = 100;
3926
- function envNameProblem(name) {
3927
- if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
3928
- if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
3929
- if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
3930
- return null;
3931
- }
3932
- function envValueProblem(value) {
3933
- if (/[\n\r\0]/.test(value)) return "a value is one line: no line breaks (base64 a multi-line value such as a key file)";
3934
- if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
3935
- return null;
3936
- }
3937
-
3938
- // src/core/env.ts
3939
- var OwnerEnvSchema = z7.object({
3940
- /** The control plane's counter for the list; only ever grows. */
3941
- version: z7.number().int().min(0),
3942
- vars: z7.array(z7.object({ name: z7.string(), value: z7.string() }))
3943
- });
3944
- async function readOwnerEnv(owner, p = paths()) {
3945
- try {
3946
- return OwnerEnvSchema.parse(JSON.parse(await readFile7(p.ownerEnv(owner), "utf8")));
3947
- } catch (err) {
3948
- if (err.code === "ENOENT") return null;
3949
- throw err;
3950
- }
3951
- }
3952
- async function envForBoot(box, p = paths()) {
3953
- const env = await readOwnerEnv(box.owner, p).catch(() => null);
3954
- const own = await readBoxEnv(box, p).catch((err) => {
3955
- log.warn(`box ${shown(box)}: its own variables are unreadable, it boots without them: ${err.message}`);
3956
- return [];
4093
+ const same = sameTarget2(to, req.port);
4094
+ const before = (meta.farTargets ?? []).find(same);
4095
+ const kept = (meta.farTargets ?? []).filter((t) => !same(t));
4096
+ if (kept.length >= MAX_BOX_LINKS) throw new KvboxError(`a box reaches at most ${MAX_BOX_LINKS} ports of boxes on other hosts; box ${shown(ref)} has ${kept.length}`);
4097
+ return withHostLock("links", async () => {
4098
+ const taken = (await readAllMeta(p)).flatMap((m) => m.farTargets ?? []);
4099
+ const ip = taken.find((t) => t.owner === to.owner && t.name === to.name)?.ip ?? driver().net.standIn(cfg, taken.map((t) => t.ip));
4100
+ const entry = { owner: to.owner, name: to.name, port: req.port, ip, url: req.url, pin: req.pin, key: req.key };
4101
+ const next = { ...meta, farTargets: [...kept, entry] };
4102
+ if (before) await close(meta, before, cfg);
4103
+ await writeMachineMeta(next, p);
4104
+ boxListChanged();
4105
+ if (vmAlive(meta)) {
4106
+ try {
4107
+ await open(next, entry, cfg, p);
4108
+ } catch (err) {
4109
+ await close(next, entry, cfg).catch(() => void 0);
4110
+ await writeMachineMeta(meta, p);
4111
+ boxListChanged();
4112
+ if (before && vmAlive(meta)) await open(meta, before, cfg, p).catch((e) => log.warn(`box ${meta.name} cannot reach ${before.name} port ${before.port} on another host: ${e.message}`));
4113
+ throw err;
4114
+ }
4115
+ }
4116
+ return toMachine(next, p);
3957
4117
  });
3958
- const slug = env?.vars ?? (realmOf(box.owner) !== null ? [] : null);
3959
- if (own.length === 0) return slug ?? (existsSync7(p.machine(box.owner, box.name).env) ? [] : null);
3960
- const mine = new Set(own.map((v) => v.name));
3961
- return [...(slug ?? []).filter((v) => !mine.has(v.name)), ...own.map((v) => ({ name: v.name, value: v.value }))];
3962
- }
3963
- var BoxEnvFileSchema = z7.object({
3964
- vars: z7.array(z7.object({ name: z7.string(), value: z7.string(), secret: z7.boolean(), updatedAt: z7.string() }))
3965
4118
  });
3966
- async function readBoxEnv(box, p = paths()) {
3967
- return readBoxEnvFile(p.machine(box.owner, box.name).env);
3968
- }
3969
- async function readBoxEnvFile(file) {
3970
- try {
3971
- return BoxEnvFileSchema.parse(JSON.parse(await readFile7(file, "utf8"))).vars;
3972
- } catch (err) {
3973
- if (err.code === "ENOENT") return [];
3974
- throw err;
3975
- }
4119
+ var removeFarTarget = locked(async function removeFarTarget2(ref, req, caller, p = paths()) {
4120
+ const meta = await readMeta(ref, p);
4121
+ const same = sameTarget2(targetRef(req, caller), req.port);
4122
+ const gone = (meta.farTargets ?? []).filter(same);
4123
+ if (gone.length === 0) return toMachine(meta, p);
4124
+ return toMachine(await without(meta, gone, p), p);
4125
+ });
4126
+ async function without(meta, gone, p) {
4127
+ const cfg = await loadConfig(p);
4128
+ for (const t of gone) await close(meta, t, cfg);
4129
+ const kept = (meta.farTargets ?? []).filter((t) => !gone.includes(t));
4130
+ const next = { ...meta, farTargets: kept.length > 0 ? kept : void 0 };
4131
+ await writeMachineMeta(next, p);
4132
+ boxListChanged();
4133
+ return next;
3976
4134
  }
3977
- function checkBoxEnv(vars) {
3978
- if (vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
3979
- const seen = /* @__PURE__ */ new Set();
3980
- for (const v of vars) {
3981
- const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
3982
- if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
3983
- if (seen.has(v.name)) throw new KvboxError(`${v.name} is given twice`);
3984
- seen.add(v.name);
4135
+ var forgetFarTarget = locked(async function forgetFarTarget2(ref, t, p) {
4136
+ const meta = await readMachineMeta(ref, p).catch(() => null);
4137
+ const gone = (meta?.farTargets ?? []).filter((now) => now.owner === t.owner && now.name === t.name && now.port === t.port && now.key === t.key);
4138
+ if (meta === null || gone.length === 0) return;
4139
+ await without(meta, gone, p);
4140
+ log.info(`box ${meta.name}: its link to ${t.name} port ${t.port} no longer exists on the other host; forgotten here`);
4141
+ });
4142
+ function tellFarTargetsGone(gone) {
4143
+ for (const t of gone.farTargets ?? []) {
4144
+ void dropFar(t).catch((err) => log.warn(`removed box ${gone.name}: its link into ${t.name} on another host stays listed there (${err.message})`));
3985
4145
  }
3986
4146
  }
3987
- async function writeBoxEnv(box, vars, p = paths()) {
3988
- checkBoxEnv(vars);
3989
- const file = p.machine(box.owner, box.name).env;
3990
- const tmp = `${file}.tmp`;
3991
- await writeFile5(tmp, JSON.stringify({ vars }, null, 2) + "\n", { mode: 384 });
3992
- await rename4(tmp, file);
3993
- }
3994
- async function mergeBoxEnv(box, given, p = paths()) {
3995
- const names2 = new Set(given.map((v) => v.name));
3996
- const now = (/* @__PURE__ */ new Date()).toISOString();
3997
- const kept = (await readBoxEnv(box, p)).filter((v) => !names2.has(v.name));
3998
- await writeBoxEnv(box, [...kept, ...given.map((v) => ({ name: v.name, value: v.value, secret: v.secret === true, updatedAt: now }))], p);
3999
- }
4000
- async function copyBoxEnv(from, to) {
4001
- if (!existsSync7(from)) return;
4002
- await copyFile(from, to);
4003
- }
4004
- function shownBoxEnv(vars) {
4005
- return vars.map((v) => ({ name: v.name, ...v.secret ? {} : { value: v.value }, secret: v.secret, updatedAt: v.updatedAt }));
4147
+
4148
+ // src/core/machines/ports.ts
4149
+ var publicPortsInUse = (metas) => metas.flatMap((m) => [...m.sshPort === void 0 ? [] : [m.sshPort], ...(m.ports ?? []).map((f) => f.hostPort)]);
4150
+ var reaching = (meta) => meta.farTargets?.length && meta.owner !== void 0 && meta.name !== void 0 ? { ...meta, owner: meta.owner, name: meta.name } : null;
4151
+ function boxProxies(meta) {
4152
+ const ssh = meta.sshPort === void 0 ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];
4153
+ 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 }))];
4006
4154
  }
4007
- async function setBoxVar(box, name, value, secret, p = paths()) {
4008
- await withBoxLock(box, async () => {
4009
- if (!existsSync7(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);
4010
- const vars = (await readBoxEnv(box, p)).filter((v) => v.name !== name);
4011
- await writeBoxEnv(box, [...vars, { name, value, secret, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }], p);
4012
- });
4155
+ function boxLinks(meta) {
4156
+ return (meta.links ?? []).map((l) => ({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }));
4013
4157
  }
4014
- async function rmBoxVar(box, name, p = paths()) {
4015
- await withBoxLock(box, async () => {
4016
- if (!existsSync7(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);
4017
- const vars = await readBoxEnv(box, p);
4018
- if (!vars.some((v) => v.name === name)) throw new NotFoundError(`variable ${name} on box ${shown(box)}`);
4019
- await writeBoxEnv(box, vars.filter((v) => v.name !== name), p);
4020
- });
4158
+ async function standingLinks(meta, p) {
4159
+ const links = boxLinks(meta);
4160
+ const stands = await Promise.all(
4161
+ (meta.links ?? []).map(async (l) => !l.stale && (await readMachineMeta({ owner: l.owner, name: l.name }, p).catch(() => null))?.ip === l.ip)
4162
+ );
4163
+ return links.filter((_, i) => stands[i]);
4021
4164
  }
4022
- async function setOwnerEnv(owner, req, p = paths()) {
4023
- if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
4024
- if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
4025
- const seen = /* @__PURE__ */ new Set();
4026
- for (const v of req.vars) {
4027
- const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
4028
- if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
4029
- if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);
4030
- seen.add(v.name);
4165
+ async function openPorts(meta, cfg, p) {
4166
+ for (const proxy of boxProxies(meta)) await driver().net.openProxy(proxy, cfg);
4167
+ for (const link4 of await standingLinks(meta, p)) {
4168
+ await driver().net.openLink(link4, cfg).catch((err) => log.warn(`could not open the link from ${link4.fromIp}: ${err.message}`));
4031
4169
  }
4032
- return withHostLock("env", async () => {
4033
- const have = await readOwnerEnv(owner, p);
4034
- if (have !== null && have.version > req.version) return { version: have.version };
4035
- const file = p.ownerEnv(owner);
4036
- await mkdir4(p.env, { recursive: true, mode: 448 });
4037
- const tmp = `${file}.tmp`;
4038
- await writeFile5(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
4039
- await rename4(tmp, file);
4040
- return { version: req.version };
4041
- });
4170
+ const far = reaching(meta);
4171
+ if (far) await openFarTargets(far, cfg, p);
4172
+ await joinCluster2(meta, cfg);
4042
4173
  }
4043
- async function listEnvVersions(scope, p = paths()) {
4044
- let files;
4045
- try {
4046
- files = await readdir4(p.env);
4047
- } catch (err) {
4048
- if (err.code === "ENOENT") return [];
4049
- throw err;
4174
+ async function closePorts(meta, cfg) {
4175
+ for (const proxy of boxProxies(meta)) {
4176
+ await driver().net.closeProxy(proxy, cfg).catch((err) => log.warn(`could not close port ${proxy.hostPort}: ${err.message}`));
4050
4177
  }
4051
- const out = [];
4052
- for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
4053
- const owner = file.slice(0, -".json".length);
4054
- if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;
4055
- const env = await readOwnerEnv(owner, p).catch(() => null);
4056
- if (env !== null) out.push({ owner, version: env.version });
4178
+ for (const link4 of boxLinks(meta)) {
4179
+ await driver().net.closeLink(link4, cfg).catch((err) => log.warn(`could not close the link from ${link4.fromIp}: ${err.message}`));
4057
4180
  }
4058
- return out;
4181
+ const far = reaching(meta);
4182
+ if (far) await closeFarTargets(far, cfg);
4183
+ await leaveCluster2(meta, cfg);
4059
4184
  }
4060
-
4061
- // src/core/machines/common.ts
4062
- import { existsSync as existsSync8 } from "node:fs";
4063
- import { readFile as readFile8 } from "node:fs/promises";
4064
-
4065
- // src/core/machines/disk.ts
4066
- import { statSync as statSync2 } from "node:fs";
4067
- import { truncate as truncate2, writeFile as writeFile6 } from "node:fs/promises";
4068
-
4069
- // src/core/ext4.ts
4070
- import { closeSync as closeSync3, openSync as openSync4, readSync } from "node:fs";
4071
- var SUPERBLOCK_OFFSET = 1024;
4072
- var EXT4_MAGIC = 61267;
4073
- var INCOMPAT_META_BG = 16;
4074
- var INCOMPAT_64BIT = 128;
4075
- function ext4Usage(file) {
4076
- let fd;
4077
- try {
4078
- fd = openSync4(file, "r");
4079
- const sb = Buffer.alloc(1024);
4080
- if (readSync(fd, sb, 0, sb.length, SUPERBLOCK_OFFSET) !== sb.length) return null;
4081
- if (sb.readUInt16LE(56) !== EXT4_MAGIC) return null;
4082
- const incompat = sb.readUInt32LE(96);
4083
- if (incompat & INCOMPAT_META_BG) return null;
4084
- const is64 = (incompat & INCOMPAT_64BIT) !== 0;
4085
- const blockSize = 1024 << sb.readUInt32LE(24);
4086
- const blocks = sb.readUInt32LE(4) + (is64 ? sb.readUInt32LE(336) * 2 ** 32 : 0);
4087
- const firstDataBlock = sb.readUInt32LE(20);
4088
- const blocksPerGroup = sb.readUInt32LE(32);
4089
- const descSize = is64 ? sb.readUInt16LE(254) : 32;
4090
- if (blocksPerGroup === 0 || descSize < 32) return null;
4091
- const groups = Math.ceil((blocks - firstDataBlock) / blocksPerGroup);
4092
- const table = Buffer.alloc(groups * descSize);
4093
- if (readSync(fd, table, 0, table.length, (firstDataBlock + 1) * blockSize) !== table.length) return null;
4094
- let free = 0;
4095
- for (let g = 0; g < groups; g++) {
4096
- const at = g * descSize;
4097
- free += table.readUInt16LE(at + 12) + (descSize >= 64 ? table.readUInt16LE(at + 44) * 65536 : 0);
4185
+ var reservedPorts = /* @__PURE__ */ new Set();
4186
+ async function drawPorts(count, p) {
4187
+ return withHostLock("ports", async () => {
4188
+ const reserved2 = [...reservedPorts];
4189
+ const taken = /* @__PURE__ */ new Set([...reserved2, ...publicPortsInUse(await readAllMeta(p)), ...await driver().net.listeningPorts()]);
4190
+ const ports = [];
4191
+ for (let i = 0; i < count; i++) {
4192
+ const port = pickSshPort(taken);
4193
+ taken.add(port);
4194
+ ports.push(port);
4098
4195
  }
4099
- return { sizeBytes: blocks * blockSize, usedBytes: (blocks - free) * blockSize };
4100
- } catch {
4101
- return null;
4102
- } finally {
4103
- if (fd !== void 0) closeSync3(fd);
4104
- }
4105
- }
4106
-
4107
- // src/core/machines/disk.ts
4108
- function diskStats(disk) {
4109
- try {
4110
- const st = statSync2(disk);
4111
- const diskHostBytes = st.blocks * 512;
4112
- const fs = ext4Usage(disk);
4113
- return { diskBytes: st.size, diskUsedBytes: fs ? Math.min(fs.usedBytes, st.size) : diskHostBytes, diskHostBytes };
4114
- } catch {
4115
- return { diskBytes: 0, diskUsedBytes: 0, diskHostBytes: 0 };
4116
- }
4117
- }
4118
- async function compactDisk(file) {
4119
- await run(["e2fsck", "-f", "-p", "-E", "discard", file], { okExitCodes: [1, 2], timeoutMs: 10 * 6e4 });
4120
- }
4121
- function diskGibOf(meta, p) {
4122
- try {
4123
- return Math.round(statSync2(p.machine(meta.owner, meta.name).overlay).size / 1024 ** 3);
4124
- } catch {
4125
- return 0;
4126
- }
4127
- }
4128
- async function createOverlay(file, gib) {
4129
- await writeFile6(file, "", { mode: 384 });
4130
- await truncate2(file, gib * 1024 ** 3);
4131
- await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", "kvbox-box", "-E", "lazy_itable_init=1,lazy_journal_init=1", file]);
4132
- }
4133
- async function growDisk(file, gib) {
4134
- await truncate2(file, gib * 1024 ** 3);
4135
- await run(["e2fsck", "-f", "-p", file], { okExitCodes: [1] });
4136
- await run(["resize2fs", file]);
4196
+ for (const port of ports) reservedPorts.add(port);
4197
+ return { ports, release: () => ports.forEach((port) => reservedPorts.delete(port)) };
4198
+ });
4137
4199
  }
4138
-
4139
- // src/core/machines/common.ts
4140
- var idsInUse = (metas) => new Set(metas.map((m) => m.id));
4141
- var isCloudBox = (owner) => realmOf(owner) !== null;
4142
- async function readMeta(ref, p) {
4200
+ var portKeys = (req) => {
4201
+ const keys = req.ports.map((x) => ({ guestPort: x.guestPort, proto: x.proto ?? "tcp" }));
4202
+ return keys.filter((k, i) => keys.findIndex((o) => o.guestPort === k.guestPort && o.proto === k.proto) === i);
4203
+ };
4204
+ var samePort = (a) => (b) => a.guestPort === b.guestPort && a.proto === b.proto;
4205
+ var addPorts = locked(async function addPorts2(ref, req, p = paths()) {
4206
+ const meta = await readMeta(ref, p);
4207
+ const cfg = await loadConfig(p);
4208
+ const current2 = meta.ports ?? [];
4209
+ const wanted = portKeys(req);
4210
+ const isClosed = (k) => current2.some((f) => samePort(k)(f) && f.closed);
4211
+ const reopened = wanted.filter(isClosed);
4212
+ const fresh = wanted.filter((w) => !current2.some(samePort(w)));
4213
+ const already = wanted.find((w) => current2.some(samePort(w)) && !isClosed(w));
4214
+ if (already) throw new KvboxError(`box ${shown(ref)} already publishes port ${already.guestPort} (${already.proto})`);
4215
+ if (meta.sshPort !== void 0 && wanted.some(samePort({ guestPort: 22, proto: "tcp" }))) {
4216
+ throw new KvboxError(`box ${shown(ref)} already reaches port 22 from outside on port ${meta.sshPort} (kvbox connect)`);
4217
+ }
4218
+ if (current2.length + fresh.length > MAX_BOX_PORTS) {
4219
+ throw new KvboxError(`a box publishes at most ${MAX_BOX_PORTS} ports; box ${shown(ref)} has ${current2.length}`);
4220
+ }
4221
+ const drawn = await drawPorts(fresh.length, p);
4222
+ const opened = [];
4143
4223
  try {
4144
- return await readMachineMeta(ref, p);
4224
+ const added = fresh.map((w, i) => ({ ...w, hostPort: drawn.ports[i] }));
4225
+ const open4 = ({ closed: _closed, ...f }) => f;
4226
+ const again = current2.filter((f) => reopened.some(samePort(f))).map(open4);
4227
+ if (vmAlive(meta)) {
4228
+ for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: [...again, ...added] })) {
4229
+ await driver().net.openProxy(proxy, cfg);
4230
+ opened.push(proxy);
4231
+ }
4232
+ }
4233
+ const next = { ...meta, ports: [...current2.map((f) => reopened.some(samePort(f)) ? open4(f) : f), ...added] };
4234
+ await writeMachineMeta(next, p);
4235
+ return toMachine(next, p);
4145
4236
  } catch (err) {
4146
- if (err.code === "ENOENT") throw new NotFoundError(`box ${shown(ref)}`);
4237
+ for (const proxy of opened) await driver().net.closeProxy(proxy, cfg).catch(() => void 0);
4147
4238
  throw err;
4239
+ } finally {
4240
+ drawn.release();
4148
4241
  }
4242
+ });
4243
+ var removePorts = locked(async function removePorts2(ref, req, p = paths()) {
4244
+ const meta = await readMeta(ref, p);
4245
+ const cfg = await loadConfig(p);
4246
+ const current2 = meta.ports ?? [];
4247
+ const gone = portKeys(req);
4248
+ const missing = gone.find((g) => !current2.some(samePort(g)));
4249
+ if (missing) throw new KvboxError(`box ${shown(ref)} does not publish port ${missing.guestPort} (${missing.proto})`);
4250
+ const removed = current2.filter((f) => gone.some(samePort(f)));
4251
+ for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: removed })) await driver().net.closeProxy(proxy, cfg);
4252
+ const kept = req.keep ? current2.map((f) => gone.some(samePort(f)) ? { ...f, closed: true } : f) : current2.filter((f) => !gone.some(samePort(f)));
4253
+ const next = { ...meta, ports: kept.length > 0 ? kept : void 0 };
4254
+ await writeMachineMeta(next, p);
4255
+ return toMachine(next, p);
4256
+ });
4257
+
4258
+ // src/core/machines/address.ts
4259
+ var reserved = /* @__PURE__ */ new Set();
4260
+ async function drawAddress(cfg, p) {
4261
+ return withHostLock("addresses", async () => {
4262
+ const held2 = [...reserved];
4263
+ const { ip, mac } = driver().net.allocate(cfg, [...held2, ...(await readAllMeta(p)).map((m) => m.ip)]);
4264
+ reserved.add(ip);
4265
+ return { ip, mac, release: () => void reserved.delete(ip) };
4266
+ });
4149
4267
  }
4150
- async function readAllMeta(p) {
4151
- const metas = [];
4152
- for (const ref of await listMachineRefs(p)) {
4268
+ var offRange = (meta, cfg) => cfg.boxRange !== void 0 && !inRange(meta.ip, cfg.boxRange);
4269
+ async function countOffRange(p = paths()) {
4270
+ const cfg = await loadConfig(p);
4271
+ return cfg.boxRange === void 0 ? 0 : (await readAllMeta(p)).filter((m) => offRange(m, cfg) && m.cluster === void 0).length;
4272
+ }
4273
+ async function moveToRange(meta, cfg, p) {
4274
+ if (!offRange(meta, cfg) || meta.cluster !== void 0) return meta;
4275
+ try {
4276
+ await closePorts(meta, cfg);
4277
+ const address = await drawAddress(cfg, p);
4153
4278
  try {
4154
- metas.push(await readMachineMeta(ref, p));
4155
- } catch (err) {
4156
- log.warn(`skipping machines/${refKey(ref)}: ${err.message}`);
4279
+ const moved = { ...meta, ip: address.ip, mac: address.mac, movedFrom: meta.movedFrom ?? meta.ip };
4280
+ await writeMachineMeta(moved, p);
4281
+ log.info(`box ${shown(meta)} moves from ${meta.ip} to ${moved.ip}, in this host's range ${cfg.boxRange}`);
4282
+ return moved;
4283
+ } finally {
4284
+ address.release();
4157
4285
  }
4286
+ } catch (err) {
4287
+ log.warn(`box ${shown(meta)} keeps its address ${meta.ip}, outside this host's range ${cfg.boxRange}, until its next start: ${err.message}`);
4288
+ return meta;
4158
4289
  }
4159
- return metas;
4160
4290
  }
4161
- async function readHostPubkey(p) {
4162
- try {
4163
- return (await readFile8(`${p.sshKey}.pub`, "utf8")).trim();
4164
- } catch {
4165
- throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);
4166
- }
4291
+ async function unmove(ref, before, p) {
4292
+ const now = await readMachineMeta(ref, p);
4293
+ await writeMachineMeta({ ...now, ip: before.ip, mac: before.mac, movedFrom: before.movedFrom }, p);
4167
4294
  }
4168
- function assertAssets(cfg) {
4169
- for (const [what, file] of [["kernel", cfg.kernel], ["base image", cfg.rootfs], ["firecracker", cfg.firecracker]]) {
4170
- if (!existsSync8(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
4295
+ async function followMove(ref, p = paths()) {
4296
+ const moved = await readMachineMeta(ref, p).catch(() => null);
4297
+ const from = moved?.movedFrom;
4298
+ if (!moved || from === void 0) return;
4299
+ const cfg = await loadConfig(p);
4300
+ const isOld = (l) => !l.stale && l.owner === moved.owner && l.name === moved.name && l.ip === from;
4301
+ let left = 0;
4302
+ for (const other of await listMachineRefs(p)) {
4303
+ const peek = await readMachineMeta(other, p).catch(() => null);
4304
+ if (!peek?.links?.some(isOld)) continue;
4305
+ await withBoxLock(other, async () => {
4306
+ const meta = await readMachineMeta(other, p).catch(() => null);
4307
+ const old = meta?.links?.filter(isOld) ?? [];
4308
+ if (!meta?.links || old.length === 0) return;
4309
+ const now = await readMachineMeta(ref, p).catch(() => null);
4310
+ if (now?.ip !== moved.ip || now.movedFrom !== from) return;
4311
+ for (const l of old) await driver().net.closeLink({ box: meta.id, fromIp: from, toIp: meta.ip, port: l.port }, cfg);
4312
+ const next = { ...meta, links: meta.links.map((l) => isOld(l) ? { ...l, ip: moved.ip } : l) };
4313
+ await writeMachineMeta(next, p);
4314
+ if (!vmAlive(next)) return;
4315
+ for (const l of old) {
4316
+ await driver().net.openLink({ box: meta.id, fromIp: moved.ip, toIp: meta.ip, port: l.port }, cfg).catch((err) => log.warn(`could not open the link from ${moved.name} (${moved.ip}) into ${meta.name}: ${err.message}`));
4317
+ }
4318
+ }).catch((err) => {
4319
+ left += 1;
4320
+ log.warn(`box ${moved.name} moved to ${moved.ip}, but its link into ${other.name} still names ${from}: ${err.message}`);
4321
+ });
4171
4322
  }
4323
+ if (left > 0) return;
4324
+ await withBoxLock(ref, async () => {
4325
+ const now = await readMachineMeta(ref, p).catch(() => null);
4326
+ if (now?.movedFrom === from) await writeMachineMeta({ ...now, movedFrom: void 0 }, p);
4327
+ });
4172
4328
  }
4173
- function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISOString()) {
4174
- try {
4175
- insertUsageEvent({ boxId: meta.id, owner: meta.owner, name: meta.name, at, state, by, vcpu: meta.vcpu, memMib: meta.memMib, diskGib: diskGibOf(meta, p) }, p);
4176
- } catch (err) {
4177
- log.warn(`usage ledger: ${err.message}`);
4329
+ function followMoveSoon(ref, p) {
4330
+ outsideLocks(() => void followMove(ref, p).catch((err) => log.warn(`box ${ref.name}: the links from it were not moved to its new address: ${err.message}`)));
4331
+ }
4332
+ async function followMoves(p = paths()) {
4333
+ for (const meta of await readAllMeta(p)) {
4334
+ if (meta.movedFrom !== void 0) await followMove(meta, p);
4178
4335
  }
4179
4336
  }
4180
4337
 
4181
- // src/core/machines/integrations.ts
4182
- import { setTimeout as sleep3 } from "node:timers/promises";
4338
+ // src/core/machines/change.ts
4339
+ import { statSync as statSync3 } from "node:fs";
4340
+ import { rename as rename5, rm as rm8 } from "node:fs/promises";
4183
4341
 
4184
- // src/core/agent.ts
4185
- import { connect } from "node:net";
4186
- var AGENT_PORT = 52;
4187
- async function agentCall(udsPath, req, timeoutMs = 5e3, connectMs = timeoutMs) {
4188
- const reply = await new Promise((resolve3, reject) => {
4189
- const sock = connect(udsPath);
4190
- let buf = "";
4191
- let handshaken = false;
4192
- const fail = (err) => {
4193
- sock.destroy();
4194
- reject(err);
4195
- };
4196
- sock.setTimeout(connectMs, () => fail(new KvboxError(handshaken ? `kvbox-agent did not answer within ${timeoutMs} ms` : `the guest did not accept the vsock connection within ${connectMs} ms`)));
4197
- sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
4198
- sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
4199
- `));
4200
- sock.on("data", (chunk) => {
4201
- buf += chunk.toString("utf8");
4202
- let nl;
4203
- while ((nl = buf.indexOf("\n")) !== -1) {
4204
- const line = buf.slice(0, nl);
4205
- buf = buf.slice(nl + 1);
4206
- if (!handshaken) {
4207
- if (!line.startsWith("OK ")) return fail(new KvboxError(`vsock connect refused: ${line}`));
4208
- handshaken = true;
4209
- sock.setTimeout(timeoutMs);
4210
- sock.write(JSON.stringify(req) + "\n");
4211
- } else {
4212
- sock.end();
4213
- return resolve3(line);
4214
- }
4215
- }
4216
- });
4217
- sock.once("close", () => {
4218
- if (!handshaken) fail(new KvboxError("vsock connection closed before the guest accepted"));
4219
- else fail(new KvboxError("kvbox-agent closed the connection without a reply"));
4220
- });
4342
+ // src/core/capacity.ts
4343
+ import { cpus, totalmem } from "node:os";
4344
+
4345
+ // src/core/backupStore.ts
4346
+ import { createHash as createHash2, randomBytes as randomBytes3 } from "node:crypto";
4347
+ import { existsSync as existsSync8 } from "node:fs";
4348
+ import { chmod as chmod2, mkdir as mkdir3, readFile as readFile7, rename as rename3, rm as rm4, stat as stat2, statfs as statfs2, writeFile as writeFile5 } from "node:fs/promises";
4349
+ import { request as httpRequest } from "node:http";
4350
+ import { userInfo as userInfo2 } from "node:os";
4351
+ import { isAbsolute, join as join2 } from "node:path";
4352
+ import { pipeline } from "node:stream";
4353
+ import { setTimeout as sleep2 } from "node:timers/promises";
4354
+ import { request as request2 } from "undici";
4355
+ var GARAGE_VERSION = "2.5.0";
4356
+ var GARAGE_SHA256 = {
4357
+ x64: { arch: "x86_64", sha256: "2ff667286217cd73ebcb1c03af993822365000441dfe31a80cb64c5189a9dea8" },
4358
+ arm64: { arch: "aarch64", sha256: "69b6040cef428b993500c17dd0d0c1240acf2f3f667b9b05ceba4b9660db4e8c" }
4359
+ };
4360
+ var GARAGE_S3_PORT = 3900;
4361
+ var GARAGE_RPC_PORT = 3901;
4362
+ var KEY_NAME = "kvbox-control-plane";
4363
+ var START_WAIT_MS = 6e4;
4364
+ var WATCH_MS = 3e4;
4365
+ var garage = (p, args, timeoutMs = 2e4) => run([p.garage, "-c", p.backupStore.conf, ...args], { timeoutMs });
4366
+ var realDeps = {
4367
+ install: installGarage,
4368
+ start: (p) => spawnDetached([p.garage, "-c", p.backupStore.conf, "server"], p.backupStore.log),
4369
+ running: (p) => garageRunning(p),
4370
+ stop: stopGarage,
4371
+ api: async (p, operation, body) => {
4372
+ const { stdout } = await garage(p, ["json-api", operation, ...body === void 0 ? [] : [JSON.stringify(body)]]);
4373
+ const text = stdout.trim();
4374
+ return text === "" ? null : JSON.parse(text);
4375
+ },
4376
+ cli: async (p, args) => (await garage(p, args)).stdout,
4377
+ register: registerWithControlPlane,
4378
+ device: async (path) => (await stat2(path)).dev
4379
+ };
4380
+ var versionFile = (p) => `${p.garage}.version`;
4381
+ async function installGarage(p) {
4382
+ if (existsSync8(p.garage) && (await readFile7(versionFile(p), "utf8").catch(() => "")).trim() === GARAGE_VERSION) return false;
4383
+ const build = GARAGE_SHA256[process.arch];
4384
+ if (!build) throw new KvboxError(`there is no Garage build for this machine (${process.arch})`);
4385
+ const url = `https://garagehq.deuxfleurs.fr/_releases/v${GARAGE_VERSION}/${build.arch}-unknown-linux-musl/garage`;
4386
+ const res = await fetch(url, { signal: AbortSignal.timeout(3e5) }).catch((err) => {
4387
+ throw new KvboxError(`could not download Garage from ${url} (${err.message})`);
4221
4388
  });
4222
- let parsed;
4223
- try {
4224
- parsed = JSON.parse(reply);
4225
- } catch {
4226
- throw new KvboxError(`kvbox-agent sent something that is not JSON: ${reply}`);
4227
- }
4228
- if (!parsed.ok) throw new KvboxError(`kvbox-agent: ${parsed.error}`);
4229
- return parsed;
4230
- }
4231
- function setIdentity(udsPath, id, timeoutMs) {
4232
- return agentCall(udsPath, { op: "identity", ...id }, timeoutMs);
4233
- }
4234
- function setAuthorizedKeys(udsPath, lines, timeoutMs) {
4235
- return agentCall(udsPath, { op: "authorizedKeys", lines: [...lines] }, timeoutMs);
4236
- }
4237
- async function stats(udsPath, timeoutMs) {
4238
- const reply = GuestStatsSchema.safeParse(await agentCall(udsPath, { op: "stats" }, timeoutMs));
4239
- if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? "invalid"}`);
4240
- return reply.data;
4241
- }
4242
- async function dropVolumes(udsPath, timeoutMs) {
4243
- const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
4244
- return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
4245
- }
4246
- function setEnv(udsPath, vars, timeoutMs) {
4247
- return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
4248
- }
4249
- async function idle(udsPath, script, timeoutMs = 15e3) {
4250
- return (await agentCall(udsPath, { op: "idle", path: script }, timeoutMs))["idle"] === true;
4251
- }
4252
- async function runScript(udsPath, path, input, timeoutMs = 35e3) {
4253
- return (await agentCall(udsPath, { op: "script", path, input: input ?? null }, timeoutMs))["output"];
4254
- }
4255
- async function setIntegrations(udsPath, list, identity, timeoutMs) {
4256
- const reply = await agentCall(udsPath, { op: "integrations", list: [...list], ...identity ? { identity } : {} }, timeoutMs);
4257
- const known = reply["known"];
4258
- return { known: Array.isArray(known) ? known.filter((n) => typeof n === "string") : ["github"] };
4259
- }
4260
- async function startRun(udsPath, id, command, timeoutSec, timeoutMs = 15e3) {
4261
- return (await agentCall(udsPath, { op: "run", id, command, timeoutSec }, timeoutMs))["started"] === true;
4262
- }
4263
- async function runStatus(udsPath, id, timeoutMs) {
4264
- const reply = await agentCall(udsPath, { op: "runStatus", id }, timeoutMs);
4265
- const state = reply["state"];
4266
- if (state !== "running" && state !== "exited" && state !== "timeout" && state !== "unknown") throw new KvboxError("kvbox-agent sent a run state this server does not know");
4267
- const durationMs = reply["durationMs"];
4268
- return {
4269
- state,
4270
- ...typeof reply["exitCode"] === "number" ? { exitCode: reply["exitCode"] } : {},
4271
- ...typeof durationMs === "number" && Number.isInteger(durationMs) && durationMs >= 0 ? { durationMs } : {}
4272
- };
4273
- }
4274
- async function runOutput(udsPath, id, stream, offset, limit, timeoutMs = 15e3) {
4275
- const reply = await agentCall(udsPath, { op: "runOutput", id, stream, offset, limit }, timeoutMs);
4276
- const { size: size2, data } = reply;
4277
- if (typeof size2 !== "number" || !Number.isInteger(size2) || size2 < 0 || typeof data !== "string") throw new KvboxError("kvbox-agent sent run output this server does not understand");
4278
- return { size: size2, offset, data };
4279
- }
4280
- var FREEZE_BASE = "v0.19.0";
4281
- var FREEZE_TIMEOUT_MS = 2e4;
4282
- var FREEZE_CONNECT_MS = 3e3;
4283
- var isAgentRefusal = (err) => /^kvbox-agent: /.test(err.message ?? "");
4284
- async function freezeDisks(udsPath, disks, thawAfterSec, timeoutMs = FREEZE_TIMEOUT_MS) {
4285
- const reply = await agentCall(udsPath, { op: "freeze", box: disks.box === true, volumes: [...disks.volumes ?? []], thawAfterSec }, timeoutMs, FREEZE_CONNECT_MS);
4286
- const frozen = reply["frozen"];
4287
- return Array.isArray(frozen) ? frozen.filter((m) => typeof m === "string") : [];
4288
- }
4289
- async function thawDisks(udsPath, timeoutMs) {
4290
- const thawed = (await agentCall(udsPath, { op: "thaw" }, timeoutMs))["thawed"];
4291
- return Array.isArray(thawed) ? thawed.filter((m) => typeof m === "string") : [];
4389
+ if (!res.ok) throw new KvboxError(`could not download Garage from ${url}: HTTP ${res.status}`);
4390
+ const bytes = Buffer.from(await res.arrayBuffer());
4391
+ const got = createHash2("sha256").update(bytes).digest("hex");
4392
+ if (got !== build.sha256) throw new KvboxError(`the Garage download is not the expected file (sha256 ${got}); nothing was installed`);
4393
+ await mkdir3(p.bin, { recursive: true });
4394
+ const tmp = `${p.garage}.tmp`;
4395
+ await writeFile5(tmp, bytes, { mode: 493 });
4396
+ await chmod2(tmp, 493);
4397
+ await rename3(tmp, p.garage);
4398
+ await writeFile5(versionFile(p), `${GARAGE_VERSION}
4399
+ `);
4400
+ return true;
4292
4401
  }
4293
- var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
4294
- var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
4295
- 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 ?? "");
4296
-
4297
- // src/core/credentials.ts
4298
- import { request as request3 } from "undici";
4299
- var TIMEOUT_MS = 1e4;
4300
- var PROBE_KEPT_MS = 6e4;
4301
- var unavailable = (message) => ({ ok: false, code: "unavailable", message });
4302
- async function ask(cp, body) {
4303
- const res = await request3(`${cp.url}/hosts/self/integrations/credential`, {
4304
- method: "POST",
4402
+ async function registerWithControlPlane(cfg, body) {
4403
+ const cp = cfg.controlPlane;
4404
+ if (!cp) throw new KvboxError("this host has not joined a control plane");
4405
+ const res = await request2(`${cp.url}/hosts/self/backup-store`, {
4406
+ method: "PUT",
4305
4407
  headers: { authorization: `Bearer ${cp.secret}`, "content-type": "application/json" },
4306
4408
  body: JSON.stringify(body),
4307
- headersTimeout: TIMEOUT_MS,
4308
- bodyTimeout: TIMEOUT_MS
4409
+ headersTimeout: 1e4,
4410
+ bodyTimeout: 1e4
4411
+ }).catch((err) => {
4412
+ throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
4309
4413
  });
4310
4414
  const text = await res.body.text();
4311
- try {
4312
- return { status: res.statusCode, json: JSON.parse(text) };
4313
- } catch {
4314
- return { status: res.statusCode, json: null };
4415
+ if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not know backup stores yet: it is older than this host`);
4416
+ if (res.statusCode < 200 || res.statusCode >= 300) {
4417
+ let error;
4418
+ try {
4419
+ error = JSON.parse(text).error;
4420
+ } catch {
4421
+ }
4422
+ throw new KvboxError(typeof error === "string" ? error : `${cp.name} answered ${res.statusCode}`);
4315
4423
  }
4316
4424
  }
4317
- async function askCredential(cp, box, integration) {
4318
- let answer2;
4319
- try {
4320
- answer2 = await ask(cp, { owner: box.owner, box: box.name, integration });
4321
- } catch (err) {
4322
- return unavailable(`${cp.name} could not be reached (${err.message}); try again shortly`);
4323
- }
4324
- if (answer2.status === 404) return unavailable(`${cp.name} has no integrations yet`);
4325
- const parsed = CredentialAnswerSchema.safeParse(answer2.json);
4326
- if (!parsed.success) return unavailable(`${cp.name} answered ${answer2.status}; try again shortly`);
4327
- return parsed.data;
4425
+ function garageToml(path) {
4426
+ const q = (s) => JSON.stringify(s);
4427
+ return [
4428
+ "# written by kvbox-server backup setup: this host's backup store",
4429
+ `metadata_dir = ${q(join2(path, "meta"))}`,
4430
+ `data_dir = ${q(join2(path, "data"))}`,
4431
+ 'db_engine = "lmdb"',
4432
+ "metadata_fsync = true",
4433
+ "data_fsync = true",
4434
+ "replication_factor = 1",
4435
+ `rpc_bind_addr = "127.0.0.1:${GARAGE_RPC_PORT}"`,
4436
+ `rpc_public_addr = "127.0.0.1:${GARAGE_RPC_PORT}"`,
4437
+ `rpc_secret_file = ${q(join2(path, "rpc_secret"))}`,
4438
+ "",
4439
+ "[s3_api]",
4440
+ `s3_region = ${q(BACKUP_STORE_REGION)}`,
4441
+ `api_bind_addr = "127.0.0.1:${GARAGE_S3_PORT}"`,
4442
+ ""
4443
+ ].join("\n");
4328
4444
  }
4329
- var probes = /* @__PURE__ */ new Map();
4330
- async function probeConnection(cp, box, integration, now = Date.now()) {
4331
- const key = `${box.owner}/${box.name}/${integration}`;
4332
- const kept = probes.get(key);
4333
- if (kept && now - kept.at < PROBE_KEPT_MS) return kept.answer;
4334
- try {
4335
- const parsed = ConnectedAnswerSchema.safeParse((await ask(cp, { owner: box.owner, box: box.name, integration, probe: true })).json);
4336
- if (!parsed.success) return null;
4337
- probes.set(key, { at: now, answer: parsed.data });
4338
- if (probes.size > 5e3) {
4339
- for (const [k, v] of probes) if (now - v.at >= PROBE_KEPT_MS) probes.delete(k);
4340
- }
4341
- return parsed.data;
4342
- } catch {
4343
- return null;
4445
+ async function readPid(p) {
4446
+ const n = Number((await readFile7(p.backupStore.pid, "utf8").catch(() => "")).trim());
4447
+ return Number.isInteger(n) && n > 0 ? n : null;
4448
+ }
4449
+ async function garageRunning(p = paths()) {
4450
+ const pid = await readPid(p);
4451
+ if (!pidAlive(pid)) return false;
4452
+ const cmdline = await readFile7(`/proc/${pid}/cmdline`, "utf8").catch(() => null);
4453
+ return cmdline === null || cmdline.split("\0")[0] === p.garage;
4454
+ }
4455
+ async function stopGarage(p) {
4456
+ const pid = await readPid(p);
4457
+ if (pid === null || !await garageRunning(p)) return;
4458
+ const cmdline = await readFile7(`/proc/${pid}/cmdline`, "utf8").catch(() => null);
4459
+ if (cmdline?.split("\0")[0] !== p.garage) throw new KvboxError(`cannot tell whether pid ${pid} is this host's Garage, so it was not stopped; stop Garage by hand and run this again`);
4460
+ process.kill(pid, "SIGTERM");
4461
+ const until = Date.now() + 15e3;
4462
+ while (pidAlive(pid)) {
4463
+ if (Date.now() > until) throw new KvboxError(`Garage (pid ${pid}) did not stop within 15s`);
4464
+ await sleep2(200);
4344
4465
  }
4466
+ await rm4(p.backupStore.pid, { force: true });
4345
4467
  }
4346
-
4347
- // src/core/guestRequests.ts
4348
- import { rm as rm5 } from "node:fs/promises";
4349
- import { createServer } from "node:net";
4350
- var MAX_REQUEST_BYTES = 4096;
4351
- var REQUEST_TIMEOUT_MS = 5e3;
4352
- var MAX_OPEN = 32;
4353
- var listeners = /* @__PURE__ */ new Map();
4354
- var unreadable = (message) => ({ ok: false, code: "unavailable", message });
4355
- function serve(sock, answer2, timeoutMs) {
4356
- let buf = "";
4357
- let taken = false;
4358
- const reply = (body) => {
4359
- if (!sock.destroyed) sock.end(JSON.stringify(body) + "\n");
4360
- };
4361
- const late = setTimeout(() => sock.destroy(), timeoutMs);
4362
- late.unref();
4363
- sock.once("close", () => clearTimeout(late));
4364
- sock.on("error", () => void 0);
4365
- sock.on("data", (chunk) => {
4366
- if (taken) return;
4367
- buf += chunk.toString("utf8");
4368
- const nl = buf.indexOf("\n");
4369
- if (nl === -1) {
4370
- if (buf.length > MAX_REQUEST_BYTES) sock.destroy();
4371
- return;
4372
- }
4373
- taken = true;
4374
- clearTimeout(late);
4375
- let request7;
4468
+ async function ensureGarage(p, deps) {
4469
+ if (!await deps.running(p)) {
4470
+ const pid = await deps.start(p);
4471
+ await writeFile5(p.backupStore.pid, `${pid}
4472
+ `);
4473
+ }
4474
+ const until = Date.now() + START_WAIT_MS;
4475
+ for (; ; ) {
4376
4476
  try {
4377
- request7 = JSON.parse(buf.slice(0, nl));
4378
- } catch {
4379
- return reply(unreadable("the request is not JSON"));
4477
+ await deps.cli(p, ["status"]);
4478
+ return;
4479
+ } catch (err) {
4480
+ if (Date.now() > until) throw new KvboxError(`Garage did not answer after ${START_WAIT_MS / 1e3}s (see ${p.backupStore.log}): ${err.message}`);
4481
+ await sleep2(500);
4380
4482
  }
4381
- answer2(request7).then(reply, (err) => reply(unreadable(err.message)));
4382
- });
4483
+ }
4383
4484
  }
4384
- async function listenGuest(path, answer2, timeoutMs = REQUEST_TIMEOUT_MS) {
4385
- await closeGuest(path);
4386
- await rm5(path, { force: true });
4387
- const open4 = /* @__PURE__ */ new Set();
4388
- const server = createServer((sock) => {
4389
- open4.add(sock);
4390
- sock.once("close", () => open4.delete(sock));
4391
- serve(sock, answer2, timeoutMs);
4392
- });
4393
- server.maxConnections = MAX_OPEN;
4394
- await new Promise((resolve3, reject) => {
4395
- server.once("error", reject);
4396
- server.listen(path, () => {
4397
- server.off("error", reject);
4398
- resolve3();
4399
- });
4400
- });
4401
- server.unref();
4402
- server.on("error", () => void 0);
4403
- listeners.set(path, { server, open: open4 });
4485
+ function setupBackupStore(req, p = paths(), deps = realDeps) {
4486
+ return serial(() => setup(req, p, deps));
4404
4487
  }
4405
- async function closeGuest(path) {
4406
- const l = listeners.get(path);
4407
- if (!l) return;
4408
- listeners.delete(path);
4409
- for (const sock of l.open) sock.destroy();
4410
- await new Promise((resolve3) => l.server.close(() => resolve3()));
4411
- await rm5(path, { force: true });
4488
+ var turn = Promise.resolve();
4489
+ function serial(step) {
4490
+ const mine = turn.then(step, step);
4491
+ turn = mine.catch(() => void 0);
4492
+ return mine;
4412
4493
  }
4413
- var guestListening = (path) => listeners.has(path);
4414
-
4415
- // src/core/machines/integrations.ts
4416
- var AGENT_REPLY_MS = 2e4;
4417
- function socketOf(box, p) {
4418
- try {
4419
- return driver().vm.guestSocket(box, GUEST_REQUEST_PORT, p);
4420
- } catch (err) {
4421
- if (err instanceof NotImplementedError) return void 0;
4422
- throw err;
4494
+ async function setup(req, p, deps) {
4495
+ const path = req.path.replace(/\/+$/, "") || "/";
4496
+ if (!isAbsolute(path) || /["\\\n\0]/.test(path)) throw new KvboxError(`${req.path} is not a path a store can use: give the full path of a directory on the backup disk`);
4497
+ const cfg = await loadConfig(p);
4498
+ if (!cfg.controlPlane) throw new KvboxError("this host has not joined a control plane, which is what takes backups; run kvbox-server join first");
4499
+ if (cfg.backupStore && cfg.backupStore.path !== path) {
4500
+ throw new KvboxError(`this host already is a backup store, with its data in ${cfg.backupStore.path}; a host has one store`);
4423
4501
  }
4424
- }
4425
- async function listenForGuest(box, p) {
4426
- const ref = { owner: box.owner, name: box.name };
4502
+ const dir = await stat2(path).catch(() => null);
4503
+ if (!dir?.isDirectory()) throw new KvboxError(`${path} is not a directory: mount the backup disk and give a directory on it`);
4504
+ if (!req.force && await deps.device(path) === await deps.device(p.home)) {
4505
+ throw new KvboxError(`${path} is on the same disk as this host's boxes, so the backups would be lost with them; mount a disk for backups there, or pass --force to use it anyway`);
4506
+ }
4507
+ if (cfg.backupStore && !req.newStore && !existsSync8(join2(path, "rpc_secret"))) throw notTheStoreDisk(path);
4508
+ const newBinary = await deps.install(p);
4509
+ await mkdir3(p.backupStore.dir, { recursive: true, mode: 448 });
4427
4510
  try {
4428
- const path = socketOf(box, p);
4429
- if (path !== void 0) await listenGuest(path, (request7) => answerGuest(ref, request7, p));
4511
+ for (const sub of ["meta", "data"]) await mkdir3(join2(path, sub), { recursive: true, mode: 448 });
4512
+ const rpcSecret = join2(path, "rpc_secret");
4513
+ if (!existsSync8(rpcSecret)) await writeFile5(rpcSecret, `${randomBytes3(32).toString("hex")}
4514
+ `, { mode: 384 });
4430
4515
  } catch (err) {
4431
- log.warn(`box ${shown(ref)}: integrations will not answer in it: ${err.message}`);
4516
+ const code = err.code;
4517
+ if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS") throw err;
4518
+ const user = userInfo2().username;
4519
+ throw new KvboxError(`kvbox-server (user ${user}) cannot write in ${path}: make the directory ${user}'s (sudo chown ${user} ${path}) and run this again`);
4432
4520
  }
4433
- }
4434
- async function stopListeningForGuest(box, p) {
4435
- try {
4436
- const path = socketOf(box, p);
4437
- if (path !== void 0) await closeGuest(path);
4438
- } catch {
4521
+ const conf = garageToml(path);
4522
+ const had = await readFile7(p.backupStore.conf, "utf8").catch(() => null);
4523
+ await writeFile5(p.backupStore.conf, conf, { mode: 384 });
4524
+ if ((newBinary || had !== null && had !== conf) && await deps.running(p)) await deps.stop(p);
4525
+ await ensureGarage(p, deps);
4526
+ const layout = await deps.api(p, "GetClusterLayout");
4527
+ if ((layout?.version ?? 0) === 0) {
4528
+ const node = (await deps.cli(p, ["node", "id", "-q"])).trim().split("@")[0];
4529
+ const fs = await statfs2(path);
4530
+ await deps.cli(p, ["layout", "assign", "-z", "kvbox", "-c", String(fs.blocks * fs.bsize), node]);
4531
+ await deps.cli(p, ["layout", "apply", "--version", "1"]);
4439
4532
  }
4440
- }
4441
- async function listenForRunning(p) {
4442
- for (const listed of await readAllMeta(p)) {
4443
- if (!vmAlive(listed)) continue;
4444
- await withBoxLock(listed, async () => {
4445
- const meta = await readMachineMeta(listed, p).catch(() => null);
4446
- if (meta !== null && vmAlive(meta)) await listenForGuest(meta, p);
4447
- });
4533
+ const bucket = await bucketInfo(p, deps).then(async (info) => info ?? await deps.api(p, "CreateBucket", { globalAlias: BACKUP_STORE_BUCKET }));
4534
+ let store;
4535
+ if (cfg.backupStore && await hasKey(p, deps, cfg.backupStore.accessKey)) {
4536
+ store = cfg.backupStore;
4537
+ } else {
4538
+ if (cfg.backupStore && !req.newStore) {
4539
+ await deps.stop(p);
4540
+ throw notTheStoreDisk(path);
4541
+ }
4542
+ if (cfg.backupStore) log.warn(`backup store: a new store in ${path} replaces the one with key ${cfg.backupStore.accessKey}; the backups kept on the old disk are gone`);
4543
+ const key = await deps.api(p, "CreateKey", { name: KEY_NAME });
4544
+ store = { path, bucket: BACKUP_STORE_BUCKET, region: BACKUP_STORE_REGION, accessKey: key.accessKeyId, secretKey: key.secretAccessKey, registered: false };
4448
4545
  }
4449
- }
4450
- async function closeDeadListeners(p) {
4451
- for (const meta of await readAllMeta(p)) {
4452
- if (vmAlive(meta)) continue;
4453
- const path = socketOf(meta, p);
4454
- if (path === void 0 || !guestListening(path)) continue;
4455
- await withBoxLock(meta, async () => {
4456
- const now = await readMachineMeta(meta, p).catch(() => null);
4457
- if (now === null || !vmAlive(now)) await stopListeningForGuest(meta, p);
4458
- });
4546
+ await deps.api(p, "AllowBucketKey", { bucketId: bucket.id, accessKeyId: store.accessKey, permissions: { read: true, write: true, owner: false } });
4547
+ const now = await loadConfig(p);
4548
+ await saveConfig({ ...now, backupStore: { ...store, registered: false } }, p);
4549
+ log.info(`backup store: Garage keeps its data in ${path}`);
4550
+ try {
4551
+ await deps.register(now, { bucket: store.bucket, region: store.region, accessKey: store.accessKey, secretKey: store.secretKey });
4552
+ } catch (err) {
4553
+ throw new KvboxError(`the store is set up, but the control plane did not take it: ${err.message}. Run the same command again once that is solved`);
4459
4554
  }
4555
+ await saveConfig({ ...await loadConfig(p), backupStore: { ...store, registered: true } }, p);
4556
+ log.info(`backup store: registered with ${now.controlPlane?.name ?? cfg.controlPlane.name}`);
4557
+ return backupStoreStatus(p, deps);
4460
4558
  }
4461
- function forgetGuest(box) {
4462
- asked.delete(refKey(box));
4463
- told.delete(box.id);
4464
- }
4465
- var refusal = (code, message, connected) => ({ ok: false, code, message, ...connected === void 0 ? {} : { connected } });
4466
- var asked = /* @__PURE__ */ new Map();
4467
- function withinLimit(box, now) {
4468
- const w = asked.get(box);
4469
- if (!w || now - w.since >= 6e4) {
4470
- asked.set(box, { since: now, count: 1 });
4471
- return true;
4472
- }
4473
- w.count += 1;
4474
- return w.count <= GUEST_REQUESTS_PER_MINUTE;
4559
+ var notTheStoreDisk = (path) => new KvboxError(
4560
+ `${path} does not hold this host's backup store: is its disk mounted there? Mount it and run this again. If that disk is gone for good, pass --new-store to start a new store here (the backups kept on the old disk can no longer be restored)`
4561
+ );
4562
+ async function hasKey(p, deps, id) {
4563
+ const keys = await deps.api(p, "ListKeys");
4564
+ return (keys ?? []).some((k) => k.id === id);
4475
4565
  }
4476
- async function answerGuest(ref, request7, p, now = Date.now()) {
4477
- if (!withinLimit(refKey(ref), now)) return refusal("unavailable", `this box asked more than ${GUEST_REQUESTS_PER_MINUTE} times in a minute; try again shortly`);
4478
- const parsed = GuestRequestSchema.safeParse(request7);
4479
- if (!parsed.success) return refusal("unavailable", "this host does not know that request; it may need updating");
4480
- const integration = parsed.data.integration;
4481
- let meta;
4566
+ async function bucketInfo(p, deps) {
4482
4567
  try {
4483
- meta = await readMachineMeta(ref, p);
4484
- } catch {
4485
- return refusal("unavailable", "this box is being removed");
4486
- }
4487
- const cp = (await loadConfig(p)).controlPlane;
4488
- if (!cp || !isCloudBox(meta.owner)) return refusal("unavailable", "integrations are not available in a box made on the host itself");
4489
- if (!(meta.integrations ?? []).includes(integration)) {
4490
- const probe = await probeConnection(cp, meta, integration, now);
4491
- return refusal("off", `${integration} is not turned on for this box`, probe?.connected);
4492
- }
4493
- const answer2 = await askCredential(cp, meta, integration);
4494
- if (answer2.ok && answer2.identity && !(told.has(meta.id) && sameIdentity(told.get(meta.id), answer2.identity))) {
4495
- void tellCurrent(ref, p.machine(meta.owner, meta.name).vsock, p, answer2.identity).catch(() => void 0);
4568
+ return await deps.api(p, "GetBucketInfo", { globalAlias: BACKUP_STORE_BUCKET });
4569
+ } catch (err) {
4570
+ if (/not found|nosuchbucket/i.test(err.message)) return null;
4571
+ throw err;
4496
4572
  }
4497
- return answer2;
4498
4573
  }
4499
- var told = /* @__PURE__ */ new Map();
4500
- var sameIdentity = (a, b) => a?.name === b?.name && a?.email === b?.email;
4501
- async function tellGuest(box, vsock, identity) {
4502
- const { known } = await setIntegrations(vsock, box.integrations ?? [], identity, AGENT_REPLY_MS);
4503
- told.set(box.id, identity);
4504
- return (box.integrations ?? []).filter((n) => !known.includes(n));
4574
+ async function backupStoreStatus(p = paths(), deps = realDeps) {
4575
+ const store = (await loadConfig(p)).backupStore;
4576
+ if (!store) throw new KvboxError("this host is not a backup store; make it one with: kvbox-server backup setup --path <directory on the backup disk>");
4577
+ const fs = await statfs2(store.path).catch(() => null);
4578
+ const running = await deps.running(p);
4579
+ const info = running ? await bucketInfo(p, deps).catch(() => null) : null;
4580
+ return {
4581
+ path: store.path,
4582
+ bucket: store.bucket,
4583
+ accessKey: store.accessKey,
4584
+ running: running && info !== null,
4585
+ totalBytes: fs ? fs.blocks * fs.bsize : 0,
4586
+ freeBytes: fs ? fs.bavail * fs.bsize : 0,
4587
+ ...info ? { objects: info.objects ?? 0, storedBytes: info.bytes ?? 0 } : {},
4588
+ registered: store.registered
4589
+ };
4505
4590
  }
4506
- var tooOldFor = (box, names2) => `its image is from before base v${names2.map((n) => INTEGRATION_BASES[n] ?? INTEGRATIONS_BASE).sort().at(-1)}, which cannot use ${names2.join(", ")} (kvbox vm update ${shown(box)} moves it onto the current one)`;
4507
- async function identityOf(box, p) {
4508
- if (!(box.integrations ?? []).includes("github")) return void 0;
4509
- const cp = (await loadConfig(p)).controlPlane;
4510
- if (!cp) return void 0;
4511
- const probe = await probeConnection(cp, box, "github");
4512
- if (probe !== null) return probe.identity;
4513
- return told.has(box.id) ? told.get(box.id) : null;
4591
+ async function backupStoreCapacity(p = paths(), deps = realDeps) {
4592
+ const store = (await loadConfig(p)).backupStore;
4593
+ if (!store) return void 0;
4594
+ const fs = await statfs2(store.path).catch(() => null);
4595
+ return { totalBytes: fs ? fs.blocks * fs.bsize : 0, freeBytes: fs ? fs.bavail * fs.bsize : 0, running: fs !== null && await deps.running(p) };
4514
4596
  }
4515
- var sameList = (a, b) => JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
4516
- async function tellCurrent(ref, vsock, p, identity) {
4517
- for (; ; ) {
4518
- const asked3 = await readMachineMeta(ref, p);
4519
- const who = identity !== void 0 && (asked3.integrations ?? []).includes("github") ? identity : await identityOf(asked3, p);
4520
- if (who === null) return false;
4521
- const done = await withBoxLock(ref, async () => {
4522
- const box = await readMachineMeta(ref, p);
4523
- if (!sameList(box.integrations, asked3.integrations)) return false;
4524
- const unusable = await tellGuest(box, vsock, who);
4525
- if (unusable.length > 0) log.warn(`box ${shown(box)} has integrations it cannot use: ${tooOldFor(box, unusable)}`);
4526
- return true;
4597
+ function reviveBackupStore(p = paths(), deps = realDeps) {
4598
+ return serial(() => revive(p, deps));
4599
+ }
4600
+ var upgraded = /* @__PURE__ */ new Set();
4601
+ var restartDue = /* @__PURE__ */ new Set();
4602
+ async function revive(p, deps) {
4603
+ const store = (await loadConfig(p)).backupStore;
4604
+ if (!store) return "none";
4605
+ if (!upgraded.has(p.home)) {
4606
+ upgraded.add(p.home);
4607
+ const fresh = await deps.install(p).catch((err) => {
4608
+ log.warn(`backup store: Garage ${GARAGE_VERSION} could not be installed, the one there keeps running (${err.message})`);
4609
+ return false;
4527
4610
  });
4528
- if (done) return true;
4611
+ if (fresh) restartDue.add(p.home);
4529
4612
  }
4530
- }
4531
- function assertImageCanUse(box, list, before) {
4532
- if (box.image !== void 0) return;
4533
- const unusable = unusableOnBase(box.base, (list ?? []).filter((n) => !(before ?? []).includes(n)));
4534
- if (unusable.length > 0) throw new KvboxError(`box ${shown(box)} cannot use ${unusable.join(", ")} yet: ${tooOldFor(box, unusable)}`);
4535
- }
4536
- var outdated = (box) => `its image is from before base v${INTEGRATIONS_BASE}, which has no integrations (kvbox vm update ${shown(box)} moves it onto the current one)`;
4537
- async function applyIntegrations(box, vsock, p, before) {
4538
- if (!isCloudBox(box.owner)) return;
4539
- let unusable;
4540
- try {
4541
- const prior = told.has(box.id) ? { who: told.get(box.id) } : null;
4542
- const who = await identityOf(box, p);
4543
- unusable = await tellGuest(box, vsock, who ?? void 0);
4544
- let unsure = who === null;
4545
- if (unusable.length > 0) {
4546
- if (prior) told.set(box.id, prior.who);
4547
- else told.delete(box.id);
4548
- const kept = { ...box, integrations: before && before.length > 0 ? [...before] : void 0 };
4549
- const keptWho = await identityOf(kept, p);
4550
- unsure = keptWho === null;
4551
- await tellGuest(kept, vsock, keptWho ?? void 0).catch(() => unsure = true);
4552
- }
4553
- if (unsure) {
4554
- told.delete(box.id);
4555
- if (box.pid !== null) void tellIntegrationsWhenUp(box, box.pid, vsock, p);
4556
- }
4557
- } catch (err) {
4558
- if (!isUnknownOp(err)) return void log.warn(`box ${shown(box)} was not told its integrations: ${err.message}`);
4559
- if ((box.integrations ?? []).length > 0) throw new KvboxError(`box ${shown(box)} cannot use integrations yet: ${outdated(box)}`);
4560
- return;
4613
+ if (restartDue.has(p.home) && existsSync8(join2(store.path, "rpc_secret"))) {
4614
+ if (await deps.running(p)) await deps.stop(p);
4615
+ const pid2 = await deps.start(p);
4616
+ await writeFile5(p.backupStore.pid, `${pid2}
4617
+ `);
4618
+ restartDue.delete(p.home);
4619
+ return "upgraded";
4561
4620
  }
4562
- if (unusable.length > 0) throw new KvboxError(`box ${shown(box)} cannot use ${unusable.join(", ")} yet: ${tooOldFor(box, unusable)}`);
4563
- }
4564
- var BOOT_WAIT_MS = 12e4;
4565
- var WHO_RETRY_MS = 3e3;
4566
- function tellIntegrationsWhenUp(ref, pid, vsock, p, timing = { waitMs: BOOT_WAIT_MS }) {
4567
- return outsideLocks(async () => {
4568
- if (!isCloudBox(ref.owner)) return;
4569
- const deadline = Date.now() + timing.waitMs;
4570
- for (; ; ) {
4571
- if (!pidAlive(pid)) return;
4572
- try {
4573
- if (await tellCurrent(ref, vsock, p)) return;
4574
- if (Date.now() >= deadline) return void log.warn(`box ${shown(ref)} was not told who commits in it: the control plane could not be asked`);
4575
- await sleep3(timing.retryMs ?? WHO_RETRY_MS);
4576
- } catch (err) {
4577
- if (!pidAlive(pid)) return;
4578
- if (isNoAgent(err) && Date.now() < deadline) {
4579
- await sleep3(500);
4580
- continue;
4581
- }
4582
- const box = await readMachineMeta(ref, p).catch(() => null);
4583
- if (box === null) return;
4584
- if (!isUnknownOp(err)) log.warn(`box ${shown(ref)} was not told its integrations: ${err.message}`);
4585
- else if ((box.integrations ?? []).length > 0) log.warn(`box ${shown(ref)} has integrations it cannot use: ${outdated(ref)}`);
4586
- return;
4587
- }
4588
- }
4589
- }).catch(() => void 0);
4621
+ if (await deps.running(p)) return "running";
4622
+ if (!existsSync8(join2(store.path, "rpc_secret"))) return "no-disk";
4623
+ await rm4(p.backupStore.pid, { force: true });
4624
+ const pid = await deps.start(p);
4625
+ await writeFile5(p.backupStore.pid, `${pid}
4626
+ `);
4627
+ return "started";
4590
4628
  }
4591
-
4592
- // src/core/machines/status.ts
4593
- import { existsSync as existsSync9 } from "node:fs";
4594
- function isHibernated(meta, p) {
4595
- return !vmAlive(meta) && existsSync9(p.machine(meta.owner, meta.name).hibernateVmstate);
4629
+ var watch;
4630
+ function startBackupStoreWatch(p = paths()) {
4631
+ let warned = false;
4632
+ const tick = () => {
4633
+ reviveBackupStore(p).then((state) => {
4634
+ if (state === "started") log.info("backup store: Garage was not running; started it");
4635
+ if (state === "upgraded") log.info(`backup store: Garage ${GARAGE_VERSION} installed and started`);
4636
+ if (state === "no-disk" && !warned) log.warn("backup store: its disk is not mounted, so Garage is not started; backups to this host fail until it is back");
4637
+ warned = state === "no-disk";
4638
+ }).catch((err) => log.warn(`backup store: Garage did not start (${err.message})`));
4639
+ };
4640
+ tick();
4641
+ watch ??= setInterval(tick, WATCH_MS);
4642
+ watch.unref();
4596
4643
  }
4597
- function statusOf(meta, p = paths()) {
4598
- if (vmAlive(meta)) return meta.paused ? "standby" : "running";
4599
- return isHibernated(meta, p) ? "hibernated" : "stopped";
4644
+ function isStoreRequest(url) {
4645
+ return url !== void 0 && (url.startsWith(`/${BACKUP_STORE_BUCKET}/`) || url.startsWith(`/${BACKUP_STORE_BUCKET}?`) || url === `/${BACKUP_STORE_BUCKET}`);
4600
4646
  }
4601
- function stateMessage(ref, status) {
4602
- return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
4647
+ function forStore(url, p = paths()) {
4648
+ return isStoreRequest(url) && existsSync8(p.backupStore.conf);
4603
4649
  }
4604
- function assertNotHibernated(meta, p) {
4605
- if (isHibernated(meta, p)) {
4606
- throw new KvboxError(`${stateMessage(meta, "hibernated")}; its memory image was made with its current shape and base: kvbox wake ${shown(meta)} first`);
4607
- }
4650
+ function storeProxy(req, res, port = GARAGE_S3_PORT) {
4651
+ const up = httpRequest({ host: "127.0.0.1", port, method: req.method, path: req.url, headers: req.headers }, (answer2) => {
4652
+ res.writeHead(answer2.statusCode ?? 502, answer2.headers);
4653
+ pipeline(answer2, res, (err) => {
4654
+ if (err) res.destroy();
4655
+ });
4656
+ });
4657
+ up.on("error", () => {
4658
+ if (res.headersSent) return res.destroy();
4659
+ res.writeHead(503, { "content-type": "application/json" });
4660
+ res.end(JSON.stringify({ error: "this host's backup store is not running" }));
4661
+ });
4662
+ res.once("close", () => {
4663
+ if (!res.writableFinished) up.destroy();
4664
+ });
4665
+ req.pipe(up);
4608
4666
  }
4609
4667
 
4610
- // src/core/machines/list.ts
4611
- function toMachine(meta, p = paths()) {
4612
- const alive2 = vmAlive(meta);
4613
- if (!alive2 && meta.pid !== null) {
4668
+ // src/core/capacity.ts
4669
+ function hostResources() {
4670
+ return { memMib: Math.floor(totalmem() / 1024 ** 2), cores: cpus().length };
4671
+ }
4672
+ async function runningReservations(p = paths()) {
4673
+ const out = [];
4674
+ for (const ref of await listMachineRefs(p)) {
4614
4675
  try {
4615
- closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
4616
- } catch (err) {
4617
- log.warn(`usage ledger: ${err.message}`);
4676
+ const meta = await readMachineMeta(ref, p);
4677
+ if (vmAlive(meta)) out.push({ owner: meta.owner, name: meta.name, vcpu: meta.vcpu, memMib: meta.memMib });
4678
+ } catch {
4618
4679
  }
4619
4680
  }
4681
+ return out;
4682
+ }
4683
+ async function capacity(p = paths()) {
4684
+ const host = hostResources();
4685
+ const running = await runningReservations(p);
4686
+ const cfg = await loadConfig(p);
4620
4687
  return {
4621
- id: meta.id,
4622
- name: meta.name,
4623
- owner: meta.owner,
4624
- ip: meta.ip,
4625
- mac: meta.mac,
4626
- pid: alive2 ? meta.pid : null,
4627
- vcpu: meta.vcpu,
4628
- memMib: meta.memMib,
4629
- ...diskStats(p.machine(meta.owner, meta.name).overlay),
4630
- base: meta.base,
4631
- ...meta.image !== void 0 ? { image: meta.image } : {},
4632
- ...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
4633
- createdAt: meta.createdAt,
4634
- ...meta.bootedAt !== void 0 ? { bootedAt: meta.bootedAt } : {},
4635
- source: meta.source,
4636
- status: statusOf(meta, p),
4637
- ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
4638
- ...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
4639
- ...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
4640
- ...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
4641
- ...meta.integrations?.length ? { integrations: [...meta.integrations] } : {},
4642
- ...meta.cluster !== void 0 ? { clusterId: meta.cluster } : {},
4643
- ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
4644
- ...linksOf(meta)
4688
+ hostMemMib: host.memMib,
4689
+ memHeadroomMib: cfg.memHeadroomMib,
4690
+ hostCores: host.cores,
4691
+ reservedMemMib: running.reduce((n, r) => n + r.memMib, 0),
4692
+ reservedVcpu: running.reduce((n, r) => n + r.vcpu, 0),
4693
+ running: running.length,
4694
+ disk: await diskCapacity(p),
4695
+ // What a box can be made from here (#87): the control plane places `--base postgres` by it.
4696
+ images: await listImages(cfg, p),
4697
+ ...await backupStoreCapacity(p).then((store) => store ? { backupStore: store } : {}),
4698
+ // Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).
4699
+ storeClient: true,
4700
+ // A new box on a backup's disk (#141): the control plane places `new --from-backup` only here.
4701
+ fromBackup: true,
4702
+ // A link to a box on another host is carried here (#207): the control plane links across hosts only between two such.
4703
+ // Only once the host's privileged network script knows them: an update without its root step does not.
4704
+ farLinks: driver().net.carriesFarLinks(),
4705
+ // The boxes of a cluster reach each other here (#215), on the same condition: the control plane places a cluster's box only on such a host.
4706
+ clusters: driver().net.carriesClusters(),
4707
+ // A box's integrations are kept here (#205): the control plane sends a list only to such a host.
4708
+ integrations: true,
4709
+ // ...and which (the control plane places a box with `claude` only on a host that names it).
4710
+ integrationIds: [...INTEGRATION_IDS],
4711
+ // A range of its own for its boxes (#240) can be taken here, on the privileged script's condition again;
4712
+ // the one it has, and how many boxes are still on an address from before it.
4713
+ ranges: driver().net.carriesRanges(),
4714
+ ...cfg.boxRange === void 0 ? {} : { boxRange: cfg.boxRange, offRange: await countOffRange(p) }
4645
4715
  };
4646
4716
  }
4647
- function linksOf(meta) {
4648
- const all = [...(meta.links ?? []).filter((l) => !l.stale), ...meta.farLinks ?? []];
4649
- return all.length > 0 ? { links: all.map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {};
4717
+ function gb(mib) {
4718
+ const g = mib / 1024;
4719
+ return `${Number.isInteger(g) ? g : g.toFixed(1)} GB`;
4650
4720
  }
4651
- var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
4652
- async function listMachines(scope, p = paths()) {
4653
- return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
4721
+ function describeRunning(running, viewer) {
4722
+ if (running.length === 0) return "no box is running";
4723
+ const own = viewer === void 0 ? running : running.filter((r) => r.owner === viewer);
4724
+ const others = running.length - own.length;
4725
+ const named = own.map((r) => `${r.name} ${r.vcpu} vCPU/${gb(r.memMib)}`);
4726
+ if (others > 0) named.push(`${others} ${others === 1 ? "box" : "boxes"} of other users`);
4727
+ const list = named.join(", ");
4728
+ const vcpu = running.reduce((n, r) => n + r.vcpu, 0);
4729
+ const mem = running.reduce((n, r) => n + r.memMib, 0);
4730
+ return `${running.length} running ${running.length === 1 ? "box reserves" : "boxes reserve"} ${vcpu} vCPU and ${gb(mem)} (${list})`;
4654
4731
  }
4655
- async function getMachine(ref, p = paths()) {
4656
- return toMachine(await readMeta(ref, p), p);
4732
+ var HINTS = {
4733
+ new: "stop or remove a box (kvbox stop, kvbox rm), pick a smaller --size, or pass --force to start it anyway",
4734
+ start: "stop or remove a box (kvbox stop, kvbox rm), or pass --force to start it anyway",
4735
+ rescale: "stop or remove a box (kvbox stop, kvbox rm), ask for less, or pass --force to rescale it anyway"
4736
+ };
4737
+ function roomFor(host, running, want, opts = {}) {
4738
+ const { viewer, by = "new" } = opts;
4739
+ const reservedMem = running.reduce((n, r) => n + r.memMib, 0);
4740
+ const reservedVcpu = running.reduce((n, r) => n + r.vcpu, 0);
4741
+ const headroom = host.headroomMib ?? 0;
4742
+ const memLimit = host.memMib - headroom;
4743
+ const vcpuLimit = host.cores * VCPU_OVERSUBSCRIPTION;
4744
+ const hint = HINTS[by];
4745
+ if (reservedMem + want.memMib > memLimit) {
4746
+ return `not enough memory for a ${gb(want.memMib)} box: ${describeRunning(running, viewer)}; ` + (headroom > 0 ? `this host has ${gb(host.memMib)} and keeps ${gb(headroom)} for itself, so boxes may reserve ${gb(memLimit)} in total. ` : `this host has ${gb(host.memMib)}, all of it for its boxes. `) + hint;
4747
+ }
4748
+ if (reservedVcpu + want.vcpu > vcpuLimit) {
4749
+ return `too many vCPUs for a ${want.vcpu} vCPU box: ${describeRunning(running, viewer)}; this host has ${host.cores} cores and allows ${vcpuLimit} vCPUs in total (${VCPU_OVERSUBSCRIPTION}x). ` + hint;
4750
+ }
4751
+ return void 0;
4752
+ }
4753
+ async function assertRoomFor(vcpu, memMib, force, box, by, p = paths()) {
4754
+ if (force) return;
4755
+ const running = (await runningReservations(p)).filter((r) => box.name === void 0 || !(r.owner === box.owner && r.name === box.name));
4756
+ const host = { ...hostResources(), headroomMib: (await loadConfig(p)).memHeadroomMib };
4757
+ const reason = roomFor(host, running, { vcpu, memMib }, { viewer: box.owner, by });
4758
+ if (reason !== void 0) throw new KvboxError(reason);
4657
4759
  }
4658
4760
 
4659
- // src/core/machines/boot.ts
4660
- async function launch(spec, nic, cfg, pubkeyB64, p) {
4661
- const root = imageFileFor(spec, p);
4662
- const kernel = kernelFor(await imageManifest(root), cfg, p);
4663
- const volumes = (await placeVolumeDrives(spec, p)).map((v) => ({ id: volumeDriveId(v.name), path: volumeDriveRel(v.name) }));
4664
- return withGuestListener(spec, p, () => driver().vm.boot(spec, { kernel, root, volumes, pubkeyB64 }, nic, cfg, p));
4761
+ // src/core/env.ts
4762
+ import { existsSync as existsSync9 } from "node:fs";
4763
+ import { copyFile, mkdir as mkdir4, readFile as readFile8, readdir as readdir4, rename as rename4, writeFile as writeFile6 } from "node:fs/promises";
4764
+ import { z as z7 } from "zod";
4765
+
4766
+ // ../shared/src/env.ts
4767
+ var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
4768
+ var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
4769
+ var ENV_MAX_VALUE_BYTES = 4096;
4770
+ var ENV_MAX_VARS = 100;
4771
+ function envNameProblem(name) {
4772
+ if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
4773
+ if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
4774
+ if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
4775
+ return null;
4665
4776
  }
4666
- async function loadSnapshot(spec, image, nic, cfg, p) {
4667
- return withGuestListener(spec, p, () => driver().vm.restore(spec, { vmstate: image.vmstate, mem: image.mem }, nic, cfg, p));
4777
+ function envValueProblem(value) {
4778
+ if (/[\n\r\0]/.test(value)) return "a value is one line: no line breaks (base64 a multi-line value such as a key file)";
4779
+ if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
4780
+ return null;
4668
4781
  }
4669
- async function withGuestListener(box, p, bringUp) {
4670
- await listenForGuest(box, p);
4782
+
4783
+ // src/core/env.ts
4784
+ var OwnerEnvSchema = z7.object({
4785
+ /** The control plane's counter for the list; only ever grows. */
4786
+ version: z7.number().int().min(0),
4787
+ vars: z7.array(z7.object({ name: z7.string(), value: z7.string() }))
4788
+ });
4789
+ async function readOwnerEnv(owner, p = paths()) {
4671
4790
  try {
4672
- return await bringUp();
4791
+ return OwnerEnvSchema.parse(JSON.parse(await readFile8(p.ownerEnv(owner), "utf8")));
4673
4792
  } catch (err) {
4674
- await stopListeningForGuest(box, p);
4793
+ if (err.code === "ENOENT") return null;
4675
4794
  throw err;
4676
4795
  }
4677
4796
  }
4678
- async function resumeVm(box, p) {
4679
- await driver().vm.resume(box, p);
4680
- }
4681
-
4682
- // src/core/machines/guest.ts
4683
- import { setTimeout as sleep4 } from "node:timers/promises";
4684
- function prefixLenOf(subnet) {
4685
- return Number(subnet.split("/")[1]);
4797
+ async function envForBoot(box, p = paths()) {
4798
+ const env = await readOwnerEnv(box.owner, p).catch(() => null);
4799
+ const own = await readBoxEnv(box, p).catch((err) => {
4800
+ log.warn(`box ${shown(box)}: its own variables are unreadable, it boots without them: ${err.message}`);
4801
+ return [];
4802
+ });
4803
+ const slug = env?.vars ?? (realmOf(box.owner) !== null ? [] : null);
4804
+ if (own.length === 0) return slug ?? (existsSync9(p.machine(box.owner, box.name).env) ? [] : null);
4805
+ const mine = new Set(own.map((v) => v.name));
4806
+ return [...(slug ?? []).filter((v) => !mine.has(v.name)), ...own.map((v) => ({ name: v.name, value: v.value }))];
4686
4807
  }
4687
- var AGENT_REPLY_MS2 = 2e4;
4688
- async function introduce(spec, vsock, cfg, failure2) {
4689
- const id = { name: spec.name, ip: spec.ip, prefixLen: prefixLenOf(cfg.subnet), gateway: cfg.gateway, mac: spec.mac, time: Math.floor(Date.now() / 1e3) };
4690
- const deadline = Date.now() + 3e3;
4691
- for (; ; ) {
4692
- try {
4693
- await setIdentity(vsock, id, AGENT_REPLY_MS2);
4694
- return;
4695
- } catch (err) {
4696
- const msg = err.message;
4697
- const transient = /unreachable|refused|before the guest accepted/.test(msg);
4698
- if (transient && Date.now() < deadline) {
4699
- await sleep4(100);
4700
- continue;
4701
- }
4702
- if (transient) throw new KvboxError(`${msg}
4703
- ${failure2.silent}`);
4704
- throw new KvboxError(`${msg}
4705
- ${failure2.noAnswer}`);
4706
- }
4707
- }
4808
+ var BoxEnvFileSchema = z7.object({
4809
+ vars: z7.array(z7.object({ name: z7.string(), value: z7.string(), secret: z7.boolean(), updatedAt: z7.string() }))
4810
+ });
4811
+ async function readBoxEnv(box, p = paths()) {
4812
+ return readBoxEnvFile(p.machine(box.owner, box.name).env);
4708
4813
  }
4709
- async function dropGuestVolumes(box, vsock) {
4814
+ async function readBoxEnvFile(file) {
4710
4815
  try {
4711
- await dropVolumes(vsock, AGENT_REPLY_MS2);
4816
+ return BoxEnvFileSchema.parse(JSON.parse(await readFile8(file, "utf8"))).vars;
4712
4817
  } catch (err) {
4713
- const why = isUnknownOp(err) ? `its image predates base v0.9.0, whose kvbox-agent can unmount them (kvbox vm update ${shown(box)} moves it onto the current base)` : err.message;
4714
- log.warn(`box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);
4818
+ if (err.code === "ENOENT") return [];
4819
+ throw err;
4715
4820
  }
4716
4821
  }
4717
- async function pushEnv(box, vsock, p) {
4718
- const vars = await envForBoot(box, p);
4719
- if (vars === null) return;
4720
- try {
4721
- await setEnv(vsock, vars, AGENT_REPLY_MS2);
4722
- } catch (err) {
4723
- warnEnv(box, vars, err);
4822
+ function checkBoxEnv(vars) {
4823
+ if (vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
4824
+ const seen = /* @__PURE__ */ new Set();
4825
+ for (const v of vars) {
4826
+ const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
4827
+ if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
4828
+ if (seen.has(v.name)) throw new KvboxError(`${v.name} is given twice`);
4829
+ seen.add(v.name);
4724
4830
  }
4725
4831
  }
4726
- function warnEnv(box, vars, err) {
4727
- if (isUnknownOp(err)) {
4728
- if (vars.length === 0) return;
4729
- log.warn(`box ${shown(box)} did not get its environment variables: its image predates base v0.10.0, whose kvbox-agent takes them (kvbox vm update ${shown(box)} moves it onto the current base)`);
4730
- return;
4731
- }
4732
- log.warn(`box ${shown(box)} did not get its environment variables: ${err.message}`);
4832
+ async function writeBoxEnv(box, vars, p = paths()) {
4833
+ checkBoxEnv(vars);
4834
+ const file = p.machine(box.owner, box.name).env;
4835
+ const tmp = `${file}.tmp`;
4836
+ await writeFile6(tmp, JSON.stringify({ vars }, null, 2) + "\n", { mode: 384 });
4837
+ await rename4(tmp, file);
4733
4838
  }
4734
- var ENV_BOOT_WAIT_MS = 12e4;
4735
- function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS2, waitMs: ENV_BOOT_WAIT_MS }) {
4736
- return (async () => {
4737
- const deadline = Date.now() + timing.waitMs;
4738
- for (; ; ) {
4739
- if (!pidAlive(pid)) return;
4740
- const vars = await envForBoot(box, p);
4741
- if (vars === null) return;
4742
- try {
4743
- await setEnv(vsock, vars, timing.replyMs);
4744
- return;
4745
- } catch (err) {
4746
- if (!pidAlive(pid)) return;
4747
- if (isNoAgent(err) && Date.now() < deadline) {
4748
- await sleep4(500);
4749
- continue;
4750
- }
4751
- warnEnv(box, vars, err);
4752
- return;
4753
- }
4754
- }
4755
- })();
4839
+ async function mergeBoxEnv(box, given, p = paths()) {
4840
+ const names2 = new Set(given.map((v) => v.name));
4841
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4842
+ const kept = (await readBoxEnv(box, p)).filter((v) => !names2.has(v.name));
4843
+ await writeBoxEnv(box, [...kept, ...given.map((v) => ({ name: v.name, value: v.value, secret: v.secret === true, updatedAt: now }))], p);
4756
4844
  }
4757
-
4758
- // ../shared/src/ssh.ts
4759
- import { createHash as createHash2 } from "node:crypto";
4760
- var SSH_PUBLIC_KEY_RE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com) ([A-Za-z0-9+/]+=*)(?: [^\r\n]*)?$/;
4761
- function parseSshPublicKey(text) {
4762
- const key = text.trim().replace(/^cert-authority\s+/, "");
4763
- if (!SSH_PUBLIC_KEY_RE.test(key)) {
4764
- throw new KvboxError("that is not an SSH public key; expected one line like: ssh-ed25519 AAAA\u2026 kvbox-ca@kvbox.sh");
4765
- }
4766
- return key;
4845
+ async function copyBoxEnv(from, to) {
4846
+ if (!existsSync9(from)) return;
4847
+ await copyFile(from, to);
4767
4848
  }
4768
- function sshKeyFingerprint(publicKey) {
4769
- const m = SSH_PUBLIC_KEY_RE.exec(publicKey.trim());
4770
- if (!m) throw new KvboxError("cannot fingerprint: not an SSH public key");
4771
- return `SHA256:${createHash2("sha256").update(Buffer.from(m[2], "base64")).digest("base64").replace(/=+$/, "")}`;
4849
+ function shownBoxEnv(vars) {
4850
+ return vars.map((v) => ({ name: v.name, ...v.secret ? {} : { value: v.value }, secret: v.secret, updatedAt: v.updatedAt }));
4772
4851
  }
4773
- function caLineFor(principal, caPublicKey) {
4774
- return `cert-authority,principals="${principal}" ${caPublicKey}`;
4852
+ async function setBoxVar(box, name, value, secret, p = paths()) {
4853
+ await withBoxLock(box, async () => {
4854
+ if (!existsSync9(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);
4855
+ const vars = (await readBoxEnv(box, p)).filter((v) => v.name !== name);
4856
+ await writeBoxEnv(box, [...vars, { name, value, secret, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }], p);
4857
+ });
4775
4858
  }
4776
- var isCaLine = (line) => /^cert-authority(,|\s)/.test(line.trim());
4777
-
4778
- // src/core/machines/keys.ts
4779
- var MAX_SSH_KEY_LINES = 8;
4780
- var MAX_SSH_KEYS_B64 = 1500;
4781
- function authorizedKeysLines(hostKey, extra) {
4782
- const lines = [hostKey.trim(), ...extra.map((l) => l.trim())];
4783
- if (lines.some((l) => l === "" || /[\r\n]/.test(l))) throw new KvboxError("sshKeys: every entry must be one non-empty authorized_keys line");
4784
- if (lines.length > MAX_SSH_KEY_LINES) {
4785
- throw new KvboxError(`a box takes at most ${MAX_SSH_KEY_LINES - 1} SSH keys on top of the host's own; ${extra.length} were given`);
4786
- }
4787
- return lines;
4859
+ async function rmBoxVar(box, name, p = paths()) {
4860
+ await withBoxLock(box, async () => {
4861
+ if (!existsSync9(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);
4862
+ const vars = await readBoxEnv(box, p);
4863
+ if (!vars.some((v) => v.name === name)) throw new NotFoundError(`variable ${name} on box ${shown(box)}`);
4864
+ await writeBoxEnv(box, vars.filter((v) => v.name !== name), p);
4865
+ });
4788
4866
  }
4789
- function authorizedKeysB64(hostKey, extra) {
4790
- const lines = authorizedKeysLines(hostKey, extra);
4791
- const b64 = Buffer.from(lines.join("\n") + "\n").toString("base64");
4792
- if (b64.length > MAX_SSH_KEYS_B64) {
4793
- throw new KvboxError(`the SSH keys for this box do not fit the kernel command line (${b64.length} bytes encoded, ${MAX_SSH_KEYS_B64} at most); use fewer or shorter keys`);
4867
+ async function setOwnerEnv(owner, req, p = paths()) {
4868
+ if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
4869
+ if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
4870
+ const seen = /* @__PURE__ */ new Set();
4871
+ for (const v of req.vars) {
4872
+ const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
4873
+ if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
4874
+ if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);
4875
+ seen.add(v.name);
4794
4876
  }
4795
- return b64;
4877
+ return withHostLock("env", async () => {
4878
+ const have = await readOwnerEnv(owner, p);
4879
+ if (have !== null && have.version > req.version) return { version: have.version };
4880
+ const file = p.ownerEnv(owner);
4881
+ await mkdir4(p.env, { recursive: true, mode: 448 });
4882
+ const tmp = `${file}.tmp`;
4883
+ await writeFile6(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
4884
+ await rename4(tmp, file);
4885
+ return { version: req.version };
4886
+ });
4796
4887
  }
4797
- async function pushAuthorizedKeys(box, vsock, p) {
4888
+ async function listEnvVersions(scope, p = paths()) {
4889
+ let files;
4798
4890
  try {
4799
- await setAuthorizedKeys(vsock, authorizedKeysLines(await readHostPubkey(p), box.sshKeys ?? []), AGENT_REPLY_MS2);
4800
- return void 0;
4891
+ files = await readdir4(p.env);
4801
4892
  } catch (err) {
4802
- const why = isUnknownOp(err) ? `its image predates base v0.6.0, whose kvbox-agent can replace authorized_keys (kvbox vm update ${shown(box)} moves it onto the current base)` : err.message;
4803
- log.warn(`box ${shown(box)} keeps the authorized_keys it was frozen with: ${why}`);
4804
- return why;
4893
+ if (err.code === "ENOENT") return [];
4894
+ throw err;
4805
4895
  }
4806
- }
4807
- var setSshKeys = locked(async function setSshKeys2(ref, sshKeys, p = paths()) {
4808
- const meta = await readMeta(ref, p);
4809
- if (!isCloudBox(meta.owner)) throw new KvboxError(`box ${shown(ref)} is local: it trusts this host's key, there are no authorized_keys lines to replace`);
4810
- if (sshKeys.length === 0) throw new KvboxError("sshKeys: at least one authorized_keys line (the box would keep only the host's own key)");
4811
- authorizedKeysB64(await readHostPubkey(p), sshKeys);
4812
- const { meta: updated, applied } = await applySshKeys(meta, sshKeys, p);
4813
- return { machine: toMachine(updated, p), applied };
4814
- });
4815
- async function applySshKeys(meta, sshKeys, p) {
4816
- const status = statusOf(meta, p);
4817
- let updated = { ...meta, sshKeys: [...sshKeys], sshKeysStale: status === "stopped" ? void 0 : true };
4818
- let applied = status === "stopped" ? "start" : status === "standby" ? "resume" : status === "hibernated" ? "wake" : "later";
4819
- let why;
4820
- if (status === "running") {
4821
- why = await pushAuthorizedKeys(updated, p.machine(meta.owner, meta.name).vsock, p);
4822
- if (why === void 0) {
4823
- updated = { ...updated, sshKeysStale: void 0 };
4824
- applied = "now";
4825
- }
4896
+ const out = [];
4897
+ for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
4898
+ const owner = file.slice(0, -".json".length);
4899
+ if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;
4900
+ const env = await readOwnerEnv(owner, p).catch(() => null);
4901
+ if (env !== null) out.push({ owner, version: env.version });
4826
4902
  }
4827
- await writeMachineMeta(updated, p);
4828
- return why === void 0 ? { meta: updated, applied } : { meta: updated, applied, why };
4903
+ return out;
4829
4904
  }
4830
- async function trustCa(publicKeyText, p = paths()) {
4831
- const publicKey = parseSshPublicKey(publicKeyText);
4832
- const report2 = { publicKey, fingerprint: sshKeyFingerprint(publicKey), updated: [], pending: [], failed: [], local: 0, skipped: [] };
4833
- const hostKey = await readHostPubkey(p);
4834
- for (const listed of await readAllMeta(p)) {
4835
- if (!isCloudBox(listed.owner)) {
4836
- report2.local++;
4837
- continue;
4838
- }
4839
- const box = refKey(listed);
4840
- try {
4841
- await withBoxLock(listed, async () => {
4842
- const meta = await readMeta(listed, p);
4843
- if (!(meta.sshKeys ?? []).some(isCaLine)) {
4844
- report2.skipped.push(box);
4845
- return;
4905
+
4906
+ // src/core/machines/integrations.ts
4907
+ import { setTimeout as sleep3 } from "node:timers/promises";
4908
+
4909
+ // src/core/agent.ts
4910
+ import { connect } from "node:net";
4911
+ var AGENT_PORT = 52;
4912
+ async function agentCall(udsPath, req, timeoutMs = 5e3, connectMs = timeoutMs) {
4913
+ const reply = await new Promise((resolve3, reject) => {
4914
+ const sock = connect(udsPath);
4915
+ let buf = "";
4916
+ let handshaken = false;
4917
+ const fail = (err) => {
4918
+ sock.destroy();
4919
+ reject(err);
4920
+ };
4921
+ sock.setTimeout(connectMs, () => fail(new KvboxError(handshaken ? `kvbox-agent did not answer within ${timeoutMs} ms` : `the guest did not accept the vsock connection within ${connectMs} ms`)));
4922
+ sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
4923
+ sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
4924
+ `));
4925
+ sock.on("data", (chunk) => {
4926
+ buf += chunk.toString("utf8");
4927
+ let nl;
4928
+ while ((nl = buf.indexOf("\n")) !== -1) {
4929
+ const line = buf.slice(0, nl);
4930
+ buf = buf.slice(nl + 1);
4931
+ if (!handshaken) {
4932
+ if (!line.startsWith("OK ")) return fail(new KvboxError(`vsock connect refused: ${line}`));
4933
+ handshaken = true;
4934
+ sock.setTimeout(timeoutMs);
4935
+ sock.write(JSON.stringify(req) + "\n");
4936
+ } else {
4937
+ sock.end();
4938
+ return resolve3(line);
4846
4939
  }
4847
- const sshKeys = [...(meta.sshKeys ?? []).filter((l) => !isCaLine(l)), caLineFor(meta.owner, publicKey)];
4848
- authorizedKeysLines(hostKey, sshKeys);
4849
- const { applied, why } = await applySshKeys(meta, sshKeys, p);
4850
- if (applied === "now") report2.updated.push(box);
4851
- else report2.pending.push(why === void 0 ? { box, when: applied } : { box, when: applied, why });
4852
- });
4853
- } catch (err) {
4854
- report2.failed.push({ box, error: err.message });
4855
- }
4940
+ }
4941
+ });
4942
+ sock.once("close", () => {
4943
+ if (!handshaken) fail(new KvboxError("vsock connection closed before the guest accepted"));
4944
+ else fail(new KvboxError("kvbox-agent closed the connection without a reply"));
4945
+ });
4946
+ });
4947
+ let parsed;
4948
+ try {
4949
+ parsed = JSON.parse(reply);
4950
+ } catch {
4951
+ throw new KvboxError(`kvbox-agent sent something that is not JSON: ${reply}`);
4856
4952
  }
4857
- return report2;
4953
+ if (!parsed.ok) throw new KvboxError(`kvbox-agent: ${parsed.error}`);
4954
+ return parsed;
4858
4955
  }
4859
-
4860
- // src/core/publicPorts.ts
4861
- import { randomInt } from "node:crypto";
4862
- var SSH_PORT_MIN = 2e4;
4863
- var SSH_PORT_MAX = 6e4;
4864
- function pickSshPort(taken) {
4865
- const span = SSH_PORT_MAX - SSH_PORT_MIN + 1;
4866
- for (let i = 0; i < 32; i++) {
4867
- const port = SSH_PORT_MIN + randomInt(span);
4868
- if (!taken.has(port)) return port;
4869
- }
4870
- const start = randomInt(span);
4871
- for (let i = 0; i < span; i++) {
4872
- const port = SSH_PORT_MIN + (start + i) % span;
4873
- if (!taken.has(port)) return port;
4874
- }
4875
- throw new KvboxError(`no free port left between ${SSH_PORT_MIN} and ${SSH_PORT_MAX} on this host`);
4956
+ function setIdentity(udsPath, id, timeoutMs) {
4957
+ return agentCall(udsPath, { op: "identity", ...id }, timeoutMs);
4876
4958
  }
4877
-
4878
- // src/core/machines/cluster.ts
4879
- import { createHash as createHash3 } from "node:crypto";
4880
- var clusterKey = (owner, cluster) => createHash3("sha256").update(`${owner}
4881
- ${cluster}`).digest("hex").slice(0, 16);
4882
- function requestedCluster(req, owner, fromBackup = false) {
4883
- if (req.cluster === void 0) return void 0;
4884
- if (!isCloudBox(owner)) throw new KvboxError("a box is put in a cluster by a control plane; this host's own boxes have none");
4885
- if (req.from !== void 0 || fromBackup) throw new KvboxError("a box of a cluster is made from its image, never from a snapshot or a backup");
4886
- if (!driver().net.carriesClusters()) {
4887
- throw new KvboxError("this host's network setup is from before clusters; its operator finishes the update by running install-server.sh on it (the root step)");
4888
- }
4889
- return req.cluster;
4959
+ function setAuthorizedKeys(udsPath, lines, timeoutMs) {
4960
+ return agentCall(udsPath, { op: "authorizedKeys", lines: [...lines] }, timeoutMs);
4890
4961
  }
4891
- async function joinCluster2(meta, cfg) {
4892
- if (meta.cluster === void 0 || meta.owner === void 0) return;
4893
- await driver().net.joinCluster({ box: meta.id, ip: meta.ip, cluster: clusterKey(meta.owner, meta.cluster) }, cfg);
4962
+ async function stats(udsPath, timeoutMs) {
4963
+ const reply = GuestStatsSchema.safeParse(await agentCall(udsPath, { op: "stats" }, timeoutMs));
4964
+ if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? "invalid"}`);
4965
+ return reply.data;
4894
4966
  }
4895
- async function leaveCluster2(meta, cfg) {
4896
- await leftCluster(meta, cfg).catch((err) => log.warn(`could not take box ${meta.id} out of its cluster: ${err.message}`));
4967
+ async function dropVolumes(udsPath, timeoutMs) {
4968
+ const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
4969
+ return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
4897
4970
  }
4898
- async function leftCluster(meta, cfg) {
4899
- if (meta.cluster === void 0) return;
4900
- await driver().net.leaveCluster({ box: meta.id, ip: meta.ip }, cfg);
4971
+ function setEnv(udsPath, vars, timeoutMs) {
4972
+ return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
4901
4973
  }
4902
- async function rejoinClusters(p = paths()) {
4903
- const cfg = await loadConfig(p);
4904
- for (const listed of await readAllMeta(p)) {
4905
- if (!vmAlive(listed) || listed.cluster === void 0) continue;
4906
- await withBoxLock(listed, async () => {
4907
- const meta = await readMachineMeta(listed, p).catch(() => null);
4908
- if (meta === null || !vmAlive(meta)) return;
4909
- await joinCluster2(meta, cfg).catch((err) => log.warn(`box ${meta.name} is cut off from its cluster: ${err.message}`));
4910
- });
4911
- }
4974
+ async function idle(udsPath, script, timeoutMs = 15e3) {
4975
+ return (await agentCall(udsPath, { op: "idle", path: script }, timeoutMs))["idle"] === true;
4912
4976
  }
4913
-
4914
- // src/core/farTunnel.ts
4915
- import { createServer as createServer2 } from "node:net";
4916
- import { connect as tlsConnect } from "node:tls";
4917
-
4918
- // ../shared/src/httpHead.ts
4919
- var END = "\r\n\r\n";
4920
- var HeadTimeoutError = class extends Error {
4921
- };
4922
- function readHead(socket, opts) {
4923
- return new Promise((resolve3, reject) => {
4924
- let bytes = Buffer.alloc(0);
4925
- const done = (err) => {
4926
- clearTimeout(timer);
4927
- socket.off("data", onData);
4928
- socket.off("close", onClose);
4929
- socket.pause();
4930
- if (err) return reject(err);
4931
- const end = bytes.indexOf(END);
4932
- resolve3({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
4933
- };
4934
- const onData = (chunk) => {
4935
- bytes = Buffer.concat([bytes, chunk]);
4936
- if (bytes.includes(END)) done();
4937
- else if (bytes.length > opts.maxBytes) done(new Error("answer head too large"));
4938
- };
4939
- const onClose = () => done(new Error("closed before answering"));
4940
- const timer = setTimeout(() => done(new HeadTimeoutError(`no answer within ${opts.timeoutMs / 1e3} s`)), opts.timeoutMs);
4941
- socket.on("data", onData);
4942
- socket.once("close", onClose);
4943
- });
4977
+ async function runScript(udsPath, path, input, timeoutMs = 35e3) {
4978
+ return (await agentCall(udsPath, { op: "script", path, input: input ?? null }, timeoutMs))["output"];
4944
4979
  }
4945
- function headStatus(head) {
4946
- const m = /^HTTP\/\d(?:\.\d)? (\d{3})(?: |\r|$)/.exec(head);
4947
- return m ? Number(m[1]) : void 0;
4980
+ async function setIntegrations(udsPath, list, identity, timeoutMs) {
4981
+ const reply = await agentCall(udsPath, { op: "integrations", list: [...list], ...identity ? { identity } : {} }, timeoutMs);
4982
+ const known = reply["known"];
4983
+ return { known: Array.isArray(known) ? known.filter((n) => typeof n === "string") : ["github"] };
4948
4984
  }
4949
- function headHeader(head, name) {
4950
- const line = head.split("\r\n").slice(1).find((l) => l.slice(0, l.indexOf(":")).trim().toLowerCase() === name);
4951
- return line?.slice(line.indexOf(":") + 1).trim();
4985
+ async function startRun(udsPath, id, command, timeoutSec, timeoutMs = 15e3) {
4986
+ return (await agentCall(udsPath, { op: "run", id, command, timeoutSec }, timeoutMs))["started"] === true;
4952
4987
  }
4953
- function rewriteHead(head, drop, add = {}) {
4954
- const [status, ...lines] = head.split("\r\n");
4955
- const kept = lines.filter((l) => !drop(l.slice(0, l.indexOf(":")).trim().toLowerCase()));
4956
- const extra = Object.entries(add).map(([k, v]) => `${k}: ${v}`);
4957
- return Buffer.from(`${[status, ...kept, ...extra].join("\r\n")}${END}`, "latin1");
4988
+ async function runStatus(udsPath, id, timeoutMs) {
4989
+ const reply = await agentCall(udsPath, { op: "runStatus", id }, timeoutMs);
4990
+ const state = reply["state"];
4991
+ if (state !== "running" && state !== "exited" && state !== "timeout" && state !== "unknown") throw new KvboxError("kvbox-agent sent a run state this server does not know");
4992
+ const durationMs = reply["durationMs"];
4993
+ return {
4994
+ state,
4995
+ ...typeof reply["exitCode"] === "number" ? { exitCode: reply["exitCode"] } : {},
4996
+ ...typeof durationMs === "number" && Number.isInteger(durationMs) && durationMs >= 0 ? { durationMs } : {}
4997
+ };
4998
+ }
4999
+ async function runOutput(udsPath, id, stream, offset, limit, timeoutMs = 15e3) {
5000
+ const reply = await agentCall(udsPath, { op: "runOutput", id, stream, offset, limit }, timeoutMs);
5001
+ const { size: size2, data } = reply;
5002
+ if (typeof size2 !== "number" || !Number.isInteger(size2) || size2 < 0 || typeof data !== "string") throw new KvboxError("kvbox-agent sent run output this server does not understand");
5003
+ return { size: size2, offset, data };
4958
5004
  }
4959
-
4960
- // ../shared/src/names.ts
4961
- import { createHmac } from "node:crypto";
4962
- var PROXY_ERROR_HEADER = "x-kvbox-proxy-error";
4963
- var PROXIED_HEADER = "x-kvbox-proxied";
4964
- var VISITOR_PATH_HEADER = "x-kvbox-path";
4965
- var WAKE_HEADER = "x-kvbox-wake";
4966
- var WAKE_WAIT_MS = 3e4;
4967
- var REQUEST_TIMEOUT_MS2 = 36e5;
4968
- var WOKE_HEADER = "x-kvbox-woke";
4969
- var VISITOR_AUTH_HEADER = "x-kvbox-authorization";
4970
- var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
4971
- var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
4972
- var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
4973
- function edgeCredential(hostSecret) {
4974
- return createHmac("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
5005
+ var FREEZE_BASE = "v0.19.0";
5006
+ var FREEZE_TIMEOUT_MS = 2e4;
5007
+ var FREEZE_CONNECT_MS = 3e3;
5008
+ var isAgentRefusal = (err) => /^kvbox-agent: /.test(err.message ?? "");
5009
+ async function freezeDisks(udsPath, disks, thawAfterSec, timeoutMs = FREEZE_TIMEOUT_MS) {
5010
+ const reply = await agentCall(udsPath, { op: "freeze", box: disks.box === true, volumes: [...disks.volumes ?? []], thawAfterSec }, timeoutMs, FREEZE_CONNECT_MS);
5011
+ const frozen = reply["frozen"];
5012
+ return Array.isArray(frozen) ? frozen.filter((m) => typeof m === "string") : [];
4975
5013
  }
4976
- var BOX_LINK_PATH_RE = /^\/machines\/([^/]+)\/link\/(\d{1,5})\/?$/;
4977
- var LINK_PROTOCOL = "kvbox-link";
4978
- var LINK_ERROR_HEADER = "x-kvbox-link-error";
4979
- var BOX_RUN_PATH_RE = /^\/machines\/([^/]+)\/runs(\/[A-Za-z0-9_-]{1,64})?\/?$/;
4980
- function cronCredential(hostSecret) {
4981
- return createHmac("sha256", hostSecret).update("kvbox-cron-v1").digest("base64url");
5014
+ async function thawDisks(udsPath, timeoutMs) {
5015
+ const thawed = (await agentCall(udsPath, { op: "thaw" }, timeoutMs))["thawed"];
5016
+ return Array.isArray(thawed) ? thawed.filter((m) => typeof m === "string") : [];
4982
5017
  }
5018
+ var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
5019
+ var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
5020
+ 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 ?? "");
4983
5021
 
4984
- // src/core/farTunnel.ts
4985
- var FarRefusal = class extends Error {
4986
- constructor(code, message) {
4987
- super(message);
4988
- this.code = code;
4989
- this.name = "FarRefusal";
4990
- }
4991
- code;
4992
- };
4993
- var DIAL_TIMEOUT_MS = 1e4;
4994
- var MAX_HEAD_BYTES = 16 * 1024;
4995
- var MAX_OPEN2 = 256;
4996
- var WARN_EVERY_MS = 6e4;
4997
- var KEEPALIVE_MS = 3e4;
4998
- function splice(a, b) {
4999
- for (const s of [a, b]) {
5000
- s.allowHalfOpen = true;
5001
- s.setKeepAlive(true, KEEPALIVE_MS);
5002
- }
5003
- a.pipe(b);
5004
- b.pipe(a);
5005
- const after = (gone, other) => (hadError) => {
5006
- if (hadError || other.writableFinished || gone.errored) return void other.destroy();
5007
- other.end(() => other.destroy());
5008
- };
5009
- a.once("close", after(a, b));
5010
- b.once("close", after(b, a));
5011
- }
5012
- function connectPinned(url, pin, timeoutMs) {
5013
- const target = new URL(url);
5014
- return new Promise((resolve3, reject) => {
5015
- const socket = tlsConnect({ host: target.hostname, port: Number(target.port || 443), rejectUnauthorized: false, timeout: timeoutMs });
5016
- socket.allowHalfOpen = true;
5017
- socket.once("timeout", () => socket.destroy(new Error(`no answer within ${timeoutMs / 1e3} s`)));
5018
- socket.once("error", reject);
5019
- socket.once("secureConnect", () => {
5020
- if (socket.getPeerCertificate().fingerprint256 !== pin) {
5021
- socket.destroy();
5022
- return reject(new Error("its certificate is not the one the control plane named (fingerprint mismatch)"));
5023
- }
5024
- socket.setTimeout(0);
5025
- socket.off("error", reject);
5026
- socket.on("error", () => socket.destroy());
5027
- resolve3(socket);
5028
- });
5022
+ // src/core/credentials.ts
5023
+ import { request as request3 } from "undici";
5024
+ var TIMEOUT_MS = 1e4;
5025
+ var PROBE_KEPT_MS = 6e4;
5026
+ var unavailable = (message) => ({ ok: false, code: "unavailable", message });
5027
+ async function ask2(cp, body) {
5028
+ const res = await request3(`${cp.url}/hosts/self/integrations/credential`, {
5029
+ method: "POST",
5030
+ headers: { authorization: `Bearer ${cp.secret}`, "content-type": "application/json" },
5031
+ body: JSON.stringify(body),
5032
+ headersTimeout: TIMEOUT_MS,
5033
+ bodyTimeout: TIMEOUT_MS
5029
5034
  });
5035
+ const text = await res.body.text();
5036
+ try {
5037
+ return { status: res.statusCode, json: JSON.parse(text) };
5038
+ } catch {
5039
+ return { status: res.statusCode, json: null };
5040
+ }
5030
5041
  }
5031
- async function ask2(t, method, timeoutMs) {
5032
- const socket = await connectPinned(t.url, t.pin, timeoutMs);
5033
- const slug = t.owner.split("@")[0];
5034
- socket.write(
5035
- `${method} /machines/${encodeURIComponent(t.name)}/link/${t.port} HTTP/1.1\r
5036
- host: ${new URL(t.url).host}\r
5037
- connection: Upgrade\r
5038
- upgrade: ${LINK_PROTOCOL}\r
5039
- authorization: Bearer ${t.key}\r
5040
- x-kvbox-owner: ${slug}\r
5041
- \r
5042
- `
5043
- );
5042
+ async function askCredential(cp, box, integration) {
5043
+ let answer2;
5044
5044
  try {
5045
- return { socket, ...await readHead(socket, { maxBytes: MAX_HEAD_BYTES, timeoutMs }) };
5045
+ answer2 = await ask2(cp, { owner: box.owner, box: box.name, integration });
5046
5046
  } catch (err) {
5047
- socket.destroy();
5048
- throw err;
5047
+ return unavailable(`${cp.name} could not be reached (${err.message}); try again shortly`);
5049
5048
  }
5049
+ if (answer2.status === 404) return unavailable(`${cp.name} has no integrations yet`);
5050
+ const parsed = CredentialAnswerSchema.safeParse(answer2.json);
5051
+ if (!parsed.success) return unavailable(`${cp.name} answered ${answer2.status}; try again shortly`);
5052
+ return parsed.data;
5050
5053
  }
5051
- var refusal2 = (head) => {
5052
- const code = headHeader(head, LINK_ERROR_HEADER);
5053
- return new FarRefusal(code === "gone" || code === "down" || code === "unreachable" ? code : "refused", `the other host answered ${headStatus(head) ?? "nothing it should"}${code ? ` (${code})` : ""}`);
5054
- };
5055
- async function dialFar(t, timeoutMs = DIAL_TIMEOUT_MS) {
5056
- const { socket, head, rest } = await ask2(t, "GET", timeoutMs);
5057
- if (headStatus(head) === 101) return { socket, rest };
5058
- socket.destroy();
5059
- throw refusal2(head);
5060
- }
5061
- async function dropFar(t, timeoutMs = DIAL_TIMEOUT_MS) {
5062
- const { socket, head } = await ask2(t, "DELETE", timeoutMs);
5063
- socket.destroy();
5064
- if (headStatus(head) === 200) return;
5065
- const refused = refusal2(head);
5066
- if (refused.code !== "gone") throw refused;
5054
+ var probes = /* @__PURE__ */ new Map();
5055
+ async function probeConnection(cp, box, integration, now = Date.now()) {
5056
+ const key = `${box.owner}/${box.name}/${integration}`;
5057
+ const kept = probes.get(key);
5058
+ if (kept && now - kept.at < PROBE_KEPT_MS) return kept.answer;
5059
+ try {
5060
+ const parsed = ConnectedAnswerSchema.safeParse((await ask2(cp, { owner: box.owner, box: box.name, integration, probe: true })).json);
5061
+ if (!parsed.success) return null;
5062
+ probes.set(key, { at: now, answer: parsed.data });
5063
+ if (probes.size > 5e3) {
5064
+ for (const [k, v] of probes) if (now - v.at >= PROBE_KEPT_MS) probes.delete(k);
5065
+ }
5066
+ return parsed.data;
5067
+ } catch {
5068
+ return null;
5069
+ }
5067
5070
  }
5068
- var sameTarget = (a, b) => a.owner === b.owner && a.name === b.name && a.port === b.port && a.url === b.url && a.pin === b.pin && a.key === b.key;
5071
+
5072
+ // src/core/guestRequests.ts
5073
+ import { rm as rm5 } from "node:fs/promises";
5074
+ import { createServer as createServer2 } from "node:net";
5075
+ var MAX_REQUEST_BYTES = 4096;
5076
+ var REQUEST_TIMEOUT_MS2 = 5e3;
5077
+ var MAX_OPEN2 = 32;
5069
5078
  var listeners2 = /* @__PURE__ */ new Map();
5070
- async function listenFar(id, opts) {
5071
- const have = listeners2.get(id);
5072
- if (have && sameTarget(have.target, opts.target)) return have.port;
5073
- if (have) await closeFar(id);
5074
- const open4 = /* @__PURE__ */ new Set();
5075
- const track = (s) => {
5076
- open4.add(s);
5077
- s.once("close", () => open4.delete(s));
5079
+ var unreadable = (message) => ({ ok: false, code: "unavailable", message });
5080
+ function serve(sock, answer2, timeoutMs) {
5081
+ let buf = "";
5082
+ let taken = false;
5083
+ const reply = (body) => {
5084
+ if (!sock.destroyed) sock.end(JSON.stringify(body) + "\n");
5078
5085
  };
5079
- let warnedAt = 0;
5080
- const server = createServer2({ allowHalfOpen: true }, (box) => {
5081
- track(box);
5082
- box.on("error", () => box.destroy());
5083
- if (box.remoteAddress !== opts.fromIp) return void box.destroy();
5084
- dialFar(opts.target, opts.dialTimeoutMs).then(
5085
- ({ socket, rest }) => {
5086
- if (box.destroyed) return void socket.destroy();
5087
- track(socket);
5088
- if (rest.length > 0) box.write(rest);
5089
- splice(box, socket);
5090
- },
5091
- (err) => {
5092
- box.destroy();
5093
- if (err instanceof FarRefusal && err.code === "gone") return opts.onGone?.();
5094
- if (err instanceof FarRefusal && err.code !== "refused") return;
5095
- if (Date.now() - warnedAt < WARN_EVERY_MS) return;
5096
- warnedAt = Date.now();
5097
- log.warn(`link to ${opts.target.name} port ${opts.target.port} on another host: ${err.message}`);
5098
- }
5099
- );
5086
+ const late = setTimeout(() => sock.destroy(), timeoutMs);
5087
+ late.unref();
5088
+ sock.once("close", () => clearTimeout(late));
5089
+ sock.on("error", () => void 0);
5090
+ sock.on("data", (chunk) => {
5091
+ if (taken) return;
5092
+ buf += chunk.toString("utf8");
5093
+ const nl = buf.indexOf("\n");
5094
+ if (nl === -1) {
5095
+ if (buf.length > MAX_REQUEST_BYTES) sock.destroy();
5096
+ return;
5097
+ }
5098
+ taken = true;
5099
+ clearTimeout(late);
5100
+ let request8;
5101
+ try {
5102
+ request8 = JSON.parse(buf.slice(0, nl));
5103
+ } catch {
5104
+ return reply(unreadable("the request is not JSON"));
5105
+ }
5106
+ answer2(request8).then(reply, (err) => reply(unreadable(err.message)));
5107
+ });
5108
+ }
5109
+ async function listenGuest(path, answer2, timeoutMs = REQUEST_TIMEOUT_MS2) {
5110
+ await closeGuest(path);
5111
+ await rm5(path, { force: true });
5112
+ const open4 = /* @__PURE__ */ new Set();
5113
+ const server = createServer2((sock) => {
5114
+ open4.add(sock);
5115
+ sock.once("close", () => open4.delete(sock));
5116
+ serve(sock, answer2, timeoutMs);
5100
5117
  });
5101
5118
  server.maxConnections = MAX_OPEN2;
5102
5119
  await new Promise((resolve3, reject) => {
5103
5120
  server.once("error", reject);
5104
- server.listen(0, opts.host, () => {
5121
+ server.listen(path, () => {
5105
5122
  server.off("error", reject);
5106
5123
  resolve3();
5107
5124
  });
5108
5125
  });
5109
5126
  server.unref();
5110
5127
  server.on("error", () => void 0);
5111
- const port = server.address().port;
5112
- listeners2.set(id, { server, open: open4, port, target: { ...opts.target } });
5113
- return port;
5128
+ listeners2.set(path, { server, open: open4 });
5114
5129
  }
5115
- async function closeFar(id) {
5116
- const l = listeners2.get(id);
5130
+ async function closeGuest(path) {
5131
+ const l = listeners2.get(path);
5117
5132
  if (!l) return;
5118
- listeners2.delete(id);
5133
+ listeners2.delete(path);
5119
5134
  for (const sock of l.open) sock.destroy();
5120
5135
  await new Promise((resolve3) => l.server.close(() => resolve3()));
5136
+ await rm5(path, { force: true });
5137
+ }
5138
+ var guestListening = (path) => listeners2.has(path);
5139
+
5140
+ // src/core/machines/integrations.ts
5141
+ var AGENT_REPLY_MS = 2e4;
5142
+ function socketOf(box, p) {
5143
+ try {
5144
+ return driver().vm.guestSocket(box, GUEST_REQUEST_PORT, p);
5145
+ } catch (err) {
5146
+ if (err instanceof NotImplementedError) return void 0;
5147
+ throw err;
5148
+ }
5149
+ }
5150
+ async function listenForGuest(box, p) {
5151
+ const ref = { owner: box.owner, name: box.name };
5152
+ try {
5153
+ const path = socketOf(box, p);
5154
+ if (path !== void 0) await listenGuest(path, (request8) => answerGuest(ref, request8, p));
5155
+ } catch (err) {
5156
+ log.warn(`box ${shown(ref)}: integrations will not answer in it: ${err.message}`);
5157
+ }
5158
+ }
5159
+ async function stopListeningForGuest(box, p) {
5160
+ try {
5161
+ const path = socketOf(box, p);
5162
+ if (path !== void 0) await closeGuest(path);
5163
+ } catch {
5164
+ }
5165
+ }
5166
+ async function listenForRunning(p) {
5167
+ for (const listed of await readAllMeta(p)) {
5168
+ if (!vmAlive(listed)) continue;
5169
+ await withBoxLock(listed, async () => {
5170
+ const meta = await readMachineMeta(listed, p).catch(() => null);
5171
+ if (meta !== null && vmAlive(meta)) await listenForGuest(meta, p);
5172
+ });
5173
+ }
5174
+ }
5175
+ async function closeDeadListeners(p) {
5176
+ for (const meta of await readAllMeta(p)) {
5177
+ if (vmAlive(meta)) continue;
5178
+ const path = socketOf(meta, p);
5179
+ if (path === void 0 || !guestListening(path)) continue;
5180
+ await withBoxLock(meta, async () => {
5181
+ const now = await readMachineMeta(meta, p).catch(() => null);
5182
+ if (now === null || !vmAlive(now)) await stopListeningForGuest(meta, p);
5183
+ });
5184
+ }
5121
5185
  }
5122
-
5123
- // src/core/machines/farTargets.ts
5124
- var listenerId = (boxId, t) => `${boxId}|${t.owner}/${t.name}:${t.port}`;
5125
- var sameTarget2 = (to, port) => (t) => t.owner === to.owner && t.name === to.name && t.port === port;
5126
- function targetRef(req, caller) {
5127
- if (req.toOwner !== void 0) return { owner: ownerFor(req.toOwner, caller), name: req.to, display: `${req.toOwner}/${req.to}` };
5128
- return parseRef(req.to, caller);
5186
+ function forgetGuest(box) {
5187
+ asked.delete(refKey(box));
5188
+ told.delete(box.id);
5129
5189
  }
5130
- async function open(meta, t, cfg, p) {
5131
- const ref = { owner: meta.owner, name: meta.name };
5132
- const via = await listenFar(listenerId(meta.id, t), {
5133
- host: driver().net.farListenHost(cfg),
5134
- fromIp: meta.ip,
5135
- target: t,
5136
- // The listener was made under the box's lock, and its connections would read as holding it: the forget
5137
- // waits for the lock like any other change of the box.
5138
- onGone: () => outsideLocks(() => void forgetFarTarget(ref, t, p).catch((err) => log.warn(`box ${meta.name}: could not forget its link to ${t.name}: ${err.message}`)))
5139
- });
5140
- await driver().net.openFarLink({ box: meta.id, fromIp: meta.ip, standIn: t.ip, port: t.port, via }, cfg);
5190
+ var refusal2 = (code, message, connected) => ({ ok: false, code, message, ...connected === void 0 ? {} : { connected } });
5191
+ var asked = /* @__PURE__ */ new Map();
5192
+ function withinLimit(box, now) {
5193
+ const w = asked.get(box);
5194
+ if (!w || now - w.since >= 6e4) {
5195
+ asked.set(box, { since: now, count: 1 });
5196
+ return true;
5197
+ }
5198
+ w.count += 1;
5199
+ return w.count <= GUEST_REQUESTS_PER_MINUTE;
5141
5200
  }
5142
- async function close(meta, t, cfg) {
5201
+ async function answerGuest(ref, request8, p, now = Date.now()) {
5202
+ if (!withinLimit(refKey(ref), now)) return refusal2("unavailable", `this box asked more than ${GUEST_REQUESTS_PER_MINUTE} times in a minute; try again shortly`);
5203
+ const parsed = GuestRequestSchema.safeParse(request8);
5204
+ if (!parsed.success) return refusal2("unavailable", "this host does not know that request; it may need updating");
5205
+ const integration = parsed.data.integration;
5206
+ let meta;
5143
5207
  try {
5144
- await driver().net.closeFarLink({ box: meta.id, fromIp: meta.ip, standIn: t.ip, port: t.port }, cfg);
5145
- } finally {
5146
- await closeFar(listenerId(meta.id, t));
5208
+ meta = await readMachineMeta(ref, p);
5209
+ } catch {
5210
+ return refusal2("unavailable", "this box is being removed");
5147
5211
  }
5148
- }
5149
- async function openFarTargets(meta, cfg, p) {
5150
- for (const t of meta.farTargets ?? []) {
5151
- await open(meta, t, cfg, p).catch((err) => log.warn(`box ${meta.name} cannot reach ${t.name} port ${t.port} on another host: ${err.message}`));
5212
+ const cp = (await loadConfig(p)).controlPlane;
5213
+ if (!cp || !isCloudBox(meta.owner)) return refusal2("unavailable", "integrations are not available in a box made on the host itself");
5214
+ if (!(meta.integrations ?? []).includes(integration)) {
5215
+ const probe = await probeConnection(cp, meta, integration, now);
5216
+ return refusal2("off", `${integration} is not turned on for this box`, probe?.connected);
5152
5217
  }
5153
- }
5154
- async function closeFarTargets(meta, cfg) {
5155
- for (const t of meta.farTargets ?? []) {
5156
- await close(meta, t, cfg).catch((err) => log.warn(`could not close box ${meta.name}'s link to ${t.name} on another host: ${err.message}`));
5218
+ const answer2 = await askCredential(cp, meta, integration);
5219
+ if (answer2.ok && answer2.identity && !(told.has(meta.id) && sameIdentity(told.get(meta.id), answer2.identity))) {
5220
+ void tellCurrent(ref, p.machine(meta.owner, meta.name).vsock, p, answer2.identity).catch(() => void 0);
5157
5221
  }
5222
+ return answer2;
5158
5223
  }
5159
- async function reopenFarTargets(p = paths()) {
5160
- const cfg = await loadConfig(p);
5161
- for (const listed of await readAllMeta(p)) {
5162
- if (!vmAlive(listed) || !listed.farTargets?.length) continue;
5163
- await withBoxLock(listed, async () => {
5164
- const meta = await readMachineMeta(listed, p).catch(() => null);
5165
- if (meta !== null && vmAlive(meta)) await openFarTargets(meta, cfg, p);
5224
+ var told = /* @__PURE__ */ new Map();
5225
+ var sameIdentity = (a, b) => a?.name === b?.name && a?.email === b?.email;
5226
+ async function tellGuest(box, vsock, identity) {
5227
+ const { known } = await setIntegrations(vsock, box.integrations ?? [], identity, AGENT_REPLY_MS);
5228
+ told.set(box.id, identity);
5229
+ return (box.integrations ?? []).filter((n) => !known.includes(n));
5230
+ }
5231
+ var tooOldFor = (box, names2) => `its image is from before base v${names2.map((n) => INTEGRATION_BASES[n] ?? INTEGRATIONS_BASE).sort().at(-1)}, which cannot use ${names2.join(", ")} (kvbox vm update ${shown(box)} moves it onto the current one)`;
5232
+ async function identityOf(box, p) {
5233
+ if (!(box.integrations ?? []).includes("github")) return void 0;
5234
+ const cp = (await loadConfig(p)).controlPlane;
5235
+ if (!cp) return void 0;
5236
+ const probe = await probeConnection(cp, box, "github");
5237
+ if (probe !== null) return probe.identity;
5238
+ return told.has(box.id) ? told.get(box.id) : null;
5239
+ }
5240
+ var sameList = (a, b) => JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
5241
+ async function tellCurrent(ref, vsock, p, identity) {
5242
+ for (; ; ) {
5243
+ const asked3 = await readMachineMeta(ref, p);
5244
+ const who = identity !== void 0 && (asked3.integrations ?? []).includes("github") ? identity : await identityOf(asked3, p);
5245
+ if (who === null) return false;
5246
+ const done = await withBoxLock(ref, async () => {
5247
+ const box = await readMachineMeta(ref, p);
5248
+ if (!sameList(box.integrations, asked3.integrations)) return false;
5249
+ const unusable = await tellGuest(box, vsock, who);
5250
+ if (unusable.length > 0) log.warn(`box ${shown(box)} has integrations it cannot use: ${tooOldFor(box, unusable)}`);
5251
+ return true;
5166
5252
  });
5253
+ if (done) return true;
5167
5254
  }
5168
5255
  }
5169
- var addFarTarget = locked(async function addFarTarget2(ref, req, caller, p = paths()) {
5170
- const meta = await readMeta(ref, p);
5171
- const to = targetRef(req, caller);
5172
- if (realmOf(meta.owner) === null || realmOf(to.owner) !== realmOf(meta.owner)) {
5173
- throw new KvboxError(`a link to a box on another host joins two boxes of one control plane; box ${shown(ref)} and box ${shown(to)} are not`);
5256
+ function assertImageCanUse(box, list, before) {
5257
+ if (box.image !== void 0) return;
5258
+ const unusable = unusableOnBase(box.base, (list ?? []).filter((n) => !(before ?? []).includes(n)));
5259
+ if (unusable.length > 0) throw new KvboxError(`box ${shown(box)} cannot use ${unusable.join(", ")} yet: ${tooOldFor(box, unusable)}`);
5260
+ }
5261
+ var outdated = (box) => `its image is from before base v${INTEGRATIONS_BASE}, which has no integrations (kvbox vm update ${shown(box)} moves it onto the current one)`;
5262
+ async function applyIntegrations(box, vsock, p, before) {
5263
+ if (!isCloudBox(box.owner)) return;
5264
+ let unusable;
5265
+ try {
5266
+ const prior = told.has(box.id) ? { who: told.get(box.id) } : null;
5267
+ const who = await identityOf(box, p);
5268
+ unusable = await tellGuest(box, vsock, who ?? void 0);
5269
+ let unsure = who === null;
5270
+ if (unusable.length > 0) {
5271
+ if (prior) told.set(box.id, prior.who);
5272
+ else told.delete(box.id);
5273
+ const kept = { ...box, integrations: before && before.length > 0 ? [...before] : void 0 };
5274
+ const keptWho = await identityOf(kept, p);
5275
+ unsure = keptWho === null;
5276
+ await tellGuest(kept, vsock, keptWho ?? void 0).catch(() => unsure = true);
5277
+ }
5278
+ if (unsure) {
5279
+ told.delete(box.id);
5280
+ if (box.pid !== null) void tellIntegrationsWhenUp(box, box.pid, vsock, p);
5281
+ }
5282
+ } catch (err) {
5283
+ if (!isUnknownOp(err)) return void log.warn(`box ${shown(box)} was not told its integrations: ${err.message}`);
5284
+ if ((box.integrations ?? []).length > 0) throw new KvboxError(`box ${shown(box)} cannot use integrations yet: ${outdated(box)}`);
5285
+ return;
5174
5286
  }
5175
- const cfg = await loadConfig(p);
5176
- const same = sameTarget2(to, req.port);
5177
- const before = (meta.farTargets ?? []).find(same);
5178
- const kept = (meta.farTargets ?? []).filter((t) => !same(t));
5179
- if (kept.length >= MAX_BOX_LINKS) throw new KvboxError(`a box reaches at most ${MAX_BOX_LINKS} ports of boxes on other hosts; box ${shown(ref)} has ${kept.length}`);
5180
- return withHostLock("links", async () => {
5181
- const taken = (await readAllMeta(p)).flatMap((m) => m.farTargets ?? []);
5182
- const ip = taken.find((t) => t.owner === to.owner && t.name === to.name)?.ip ?? driver().net.standIn(cfg, taken.map((t) => t.ip));
5183
- const entry = { owner: to.owner, name: to.name, port: req.port, ip, url: req.url, pin: req.pin, key: req.key };
5184
- const next = { ...meta, farTargets: [...kept, entry] };
5185
- if (before) await close(meta, before, cfg);
5186
- await writeMachineMeta(next, p);
5187
- boxListChanged();
5188
- if (vmAlive(meta)) {
5287
+ if (unusable.length > 0) throw new KvboxError(`box ${shown(box)} cannot use ${unusable.join(", ")} yet: ${tooOldFor(box, unusable)}`);
5288
+ }
5289
+ var BOOT_WAIT_MS = 12e4;
5290
+ var WHO_RETRY_MS = 3e3;
5291
+ function tellIntegrationsWhenUp(ref, pid, vsock, p, timing = { waitMs: BOOT_WAIT_MS }) {
5292
+ return outsideLocks(async () => {
5293
+ if (!isCloudBox(ref.owner)) return;
5294
+ const deadline = Date.now() + timing.waitMs;
5295
+ for (; ; ) {
5296
+ if (!pidAlive(pid)) return;
5189
5297
  try {
5190
- await open(next, entry, cfg, p);
5298
+ if (await tellCurrent(ref, vsock, p)) return;
5299
+ if (Date.now() >= deadline) return void log.warn(`box ${shown(ref)} was not told who commits in it: the control plane could not be asked`);
5300
+ await sleep3(timing.retryMs ?? WHO_RETRY_MS);
5191
5301
  } catch (err) {
5192
- await close(next, entry, cfg).catch(() => void 0);
5193
- await writeMachineMeta(meta, p);
5194
- boxListChanged();
5195
- if (before && vmAlive(meta)) await open(meta, before, cfg, p).catch((e) => log.warn(`box ${meta.name} cannot reach ${before.name} port ${before.port} on another host: ${e.message}`));
5196
- throw err;
5302
+ if (!pidAlive(pid)) return;
5303
+ if (isNoAgent(err) && Date.now() < deadline) {
5304
+ await sleep3(500);
5305
+ continue;
5306
+ }
5307
+ const box = await readMachineMeta(ref, p).catch(() => null);
5308
+ if (box === null) return;
5309
+ if (!isUnknownOp(err)) log.warn(`box ${shown(ref)} was not told its integrations: ${err.message}`);
5310
+ else if ((box.integrations ?? []).length > 0) log.warn(`box ${shown(ref)} has integrations it cannot use: ${outdated(ref)}`);
5311
+ return;
5197
5312
  }
5198
5313
  }
5199
- return toMachine(next, p);
5200
- });
5201
- });
5202
- var removeFarTarget = locked(async function removeFarTarget2(ref, req, caller, p = paths()) {
5203
- const meta = await readMeta(ref, p);
5204
- const same = sameTarget2(targetRef(req, caller), req.port);
5205
- const gone = (meta.farTargets ?? []).filter(same);
5206
- if (gone.length === 0) return toMachine(meta, p);
5207
- return toMachine(await without(meta, gone, p), p);
5208
- });
5209
- async function without(meta, gone, p) {
5210
- const cfg = await loadConfig(p);
5211
- for (const t of gone) await close(meta, t, cfg);
5212
- const kept = (meta.farTargets ?? []).filter((t) => !gone.includes(t));
5213
- const next = { ...meta, farTargets: kept.length > 0 ? kept : void 0 };
5214
- await writeMachineMeta(next, p);
5215
- boxListChanged();
5216
- return next;
5314
+ }).catch(() => void 0);
5217
5315
  }
5218
- var forgetFarTarget = locked(async function forgetFarTarget2(ref, t, p) {
5219
- const meta = await readMachineMeta(ref, p).catch(() => null);
5220
- const gone = (meta?.farTargets ?? []).filter((now) => now.owner === t.owner && now.name === t.name && now.port === t.port && now.key === t.key);
5221
- if (meta === null || gone.length === 0) return;
5222
- await without(meta, gone, p);
5223
- log.info(`box ${meta.name}: its link to ${t.name} port ${t.port} no longer exists on the other host; forgotten here`);
5224
- });
5225
- function tellFarTargetsGone(gone) {
5226
- for (const t of gone.farTargets ?? []) {
5227
- void dropFar(t).catch((err) => log.warn(`removed box ${gone.name}: its link into ${t.name} on another host stays listed there (${err.message})`));
5316
+
5317
+ // src/core/machines/boot.ts
5318
+ async function launch(spec, nic, cfg, pubkeyB64, p) {
5319
+ const root = imageFileFor(spec, p);
5320
+ const kernel = kernelFor(await imageManifest(root), cfg, p);
5321
+ const volumes = (await placeVolumeDrives(spec, p)).map((v) => ({ id: volumeDriveId(v.name), path: volumeDriveRel(v.name) }));
5322
+ return withGuestListener(spec, p, () => driver().vm.boot(spec, { kernel, root, volumes, pubkeyB64 }, nic, cfg, p));
5323
+ }
5324
+ async function loadSnapshot(spec, image, nic, cfg, p) {
5325
+ return withGuestListener(spec, p, () => driver().vm.restore(spec, { vmstate: image.vmstate, mem: image.mem }, nic, cfg, p));
5326
+ }
5327
+ async function withGuestListener(box, p, bringUp) {
5328
+ await listenForGuest(box, p);
5329
+ try {
5330
+ return await bringUp();
5331
+ } catch (err) {
5332
+ await stopListeningForGuest(box, p);
5333
+ throw err;
5334
+ }
5335
+ }
5336
+ async function resumeVm(box, p) {
5337
+ await driver().vm.resume(box, p);
5338
+ }
5339
+
5340
+ // src/core/machines/guest.ts
5341
+ import { setTimeout as sleep4 } from "node:timers/promises";
5342
+ function prefixLenOf(subnet) {
5343
+ return Number(subnet.split("/")[1]);
5344
+ }
5345
+ var AGENT_REPLY_MS2 = 2e4;
5346
+ async function introduce(spec, vsock, cfg, failure2) {
5347
+ const id = { name: spec.name, ip: spec.ip, prefixLen: prefixLenOf(cfg.subnet), gateway: cfg.gateway, mac: spec.mac, time: Math.floor(Date.now() / 1e3) };
5348
+ const deadline = Date.now() + 3e3;
5349
+ for (; ; ) {
5350
+ try {
5351
+ await setIdentity(vsock, id, AGENT_REPLY_MS2);
5352
+ return;
5353
+ } catch (err) {
5354
+ const msg = err.message;
5355
+ const transient = /unreachable|refused|before the guest accepted/.test(msg);
5356
+ if (transient && Date.now() < deadline) {
5357
+ await sleep4(100);
5358
+ continue;
5359
+ }
5360
+ if (transient) throw new KvboxError(`${msg}
5361
+ ${failure2.silent}`);
5362
+ throw new KvboxError(`${msg}
5363
+ ${failure2.noAnswer}`);
5364
+ }
5365
+ }
5366
+ }
5367
+ async function dropGuestVolumes(box, vsock) {
5368
+ try {
5369
+ await dropVolumes(vsock, AGENT_REPLY_MS2);
5370
+ } catch (err) {
5371
+ const why = isUnknownOp(err) ? `its image predates base v0.9.0, whose kvbox-agent can unmount them (kvbox vm update ${shown(box)} moves it onto the current base)` : err.message;
5372
+ log.warn(`box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);
5228
5373
  }
5229
5374
  }
5230
-
5231
- // src/core/machines/ports.ts
5232
- var publicPortsInUse = (metas) => metas.flatMap((m) => [...m.sshPort === void 0 ? [] : [m.sshPort], ...(m.ports ?? []).map((f) => f.hostPort)]);
5233
- var reaching = (meta) => meta.farTargets?.length && meta.owner !== void 0 && meta.name !== void 0 ? { ...meta, owner: meta.owner, name: meta.name } : null;
5234
- function boxProxies(meta) {
5235
- const ssh = meta.sshPort === void 0 ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];
5236
- 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 }))];
5375
+ async function pushEnv(box, vsock, p) {
5376
+ const vars = await envForBoot(box, p);
5377
+ if (vars === null) return;
5378
+ try {
5379
+ await setEnv(vsock, vars, AGENT_REPLY_MS2);
5380
+ } catch (err) {
5381
+ warnEnv(box, vars, err);
5382
+ }
5237
5383
  }
5238
- function boxLinks(meta) {
5239
- return (meta.links ?? []).map((l) => ({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }));
5384
+ function warnEnv(box, vars, err) {
5385
+ if (isUnknownOp(err)) {
5386
+ if (vars.length === 0) return;
5387
+ log.warn(`box ${shown(box)} did not get its environment variables: its image predates base v0.10.0, whose kvbox-agent takes them (kvbox vm update ${shown(box)} moves it onto the current base)`);
5388
+ return;
5389
+ }
5390
+ log.warn(`box ${shown(box)} did not get its environment variables: ${err.message}`);
5240
5391
  }
5241
- async function standingLinks(meta, p) {
5242
- const links = boxLinks(meta);
5243
- const stands = await Promise.all(
5244
- (meta.links ?? []).map(async (l) => !l.stale && (await readMachineMeta({ owner: l.owner, name: l.name }, p).catch(() => null))?.ip === l.ip)
5245
- );
5246
- return links.filter((_, i) => stands[i]);
5392
+ var ENV_BOOT_WAIT_MS = 12e4;
5393
+ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS2, waitMs: ENV_BOOT_WAIT_MS }) {
5394
+ return (async () => {
5395
+ const deadline = Date.now() + timing.waitMs;
5396
+ for (; ; ) {
5397
+ if (!pidAlive(pid)) return;
5398
+ const vars = await envForBoot(box, p);
5399
+ if (vars === null) return;
5400
+ try {
5401
+ await setEnv(vsock, vars, timing.replyMs);
5402
+ return;
5403
+ } catch (err) {
5404
+ if (!pidAlive(pid)) return;
5405
+ if (isNoAgent(err) && Date.now() < deadline) {
5406
+ await sleep4(500);
5407
+ continue;
5408
+ }
5409
+ warnEnv(box, vars, err);
5410
+ return;
5411
+ }
5412
+ }
5413
+ })();
5247
5414
  }
5248
- async function openPorts(meta, cfg, p) {
5249
- for (const proxy of boxProxies(meta)) await driver().net.openProxy(proxy, cfg);
5250
- for (const link4 of await standingLinks(meta, p)) {
5251
- await driver().net.openLink(link4, cfg).catch((err) => log.warn(`could not open the link from ${link4.fromIp}: ${err.message}`));
5415
+
5416
+ // ../shared/src/ssh.ts
5417
+ import { createHash as createHash3 } from "node:crypto";
5418
+ var SSH_PUBLIC_KEY_RE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com) ([A-Za-z0-9+/]+=*)(?: [^\r\n]*)?$/;
5419
+ function parseSshPublicKey(text) {
5420
+ const key = text.trim().replace(/^cert-authority\s+/, "");
5421
+ if (!SSH_PUBLIC_KEY_RE.test(key)) {
5422
+ throw new KvboxError("that is not an SSH public key; expected one line like: ssh-ed25519 AAAA\u2026 kvbox-ca@kvbox.sh");
5252
5423
  }
5253
- const far = reaching(meta);
5254
- if (far) await openFarTargets(far, cfg, p);
5255
- await joinCluster2(meta, cfg);
5424
+ return key;
5256
5425
  }
5257
- async function closePorts(meta, cfg) {
5258
- for (const proxy of boxProxies(meta)) {
5259
- await driver().net.closeProxy(proxy, cfg).catch((err) => log.warn(`could not close port ${proxy.hostPort}: ${err.message}`));
5260
- }
5261
- for (const link4 of boxLinks(meta)) {
5262
- await driver().net.closeLink(link4, cfg).catch((err) => log.warn(`could not close the link from ${link4.fromIp}: ${err.message}`));
5263
- }
5264
- const far = reaching(meta);
5265
- if (far) await closeFarTargets(far, cfg);
5266
- await leaveCluster2(meta, cfg);
5426
+ function sshKeyFingerprint(publicKey) {
5427
+ const m = SSH_PUBLIC_KEY_RE.exec(publicKey.trim());
5428
+ if (!m) throw new KvboxError("cannot fingerprint: not an SSH public key");
5429
+ return `SHA256:${createHash3("sha256").update(Buffer.from(m[2], "base64")).digest("base64").replace(/=+$/, "")}`;
5267
5430
  }
5268
- var reservedPorts = /* @__PURE__ */ new Set();
5269
- async function drawPorts(count, p) {
5270
- return withHostLock("ports", async () => {
5271
- const reserved = [...reservedPorts];
5272
- const taken = /* @__PURE__ */ new Set([...reserved, ...publicPortsInUse(await readAllMeta(p)), ...await driver().net.listeningPorts()]);
5273
- const ports = [];
5274
- for (let i = 0; i < count; i++) {
5275
- const port = pickSshPort(taken);
5276
- taken.add(port);
5277
- ports.push(port);
5278
- }
5279
- for (const port of ports) reservedPorts.add(port);
5280
- return { ports, release: () => ports.forEach((port) => reservedPorts.delete(port)) };
5281
- });
5431
+ function caLineFor(principal, caPublicKey) {
5432
+ return `cert-authority,principals="${principal}" ${caPublicKey}`;
5282
5433
  }
5283
- var portKeys = (req) => {
5284
- const keys = req.ports.map((x) => ({ guestPort: x.guestPort, proto: x.proto ?? "tcp" }));
5285
- return keys.filter((k, i) => keys.findIndex((o) => o.guestPort === k.guestPort && o.proto === k.proto) === i);
5286
- };
5287
- var samePort = (a) => (b) => a.guestPort === b.guestPort && a.proto === b.proto;
5288
- var addPorts = locked(async function addPorts2(ref, req, p = paths()) {
5289
- const meta = await readMeta(ref, p);
5290
- const cfg = await loadConfig(p);
5291
- const current2 = meta.ports ?? [];
5292
- const wanted = portKeys(req);
5293
- const isClosed = (k) => current2.some((f) => samePort(k)(f) && f.closed);
5294
- const reopened = wanted.filter(isClosed);
5295
- const fresh = wanted.filter((w) => !current2.some(samePort(w)));
5296
- const already = wanted.find((w) => current2.some(samePort(w)) && !isClosed(w));
5297
- if (already) throw new KvboxError(`box ${shown(ref)} already publishes port ${already.guestPort} (${already.proto})`);
5298
- if (meta.sshPort !== void 0 && wanted.some(samePort({ guestPort: 22, proto: "tcp" }))) {
5299
- throw new KvboxError(`box ${shown(ref)} already reaches port 22 from outside on port ${meta.sshPort} (kvbox connect)`);
5434
+ var isCaLine = (line) => /^cert-authority(,|\s)/.test(line.trim());
5435
+
5436
+ // src/core/machines/keys.ts
5437
+ var MAX_SSH_KEY_LINES = 8;
5438
+ var MAX_SSH_KEYS_B64 = 1500;
5439
+ function authorizedKeysLines(hostKey, extra) {
5440
+ const lines = [hostKey.trim(), ...extra.map((l) => l.trim())];
5441
+ if (lines.some((l) => l === "" || /[\r\n]/.test(l))) throw new KvboxError("sshKeys: every entry must be one non-empty authorized_keys line");
5442
+ if (lines.length > MAX_SSH_KEY_LINES) {
5443
+ throw new KvboxError(`a box takes at most ${MAX_SSH_KEY_LINES - 1} SSH keys on top of the host's own; ${extra.length} were given`);
5300
5444
  }
5301
- if (current2.length + fresh.length > MAX_BOX_PORTS) {
5302
- throw new KvboxError(`a box publishes at most ${MAX_BOX_PORTS} ports; box ${shown(ref)} has ${current2.length}`);
5445
+ return lines;
5446
+ }
5447
+ function authorizedKeysB64(hostKey, extra) {
5448
+ const lines = authorizedKeysLines(hostKey, extra);
5449
+ const b64 = Buffer.from(lines.join("\n") + "\n").toString("base64");
5450
+ if (b64.length > MAX_SSH_KEYS_B64) {
5451
+ throw new KvboxError(`the SSH keys for this box do not fit the kernel command line (${b64.length} bytes encoded, ${MAX_SSH_KEYS_B64} at most); use fewer or shorter keys`);
5303
5452
  }
5304
- const drawn = await drawPorts(fresh.length, p);
5305
- const opened = [];
5453
+ return b64;
5454
+ }
5455
+ async function pushAuthorizedKeys(box, vsock, p) {
5306
5456
  try {
5307
- const added = fresh.map((w, i) => ({ ...w, hostPort: drawn.ports[i] }));
5308
- const open4 = ({ closed: _closed, ...f }) => f;
5309
- const again = current2.filter((f) => reopened.some(samePort(f))).map(open4);
5310
- if (vmAlive(meta)) {
5311
- for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: [...again, ...added] })) {
5312
- await driver().net.openProxy(proxy, cfg);
5313
- opened.push(proxy);
5314
- }
5315
- }
5316
- const next = { ...meta, ports: [...current2.map((f) => reopened.some(samePort(f)) ? open4(f) : f), ...added] };
5317
- await writeMachineMeta(next, p);
5318
- return toMachine(next, p);
5457
+ await setAuthorizedKeys(vsock, authorizedKeysLines(await readHostPubkey(p), box.sshKeys ?? []), AGENT_REPLY_MS2);
5458
+ return void 0;
5319
5459
  } catch (err) {
5320
- for (const proxy of opened) await driver().net.closeProxy(proxy, cfg).catch(() => void 0);
5321
- throw err;
5322
- } finally {
5323
- drawn.release();
5460
+ const why = isUnknownOp(err) ? `its image predates base v0.6.0, whose kvbox-agent can replace authorized_keys (kvbox vm update ${shown(box)} moves it onto the current base)` : err.message;
5461
+ log.warn(`box ${shown(box)} keeps the authorized_keys it was frozen with: ${why}`);
5462
+ return why;
5324
5463
  }
5325
- });
5326
- var removePorts = locked(async function removePorts2(ref, req, p = paths()) {
5464
+ }
5465
+ var setSshKeys = locked(async function setSshKeys2(ref, sshKeys, p = paths()) {
5327
5466
  const meta = await readMeta(ref, p);
5328
- const cfg = await loadConfig(p);
5329
- const current2 = meta.ports ?? [];
5330
- const gone = portKeys(req);
5331
- const missing = gone.find((g) => !current2.some(samePort(g)));
5332
- if (missing) throw new KvboxError(`box ${shown(ref)} does not publish port ${missing.guestPort} (${missing.proto})`);
5333
- const removed = current2.filter((f) => gone.some(samePort(f)));
5334
- for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: removed })) await driver().net.closeProxy(proxy, cfg);
5335
- const kept = req.keep ? current2.map((f) => gone.some(samePort(f)) ? { ...f, closed: true } : f) : current2.filter((f) => !gone.some(samePort(f)));
5336
- const next = { ...meta, ports: kept.length > 0 ? kept : void 0 };
5337
- await writeMachineMeta(next, p);
5338
- return toMachine(next, p);
5467
+ if (!isCloudBox(meta.owner)) throw new KvboxError(`box ${shown(ref)} is local: it trusts this host's key, there are no authorized_keys lines to replace`);
5468
+ if (sshKeys.length === 0) throw new KvboxError("sshKeys: at least one authorized_keys line (the box would keep only the host's own key)");
5469
+ authorizedKeysB64(await readHostPubkey(p), sshKeys);
5470
+ const { meta: updated, applied } = await applySshKeys(meta, sshKeys, p);
5471
+ return { machine: toMachine(updated, p), applied };
5339
5472
  });
5473
+ async function applySshKeys(meta, sshKeys, p) {
5474
+ const status = statusOf(meta, p);
5475
+ let updated = { ...meta, sshKeys: [...sshKeys], sshKeysStale: status === "stopped" ? void 0 : true };
5476
+ let applied = status === "stopped" ? "start" : status === "standby" ? "resume" : status === "hibernated" ? "wake" : "later";
5477
+ let why;
5478
+ if (status === "running") {
5479
+ why = await pushAuthorizedKeys(updated, p.machine(meta.owner, meta.name).vsock, p);
5480
+ if (why === void 0) {
5481
+ updated = { ...updated, sshKeysStale: void 0 };
5482
+ applied = "now";
5483
+ }
5484
+ }
5485
+ await writeMachineMeta(updated, p);
5486
+ return why === void 0 ? { meta: updated, applied } : { meta: updated, applied, why };
5487
+ }
5488
+ async function trustCa(publicKeyText, p = paths()) {
5489
+ const publicKey = parseSshPublicKey(publicKeyText);
5490
+ const report2 = { publicKey, fingerprint: sshKeyFingerprint(publicKey), updated: [], pending: [], failed: [], local: 0, skipped: [] };
5491
+ const hostKey = await readHostPubkey(p);
5492
+ for (const listed of await readAllMeta(p)) {
5493
+ if (!isCloudBox(listed.owner)) {
5494
+ report2.local++;
5495
+ continue;
5496
+ }
5497
+ const box = refKey(listed);
5498
+ try {
5499
+ await withBoxLock(listed, async () => {
5500
+ const meta = await readMeta(listed, p);
5501
+ if (!(meta.sshKeys ?? []).some(isCaLine)) {
5502
+ report2.skipped.push(box);
5503
+ return;
5504
+ }
5505
+ const sshKeys = [...(meta.sshKeys ?? []).filter((l) => !isCaLine(l)), caLineFor(meta.owner, publicKey)];
5506
+ authorizedKeysLines(hostKey, sshKeys);
5507
+ const { applied, why } = await applySshKeys(meta, sshKeys, p);
5508
+ if (applied === "now") report2.updated.push(box);
5509
+ else report2.pending.push(why === void 0 ? { box, when: applied } : { box, when: applied, why });
5510
+ });
5511
+ } catch (err) {
5512
+ report2.failed.push({ box, error: err.message });
5513
+ }
5514
+ }
5515
+ return report2;
5516
+ }
5340
5517
 
5341
5518
  // src/core/machines/start.ts
5342
5519
  var startMachine = locked(async function startMachine2(ref, p = paths(), force = false) {
5343
- const meta = await readMeta(ref, p);
5520
+ const stopped = await readMeta(ref, p);
5344
5521
  const cfg = await loadConfig(p);
5345
- if (vmAlive(meta)) throw new KvboxError(`box ${shown(ref)} is already ${meta.paused ? "up, in standby (kvbox resume " + shown(ref) + ")" : "running"}`);
5346
- if (isHibernated(meta, p)) {
5522
+ if (vmAlive(stopped)) throw new KvboxError(`box ${shown(ref)} is already ${stopped.paused ? "up, in standby (kvbox resume " + shown(ref) + ")" : "running"}`);
5523
+ if (isHibernated(stopped, p)) {
5347
5524
  throw new KvboxError(`${stateMessage(ref, "hibernated")}: kvbox wake ${shown(ref)} continues where it left off; to boot fresh instead, kvbox stop ${shown(ref)} first (discards its memory)`);
5348
5525
  }
5349
5526
  assertAssets(cfg);
5350
- await assertRoomFor(meta.vcpu, meta.memMib, force, meta, "start", p);
5351
- const keysB64 = authorizedKeysB64(await readHostPubkey(p), meta.sshKeys ?? []);
5527
+ await assertRoomFor(stopped.vcpu, stopped.memMib, force, stopped, "start", p);
5528
+ const keysB64 = authorizedKeysB64(await readHostPubkey(p), stopped.sshKeys ?? []);
5352
5529
  await driver().net.prepare(cfg);
5353
- const tap = await driver().net.create(meta, cfg);
5530
+ const meta = await moveToRange(stopped, cfg, p);
5354
5531
  let pid;
5355
5532
  try {
5533
+ const tap = await driver().net.create(meta, cfg);
5356
5534
  const bootedAt = (/* @__PURE__ */ new Date()).toISOString();
5357
5535
  pid = await launch(meta, tap, cfg, keysB64, p);
5358
5536
  await openPorts(meta, cfg, p);
@@ -5361,12 +5539,14 @@ var startMachine = locked(async function startMachine2(ref, p = paths(), force =
5361
5539
  await writeMachineMeta(started, p);
5362
5540
  recordState(started, "running", "start", p);
5363
5541
  void tellIntegrationsWhenUp(started, pid, p.machine(meta.owner, meta.name).vsock, p);
5542
+ if (started.movedFrom !== void 0) followMoveSoon(ref, p);
5364
5543
  return toMachine(started, p);
5365
5544
  } catch (err) {
5366
5545
  if (pid !== void 0) killQuietly(pid);
5367
5546
  await stopListeningForGuest(meta, p);
5368
5547
  await closePorts(meta, cfg);
5369
5548
  await driver().net.remove(meta.id, cfg).catch(() => void 0);
5549
+ if (meta !== stopped) await unmove(ref, stopped, p).catch((e) => log.warn(`box ${shown(ref)} failed to start on ${meta.ip} and could not take back ${stopped.ip}: ${e.message}`));
5370
5550
  throw err;
5371
5551
  }
5372
5552
  });
@@ -5401,9 +5581,9 @@ function requestedIntegrations(list, on) {
5401
5581
  return integrationsOf(list);
5402
5582
  }
5403
5583
  var inheritedIntegrations = (list, sourceOwner, owner) => sourceOwner === owner ? integrationsOf(list) : void 0;
5404
- async function bootInto(box, prepare, origin, cfg, p) {
5405
- const { id, ip, owner, name } = box;
5406
- const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
5584
+ async function bootInto(newBox, prepare, origin, cfg, p) {
5585
+ const { id, owner, name } = newBox;
5586
+ const keysB64 = authorizedKeysB64(await readHostPubkey(p), newBox.sshKeys ?? []);
5407
5587
  const m = p.machine(owner, name);
5408
5588
  await driver().net.prepare(cfg);
5409
5589
  await mkdir5(m.dir, { recursive: true, mode: 448 });
@@ -5411,7 +5591,10 @@ async function bootInto(box, prepare, origin, cfg, p) {
5411
5591
  let pid;
5412
5592
  let sshPort;
5413
5593
  let drawn;
5594
+ let address;
5414
5595
  try {
5596
+ address = await drawAddress(cfg, p);
5597
+ const box = { ...newBox, ip: address.ip, mac: address.mac };
5415
5598
  drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
5416
5599
  sshPort = drawn?.ports[0];
5417
5600
  await prepare(m);
@@ -5429,18 +5612,19 @@ async function bootInto(box, prepare, origin, cfg, p) {
5429
5612
  return toMachine(meta, p);
5430
5613
  } catch (err) {
5431
5614
  if (pid !== void 0) killQuietly(pid);
5432
- await stopListeningForGuest(box, p);
5433
- await closePorts({ id, ip, sshPort, cluster: origin.cluster }, cfg);
5615
+ await stopListeningForGuest(newBox, p);
5616
+ if (address) await closePorts({ id, ip: address.ip, sshPort, cluster: origin.cluster }, cfg);
5434
5617
  if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
5435
5618
  await rm6(m.dir, { recursive: true, force: true });
5436
5619
  boxListChanged();
5437
5620
  throw err;
5438
5621
  } finally {
5439
5622
  drawn?.release();
5623
+ address?.release();
5440
5624
  }
5441
5625
  }
5442
- async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
5443
- const { id, ip, owner, name } = box;
5626
+ async function restoreInto(newBox, prepare, origin, cfg, p, keysOrFail) {
5627
+ const { id, owner, name } = newBox;
5444
5628
  const m = p.machine(owner, name);
5445
5629
  await driver().net.prepare(cfg);
5446
5630
  await mkdir5(m.dir, { recursive: true, mode: 448 });
@@ -5448,7 +5632,10 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
5448
5632
  let pid;
5449
5633
  let sshPort;
5450
5634
  let drawn;
5635
+ let address;
5451
5636
  try {
5637
+ address = await drawAddress(cfg, p);
5638
+ const box = { ...newBox, ip: address.ip, mac: address.mac };
5452
5639
  drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
5453
5640
  sshPort = drawn?.ports[0];
5454
5641
  const image = await prepare(m);
@@ -5475,14 +5662,15 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
5475
5662
  return toMachine(meta, p);
5476
5663
  } catch (err) {
5477
5664
  if (pid !== void 0) killQuietly(pid);
5478
- await stopListeningForGuest(box, p);
5479
- await closePorts({ id, ip, sshPort }, cfg);
5665
+ await stopListeningForGuest(newBox, p);
5666
+ if (address) await closePorts({ id, ip: address.ip, sshPort }, cfg);
5480
5667
  if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
5481
5668
  await rm6(m.dir, { recursive: true, force: true });
5482
5669
  boxListChanged();
5483
5670
  throw err;
5484
5671
  } finally {
5485
5672
  drawn?.release();
5673
+ address?.release();
5486
5674
  }
5487
5675
  }
5488
5676
 
@@ -5580,7 +5768,7 @@ var removeLink = locked(async function removeLink2(ref, req, caller, p = paths()
5580
5768
  await writeMachineMeta(next, p);
5581
5769
  return toMachine(next, p);
5582
5770
  });
5583
- var linkOf = (gone) => (l) => l.owner === gone.owner && l.name === gone.name && l.ip === gone.ip;
5771
+ var linkOf = (gone) => (l) => l.owner === gone.owner && l.name === gone.name && (l.ip === gone.ip || gone.movedFrom !== void 0 && l.ip === gone.movedFrom);
5584
5772
  async function closeLinksFrom(gone, cfg, p) {
5585
5773
  const isGone = linkOf(gone);
5586
5774
  for (const ref of await listMachineRefs(p)) {
@@ -5815,12 +6003,11 @@ async function restoreFrom(from, owner, req, cfg, p) {
5815
6003
  const existing = await readAllMeta(p);
5816
6004
  const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
5817
6005
  const id = newBoxId(idsInUse(existing));
5818
- const { ip, mac } = driver().net.allocate(cfg, existing.map((m) => m.ip));
5819
6006
  const s = p.snapshot(from.owner, from.name);
5820
6007
  const given = new Set((req.env ?? []).map((v) => v.name));
5821
6008
  const vars = [...(await readBoxEnvFile(s.env)).filter((v) => !given.has(v.name)), ...(req.env ?? []).map((v) => ({ ...v, secret: false }))];
5822
6009
  return restoreInto(
5823
- { id, name, owner, ip, mac, vcpu: snap.vcpu, memMib: snap.memMib, base: snap.base, image: snap.image, sshKeys },
6010
+ { id, name, owner, vcpu: snap.vcpu, memMib: snap.memMib, base: snap.base, image: snap.image, sshKeys },
5824
6011
  async (m) => {
5825
6012
  await run(["cp", "--sparse=always", "--reflink=auto", s.overlay, m.overlay]);
5826
6013
  await copyBoxEnv(s.env, m.env);
@@ -5868,7 +6055,6 @@ async function createMachine(req, owner, p = paths(), from) {
5868
6055
  const existing = await readAllMeta(p);
5869
6056
  const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
5870
6057
  const id = newBoxId(idsInUse(existing));
5871
- const { ip, mac } = driver().net.allocate(cfg, existing.map((m) => m.ip));
5872
6058
  const image = imageKey(from ? from.image : req.image);
5873
6059
  const base = from ? { version: from.base, file: imageFile(image, from.base, p) } : await currentImage(image, cfg, p);
5874
6060
  await assertOverlayCapable(base.file, image, base.version);
@@ -5879,7 +6065,7 @@ async function createMachine(req, owner, p = paths(), from) {
5879
6065
  const secret = /* @__PURE__ */ new Set([...env?.secrets ?? [], ...(req.env ?? []).filter((v) => v.secret === true).map((v) => v.name)]);
5880
6066
  const vars = env === null ? from?.vars ?? [] : env.vars.map((v) => ({ name: v.name, value: v.value, secret: secret.has(v.name), updatedAt: now }));
5881
6067
  const machine = await bootInto(
5882
- { id, name, owner, ip, mac, vcpu: size2.vcpu, memMib: size2.memMib, base: base.version, image, sshKeys },
6068
+ { id, name, owner, vcpu: size2.vcpu, memMib: size2.memMib, base: base.version, image, sshKeys },
5883
6069
  // The image is shared read-only by every box; only the box's own writes land in its overlay.
5884
6070
  async (m) => {
5885
6071
  if (from) {
@@ -6081,8 +6267,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
6081
6267
  const existing = await readAllMeta(p);
6082
6268
  const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
6083
6269
  const id = newBoxId(idsInUse(existing));
6084
- const { ip, mac } = driver().net.allocate(cfg, existing.map((m) => m.ip));
6085
- const box = { id, name, owner, ip, mac, ...shape, base: src.base, image: src.image, sshKeys };
6270
+ const box = { id, name, owner, ...shape, base: src.base, image: src.image, sshKeys };
6086
6271
  const srcEnv = p.machine(src.owner, src.name).env;
6087
6272
  const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, idleCheck: src.idleCheck, url: src.url, integrations: inheritedIntegrations(src.integrations, src.owner, owner) };
6088
6273
  if (!warm) {
@@ -6915,6 +7100,83 @@ async function withTries(what, fn, signal) {
6915
7100
  throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
6916
7101
  }
6917
7102
 
7103
+ // src/core/range.ts
7104
+ import { networkInterfaces } from "node:os";
7105
+ import { request as request4 } from "undici";
7106
+ var RANGE_RETRY_MS = 10 * 6e4;
7107
+ var RANGE_ASK_MS = 5e3;
7108
+ var askControlPlane = async (cfg, timeoutMs = RANGE_ASK_MS) => {
7109
+ const cp = cfg.controlPlane;
7110
+ if (!cp) return void 0;
7111
+ const res = await request4(`${cp.url}/hosts/self/range`, { headers: { authorization: `Bearer ${cp.secret}` }, signal: AbortSignal.timeout(timeoutMs) });
7112
+ const text = await res.body.text();
7113
+ if (res.statusCode === 404) return void 0;
7114
+ if (res.statusCode < 200 || res.statusCode >= 300) throw new Error(`${cp.name} answered ${res.statusCode}`);
7115
+ return HostRangeResponseSchema.parse(JSON.parse(text)).range;
7116
+ };
7117
+ function ownNetworks(bridge) {
7118
+ return Object.entries(networkInterfaces()).filter(([name]) => name !== bridge && name !== "lo").flatMap(([, addrs]) => (addrs ?? []).filter((a) => a.family === "IPv4" && a.cidr !== null).map((a) => a.cidr));
7119
+ }
7120
+ async function refusal3(range, cfg, p, networks) {
7121
+ if (!isHostRange(range)) return "it is not a range a host can have (172.30.1.0/24 to 172.30.254.0/24)";
7122
+ if (!driver().net.carriesRanges()) return "this host's network setup is from before box ranges; its operator finishes the update by running install-server.sh on it (the root step)";
7123
+ if (cfg.gateway !== BOX_GATEWAY || cfg.subnet !== UNNUMBERED_RANGE && cfg.subnet !== BOX_NETWORK) {
7124
+ return `this host's boxes are on a network of its own choosing (config.json subnet ${cfg.subnet}, gateway ${cfg.gateway}), not the default one ranges are cut from`;
7125
+ }
7126
+ const clash = networks.find((net) => rangesOverlap(net, BOX_NETWORK));
7127
+ if (clash) return `this machine is itself on ${clash}, inside the network every box would see (${BOX_NETWORK}): taking a range would cut the machine off its own network`;
7128
+ const onIt = await boxOnRange(cfg, p);
7129
+ if (onIt) return `box ${onIt} has an address in the range this host has now (${cfg.boxRange}); a host's range changes only while no box is on it`;
7130
+ return null;
7131
+ }
7132
+ async function boxOnRange(cfg, p) {
7133
+ if (cfg.boxRange === void 0) return null;
7134
+ for (const ref of await listMachineRefs(p)) {
7135
+ const meta = await readMachineMeta(ref, p).catch(() => null);
7136
+ if (meta && inRange(meta.ip, cfg.boxRange)) return meta.name;
7137
+ }
7138
+ return null;
7139
+ }
7140
+ async function heldRange(cfg, p) {
7141
+ return await boxOnRange(cfg, p) === null ? void 0 : cfg.boxRange;
7142
+ }
7143
+ async function adoptRange(p = paths(), ask3 = (cfg) => askControlPlane(cfg), networks = ownNetworks) {
7144
+ const cfg = await loadConfig(p);
7145
+ const range = cfg.controlPlane ? await ask3(cfg) : void 0;
7146
+ if (range === void 0 || range === null || range === cfg.boxRange) return { state: "unchanged", range: cfg.boxRange };
7147
+ const why = await refusal3(range, cfg, p, networks(cfg.bridge));
7148
+ if (why !== null) return { state: "refused", range, why };
7149
+ const next = { ...cfg, subnet: BOX_NETWORK, gateway: BOX_GATEWAY, boxRange: range };
7150
+ try {
7151
+ if (await driver().net.prepare(next) === "present") await driver().net.widen(next);
7152
+ } catch (err) {
7153
+ return { state: "refused", range, why: `this host's network could not be widened to ${BOX_NETWORK} (${err.message}); see kvbox-server net status` };
7154
+ }
7155
+ await saveConfig({ ...await loadConfig(p), subnet: next.subnet, gateway: next.gateway, boxRange: next.boxRange }, p);
7156
+ return { state: "taken", range };
7157
+ }
7158
+ var lastWhy;
7159
+ async function adoptRangeLogged(p = paths()) {
7160
+ try {
7161
+ const outcome = await adoptRange(p);
7162
+ if (outcome.state === "taken") log.info(`box range: this host's boxes now get addresses in ${outcome.range}; the ones from before move at their next cold start`);
7163
+ const why = outcome.state === "refused" ? `the control plane gives this host the box range ${outcome.range}, not taken: ${outcome.why}` : void 0;
7164
+ if (why !== void 0 && why !== lastWhy) log.warn(why);
7165
+ lastWhy = why;
7166
+ return outcome;
7167
+ } catch (err) {
7168
+ const why = `box range: the control plane could not be asked (${err.message}); trying again`;
7169
+ if (why !== lastWhy) log.warn(why);
7170
+ lastWhy = why;
7171
+ return null;
7172
+ }
7173
+ }
7174
+ function startRangeWatch(p = paths()) {
7175
+ return setInterval(() => {
7176
+ void loadConfig(p).then((cfg) => cfg.controlPlane && cfg.boxRange === void 0 ? adoptRangeLogged(p) : null).catch(() => void 0);
7177
+ }, RANGE_RETRY_MS).unref();
7178
+ }
7179
+
6918
7180
  // src/core/relay.ts
6919
7181
  import { access as access2, chmod as chmod4, mkdir as mkdir10, rm as rm15, writeFile as writeFile8 } from "node:fs/promises";
6920
7182
 
@@ -6953,7 +7215,7 @@ function decodeRelayJoin(text) {
6953
7215
  import { X509Certificate } from "node:crypto";
6954
7216
  import { chmod as chmod3, mkdir as mkdir9, readFile as readFile10 } from "node:fs/promises";
6955
7217
  import { hostname as osHostname } from "node:os";
6956
- import { request as request4 } from "undici";
7218
+ import { request as request5 } from "undici";
6957
7219
 
6958
7220
  // ../shared/src/country.ts
6959
7221
  var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
@@ -7057,8 +7319,9 @@ async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdverti
7057
7319
  const country = opts.country === void 0 ? void 0 : parseCountry(opts.country);
7058
7320
  const { fingerprint } = await ensureTlsCert(p);
7059
7321
  const hostUrl = `https://${advertise}:${port}`;
7060
- const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
7061
- const res = await request4(`${url}/hosts/join`, {
7322
+ const boxRange = await heldRange(cfg, p);
7323
+ const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {}, ...boxRange !== void 0 ? { boxRange } : {} };
7324
+ const res = await request5(`${url}/hosts/join`, {
7062
7325
  method: "POST",
7063
7326
  headers: { "content-type": "application/json" },
7064
7327
  body: JSON.stringify(body),
@@ -7083,7 +7346,7 @@ async function fetchCloudCa(p = paths()) {
7083
7346
  const cfg = await loadConfig(p);
7084
7347
  const cp = cfg.controlPlane;
7085
7348
  if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no CA to fetch; paste the key instead: kvbox-server trust-ca <public-key>");
7086
- const res = await request4(`${cp.url}/hosts/self/ssh-ca`, {
7349
+ const res = await request5(`${cp.url}/hosts/self/ssh-ca`, {
7087
7350
  headers: { authorization: `Bearer ${cp.secret}` },
7088
7351
  headersTimeout: 1e4,
7089
7352
  bodyTimeout: 1e4
@@ -7102,7 +7365,7 @@ async function fetchCloudName(p = paths()) {
7102
7365
  const cfg = await loadConfig(p);
7103
7366
  const cp = cfg.controlPlane;
7104
7367
  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>");
7105
- const res = await request4(`${cp.url}/health`, { headersTimeout: 1e4, bodyTimeout: 1e4 }).catch((err) => {
7368
+ const res = await request5(`${cp.url}/health`, { headersTimeout: 1e4, bodyTimeout: 1e4 }).catch((err) => {
7106
7369
  throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
7107
7370
  });
7108
7371
  const text = await res.body.text();
@@ -7115,7 +7378,7 @@ async function leaveControlPlane(p = paths()) {
7115
7378
  const cfg = await loadConfig(p);
7116
7379
  const cp = cfg.controlPlane;
7117
7380
  if (!cp) throw new KvboxError("this host has not joined a control plane");
7118
- const told2 = await request4(`${cp.url}/hosts/self`, {
7381
+ const told2 = await request5(`${cp.url}/hosts/self`, {
7119
7382
  method: "DELETE",
7120
7383
  headers: { authorization: `Bearer ${cp.secret}` },
7121
7384
  headersTimeout: 3e3,
@@ -7708,7 +7971,7 @@ function startsAtBoot(p) {
7708
7971
  }
7709
7972
 
7710
7973
  // src/socketClient.ts
7711
- import { Agent as Agent3, request as request5 } from "undici";
7974
+ import { Agent as Agent3, request as request6 } from "undici";
7712
7975
  var SocketClient = class {
7713
7976
  agent;
7714
7977
  constructor(socketPath) {
@@ -7736,7 +7999,7 @@ var SocketClient = class {
7736
7999
  async call(method, path, schema, body, timeoutMs) {
7737
8000
  let res;
7738
8001
  try {
7739
- res = await request5(`http://kvbox-server${path}`, {
8002
+ res = await request6(`http://kvbox-server${path}`, {
7740
8003
  method,
7741
8004
  dispatcher: this.agent,
7742
8005
  ...timeoutMs === void 0 ? {} : { headersTimeout: timeoutMs, bodyTimeout: timeoutMs },
@@ -7953,7 +8216,7 @@ function versionOf(srcFileUrl, injected) {
7953
8216
  }
7954
8217
 
7955
8218
  // src/version.ts
7956
- var VERSION = versionOf(import.meta.url, true ? "0.6.25" : void 0);
8219
+ var VERSION = versionOf(import.meta.url, true ? "0.6.26" : void 0);
7957
8220
 
7958
8221
  // src/caller.ts
7959
8222
  import { createHash as createHash5, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
@@ -8130,7 +8393,7 @@ function backupStoreRoutes(opts = {}) {
8130
8393
  import { connect as connect2 } from "node:net";
8131
8394
  import { Readable } from "node:stream";
8132
8395
  import { Hono as Hono3 } from "hono";
8133
- import { request as request6 } from "undici";
8396
+ import { request as request7 } from "undici";
8134
8397
  var HEADERS_TIMEOUT_MS = 55e3;
8135
8398
  var MAX_HANDSHAKE_BYTES = 16 * 1024;
8136
8399
  var CONNECT_TIMEOUT_MS = 5e3;
@@ -8239,7 +8502,7 @@ async function forward(c, wake) {
8239
8502
  raw.headers.forEach((value, name) => pairs.push([name, value]));
8240
8503
  let res;
8241
8504
  try {
8242
- res = await request6(`http://${target.ip}:${target.port}${target.path}`, {
8505
+ res = await request7(`http://${target.ip}:${target.port}${target.path}`, {
8243
8506
  method: raw.method,
8244
8507
  headers: boxHeaders(pairs, target).flat(),
8245
8508
  body: raw.body === null ? null : Readable.fromWeb(raw.body),
@@ -8535,7 +8798,7 @@ function machineRoutes() {
8535
8798
  // src/routes/runs.ts
8536
8799
  import { Hono as Hono7 } from "hono";
8537
8800
  import { z as z10 } from "zod";
8538
- var refusal3 = (c, err) => {
8801
+ var refusal4 = (c, err) => {
8539
8802
  if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
8540
8803
  if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
8541
8804
  if (err instanceof AgentNotAnsweringError) return c.json({ error: err.message, code: "unreachable" }, 503);
@@ -8556,7 +8819,7 @@ function runRoutes(wake = wakeBox) {
8556
8819
  const started = await startBoxRun(ref, body);
8557
8820
  return c.json(StartRunAnswerSchema.parse({ id: body.id, started, woke }), 202);
8558
8821
  } catch (err) {
8559
- return refusal3(c, err);
8822
+ return refusal4(c, err);
8560
8823
  }
8561
8824
  });
8562
8825
  r.get("/:name/runs/:id", async (c) => {
@@ -8564,7 +8827,7 @@ function runRoutes(wake = wakeBox) {
8564
8827
  const { ref } = await runningBox(c.req.param("name"), c.get("owner"), wants(c.req.header(WAKE_HEADER)) ? wake : void 0);
8565
8828
  return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
8566
8829
  } catch (err) {
8567
- return refusal3(c, err);
8830
+ return refusal4(c, err);
8568
8831
  }
8569
8832
  });
8570
8833
  r.get("/:name/runs/:id/output", async (c) => {
@@ -8577,7 +8840,7 @@ function runRoutes(wake = wakeBox) {
8577
8840
  const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
8578
8841
  return c.json(RunOutputSchema.parse(await boxRunOutput(ref, id, stream, offset, limit)));
8579
8842
  } catch (err) {
8580
- return refusal3(c, err);
8843
+ return refusal4(c, err);
8581
8844
  }
8582
8845
  });
8583
8846
  return r;
@@ -8868,7 +9131,7 @@ async function listen(opts = {}) {
8868
9131
  fetch: createApp({ controlPlane: { name: cp.name, secret: cp.secret } }).fetch,
8869
9132
  createServer: createHttpsServer,
8870
9133
  // A body forwarded to a box may take long to arrive (a large upload through the edge, #182).
8871
- serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS2 }
9134
+ serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS }
8872
9135
  });
8873
9136
  const appListeners = httpsServer.listeners("request");
8874
9137
  httpsServer.removeAllListeners("request");
@@ -8954,10 +9217,13 @@ var startCommand = new Command("start").description("run the daemon in the foreg
8954
9217
  await listenForRunning(paths()).catch((err) => log.warn(`running boxes cannot reach their integrations: ${err.message}`));
8955
9218
  setInterval(() => void closeDeadListeners(paths()).catch(() => void 0), 6e4).unref();
8956
9219
  try {
9220
+ await adoptRangeLogged(paths());
9221
+ startRangeWatch();
8957
9222
  const cfg = await loadConfig(paths());
8958
9223
  const state = await driver().net.prepare(cfg);
8959
9224
  log.info(`host network: bridge ${cfg.bridge} ${state}`);
8960
9225
  await pinRunningTaps(paths());
9226
+ await followMoves(paths()).catch((err) => log.warn(`links from boxes that changed address were not all moved: ${err.message}`));
8961
9227
  await rejoinClusters(paths()).catch((err) => log.warn(`running boxes may be cut off from their clusters: ${err.message}`));
8962
9228
  await reopenFarTargets(paths()).catch((err) => log.warn(`running boxes cannot reach the boxes they are linked to on other hosts: ${err.message}`));
8963
9229
  } catch (err) {
@@ -9138,6 +9404,11 @@ var netCommand = new Command8("net").description("host network: up | down | stat
9138
9404
  stdio: "inherit",
9139
9405
  env: { ...process.env, KVBOX_BRIDGE: cfg.bridge, KVBOX_SUBNET: cfg.subnet, KVBOX_GATEWAY: cfg.gateway }
9140
9406
  });
9407
+ if (action === "status" && cfg.boxRange !== void 0) {
9408
+ const old = await countOffRange(paths());
9409
+ console.log(` boxes on this host get addresses in ${cfg.boxRange}, its own range`);
9410
+ console.log(old === 0 ? " every box is on it" : ` ${old} box${old === 1 ? " still has" : "es still have"} an address from before it; each moves at its next cold start (kvbox restart)`);
9411
+ }
9141
9412
  process.exit(res.status ?? 1);
9142
9413
  });
9143
9414