@kvbox/server 0.6.16 → 0.6.18

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.
@@ -222,9 +222,15 @@ var PricingSchema = z.object({
222
222
  cronHour: z.number().nonnegative().default(0),
223
223
  /**
224
224
  * One backup a person starts, of anything, charged once it is ready (decision "A backup taken by hand
225
- * costs a flat price…"); a failed one and a scheduled one cost nothing. A price list from before it charges nothing.
225
+ * costs a flat price…"); a failed one costs nothing. A price list from before it charges nothing.
226
226
  */
227
- backup: z.number().nonnegative().default(0)
227
+ backup: z.number().nonnegative().default(0),
228
+ /**
229
+ * One nightly backup of a box, a volume or the object storage, charged once it is ready (decision "A nightly
230
+ * backup you switch on is charged…"): their switch is off until someone turns it on. A managed database's
231
+ * nightly backup, on from its creation, is included in its price. A price list from before it charges nothing.
232
+ */
233
+ scheduledBackup: z.number().nonnegative().default(0)
228
234
  });
229
235
  var PriceListSchema = PricingSchema.extend({ welcomeCredit: z.number().nonnegative() });
230
236
  var HOUR_MS = 36e5;
@@ -629,7 +635,7 @@ async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
629
635
  }
630
636
 
631
637
  // src/core/drivers/firecracker/network.ts
632
- import { existsSync } from "node:fs";
638
+ import { existsSync, readFileSync } from "node:fs";
633
639
  import { fileURLToPath } from "node:url";
634
640
  var TAP_PREFIX = "kv-";
635
641
  var PRIVILEGED_SCRIPT = "/usr/local/lib/kvbox/net-setup.sh";
@@ -713,6 +719,22 @@ async function openLink(link4, cfg) {
713
719
  async function closeLink(link4, cfg) {
714
720
  await netRun(cfg, ["link", "rm", ...linkArgs(link4)]);
715
721
  }
722
+ function carriesFarLinks() {
723
+ try {
724
+ return readFileSync(netSetupScript(), "utf8").includes("farlink add");
725
+ } catch {
726
+ return false;
727
+ }
728
+ }
729
+ async function openFarLink(link4, cfg) {
730
+ await netRun(cfg, ["farlink", "add", link4.box, link4.fromIp, link4.standIn, String(link4.port), String(link4.via)]).catch((err) => {
731
+ if (!err.message.includes("usage:")) throw err;
732
+ throw new KvboxError("this host's network setup is from before links to boxes on other hosts; its operator finishes the update by running install-server.sh on it (the root step)");
733
+ });
734
+ }
735
+ async function closeFarLink(link4, cfg) {
736
+ await netRun(cfg, ["farlink", "rm", link4.box, link4.fromIp, link4.standIn, String(link4.port)]);
737
+ }
716
738
  async function closeProxy(proxy, cfg) {
717
739
  await netRun(cfg, ["proxy", "rm", ...proxyArgs(proxy)]);
718
740
  }
@@ -731,6 +753,16 @@ function nextFreeIp(subnet, inUse) {
731
753
  }
732
754
  throw new KvboxError(`no free IP left in ${subnet}`);
733
755
  }
756
+ function standInIp(subnet, inUse) {
757
+ const [a, b, c] = (subnet.split("/")[0] ?? "").split(".");
758
+ if (a === void 0 || b === void 0 || c === void 0) throw new KvboxError(`bad subnet: ${subnet}`);
759
+ const used = new Set(inUse);
760
+ for (let n = 1; n < 255; n++) {
761
+ const ip = `${a}.${b}.${c === "255" ? 254 : 255}.${n}`;
762
+ if (!used.has(ip)) return ip;
763
+ }
764
+ throw new KvboxError("this host has no address left for a link to a box on another host (254 are in use)");
765
+ }
734
766
  function macFor(ip) {
735
767
  const hex = ip.split(".").map((o) => Number(o).toString(16).padStart(2, "0").toUpperCase());
736
768
  return ["06", "00", ...hex].join(":");
@@ -1053,6 +1085,12 @@ var firecrackerDriver = {
1053
1085
  closeProxy,
1054
1086
  openLink,
1055
1087
  closeLink,
1088
+ carriesFarLinks,
1089
+ standIn: (cfg, inUse) => standInIp(cfg.subnet, inUse),
1090
+ // A redirected connection arrives at the bridge's own address.
1091
+ farListenHost: (cfg) => cfg.gateway,
1092
+ openFarLink,
1093
+ closeFarLink,
1056
1094
  relay: netSetup,
1057
1095
  setupScript: netSetupScript
1058
1096
  },
@@ -1072,7 +1110,7 @@ import { createSocket } from "node:dgram";
1072
1110
 
1073
1111
  // src/core/state.ts
1074
1112
  import { randomBytes } from "node:crypto";
1075
- import { readFileSync } from "node:fs";
1113
+ import { readFileSync as readFileSync2 } from "node:fs";
1076
1114
  import { mkdir, readFile as readFile5, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
1077
1115
  import { z as z3 } from "zod";
1078
1116
 
@@ -1308,6 +1346,17 @@ var MachineMetaSchema = z3.object({
1308
1346
  * again, never listed (a new box of the same name may get the same IP). Absent: none.
1309
1347
  */
1310
1348
  links: z3.array(z3.object({ owner: z3.string(), name: z3.string(), ip: z3.string(), port: z3.number().int(), stale: z3.literal(true).optional() })).optional(),
1349
+ /**
1350
+ * Links into this box from boxes on other hosts (#207): box `owner/name` reaches `port` through this host's
1351
+ * HTTPS listener, presenting the link's key; `key` is its sha256 (hex), never the key. No rule on this host. Absent: none.
1352
+ */
1353
+ farLinks: z3.array(z3.object({ owner: z3.string(), name: z3.string(), port: z3.number().int(), key: z3.string() })).optional(),
1354
+ /**
1355
+ * Boxes on other hosts this box reaches (#207): `port` of box `owner/name`, on the host at `url` (certificate
1356
+ * `pin`), by presenting `key`. Inside this box the other is `ip`, a stand-in address on this host that
1357
+ * `<name>.kvbox` answers and that this host carries to the other. Open while this box runs. Absent: none.
1358
+ */
1359
+ farTargets: z3.array(z3.object({ owner: z3.string(), name: z3.string(), port: z3.number().int(), ip: z3.string(), url: z3.string(), pin: z3.string(), key: z3.string() })).optional(),
1311
1360
  /**
1312
1361
  * The integrations turned on for the box (#205): names only (`github`), never a credential. The box asks
1313
1362
  * for one each time it needs it (core/machines/integrations.ts) and is answered only for a name in this
@@ -1441,7 +1490,7 @@ var bootId;
1441
1490
  function currentBootId() {
1442
1491
  if (bootId === void 0) {
1443
1492
  try {
1444
- bootId = { id: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() };
1493
+ bootId = { id: readFileSync2("/proc/sys/kernel/random/boot_id", "utf8").trim() };
1445
1494
  } catch {
1446
1495
  bootId = { id: void 0 };
1447
1496
  }
@@ -1454,7 +1503,7 @@ function vmAlive(meta) {
1454
1503
  }
1455
1504
  function hostBootTime() {
1456
1505
  try {
1457
- const m = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
1506
+ const m = /^btime (\d+)$/m.exec(readFileSync2("/proc/stat", "utf8"));
1458
1507
  return m ? new Date(Number(m[1]) * 1e3) : null;
1459
1508
  } catch {
1460
1509
  return null;
@@ -1522,6 +1571,7 @@ function answerFor(q, asker, boxes) {
1522
1571
  let box;
1523
1572
  if (from && rest.length === 0) {
1524
1573
  box = slug === void 0 || slug === slugOf(from.owner) ? boxes.find((b) => b.owner === from.owner && b.name === name) : boxes.find((b) => slugOf(b.owner) === slug && b.name === name && b.linkedFrom?.includes(asker));
1574
+ box ??= from.far?.find((t) => t.name === name && (slug === void 0 ? t.owner === from.owner : slugOf(t.owner) === slug));
1525
1575
  }
1526
1576
  if (!box) return { rcode: RCODE.nxDomain };
1527
1577
  return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };
@@ -1530,7 +1580,10 @@ async function boxAddresses(p) {
1530
1580
  const out = [];
1531
1581
  for (const ref of await listMachineRefs(p)) {
1532
1582
  const meta = await readMachineMeta(ref, p).catch(() => null);
1533
- if (meta) out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {} });
1583
+ if (meta) {
1584
+ const far = meta.farTargets?.map((t) => ({ name: t.name, owner: t.owner, ip: t.ip }));
1585
+ out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {}, ...far ? { far } : {} });
1586
+ }
1534
1587
  }
1535
1588
  return out;
1536
1589
  }
@@ -1746,8 +1799,8 @@ function imageEnv(manifest, box, given, inherited = []) {
1746
1799
  const encode = manifest.connect !== void 0 && /^[a-z][a-z0-9+.-]*:\/\//i.test(manifest.connect);
1747
1800
  const connectVars = new Map([...vars].map(([k, v]) => [k, owners.has(k) ? `\${${k}}` : encode ? encodeURIComponent(v) : v]));
1748
1801
  connectVars.set("BOX", box);
1749
- const connect3 = manifest.connect === void 0 ? void 0 : expand(manifest.connect, connectVars);
1750
- return { vars: [...given, ...added], generated, secrets: [...generated, ...secrets], connect: connect3 };
1802
+ const connect4 = manifest.connect === void 0 ? void 0 : expand(manifest.connect, connectVars);
1803
+ return { vars: [...given, ...added], generated, secrets: [...generated, ...secrets], connect: connect4 };
1751
1804
  }
1752
1805
  var MASK = "****";
1753
1806
  function maskedUrl(manifest, vars) {
@@ -1923,7 +1976,25 @@ var PortsRequest = z6.object({
1923
1976
  var BoxPortSchema = z6.number().int().min(1).max(65535);
1924
1977
  var MAX_BOX_LINKS = 32;
1925
1978
  var BoxLinkSchema = z6.object({ from: z6.string(), port: BoxPortSchema });
1926
- var LinkRequest = z6.object({ from: z6.string().min(1), fromOwner: z6.string().optional(), port: BoxPortSchema });
1979
+ var LinkRequest = z6.object({
1980
+ from: z6.string().min(1),
1981
+ fromOwner: z6.string().optional(),
1982
+ port: BoxPortSchema,
1983
+ /**
1984
+ * The box `from` is on another host (#207, a control plane's call only): no rule opens here. Its host
1985
+ * connects to this host's HTTPS listener (`BOX_LINK_PATH_RE`) with `key`, which this link alone answers to.
1986
+ */
1987
+ far: z6.object({ key: z6.string().min(32) }).optional()
1988
+ });
1989
+ var FarLinkRequest = z6.object({
1990
+ to: z6.string().min(1),
1991
+ toOwner: z6.string().optional(),
1992
+ port: BoxPortSchema,
1993
+ url: z6.string().url(),
1994
+ pin: z6.string().min(1),
1995
+ key: z6.string().min(32)
1996
+ });
1997
+ var FarUnlinkRequest = FarLinkRequest.pick({ to: true, toOwner: true, port: true });
1927
1998
  var ClaimSubdomainRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
1928
1999
  var SubdomainPortRequest = z6.object({ port: BoxPortSchema });
1929
2000
  var SubdomainRouteRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
@@ -1989,7 +2060,10 @@ var BackupSchema = z6.object({
1989
2060
  dataBytes: z6.number().int().nullable(),
1990
2061
  /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
1991
2062
  uploadedBytes: z6.number().int().nullable(),
2063
+ /** Who asked for it; for a scheduled one, whoever made the thing it is of. */
1992
2064
  createdBy: z6.string().nullable(),
2065
+ /** Taken by its nightly schedule (`backup-schedule`) rather than by a person: free, and outside the daily limit. */
2066
+ scheduled: z6.boolean().default(false),
1993
2067
  createdAt: z6.string(),
1994
2068
  finishedAt: z6.string().nullable()
1995
2069
  });
@@ -2039,7 +2113,10 @@ var VolumeBackupSchema = z6.object({
2039
2113
  dataBytes: z6.number().int().nullable(),
2040
2114
  /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
2041
2115
  uploadedBytes: z6.number().int().nullable(),
2116
+ /** Who asked for it; for a scheduled one, whoever made the thing it is of. */
2042
2117
  createdBy: z6.string().nullable(),
2118
+ /** Taken by its nightly schedule (`backup-schedule`) rather than by a person: free, and outside the daily limit. */
2119
+ scheduled: z6.boolean().default(false),
2043
2120
  createdAt: z6.string(),
2044
2121
  finishedAt: z6.string().nullable()
2045
2122
  });
@@ -2181,7 +2258,7 @@ var MachineSchema = z6.object({
2181
2258
  ownerKind: z6.enum(["user", "org"]).optional(),
2182
2259
  /**
2183
2260
  * The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
2184
- * links to, and a volume attaches to, only a box on the same host.
2261
+ * a volume attaches only to a box on the same host, and a link between two boxes of one host stays on it.
2185
2262
  */
2186
2263
  host: z6.string().optional(),
2187
2264
  /** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
@@ -2481,6 +2558,8 @@ var CapacitySchema = z6.object({
2481
2558
  fromBackup: z6.boolean().optional(),
2482
2559
  /** True on a kvbox-server that keeps a box's `integrations` (#205); an older one drops the field without a word. */
2483
2560
  integrations: z6.boolean().optional(),
2561
+ /** True on a kvbox-server that carries a link to a box on another host (#207); the control plane links across hosts only between two such. */
2562
+ farLinks: z6.boolean().optional(),
2484
2563
  /** The integrations this kvbox-server knows (`hostKnowsIntegrations`). Absent with `integrations`: the first one's, `github` alone. */
2485
2564
  integrationIds: z6.array(z6.string()).optional()
2486
2565
  });
@@ -2624,7 +2703,9 @@ var BackupUsageSchema = z6.object({
2624
2703
  ownerKind: z6.enum(["user", "org"]).optional(),
2625
2704
  /** How many paid backups turned ready in the window. */
2626
2705
  count: z6.number().int(),
2627
- cost: z6.object({ amount: z6.number(), currency: z6.string() })
2706
+ cost: z6.object({ amount: z6.number(), currency: z6.string() }),
2707
+ /** The part of `cost` that nightly backups someone switched on make up: it recurs, the rest is one-off. Absent when none. */
2708
+ nightlyCost: z6.number().optional()
2628
2709
  });
2629
2710
  var UsageDayItemSchema = z6.object({
2630
2711
  id: z6.string(),
@@ -3562,9 +3643,9 @@ function forStore(url, p = paths()) {
3562
3643
  return isStoreRequest(url) && existsSync6(p.backupStore.conf);
3563
3644
  }
3564
3645
  function storeProxy(req, res, port = GARAGE_S3_PORT) {
3565
- const up = httpRequest({ host: "127.0.0.1", port, method: req.method, path: req.url, headers: req.headers }, (answer) => {
3566
- res.writeHead(answer.statusCode ?? 502, answer.headers);
3567
- pipeline(answer, res, (err) => {
3646
+ const up = httpRequest({ host: "127.0.0.1", port, method: req.method, path: req.url, headers: req.headers }, (answer2) => {
3647
+ res.writeHead(answer2.statusCode ?? 502, answer2.headers);
3648
+ pipeline(answer2, res, (err) => {
3568
3649
  if (err) res.destroy();
3569
3650
  });
3570
3651
  });
@@ -3613,6 +3694,9 @@ async function capacity(p = paths()) {
3613
3694
  storeClient: true,
3614
3695
  // A new box on a backup's disk (#141): the control plane places `new --from-backup` only here.
3615
3696
  fromBackup: true,
3697
+ // A link to a box on another host is carried here (#207): the control plane links across hosts only between two such.
3698
+ // Only once the host's privileged network script knows them: an update without its root step does not.
3699
+ farLinks: driver().net.carriesFarLinks(),
3616
3700
  // A box's integrations are kept here (#205): the control plane sends a list only to such a host.
3617
3701
  integrations: true,
3618
3702
  // ...and which (the control plane places a box with `claude` only on a host that names it).
@@ -4051,15 +4135,15 @@ async function ask(cp, body) {
4051
4135
  }
4052
4136
  }
4053
4137
  async function askCredential(cp, box, integration) {
4054
- let answer;
4138
+ let answer2;
4055
4139
  try {
4056
- answer = await ask(cp, { owner: box.owner, box: box.name, integration });
4140
+ answer2 = await ask(cp, { owner: box.owner, box: box.name, integration });
4057
4141
  } catch (err) {
4058
4142
  return unavailable(`${cp.name} could not be reached (${err.message}); try again shortly`);
4059
4143
  }
4060
- if (answer.status === 404) return unavailable(`${cp.name} has no integrations yet`);
4061
- const parsed = CredentialAnswerSchema.safeParse(answer.json);
4062
- if (!parsed.success) return unavailable(`${cp.name} answered ${answer.status}; try again shortly`);
4144
+ if (answer2.status === 404) return unavailable(`${cp.name} has no integrations yet`);
4145
+ const parsed = CredentialAnswerSchema.safeParse(answer2.json);
4146
+ if (!parsed.success) return unavailable(`${cp.name} answered ${answer2.status}; try again shortly`);
4063
4147
  return parsed.data;
4064
4148
  }
4065
4149
  var probes = /* @__PURE__ */ new Map();
@@ -4088,7 +4172,7 @@ var REQUEST_TIMEOUT_MS = 5e3;
4088
4172
  var MAX_OPEN = 32;
4089
4173
  var listeners = /* @__PURE__ */ new Map();
4090
4174
  var unreadable = (message) => ({ ok: false, code: "unavailable", message });
4091
- function serve(sock, answer, timeoutMs) {
4175
+ function serve(sock, answer2, timeoutMs) {
4092
4176
  let buf = "";
4093
4177
  let taken = false;
4094
4178
  const reply = (body) => {
@@ -4114,17 +4198,17 @@ function serve(sock, answer, timeoutMs) {
4114
4198
  } catch {
4115
4199
  return reply(unreadable("the request is not JSON"));
4116
4200
  }
4117
- answer(request7).then(reply, (err) => reply(unreadable(err.message)));
4201
+ answer2(request7).then(reply, (err) => reply(unreadable(err.message)));
4118
4202
  });
4119
4203
  }
4120
- async function listenGuest(path, answer, timeoutMs = REQUEST_TIMEOUT_MS) {
4204
+ async function listenGuest(path, answer2, timeoutMs = REQUEST_TIMEOUT_MS) {
4121
4205
  await closeGuest(path);
4122
4206
  await rm5(path, { force: true });
4123
- const open3 = /* @__PURE__ */ new Set();
4207
+ const open4 = /* @__PURE__ */ new Set();
4124
4208
  const server = createServer((sock) => {
4125
- open3.add(sock);
4126
- sock.once("close", () => open3.delete(sock));
4127
- serve(sock, answer, timeoutMs);
4209
+ open4.add(sock);
4210
+ sock.once("close", () => open4.delete(sock));
4211
+ serve(sock, answer2, timeoutMs);
4128
4212
  });
4129
4213
  server.maxConnections = MAX_OPEN;
4130
4214
  await new Promise((resolve3, reject) => {
@@ -4136,7 +4220,7 @@ async function listenGuest(path, answer, timeoutMs = REQUEST_TIMEOUT_MS) {
4136
4220
  });
4137
4221
  server.unref();
4138
4222
  server.on("error", () => void 0);
4139
- listeners.set(path, { server, open: open3 });
4223
+ listeners.set(path, { server, open: open4 });
4140
4224
  }
4141
4225
  async function closeGuest(path) {
4142
4226
  const l = listeners.get(path);
@@ -4226,11 +4310,11 @@ async function answerGuest(ref, request7, p, now = Date.now()) {
4226
4310
  const probe = await probeConnection(cp, meta, integration, now);
4227
4311
  return refusal("off", `${integration} is not turned on for this box`, probe?.connected);
4228
4312
  }
4229
- const answer = await askCredential(cp, meta, integration);
4230
- if (answer.ok && answer.identity && !(told.has(meta.id) && sameIdentity(told.get(meta.id), answer.identity))) {
4231
- void tellCurrent(ref, p.machine(meta.owner, meta.name).vsock, p, answer.identity).catch(() => void 0);
4313
+ const answer2 = await askCredential(cp, meta, integration);
4314
+ if (answer2.ok && answer2.identity && !(told.has(meta.id) && sameIdentity(told.get(meta.id), answer2.identity))) {
4315
+ void tellCurrent(ref, p.machine(meta.owner, meta.name).vsock, p, answer2.identity).catch(() => void 0);
4232
4316
  }
4233
- return answer;
4317
+ return answer2;
4234
4318
  }
4235
4319
  var told = /* @__PURE__ */ new Map();
4236
4320
  var sameIdentity = (a, b) => a?.name === b?.name && a?.email === b?.email;
@@ -4251,12 +4335,12 @@ async function identityOf(box, p) {
4251
4335
  var sameList = (a, b) => JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
4252
4336
  async function tellCurrent(ref, vsock, p, identity) {
4253
4337
  for (; ; ) {
4254
- const asked2 = await readMachineMeta(ref, p);
4255
- const who = identity !== void 0 && (asked2.integrations ?? []).includes("github") ? identity : await identityOf(asked2, p);
4338
+ const asked3 = await readMachineMeta(ref, p);
4339
+ const who = identity !== void 0 && (asked3.integrations ?? []).includes("github") ? identity : await identityOf(asked3, p);
4256
4340
  if (who === null) return false;
4257
4341
  const done = await withBoxLock(ref, async () => {
4258
4342
  const box = await readMachineMeta(ref, p);
4259
- if (!sameList(box.integrations, asked2.integrations)) return false;
4343
+ if (!sameList(box.integrations, asked3.integrations)) return false;
4260
4344
  const unusable = await tellGuest(box, vsock, who);
4261
4345
  if (unusable.length > 0) log.warn(`box ${shown(box)} has integrations it cannot use: ${tooOldFor(box, unusable)}`);
4262
4346
  return true;
@@ -4375,9 +4459,13 @@ function toMachine(meta, p = paths()) {
4375
4459
  ...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
4376
4460
  ...meta.integrations?.length ? { integrations: [...meta.integrations] } : {},
4377
4461
  ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
4378
- ...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
4462
+ ...linksOf(meta)
4379
4463
  };
4380
4464
  }
4465
+ function linksOf(meta) {
4466
+ const all = [...(meta.links ?? []).filter((l) => !l.stale), ...meta.farLinks ?? []];
4467
+ return all.length > 0 ? { links: all.map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {};
4468
+ }
4381
4469
  var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
4382
4470
  async function listMachines(scope, p = paths()) {
4383
4471
  return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
@@ -4605,8 +4693,326 @@ function pickSshPort(taken) {
4605
4693
  throw new KvboxError(`no free port left between ${SSH_PORT_MIN} and ${SSH_PORT_MAX} on this host`);
4606
4694
  }
4607
4695
 
4696
+ // src/core/farTunnel.ts
4697
+ import { createServer as createServer2 } from "node:net";
4698
+ import { connect as tlsConnect } from "node:tls";
4699
+
4700
+ // ../shared/src/httpHead.ts
4701
+ var END = "\r\n\r\n";
4702
+ var HeadTimeoutError = class extends Error {
4703
+ };
4704
+ function readHead(socket, opts) {
4705
+ return new Promise((resolve3, reject) => {
4706
+ let bytes = Buffer.alloc(0);
4707
+ const done = (err) => {
4708
+ clearTimeout(timer);
4709
+ socket.off("data", onData);
4710
+ socket.off("close", onClose);
4711
+ socket.pause();
4712
+ if (err) return reject(err);
4713
+ const end = bytes.indexOf(END);
4714
+ resolve3({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
4715
+ };
4716
+ const onData = (chunk) => {
4717
+ bytes = Buffer.concat([bytes, chunk]);
4718
+ if (bytes.includes(END)) done();
4719
+ else if (bytes.length > opts.maxBytes) done(new Error("answer head too large"));
4720
+ };
4721
+ const onClose = () => done(new Error("closed before answering"));
4722
+ const timer = setTimeout(() => done(new HeadTimeoutError(`no answer within ${opts.timeoutMs / 1e3} s`)), opts.timeoutMs);
4723
+ socket.on("data", onData);
4724
+ socket.once("close", onClose);
4725
+ });
4726
+ }
4727
+ function headStatus(head) {
4728
+ const m = /^HTTP\/\d(?:\.\d)? (\d{3})(?: |\r|$)/.exec(head);
4729
+ return m ? Number(m[1]) : void 0;
4730
+ }
4731
+ function headHeader(head, name) {
4732
+ const line = head.split("\r\n").slice(1).find((l) => l.slice(0, l.indexOf(":")).trim().toLowerCase() === name);
4733
+ return line?.slice(line.indexOf(":") + 1).trim();
4734
+ }
4735
+ function rewriteHead(head, drop, add = {}) {
4736
+ const [status, ...lines] = head.split("\r\n");
4737
+ const kept = lines.filter((l) => !drop(l.slice(0, l.indexOf(":")).trim().toLowerCase()));
4738
+ const extra = Object.entries(add).map(([k, v]) => `${k}: ${v}`);
4739
+ return Buffer.from(`${[status, ...kept, ...extra].join("\r\n")}${END}`, "latin1");
4740
+ }
4741
+
4742
+ // ../shared/src/names.ts
4743
+ import { createHmac } from "node:crypto";
4744
+ var PROXY_ERROR_HEADER = "x-kvbox-proxy-error";
4745
+ var PROXIED_HEADER = "x-kvbox-proxied";
4746
+ var VISITOR_PATH_HEADER = "x-kvbox-path";
4747
+ var WAKE_HEADER = "x-kvbox-wake";
4748
+ var WAKE_WAIT_MS = 3e4;
4749
+ var REQUEST_TIMEOUT_MS2 = 36e5;
4750
+ var WOKE_HEADER = "x-kvbox-woke";
4751
+ var VISITOR_AUTH_HEADER = "x-kvbox-authorization";
4752
+ var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
4753
+ var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
4754
+ var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
4755
+ function edgeCredential(hostSecret) {
4756
+ return createHmac("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
4757
+ }
4758
+ var BOX_LINK_PATH_RE = /^\/machines\/([^/]+)\/link\/(\d{1,5})\/?$/;
4759
+ var LINK_PROTOCOL = "kvbox-link";
4760
+ var LINK_ERROR_HEADER = "x-kvbox-link-error";
4761
+ var BOX_RUN_PATH_RE = /^\/machines\/([^/]+)\/runs(\/[A-Za-z0-9_-]{1,64})?\/?$/;
4762
+ function cronCredential(hostSecret) {
4763
+ return createHmac("sha256", hostSecret).update("kvbox-cron-v1").digest("base64url");
4764
+ }
4765
+
4766
+ // src/core/farTunnel.ts
4767
+ var FarRefusal = class extends Error {
4768
+ constructor(code, message) {
4769
+ super(message);
4770
+ this.code = code;
4771
+ this.name = "FarRefusal";
4772
+ }
4773
+ code;
4774
+ };
4775
+ var DIAL_TIMEOUT_MS = 1e4;
4776
+ var MAX_HEAD_BYTES = 16 * 1024;
4777
+ var MAX_OPEN2 = 256;
4778
+ var WARN_EVERY_MS = 6e4;
4779
+ var KEEPALIVE_MS = 3e4;
4780
+ function splice(a, b) {
4781
+ for (const s of [a, b]) {
4782
+ s.allowHalfOpen = true;
4783
+ s.setKeepAlive(true, KEEPALIVE_MS);
4784
+ }
4785
+ a.pipe(b);
4786
+ b.pipe(a);
4787
+ const after = (gone, other) => (hadError) => {
4788
+ if (hadError || other.writableFinished || gone.errored) return void other.destroy();
4789
+ other.end(() => other.destroy());
4790
+ };
4791
+ a.once("close", after(a, b));
4792
+ b.once("close", after(b, a));
4793
+ }
4794
+ function connectPinned(url, pin, timeoutMs) {
4795
+ const target = new URL(url);
4796
+ return new Promise((resolve3, reject) => {
4797
+ const socket = tlsConnect({ host: target.hostname, port: Number(target.port || 443), rejectUnauthorized: false, timeout: timeoutMs });
4798
+ socket.allowHalfOpen = true;
4799
+ socket.once("timeout", () => socket.destroy(new Error(`no answer within ${timeoutMs / 1e3} s`)));
4800
+ socket.once("error", reject);
4801
+ socket.once("secureConnect", () => {
4802
+ if (socket.getPeerCertificate().fingerprint256 !== pin) {
4803
+ socket.destroy();
4804
+ return reject(new Error("its certificate is not the one the control plane named (fingerprint mismatch)"));
4805
+ }
4806
+ socket.setTimeout(0);
4807
+ socket.off("error", reject);
4808
+ socket.on("error", () => socket.destroy());
4809
+ resolve3(socket);
4810
+ });
4811
+ });
4812
+ }
4813
+ async function ask2(t, method, timeoutMs) {
4814
+ const socket = await connectPinned(t.url, t.pin, timeoutMs);
4815
+ const slug = t.owner.split("@")[0];
4816
+ socket.write(
4817
+ `${method} /machines/${encodeURIComponent(t.name)}/link/${t.port} HTTP/1.1\r
4818
+ host: ${new URL(t.url).host}\r
4819
+ connection: Upgrade\r
4820
+ upgrade: ${LINK_PROTOCOL}\r
4821
+ authorization: Bearer ${t.key}\r
4822
+ x-kvbox-owner: ${slug}\r
4823
+ \r
4824
+ `
4825
+ );
4826
+ try {
4827
+ return { socket, ...await readHead(socket, { maxBytes: MAX_HEAD_BYTES, timeoutMs }) };
4828
+ } catch (err) {
4829
+ socket.destroy();
4830
+ throw err;
4831
+ }
4832
+ }
4833
+ var refusal2 = (head) => {
4834
+ const code = headHeader(head, LINK_ERROR_HEADER);
4835
+ return new FarRefusal(code === "gone" || code === "down" || code === "unreachable" ? code : "refused", `the other host answered ${headStatus(head) ?? "nothing it should"}${code ? ` (${code})` : ""}`);
4836
+ };
4837
+ async function dialFar(t, timeoutMs = DIAL_TIMEOUT_MS) {
4838
+ const { socket, head, rest } = await ask2(t, "GET", timeoutMs);
4839
+ if (headStatus(head) === 101) return { socket, rest };
4840
+ socket.destroy();
4841
+ throw refusal2(head);
4842
+ }
4843
+ async function dropFar(t, timeoutMs = DIAL_TIMEOUT_MS) {
4844
+ const { socket, head } = await ask2(t, "DELETE", timeoutMs);
4845
+ socket.destroy();
4846
+ if (headStatus(head) === 200) return;
4847
+ const refused = refusal2(head);
4848
+ if (refused.code !== "gone") throw refused;
4849
+ }
4850
+ 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;
4851
+ var listeners2 = /* @__PURE__ */ new Map();
4852
+ async function listenFar(id, opts) {
4853
+ const have = listeners2.get(id);
4854
+ if (have && sameTarget(have.target, opts.target)) return have.port;
4855
+ if (have) await closeFar(id);
4856
+ const open4 = /* @__PURE__ */ new Set();
4857
+ const track = (s) => {
4858
+ open4.add(s);
4859
+ s.once("close", () => open4.delete(s));
4860
+ };
4861
+ let warnedAt = 0;
4862
+ const server = createServer2({ allowHalfOpen: true }, (box) => {
4863
+ track(box);
4864
+ box.on("error", () => box.destroy());
4865
+ if (box.remoteAddress !== opts.fromIp) return void box.destroy();
4866
+ dialFar(opts.target, opts.dialTimeoutMs).then(
4867
+ ({ socket, rest }) => {
4868
+ if (box.destroyed) return void socket.destroy();
4869
+ track(socket);
4870
+ if (rest.length > 0) box.write(rest);
4871
+ splice(box, socket);
4872
+ },
4873
+ (err) => {
4874
+ box.destroy();
4875
+ if (err instanceof FarRefusal && err.code === "gone") return opts.onGone?.();
4876
+ if (err instanceof FarRefusal && err.code !== "refused") return;
4877
+ if (Date.now() - warnedAt < WARN_EVERY_MS) return;
4878
+ warnedAt = Date.now();
4879
+ log.warn(`link to ${opts.target.name} port ${opts.target.port} on another host: ${err.message}`);
4880
+ }
4881
+ );
4882
+ });
4883
+ server.maxConnections = MAX_OPEN2;
4884
+ await new Promise((resolve3, reject) => {
4885
+ server.once("error", reject);
4886
+ server.listen(0, opts.host, () => {
4887
+ server.off("error", reject);
4888
+ resolve3();
4889
+ });
4890
+ });
4891
+ server.unref();
4892
+ server.on("error", () => void 0);
4893
+ const port = server.address().port;
4894
+ listeners2.set(id, { server, open: open4, port, target: { ...opts.target } });
4895
+ return port;
4896
+ }
4897
+ async function closeFar(id) {
4898
+ const l = listeners2.get(id);
4899
+ if (!l) return;
4900
+ listeners2.delete(id);
4901
+ for (const sock of l.open) sock.destroy();
4902
+ await new Promise((resolve3) => l.server.close(() => resolve3()));
4903
+ }
4904
+
4905
+ // src/core/machines/farTargets.ts
4906
+ var listenerId = (boxId, t) => `${boxId}|${t.owner}/${t.name}:${t.port}`;
4907
+ var sameTarget2 = (to, port) => (t) => t.owner === to.owner && t.name === to.name && t.port === port;
4908
+ function targetRef(req, caller) {
4909
+ if (req.toOwner !== void 0) return { owner: ownerFor(req.toOwner, caller), name: req.to, display: `${req.toOwner}/${req.to}` };
4910
+ return parseRef(req.to, caller);
4911
+ }
4912
+ async function open(meta, t, cfg, p) {
4913
+ const ref = { owner: meta.owner, name: meta.name };
4914
+ const via = await listenFar(listenerId(meta.id, t), {
4915
+ host: driver().net.farListenHost(cfg),
4916
+ fromIp: meta.ip,
4917
+ target: t,
4918
+ // The listener was made under the box's lock, and its connections would read as holding it: the forget
4919
+ // waits for the lock like any other change of the box.
4920
+ onGone: () => outsideLocks(() => void forgetFarTarget(ref, t, p).catch((err) => log.warn(`box ${meta.name}: could not forget its link to ${t.name}: ${err.message}`)))
4921
+ });
4922
+ await driver().net.openFarLink({ box: meta.id, fromIp: meta.ip, standIn: t.ip, port: t.port, via }, cfg);
4923
+ }
4924
+ async function close(meta, t, cfg) {
4925
+ try {
4926
+ await driver().net.closeFarLink({ box: meta.id, fromIp: meta.ip, standIn: t.ip, port: t.port }, cfg);
4927
+ } finally {
4928
+ await closeFar(listenerId(meta.id, t));
4929
+ }
4930
+ }
4931
+ async function openFarTargets(meta, cfg, p) {
4932
+ for (const t of meta.farTargets ?? []) {
4933
+ 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}`));
4934
+ }
4935
+ }
4936
+ async function closeFarTargets(meta, cfg) {
4937
+ for (const t of meta.farTargets ?? []) {
4938
+ 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}`));
4939
+ }
4940
+ }
4941
+ async function reopenFarTargets(p = paths()) {
4942
+ const cfg = await loadConfig(p);
4943
+ for (const listed of await readAllMeta(p)) {
4944
+ if (!vmAlive(listed) || !listed.farTargets?.length) continue;
4945
+ await withBoxLock(listed, async () => {
4946
+ const meta = await readMachineMeta(listed, p).catch(() => null);
4947
+ if (meta !== null && vmAlive(meta)) await openFarTargets(meta, cfg, p);
4948
+ });
4949
+ }
4950
+ }
4951
+ var addFarTarget = locked(async function addFarTarget2(ref, req, caller, p = paths()) {
4952
+ const meta = await readMeta(ref, p);
4953
+ const to = targetRef(req, caller);
4954
+ if (realmOf(meta.owner) === null || realmOf(to.owner) !== realmOf(meta.owner)) {
4955
+ 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`);
4956
+ }
4957
+ const cfg = await loadConfig(p);
4958
+ const same = sameTarget2(to, req.port);
4959
+ const before = (meta.farTargets ?? []).find(same);
4960
+ const kept = (meta.farTargets ?? []).filter((t) => !same(t));
4961
+ 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}`);
4962
+ return withHostLock("links", async () => {
4963
+ const taken = (await readAllMeta(p)).flatMap((m) => m.farTargets ?? []);
4964
+ const ip = taken.find((t) => t.owner === to.owner && t.name === to.name)?.ip ?? driver().net.standIn(cfg, taken.map((t) => t.ip));
4965
+ const entry = { owner: to.owner, name: to.name, port: req.port, ip, url: req.url, pin: req.pin, key: req.key };
4966
+ const next = { ...meta, farTargets: [...kept, entry] };
4967
+ if (before) await close(meta, before, cfg);
4968
+ await writeMachineMeta(next, p);
4969
+ boxListChanged();
4970
+ if (vmAlive(meta)) {
4971
+ try {
4972
+ await open(next, entry, cfg, p);
4973
+ } catch (err) {
4974
+ await close(next, entry, cfg).catch(() => void 0);
4975
+ await writeMachineMeta(meta, p);
4976
+ boxListChanged();
4977
+ 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}`));
4978
+ throw err;
4979
+ }
4980
+ }
4981
+ return toMachine(next, p);
4982
+ });
4983
+ });
4984
+ var removeFarTarget = locked(async function removeFarTarget2(ref, req, caller, p = paths()) {
4985
+ const meta = await readMeta(ref, p);
4986
+ const same = sameTarget2(targetRef(req, caller), req.port);
4987
+ const gone = (meta.farTargets ?? []).filter(same);
4988
+ if (gone.length === 0) return toMachine(meta, p);
4989
+ return toMachine(await without(meta, gone, p), p);
4990
+ });
4991
+ async function without(meta, gone, p) {
4992
+ const cfg = await loadConfig(p);
4993
+ for (const t of gone) await close(meta, t, cfg);
4994
+ const kept = (meta.farTargets ?? []).filter((t) => !gone.includes(t));
4995
+ const next = { ...meta, farTargets: kept.length > 0 ? kept : void 0 };
4996
+ await writeMachineMeta(next, p);
4997
+ boxListChanged();
4998
+ return next;
4999
+ }
5000
+ var forgetFarTarget = locked(async function forgetFarTarget2(ref, t, p) {
5001
+ const meta = await readMachineMeta(ref, p).catch(() => null);
5002
+ const gone = (meta?.farTargets ?? []).filter((now) => now.owner === t.owner && now.name === t.name && now.port === t.port && now.key === t.key);
5003
+ if (meta === null || gone.length === 0) return;
5004
+ await without(meta, gone, p);
5005
+ log.info(`box ${meta.name}: its link to ${t.name} port ${t.port} no longer exists on the other host; forgotten here`);
5006
+ });
5007
+ function tellFarTargetsGone(gone) {
5008
+ for (const t of gone.farTargets ?? []) {
5009
+ void dropFar(t).catch((err) => log.warn(`removed box ${gone.name}: its link into ${t.name} on another host stays listed there (${err.message})`));
5010
+ }
5011
+ }
5012
+
4608
5013
  // src/core/machines/ports.ts
4609
5014
  var publicPortsInUse = (metas) => metas.flatMap((m) => [...m.sshPort === void 0 ? [] : [m.sshPort], ...(m.ports ?? []).map((f) => f.hostPort)]);
5015
+ var reaching = (meta) => meta.farTargets?.length && meta.owner !== void 0 && meta.name !== void 0 ? { ...meta, owner: meta.owner, name: meta.name } : null;
4610
5016
  function boxProxies(meta) {
4611
5017
  const ssh = meta.sshPort === void 0 ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];
4612
5018
  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 }))];
@@ -4626,6 +5032,8 @@ async function openPorts(meta, cfg, p) {
4626
5032
  for (const link4 of await standingLinks(meta, p)) {
4627
5033
  await driver().net.openLink(link4, cfg).catch((err) => log.warn(`could not open the link from ${link4.fromIp}: ${err.message}`));
4628
5034
  }
5035
+ const far = reaching(meta);
5036
+ if (far) await openFarTargets(far, cfg, p);
4629
5037
  }
4630
5038
  async function closePorts(meta, cfg) {
4631
5039
  for (const proxy of boxProxies(meta)) {
@@ -4634,6 +5042,8 @@ async function closePorts(meta, cfg) {
4634
5042
  for (const link4 of boxLinks(meta)) {
4635
5043
  await driver().net.closeLink(link4, cfg).catch((err) => log.warn(`could not close the link from ${link4.fromIp}: ${err.message}`));
4636
5044
  }
5045
+ const far = reaching(meta);
5046
+ if (far) await closeFarTargets(far, cfg);
4637
5047
  }
4638
5048
  var reservedPorts = /* @__PURE__ */ new Set();
4639
5049
  async function drawPorts(count, p) {
@@ -4675,15 +5085,15 @@ var addPorts = locked(async function addPorts2(ref, req, p = paths()) {
4675
5085
  const opened = [];
4676
5086
  try {
4677
5087
  const added = fresh.map((w, i) => ({ ...w, hostPort: drawn.ports[i] }));
4678
- const open3 = ({ closed: _closed, ...f }) => f;
4679
- const again = current2.filter((f) => reopened.some(samePort(f))).map(open3);
5088
+ const open4 = ({ closed: _closed, ...f }) => f;
5089
+ const again = current2.filter((f) => reopened.some(samePort(f))).map(open4);
4680
5090
  if (vmAlive(meta)) {
4681
5091
  for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: [...again, ...added] })) {
4682
5092
  await driver().net.openProxy(proxy, cfg);
4683
5093
  opened.push(proxy);
4684
5094
  }
4685
5095
  }
4686
- const next = { ...meta, ports: [...current2.map((f) => reopened.some(samePort(f)) ? open3(f) : f), ...added] };
5096
+ const next = { ...meta, ports: [...current2.map((f) => reopened.some(samePort(f)) ? open4(f) : f), ...added] };
4687
5097
  await writeMachineMeta(next, p);
4688
5098
  return toMachine(next, p);
4689
5099
  } catch (err) {
@@ -4857,6 +5267,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
4857
5267
  import { rm as rm7 } from "node:fs/promises";
4858
5268
 
4859
5269
  // src/core/machines/links.ts
5270
+ import { createHash as createHash3, timingSafeEqual } from "node:crypto";
4860
5271
  function linkSource(req, caller, target) {
4861
5272
  if (req.fromOwner !== void 0) return { owner: ownerFor(req.fromOwner, caller), name: req.from, display: `${req.fromOwner}/${req.from}` };
4862
5273
  const ref = parseRef(req.from, caller);
@@ -4867,6 +5278,7 @@ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
4867
5278
  const meta = await readMeta(ref, p);
4868
5279
  const fromRef = linkSource(req, caller, meta.owner);
4869
5280
  if (fromRef.owner === meta.owner && fromRef.name === meta.name) throw new KvboxError(`box ${shown(ref)} already reaches itself`);
5281
+ if (req.far !== void 0) return addFarLink(meta, fromRef, req.port, req.far.key, p);
4870
5282
  const from = await readMeta(fromRef, p);
4871
5283
  if (realmOf(from.owner) !== realmOf(meta.owner)) {
4872
5284
  throw new KvboxError(`box ${shown(fromRef)} and box ${shown(ref)} belong to different realms (one is this host's, one a control plane's); a link joins boxes of one realm`);
@@ -4874,7 +5286,8 @@ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
4874
5286
  const links = (meta.links ?? []).filter((l) => !(l.stale && l.owner === from.owner && l.name === from.name && l.ip === from.ip && l.port === req.port));
4875
5287
  const same = (l) => !l.stale && l.owner === from.owner && l.name === from.name && l.port === req.port;
4876
5288
  if (links.some(same)) throw new KvboxError(`box ${shown(fromRef)} already reaches box ${shown(ref)} on port ${req.port}`);
4877
- if (links.length >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${shown(ref)} has ${links.length}`);
5289
+ const held2 = links.length + (meta.farLinks?.length ?? 0);
5290
+ if (held2 >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${shown(ref)} has ${held2}`);
4878
5291
  const added = { owner: from.owner, name: from.name, ip: from.ip, port: req.port };
4879
5292
  const cfg = await loadConfig(p);
4880
5293
  if (vmAlive(meta)) await driver().net.openLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg);
@@ -4887,16 +5300,60 @@ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
4887
5300
  }
4888
5301
  return toMachine(next, p);
4889
5302
  });
5303
+ var keyHash = (key) => createHash3("sha256").update(key).digest("hex");
5304
+ async function addFarLink(meta, from, port, key, p) {
5305
+ if (realmOf(meta.owner) === null || realmOf(from.owner) !== realmOf(meta.owner)) {
5306
+ throw new KvboxError(`a link from a box on another host joins two boxes of one control plane; box ${shown(from)} and box ${meta.name} are not`);
5307
+ }
5308
+ const same = (l) => l.owner === from.owner && l.name === from.name && l.port === port;
5309
+ if ((meta.links ?? []).some((l) => !l.stale && same(l)) || (meta.farLinks ?? []).some(same)) {
5310
+ throw new KvboxError(`box ${shown(from)} already reaches box ${meta.name} on port ${port}; to link it again, unlink it first`);
5311
+ }
5312
+ const kept = meta.farLinks ?? [];
5313
+ const held2 = (meta.links ?? []).filter((l) => !l.stale).length + kept.length;
5314
+ if (held2 >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${meta.name} has ${held2}`);
5315
+ const next = { ...meta, farLinks: [...kept, { owner: from.owner, name: from.name, port, key: keyHash(key) }] };
5316
+ await writeMachineMeta(next, p);
5317
+ return toMachine(next, p);
5318
+ }
5319
+ var holdsKey = (key, port) => {
5320
+ const given = Buffer.from(keyHash(key), "hex");
5321
+ return (l) => {
5322
+ const kept = Buffer.from(l.key, "hex");
5323
+ return l.port === port && kept.length === given.length && timingSafeEqual(kept, given);
5324
+ };
5325
+ };
5326
+ async function metaIfAny(ref, p) {
5327
+ return readMachineMeta(ref, p).catch((err) => {
5328
+ if (err.code === "ENOENT") return null;
5329
+ throw err;
5330
+ });
5331
+ }
5332
+ async function farLinkInto(ref, port, key, p = paths()) {
5333
+ const meta = await metaIfAny(ref, p);
5334
+ if (!meta?.farLinks?.some(holdsKey(key, port))) return "gone";
5335
+ return vmAlive(meta) && !meta.paused ? { ip: meta.ip } : "down";
5336
+ }
5337
+ var dropFarLink = locked(async function dropFarLink2(ref, port, key, p = paths()) {
5338
+ const meta = await metaIfAny(ref, p);
5339
+ const holds = holdsKey(key, port);
5340
+ if (!meta?.farLinks?.some(holds)) return false;
5341
+ const kept = meta.farLinks.filter((l) => !holds(l));
5342
+ await writeMachineMeta({ ...meta, farLinks: kept.length > 0 ? kept : void 0 }, p);
5343
+ return true;
5344
+ });
4890
5345
  var removeLink = locked(async function removeLink2(ref, req, caller, p = paths()) {
4891
5346
  const meta = await readMeta(ref, p);
4892
5347
  const fromRef = linkSource(req, caller, meta.owner);
4893
5348
  const links = meta.links ?? [];
4894
5349
  const gone = links.filter((l) => !l.stale && l.owner === fromRef.owner && l.name === fromRef.name && l.port === req.port);
4895
- if (gone.length === 0) throw new KvboxError(`box ${shown(fromRef)} is not linked to box ${shown(ref)} on port ${req.port}`);
5350
+ const far = (meta.farLinks ?? []).filter((l) => !(l.owner === fromRef.owner && l.name === fromRef.name && l.port === req.port));
5351
+ const hadFar = far.length !== (meta.farLinks?.length ?? 0);
5352
+ if (gone.length === 0 && !hadFar) throw new KvboxError(`box ${shown(fromRef)} is not linked to box ${shown(ref)} on port ${req.port}`);
4896
5353
  const cfg = await loadConfig(p);
4897
5354
  for (const l of gone) await driver().net.closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg);
4898
5355
  const kept = links.filter((l) => !gone.includes(l));
4899
- const next = { ...meta, links: kept.length > 0 ? kept : void 0 };
5356
+ const next = { ...meta, links: kept.length > 0 ? kept : void 0, farLinks: far.length > 0 ? far : void 0 };
4900
5357
  await writeMachineMeta(next, p);
4901
5358
  return toMachine(next, p);
4902
5359
  });
@@ -4976,7 +5433,11 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
4976
5433
  });
4977
5434
  async function destroyMachine(ref, p = paths()) {
4978
5435
  const gone = await destroyBox(ref, p);
4979
- await dropLinksFrom(gone, p);
5436
+ try {
5437
+ await dropLinksFrom(gone, p);
5438
+ } finally {
5439
+ tellFarTargetsGone(gone);
5440
+ }
4980
5441
  }
4981
5442
  var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
4982
5443
  const meta = await readMeta(ref, p);
@@ -5675,12 +6136,12 @@ async function replaceVolumeDisk(volume, file, p = paths()) {
5675
6136
  // src/core/backups.ts
5676
6137
  import { randomBytes as randomBytes5 } from "node:crypto";
5677
6138
  import { existsSync as existsSync13 } from "node:fs";
5678
- import { mkdir as mkdir8, open, readdir as readdir6, readFile as readFile9, rm as rm14, stat as stat5, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
6139
+ import { mkdir as mkdir8, open as open2, readdir as readdir6, readFile as readFile9, rm as rm14, stat as stat5, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
5679
6140
  import { basename as basename2, join as join3 } from "node:path";
5680
6141
  import { setTimeout as sleep5 } from "node:timers/promises";
5681
6142
 
5682
6143
  // ../shared/src/backup.ts
5683
- import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes4 } from "node:crypto";
6144
+ import { createCipheriv, createDecipheriv, createHmac as createHmac2, randomBytes as randomBytes4 } from "node:crypto";
5684
6145
  import { promisify as promisify2 } from "node:util";
5685
6146
  import { deflateRaw as deflateRawCb, inflateRaw as inflateRawCb, constants as zlib } from "node:zlib";
5686
6147
  var deflateRaw = promisify2(deflateRawCb);
@@ -5696,8 +6157,8 @@ function backupKeys(dataKeyB64) {
5696
6157
  const dk = Buffer.from(dataKeyB64, "base64");
5697
6158
  if (dk.length !== 32) throw new Error("backup key: expected 32 bytes");
5698
6159
  return {
5699
- name: createHmac("sha256", dk).update("kvbox-backup chunk-name v1").digest(),
5700
- seal: createHmac("sha256", dk).update("kvbox-backup chunk-seal v1").digest()
6160
+ name: createHmac2("sha256", dk).update("kvbox-backup chunk-name v1").digest(),
6161
+ seal: createHmac2("sha256", dk).update("kvbox-backup chunk-seal v1").digest()
5701
6162
  };
5702
6163
  }
5703
6164
  function isZero(buf) {
@@ -5709,7 +6170,7 @@ function zeros(n) {
5709
6170
  return zeroBuf.subarray(0, n);
5710
6171
  }
5711
6172
  function chunkName(keys, plain) {
5712
- return createHmac("sha256", keys.name).update(plain).digest("hex");
6173
+ return createHmac2("sha256", keys.name).update(plain).digest("hex");
5713
6174
  }
5714
6175
  async function sealChunk(keys, name, plain) {
5715
6176
  const packed = await deflateRaw(plain, { level: zlib.Z_BEST_SPEED });
@@ -5764,7 +6225,7 @@ function storeDispatcher(pin, local) {
5764
6225
  const have = dispatchers.get(id);
5765
6226
  if (have) return have;
5766
6227
  const plain = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0, timeout: 1e4 });
5767
- const connect3 = (opts, cb) => {
6228
+ const connect4 = (opts, cb) => {
5768
6229
  plain(local ? { ...opts, hostname: "127.0.0.1" } : opts, (err, socket) => {
5769
6230
  if (err || !socket) return cb(err ?? new Error("no socket"), null);
5770
6231
  const tls = socket;
@@ -5776,7 +6237,7 @@ function storeDispatcher(pin, local) {
5776
6237
  cb(null, socket);
5777
6238
  });
5778
6239
  };
5779
- const agent = new Agent2({ connect: connect3 });
6240
+ const agent = new Agent2({ connect: connect4 });
5780
6241
  dispatchers.set(id, agent);
5781
6242
  return agent;
5782
6243
  }
@@ -5821,7 +6282,7 @@ async function readBox2(ref, p) {
5821
6282
  async function chunkNames(file, keys) {
5822
6283
  const { size: size2 } = await stat5(file);
5823
6284
  const chunks = [];
5824
- const fh = await open(file, "r");
6285
+ const fh = await open2(file, "r");
5825
6286
  try {
5826
6287
  const buf = Buffer.alloc(CHUNK_SIZE);
5827
6288
  for (let i = 0; i < chunkCount(size2); i++) {
@@ -5962,7 +6423,7 @@ async function uploadOnce(id, req, signal, p) {
5962
6423
  });
5963
6424
  const { size: size2 } = await stat5(s.disk);
5964
6425
  const fetchChunk = await chunkFetcher(req.pin, work[0]?.url, p);
5965
- const fh = await open(s.disk, "r");
6426
+ const fh = await open2(s.disk, "r");
5966
6427
  let bytes = 0;
5967
6428
  const sizes = {};
5968
6429
  try {
@@ -6009,7 +6470,7 @@ async function downloadDisk(file, req, p = paths()) {
6009
6470
  }
6010
6471
  const fetchChunk = await chunkFetcher(req.pin, req.chunks[0]?.url, p);
6011
6472
  await writeFile7(file, "", { mode: 384 });
6012
- const fh = await open(file, "r+");
6473
+ const fh = await open2(file, "r+");
6013
6474
  try {
6014
6475
  await fh.truncate(req.sizeBytes);
6015
6476
  await pool(req.chunks, async ({ index, hash, url }) => {
@@ -6701,21 +7162,21 @@ function startRelayWatch(opts = {}) {
6701
7162
 
6702
7163
  // src/daemon.ts
6703
7164
  import { spawn as spawn3 } from "node:child_process";
6704
- import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync6 } from "node:fs";
7165
+ import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync4, statSync as statSync6 } from "node:fs";
6705
7166
  import { mkdir as mkdir11, readFile as readFile11, stat as stat6 } from "node:fs/promises";
6706
7167
  import { userInfo as userInfo3 } from "node:os";
6707
7168
  import { setTimeout as sleep6 } from "node:timers/promises";
6708
7169
 
6709
7170
  // ../shared/src/systemd.ts
6710
7171
  import { spawnSync } from "node:child_process";
6711
- import { readFileSync as readFileSync2 } from "node:fs";
7172
+ import { readFileSync as readFileSync3 } from "node:fs";
6712
7173
  import { resolve } from "node:path";
6713
7174
  var UNIT = "kvbox-server";
6714
7175
  var UNIT_FILE = `/etc/systemd/system/${UNIT}.service`;
6715
7176
  function hasUnitFor(p, file = UNIT_FILE) {
6716
7177
  let text;
6717
7178
  try {
6718
- text = readFileSync2(file, "utf8");
7179
+ text = readFileSync3(file, "utf8");
6719
7180
  } catch {
6720
7181
  return false;
6721
7182
  }
@@ -6821,7 +7282,7 @@ async function refuseSecondDaemon(p = paths()) {
6821
7282
  }
6822
7283
  function isKvboxServer(pid) {
6823
7284
  try {
6824
- return readFileSync3(`/proc/${pid}/cmdline`, "utf8").split("\0").slice(1).some((arg) => arg.includes("kvbox"));
7285
+ return readFileSync4(`/proc/${pid}/cmdline`, "utf8").split("\0").slice(1).some((arg) => arg.includes("kvbox"));
6825
7286
  } catch (err) {
6826
7287
  return err.code !== "ENOENT";
6827
7288
  }
@@ -6952,7 +7413,7 @@ function shellQuote(word) {
6952
7413
  function groupWithMember(gid, user, groupFile) {
6953
7414
  let text;
6954
7415
  try {
6955
- text = readFileSync3(groupFile, "utf8");
7416
+ text = readFileSync4(groupFile, "utf8");
6956
7417
  } catch {
6957
7418
  return void 0;
6958
7419
  }
@@ -6969,27 +7430,6 @@ import { readFile as readFile13, rm as rm16, writeFile as writeFile10 } from "no
6969
7430
  import { createServer as createHttpsServer } from "node:https";
6970
7431
  import { createAdaptorServer } from "@hono/node-server";
6971
7432
 
6972
- // ../shared/src/names.ts
6973
- import { createHmac as createHmac2 } from "node:crypto";
6974
- var PROXY_ERROR_HEADER = "x-kvbox-proxy-error";
6975
- var PROXIED_HEADER = "x-kvbox-proxied";
6976
- var VISITOR_PATH_HEADER = "x-kvbox-path";
6977
- var WAKE_HEADER = "x-kvbox-wake";
6978
- var WAKE_WAIT_MS = 3e4;
6979
- var REQUEST_TIMEOUT_MS2 = 36e5;
6980
- var WOKE_HEADER = "x-kvbox-woke";
6981
- var VISITOR_AUTH_HEADER = "x-kvbox-authorization";
6982
- var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
6983
- var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
6984
- var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
6985
- function edgeCredential(hostSecret) {
6986
- return createHmac2("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
6987
- }
6988
- var BOX_RUN_PATH_RE = /^\/machines\/([^/]+)\/runs(\/[A-Za-z0-9_-]{1,64})?\/?$/;
6989
- function cronCredential(hostSecret) {
6990
- return createHmac2("sha256", hostSecret).update("kvbox-cron-v1").digest("base64url");
6991
- }
6992
-
6993
7433
  // src/app.ts
6994
7434
  import { Hono as Hono12 } from "hono";
6995
7435
 
@@ -7006,10 +7446,10 @@ function versionOf(srcFileUrl, injected) {
7006
7446
  }
7007
7447
 
7008
7448
  // src/version.ts
7009
- var VERSION = versionOf(import.meta.url, true ? "0.6.16" : void 0);
7449
+ var VERSION = versionOf(import.meta.url, true ? "0.6.18" : void 0);
7010
7450
 
7011
7451
  // src/caller.ts
7012
- import { createHash as createHash3, timingSafeEqual } from "node:crypto";
7452
+ import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
7013
7453
  var OWNER_HEADER = "x-kvbox-owner";
7014
7454
  function resolveCaller(opts = {}) {
7015
7455
  const cp = opts.controlPlane;
@@ -7059,11 +7499,11 @@ function bearerCheck(token) {
7059
7499
  const expected = digest(token);
7060
7500
  return (authorization) => {
7061
7501
  const m = /^Bearer\s+(\S+)$/i.exec(authorization ?? "");
7062
- return m !== null && timingSafeEqual(digest(m[1]), expected);
7502
+ return m !== null && timingSafeEqual2(digest(m[1]), expected);
7063
7503
  };
7064
7504
  }
7065
7505
  function digest(secret) {
7066
- return createHash3("sha256").update(secret).digest();
7506
+ return createHash4("sha256").update(secret).digest();
7067
7507
  }
7068
7508
 
7069
7509
  // src/core/update.ts
@@ -7184,42 +7624,6 @@ import { connect as connect2 } from "node:net";
7184
7624
  import { Readable } from "node:stream";
7185
7625
  import { Hono as Hono3 } from "hono";
7186
7626
  import { request as request6 } from "undici";
7187
-
7188
- // ../shared/src/httpHead.ts
7189
- var END = "\r\n\r\n";
7190
- var HeadTimeoutError = class extends Error {
7191
- };
7192
- function readHead(socket, opts) {
7193
- return new Promise((resolve3, reject) => {
7194
- let bytes = Buffer.alloc(0);
7195
- const done = (err) => {
7196
- clearTimeout(timer);
7197
- socket.off("data", onData);
7198
- socket.off("close", onClose);
7199
- socket.pause();
7200
- if (err) return reject(err);
7201
- const end = bytes.indexOf(END);
7202
- resolve3({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
7203
- };
7204
- const onData = (chunk) => {
7205
- bytes = Buffer.concat([bytes, chunk]);
7206
- if (bytes.includes(END)) done();
7207
- else if (bytes.length > opts.maxBytes) done(new Error("answer head too large"));
7208
- };
7209
- const onClose = () => done(new Error("closed before answering"));
7210
- const timer = setTimeout(() => done(new HeadTimeoutError(`no answer within ${opts.timeoutMs / 1e3} s`)), opts.timeoutMs);
7211
- socket.on("data", onData);
7212
- socket.once("close", onClose);
7213
- });
7214
- }
7215
- function rewriteHead(head, drop, add = {}) {
7216
- const [status, ...lines] = head.split("\r\n");
7217
- const kept = lines.filter((l) => !drop(l.slice(0, l.indexOf(":")).trim().toLowerCase()));
7218
- const extra = Object.entries(add).map(([k, v]) => `${k}: ${v}`);
7219
- return Buffer.from(`${[status, ...kept, ...extra].join("\r\n")}${END}`, "latin1");
7220
- }
7221
-
7222
- // src/routes/boxHttp.ts
7223
7627
  var HEADERS_TIMEOUT_MS = 55e3;
7224
7628
  var MAX_HANDSHAKE_BYTES = 16 * 1024;
7225
7629
  var CONNECT_TIMEOUT_MS = 5e3;
@@ -7409,10 +7813,10 @@ ${lines.join("")}\r
7409
7813
  `);
7410
7814
  if (head.length > 0) box.write(head);
7411
7815
  readHead(box, { maxBytes: MAX_HANDSHAKE_BYTES, timeoutMs: headersTimeoutMs }).then(
7412
- (answer) => {
7816
+ (answer2) => {
7413
7817
  if (socket.destroyed) return void box.destroy();
7414
- socket.write(rewriteHead(answer.head, (name) => name.startsWith("x-kvbox-"), { [PROXIED_HEADER]: "1", ...target.woke ? { [WOKE_HEADER]: "1" } : {} }));
7415
- if (answer.rest.length > 0) socket.write(answer.rest);
7818
+ socket.write(rewriteHead(answer2.head, (name) => name.startsWith("x-kvbox-"), { [PROXIED_HEADER]: "1", ...target.woke ? { [WOKE_HEADER]: "1" } : {} }));
7819
+ if (answer2.rest.length > 0) socket.write(answer2.rest);
7416
7820
  piped = true;
7417
7821
  box.pipe(socket);
7418
7822
  socket.pipe(box);
@@ -7562,6 +7966,16 @@ function machineRoutes() {
7562
7966
  };
7563
7967
  r.post("/:name/links", async (c) => c.json(await addLink(parseRef(c.req.param("name"), c.get("owner")), await linkBody(c), c.get("owner")), 201));
7564
7968
  r.delete("/:name/links", async (c) => c.json(await removeLink(parseRef(c.req.param("name"), c.get("owner")), await linkBody(c), c.get("owner"))));
7969
+ r.post("/:name/far-links", async (c) => {
7970
+ const body = FarLinkRequest.safeParse(await c.req.json().catch(() => ({})));
7971
+ if (!body.success) throw new KvboxError("far-links: expected {to, port, url, pin, key}");
7972
+ return c.json(await addFarTarget(parseRef(c.req.param("name"), c.get("owner")), body.data, c.get("owner")), 201);
7973
+ });
7974
+ r.delete("/:name/far-links", async (c) => {
7975
+ const body = FarUnlinkRequest.safeParse(await c.req.json().catch(() => ({})));
7976
+ if (!body.success) throw new KvboxError("far-links: expected {to, port}");
7977
+ return c.json(await removeFarTarget(parseRef(c.req.param("name"), c.get("owner")), body.data, c.get("owner")));
7978
+ });
7565
7979
  r.get("/:name/usage", async (c) => {
7566
7980
  const since = c.req.query("since");
7567
7981
  let from;
@@ -7610,7 +8024,7 @@ function machineRoutes() {
7610
8024
  // src/routes/runs.ts
7611
8025
  import { Hono as Hono7 } from "hono";
7612
8026
  import { z as z9 } from "zod";
7613
- var refusal2 = (c, err) => {
8027
+ var refusal3 = (c, err) => {
7614
8028
  if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
7615
8029
  if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
7616
8030
  if (err instanceof AgentNotAnsweringError) return c.json({ error: err.message, code: "unreachable" }, 503);
@@ -7631,7 +8045,7 @@ function runRoutes(wake = wakeBox) {
7631
8045
  const started = await startBoxRun(ref, body);
7632
8046
  return c.json(StartRunAnswerSchema.parse({ id: body.id, started, woke }), 202);
7633
8047
  } catch (err) {
7634
- return refusal2(c, err);
8048
+ return refusal3(c, err);
7635
8049
  }
7636
8050
  });
7637
8051
  r.get("/:name/runs/:id", async (c) => {
@@ -7639,7 +8053,7 @@ function runRoutes(wake = wakeBox) {
7639
8053
  const { ref } = await runningBox(c.req.param("name"), c.get("owner"), wants(c.req.header(WAKE_HEADER)) ? wake : void 0);
7640
8054
  return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
7641
8055
  } catch (err) {
7642
- return refusal2(c, err);
8056
+ return refusal3(c, err);
7643
8057
  }
7644
8058
  });
7645
8059
  r.get("/:name/runs/:id/output", async (c) => {
@@ -7652,7 +8066,7 @@ function runRoutes(wake = wakeBox) {
7652
8066
  const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
7653
8067
  return c.json(RunOutputSchema.parse(await boxRunOutput(ref, id, stream, offset, limit)));
7654
8068
  } catch (err) {
7655
- return refusal2(c, err);
8069
+ return refusal3(c, err);
7656
8070
  }
7657
8071
  });
7658
8072
  return r;
@@ -7805,6 +8219,94 @@ function createApp(opts = {}) {
7805
8219
  return app;
7806
8220
  }
7807
8221
 
8222
+ // src/routes/boxLink.ts
8223
+ import { connect as connect3 } from "node:net";
8224
+ var CONNECT_TIMEOUT_MS2 = 5e3;
8225
+ function pathOf(url) {
8226
+ try {
8227
+ return new URL(url ?? "/", "https://host").pathname;
8228
+ } catch {
8229
+ return null;
8230
+ }
8231
+ }
8232
+ var isLinkPath = (url) => BOX_LINK_PATH_RE.test(pathOf(url) ?? "");
8233
+ function dispatchUpgrade(toLinked, toBox) {
8234
+ return (req, socket, head) => {
8235
+ try {
8236
+ (isLinkPath(req.url) ? toLinked : toBox)(req, socket, head);
8237
+ } catch {
8238
+ socket.destroy();
8239
+ }
8240
+ };
8241
+ }
8242
+ function answer(socket, status, text, code) {
8243
+ const body = JSON.stringify(status === 200 ? { ok: true } : { error: text });
8244
+ socket.end(
8245
+ `HTTP/1.1 ${status} ${status === 200 ? "OK" : "Error"}\r
8246
+ content-type: application/json\r
8247
+ content-length: ${Buffer.byteLength(body)}\r
8248
+ ${code ? `${LINK_ERROR_HEADER}: ${code}\r
8249
+ ` : ""}connection: close\r
8250
+ \r
8251
+ ${body}`
8252
+ );
8253
+ }
8254
+ function asked2(req, realm) {
8255
+ const m = BOX_LINK_PATH_RE.exec(pathOf(req.url) ?? "");
8256
+ const key = /^Bearer\s+(\S+)$/i.exec(req.headers.authorization ?? "")?.[1];
8257
+ const user = req.headers[OWNER_HEADER];
8258
+ if (!m || key === void 0 || typeof user !== "string" || !LOCAL_OWNER_RE.test(user)) return null;
8259
+ const port = Number(m[2]);
8260
+ let name;
8261
+ try {
8262
+ name = decodeURIComponent(m[1]);
8263
+ } catch {
8264
+ return null;
8265
+ }
8266
+ if (port < 1 || port > 65535 || name.includes("/")) return null;
8267
+ return { ref: parseRef(name, `${user}@${realm}`), port, key };
8268
+ }
8269
+ function linkUpgradeHandler(realm, connectTimeoutMs = CONNECT_TIMEOUT_MS2) {
8270
+ return (req, socket, head) => {
8271
+ socket.on("error", () => socket.destroy());
8272
+ void (async () => {
8273
+ const link4 = asked2(req, realm);
8274
+ if (link4 === null) return answer(socket, 400, "not a link's request");
8275
+ if (req.method !== "GET" && req.method !== "DELETE") return answer(socket, 405, "a link's connection is a GET");
8276
+ const to = await farLinkInto(link4.ref, link4.port, link4.key).catch(() => null);
8277
+ if (to === null) return answer(socket, 500, "the box cannot be read on this host");
8278
+ if (req.method === "DELETE") {
8279
+ if (to === "gone") return answer(socket, 404, "no such link", "gone");
8280
+ return await dropFarLink(link4.ref, link4.port, link4.key) ? answer(socket, 200, "") : answer(socket, 404, "no such link", "gone");
8281
+ }
8282
+ if (to === "gone") return answer(socket, 404, "no such link", "gone");
8283
+ if (to === "down") return answer(socket, 503, "the box is not running", "down");
8284
+ if (socket.destroyed) return;
8285
+ const box = connect3({ host: to.ip, port: link4.port, timeout: connectTimeoutMs, allowHalfOpen: true });
8286
+ let piped = false;
8287
+ box.once("timeout", () => box.destroy(new Error("timed out")));
8288
+ box.on("error", () => {
8289
+ if (!piped && !socket.destroyed) answer(socket, 502, `nothing answers on port ${link4.port} of the box`, "unreachable");
8290
+ else socket.destroy();
8291
+ });
8292
+ const leftEarly = () => box.destroy();
8293
+ socket.once("close", leftEarly);
8294
+ box.once("connect", () => {
8295
+ box.setTimeout(0);
8296
+ socket.write(`HTTP/1.1 101 Switching Protocols\r
8297
+ connection: Upgrade\r
8298
+ upgrade: ${LINK_PROTOCOL}\r
8299
+ \r
8300
+ `);
8301
+ if (head.length > 0) box.write(head);
8302
+ piped = true;
8303
+ socket.off("close", leftEarly);
8304
+ splice(socket, box);
8305
+ });
8306
+ })().catch(() => socket.destroy());
8307
+ };
8308
+ }
8309
+
7808
8310
  // src/listen.ts
7809
8311
  async function listen(opts = {}) {
7810
8312
  const p = await ensureLayout(paths());
@@ -7845,7 +8347,7 @@ async function listen(opts = {}) {
7845
8347
  const edge = edgeCheck(cp);
7846
8348
  const cron = cronCheck(cp);
7847
8349
  limitUntrusted(httpsServer, (req) => secret(req.headers.authorization) || edge(req.headers.authorization) || cron(req.headers.authorization));
7848
- httpsServer.on("upgrade", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));
8350
+ httpsServer.on("upgrade", dispatchUpgrade(linkUpgradeHandler(cp.name), boxUpgradeHandler({ name: cp.name, secret: cp.secret })));
7849
8351
  const port = opts.httpsPort ?? cp.port;
7850
8352
  await new Promise((resolve3, reject) => {
7851
8353
  httpsServer.once("error", reject);
@@ -7859,7 +8361,7 @@ async function listen(opts = {}) {
7859
8361
  const bound = httpsServer.address().port;
7860
8362
  https = { port: bound, url: `https://${cp.advertise}:${bound}` };
7861
8363
  }
7862
- const close = async () => {
8364
+ const close2 = async () => {
7863
8365
  await Promise.all([
7864
8366
  new Promise((resolve3) => server.close(() => resolve3())),
7865
8367
  httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
@@ -7877,7 +8379,7 @@ async function listen(opts = {}) {
7877
8379
  };
7878
8380
  process.once("SIGINT", () => void shutdown3());
7879
8381
  process.once("SIGTERM", () => void shutdown3());
7880
- return https ? { socketPath, server, https, close } : { socketPath, server, close };
8382
+ return https ? { socketPath, server, https, close: close2 } : { socketPath, server, close: close2 };
7881
8383
  }
7882
8384
  var UNTRUSTED_REQUEST_MS = 3e5;
7883
8385
  function limitUntrusted(server, trusted, ms = UNTRUSTED_REQUEST_MS) {
@@ -7923,6 +8425,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
7923
8425
  const state = await driver().net.prepare(cfg);
7924
8426
  log.info(`host network: bridge ${cfg.bridge} ${state}`);
7925
8427
  await pinRunningTaps(paths());
8428
+ await reopenFarTargets(paths()).catch((err) => log.warn(`running boxes cannot reach the boxes they are linked to on other hosts: ${err.message}`));
7926
8429
  } catch (err) {
7927
8430
  log.warn(`host network not ready (${err.message}); run: kvbox-server net up`);
7928
8431
  }
@@ -8044,7 +8547,7 @@ var leaveCommand = new Command6("leave").description("take this host out from be
8044
8547
  });
8045
8548
 
8046
8549
  // src/commands/logs.ts
8047
- import { open as open2, readFile as readFile14, stat as stat7 } from "node:fs/promises";
8550
+ import { open as open3, readFile as readFile14, stat as stat7 } from "node:fs/promises";
8048
8551
  import { setTimeout as sleep7 } from "node:timers/promises";
8049
8552
  import { Command as Command7 } from "commander";
8050
8553
  var logsCommand = new Command7("logs").description("show the daemon's log ($KVBOX_HOME/server.log); -f keeps printing as it grows").option("-n, --lines <n>", "how many lines to show from the end", "50").option("-f, --follow", "keep printing new lines until Ctrl-C").action(async (opts) => {
@@ -8076,7 +8579,7 @@ async function follow(path, write, opts = {}) {
8076
8579
  const size2 = await stat7(path).then((s) => s.size, () => 0);
8077
8580
  if (size2 < offset) offset = 0;
8078
8581
  if (size2 > offset) {
8079
- const fh = await open2(path, "r");
8582
+ const fh = await open3(path, "r");
8080
8583
  try {
8081
8584
  const buf = Buffer.alloc(size2 - offset);
8082
8585
  const { bytesRead } = await fh.read(buf, 0, buf.length, offset);
@@ -8170,7 +8673,9 @@ async function plan(from, to, p) {
8170
8673
  ...sshKeys !== void 0 ? { sshKeys } : {},
8171
8674
  // A stopped box reads its lines at boot; any other guest still holds the old ones.
8172
8675
  ...keysChanged ? { sshKeysStale: status === "stopped" ? void 0 : true } : {},
8173
- ...meta.links !== void 0 ? { links: meta.links.map((l) => ({ ...l, owner: owner(l.owner) })) } : {}
8676
+ ...meta.links !== void 0 ? { links: meta.links.map((l) => ({ ...l, owner: owner(l.owner) })) } : {},
8677
+ ...meta.farLinks !== void 0 ? { farLinks: meta.farLinks.map((l) => ({ ...l, owner: owner(l.owner) })) } : {},
8678
+ ...meta.farTargets !== void 0 ? { farTargets: meta.farTargets.map((l) => ({ ...l, owner: owner(l.owner) })) } : {}
8174
8679
  }
8175
8680
  });
8176
8681
  }
@@ -8289,8 +8794,8 @@ async function confirm(question, yes) {
8289
8794
  const { createInterface } = await import("node:readline/promises");
8290
8795
  const rl = createInterface({ input: process.stdin, output: process.stderr });
8291
8796
  try {
8292
- const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
8293
- return answer === "y" || answer === "yes";
8797
+ const answer2 = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
8798
+ return answer2 === "y" || answer2 === "yes";
8294
8799
  } finally {
8295
8800
  rl.close();
8296
8801
  }