@kvbox/server 0.6.15 → 0.6.17

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.
@@ -629,7 +629,7 @@ async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
629
629
  }
630
630
 
631
631
  // src/core/drivers/firecracker/network.ts
632
- import { existsSync } from "node:fs";
632
+ import { existsSync, readFileSync } from "node:fs";
633
633
  import { fileURLToPath } from "node:url";
634
634
  var TAP_PREFIX = "kv-";
635
635
  var PRIVILEGED_SCRIPT = "/usr/local/lib/kvbox/net-setup.sh";
@@ -713,6 +713,22 @@ async function openLink(link4, cfg) {
713
713
  async function closeLink(link4, cfg) {
714
714
  await netRun(cfg, ["link", "rm", ...linkArgs(link4)]);
715
715
  }
716
+ function carriesFarLinks() {
717
+ try {
718
+ return readFileSync(netSetupScript(), "utf8").includes("farlink add");
719
+ } catch {
720
+ return false;
721
+ }
722
+ }
723
+ async function openFarLink(link4, cfg) {
724
+ await netRun(cfg, ["farlink", "add", link4.box, link4.fromIp, link4.standIn, String(link4.port), String(link4.via)]).catch((err) => {
725
+ if (!err.message.includes("usage:")) throw err;
726
+ 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)");
727
+ });
728
+ }
729
+ async function closeFarLink(link4, cfg) {
730
+ await netRun(cfg, ["farlink", "rm", link4.box, link4.fromIp, link4.standIn, String(link4.port)]);
731
+ }
716
732
  async function closeProxy(proxy, cfg) {
717
733
  await netRun(cfg, ["proxy", "rm", ...proxyArgs(proxy)]);
718
734
  }
@@ -731,6 +747,16 @@ function nextFreeIp(subnet, inUse) {
731
747
  }
732
748
  throw new KvboxError(`no free IP left in ${subnet}`);
733
749
  }
750
+ function standInIp(subnet, inUse) {
751
+ const [a, b, c] = (subnet.split("/")[0] ?? "").split(".");
752
+ if (a === void 0 || b === void 0 || c === void 0) throw new KvboxError(`bad subnet: ${subnet}`);
753
+ const used = new Set(inUse);
754
+ for (let n = 1; n < 255; n++) {
755
+ const ip = `${a}.${b}.${c === "255" ? 254 : 255}.${n}`;
756
+ if (!used.has(ip)) return ip;
757
+ }
758
+ throw new KvboxError("this host has no address left for a link to a box on another host (254 are in use)");
759
+ }
734
760
  function macFor(ip) {
735
761
  const hex = ip.split(".").map((o) => Number(o).toString(16).padStart(2, "0").toUpperCase());
736
762
  return ["06", "00", ...hex].join(":");
@@ -1053,6 +1079,12 @@ var firecrackerDriver = {
1053
1079
  closeProxy,
1054
1080
  openLink,
1055
1081
  closeLink,
1082
+ carriesFarLinks,
1083
+ standIn: (cfg, inUse) => standInIp(cfg.subnet, inUse),
1084
+ // A redirected connection arrives at the bridge's own address.
1085
+ farListenHost: (cfg) => cfg.gateway,
1086
+ openFarLink,
1087
+ closeFarLink,
1056
1088
  relay: netSetup,
1057
1089
  setupScript: netSetupScript
1058
1090
  },
@@ -1072,7 +1104,7 @@ import { createSocket } from "node:dgram";
1072
1104
 
1073
1105
  // src/core/state.ts
1074
1106
  import { randomBytes } from "node:crypto";
1075
- import { readFileSync } from "node:fs";
1107
+ import { readFileSync as readFileSync2 } from "node:fs";
1076
1108
  import { mkdir, readFile as readFile5, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
1077
1109
  import { z as z3 } from "zod";
1078
1110
 
@@ -1308,6 +1340,17 @@ var MachineMetaSchema = z3.object({
1308
1340
  * again, never listed (a new box of the same name may get the same IP). Absent: none.
1309
1341
  */
1310
1342
  links: z3.array(z3.object({ owner: z3.string(), name: z3.string(), ip: z3.string(), port: z3.number().int(), stale: z3.literal(true).optional() })).optional(),
1343
+ /**
1344
+ * Links into this box from boxes on other hosts (#207): box `owner/name` reaches `port` through this host's
1345
+ * HTTPS listener, presenting the link's key; `key` is its sha256 (hex), never the key. No rule on this host. Absent: none.
1346
+ */
1347
+ farLinks: z3.array(z3.object({ owner: z3.string(), name: z3.string(), port: z3.number().int(), key: z3.string() })).optional(),
1348
+ /**
1349
+ * Boxes on other hosts this box reaches (#207): `port` of box `owner/name`, on the host at `url` (certificate
1350
+ * `pin`), by presenting `key`. Inside this box the other is `ip`, a stand-in address on this host that
1351
+ * `<name>.kvbox` answers and that this host carries to the other. Open while this box runs. Absent: none.
1352
+ */
1353
+ 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
1354
  /**
1312
1355
  * The integrations turned on for the box (#205): names only (`github`), never a credential. The box asks
1313
1356
  * for one each time it needs it (core/machines/integrations.ts) and is answered only for a name in this
@@ -1441,7 +1484,7 @@ var bootId;
1441
1484
  function currentBootId() {
1442
1485
  if (bootId === void 0) {
1443
1486
  try {
1444
- bootId = { id: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() };
1487
+ bootId = { id: readFileSync2("/proc/sys/kernel/random/boot_id", "utf8").trim() };
1445
1488
  } catch {
1446
1489
  bootId = { id: void 0 };
1447
1490
  }
@@ -1454,7 +1497,7 @@ function vmAlive(meta) {
1454
1497
  }
1455
1498
  function hostBootTime() {
1456
1499
  try {
1457
- const m = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
1500
+ const m = /^btime (\d+)$/m.exec(readFileSync2("/proc/stat", "utf8"));
1458
1501
  return m ? new Date(Number(m[1]) * 1e3) : null;
1459
1502
  } catch {
1460
1503
  return null;
@@ -1522,6 +1565,7 @@ function answerFor(q, asker, boxes) {
1522
1565
  let box;
1523
1566
  if (from && rest.length === 0) {
1524
1567
  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));
1568
+ box ??= from.far?.find((t) => t.name === name && (slug === void 0 ? t.owner === from.owner : slugOf(t.owner) === slug));
1525
1569
  }
1526
1570
  if (!box) return { rcode: RCODE.nxDomain };
1527
1571
  return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };
@@ -1530,7 +1574,10 @@ async function boxAddresses(p) {
1530
1574
  const out = [];
1531
1575
  for (const ref of await listMachineRefs(p)) {
1532
1576
  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) } : {} });
1577
+ if (meta) {
1578
+ const far = meta.farTargets?.map((t) => ({ name: t.name, owner: t.owner, ip: t.ip }));
1579
+ out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {}, ...far ? { far } : {} });
1580
+ }
1534
1581
  }
1535
1582
  return out;
1536
1583
  }
@@ -1746,8 +1793,8 @@ function imageEnv(manifest, box, given, inherited = []) {
1746
1793
  const encode = manifest.connect !== void 0 && /^[a-z][a-z0-9+.-]*:\/\//i.test(manifest.connect);
1747
1794
  const connectVars = new Map([...vars].map(([k, v]) => [k, owners.has(k) ? `\${${k}}` : encode ? encodeURIComponent(v) : v]));
1748
1795
  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 };
1796
+ const connect4 = manifest.connect === void 0 ? void 0 : expand(manifest.connect, connectVars);
1797
+ return { vars: [...given, ...added], generated, secrets: [...generated, ...secrets], connect: connect4 };
1751
1798
  }
1752
1799
  var MASK = "****";
1753
1800
  function maskedUrl(manifest, vars) {
@@ -1800,7 +1847,8 @@ var IntegrationCatalogEntrySchema = z5.object({
1800
1847
  title: z5.string(),
1801
1848
  description: z5.string(),
1802
1849
  /**
1803
- * How Connect works: `oauth` sends the browser to the provider's consent screen; `paste` takes a credential
1850
+ * How Connect works: `oauth` sends the browser to the provider's consent screen (for an org's GitHub, the
1851
+ * kvbox GitHub App's install screen); `paste` takes a credential
1804
1852
  * the user pastes (Claude Code's). A plain string, like `id`: a released CLI must still read a catalog with a way it does not know.
1805
1853
  */
1806
1854
  connect: z5.string(),
@@ -1831,11 +1879,23 @@ var IntegrationSchema = z5.object({
1831
1879
  connectedAt: z5.string().nullable(),
1832
1880
  /** The last time a box was handed the credential (to the minute). */
1833
1881
  lastUsedAt: z5.string().nullable(),
1882
+ /** Where the connection is changed at the provider: a GitHub App installation's settings (its repositories, uninstalling it). */
1883
+ manageUrl: z5.string().optional(),
1834
1884
  /** Whether the caller may connect or disconnect it: the slug's own user, an org's owners. */
1835
1885
  canManage: z5.boolean()
1836
1886
  });
1837
1887
  var IntegrationConnectSchema = z5.object({ url: z5.string() });
1838
- var IntegrationCompleteRequestSchema = z5.object({ code: z5.string().min(1), state: z5.string().min(1) });
1888
+ var IntegrationCompleteRequestSchema = z5.object({
1889
+ code: z5.string().min(1).optional(),
1890
+ state: z5.string().min(1),
1891
+ installationId: z5.string().regex(/^\d{1,15}$/).optional()
1892
+ });
1893
+ var IntegrationNextStepSchema = z5.object({
1894
+ next: z5.enum(["install", "choose"]),
1895
+ url: z5.string(),
1896
+ state: z5.string().optional(),
1897
+ choices: z5.array(z5.object({ installationId: z5.string(), account: z5.string() })).optional()
1898
+ });
1839
1899
  var ClaudeConnectRequestSchema = z5.object({
1840
1900
  credential: z5.string().trim().min(1).max(4096).regex(/^[A-Za-z0-9_-]+$/, "a Claude Code token or an Anthropic API key has only letters, digits, - and _: paste it again on one line, with nothing inside it")
1841
1901
  });
@@ -1910,7 +1970,25 @@ var PortsRequest = z6.object({
1910
1970
  var BoxPortSchema = z6.number().int().min(1).max(65535);
1911
1971
  var MAX_BOX_LINKS = 32;
1912
1972
  var BoxLinkSchema = z6.object({ from: z6.string(), port: BoxPortSchema });
1913
- var LinkRequest = z6.object({ from: z6.string().min(1), fromOwner: z6.string().optional(), port: BoxPortSchema });
1973
+ var LinkRequest = z6.object({
1974
+ from: z6.string().min(1),
1975
+ fromOwner: z6.string().optional(),
1976
+ port: BoxPortSchema,
1977
+ /**
1978
+ * The box `from` is on another host (#207, a control plane's call only): no rule opens here. Its host
1979
+ * connects to this host's HTTPS listener (`BOX_LINK_PATH_RE`) with `key`, which this link alone answers to.
1980
+ */
1981
+ far: z6.object({ key: z6.string().min(32) }).optional()
1982
+ });
1983
+ var FarLinkRequest = z6.object({
1984
+ to: z6.string().min(1),
1985
+ toOwner: z6.string().optional(),
1986
+ port: BoxPortSchema,
1987
+ url: z6.string().url(),
1988
+ pin: z6.string().min(1),
1989
+ key: z6.string().min(32)
1990
+ });
1991
+ var FarUnlinkRequest = FarLinkRequest.pick({ to: true, toOwner: true, port: true });
1914
1992
  var ClaimSubdomainRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
1915
1993
  var SubdomainPortRequest = z6.object({ port: BoxPortSchema });
1916
1994
  var SubdomainRouteRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
@@ -1976,7 +2054,10 @@ var BackupSchema = z6.object({
1976
2054
  dataBytes: z6.number().int().nullable(),
1977
2055
  /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
1978
2056
  uploadedBytes: z6.number().int().nullable(),
2057
+ /** Who asked for it; for a scheduled one, whoever made the thing it is of. */
1979
2058
  createdBy: z6.string().nullable(),
2059
+ /** Taken by its nightly schedule (`backup-schedule`) rather than by a person: free, and outside the daily limit. */
2060
+ scheduled: z6.boolean().default(false),
1980
2061
  createdAt: z6.string(),
1981
2062
  finishedAt: z6.string().nullable()
1982
2063
  });
@@ -2026,7 +2107,10 @@ var VolumeBackupSchema = z6.object({
2026
2107
  dataBytes: z6.number().int().nullable(),
2027
2108
  /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
2028
2109
  uploadedBytes: z6.number().int().nullable(),
2110
+ /** Who asked for it; for a scheduled one, whoever made the thing it is of. */
2029
2111
  createdBy: z6.string().nullable(),
2112
+ /** Taken by its nightly schedule (`backup-schedule`) rather than by a person: free, and outside the daily limit. */
2113
+ scheduled: z6.boolean().default(false),
2030
2114
  createdAt: z6.string(),
2031
2115
  finishedAt: z6.string().nullable()
2032
2116
  });
@@ -2168,7 +2252,7 @@ var MachineSchema = z6.object({
2168
2252
  ownerKind: z6.enum(["user", "org"]).optional(),
2169
2253
  /**
2170
2254
  * The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
2171
- * links to, and a volume attaches to, only a box on the same host.
2255
+ * a volume attaches only to a box on the same host, and a link between two boxes of one host stays on it.
2172
2256
  */
2173
2257
  host: z6.string().optional(),
2174
2258
  /** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
@@ -2468,6 +2552,8 @@ var CapacitySchema = z6.object({
2468
2552
  fromBackup: z6.boolean().optional(),
2469
2553
  /** True on a kvbox-server that keeps a box's `integrations` (#205); an older one drops the field without a word. */
2470
2554
  integrations: z6.boolean().optional(),
2555
+ /** 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. */
2556
+ farLinks: z6.boolean().optional(),
2471
2557
  /** The integrations this kvbox-server knows (`hostKnowsIntegrations`). Absent with `integrations`: the first one's, `github` alone. */
2472
2558
  integrationIds: z6.array(z6.string()).optional()
2473
2559
  });
@@ -3549,9 +3635,9 @@ function forStore(url, p = paths()) {
3549
3635
  return isStoreRequest(url) && existsSync6(p.backupStore.conf);
3550
3636
  }
3551
3637
  function storeProxy(req, res, port = GARAGE_S3_PORT) {
3552
- const up = httpRequest({ host: "127.0.0.1", port, method: req.method, path: req.url, headers: req.headers }, (answer) => {
3553
- res.writeHead(answer.statusCode ?? 502, answer.headers);
3554
- pipeline(answer, res, (err) => {
3638
+ const up = httpRequest({ host: "127.0.0.1", port, method: req.method, path: req.url, headers: req.headers }, (answer2) => {
3639
+ res.writeHead(answer2.statusCode ?? 502, answer2.headers);
3640
+ pipeline(answer2, res, (err) => {
3555
3641
  if (err) res.destroy();
3556
3642
  });
3557
3643
  });
@@ -3600,6 +3686,9 @@ async function capacity(p = paths()) {
3600
3686
  storeClient: true,
3601
3687
  // A new box on a backup's disk (#141): the control plane places `new --from-backup` only here.
3602
3688
  fromBackup: true,
3689
+ // A link to a box on another host is carried here (#207): the control plane links across hosts only between two such.
3690
+ // Only once the host's privileged network script knows them: an update without its root step does not.
3691
+ farLinks: driver().net.carriesFarLinks(),
3603
3692
  // A box's integrations are kept here (#205): the control plane sends a list only to such a host.
3604
3693
  integrations: true,
3605
3694
  // ...and which (the control plane places a box with `claude` only on a host that names it).
@@ -4038,15 +4127,15 @@ async function ask(cp, body) {
4038
4127
  }
4039
4128
  }
4040
4129
  async function askCredential(cp, box, integration) {
4041
- let answer;
4130
+ let answer2;
4042
4131
  try {
4043
- answer = await ask(cp, { owner: box.owner, box: box.name, integration });
4132
+ answer2 = await ask(cp, { owner: box.owner, box: box.name, integration });
4044
4133
  } catch (err) {
4045
4134
  return unavailable(`${cp.name} could not be reached (${err.message}); try again shortly`);
4046
4135
  }
4047
- if (answer.status === 404) return unavailable(`${cp.name} has no integrations yet`);
4048
- const parsed = CredentialAnswerSchema.safeParse(answer.json);
4049
- if (!parsed.success) return unavailable(`${cp.name} answered ${answer.status}; try again shortly`);
4136
+ if (answer2.status === 404) return unavailable(`${cp.name} has no integrations yet`);
4137
+ const parsed = CredentialAnswerSchema.safeParse(answer2.json);
4138
+ if (!parsed.success) return unavailable(`${cp.name} answered ${answer2.status}; try again shortly`);
4050
4139
  return parsed.data;
4051
4140
  }
4052
4141
  var probes = /* @__PURE__ */ new Map();
@@ -4075,7 +4164,7 @@ var REQUEST_TIMEOUT_MS = 5e3;
4075
4164
  var MAX_OPEN = 32;
4076
4165
  var listeners = /* @__PURE__ */ new Map();
4077
4166
  var unreadable = (message) => ({ ok: false, code: "unavailable", message });
4078
- function serve(sock, answer, timeoutMs) {
4167
+ function serve(sock, answer2, timeoutMs) {
4079
4168
  let buf = "";
4080
4169
  let taken = false;
4081
4170
  const reply = (body) => {
@@ -4101,17 +4190,17 @@ function serve(sock, answer, timeoutMs) {
4101
4190
  } catch {
4102
4191
  return reply(unreadable("the request is not JSON"));
4103
4192
  }
4104
- answer(request7).then(reply, (err) => reply(unreadable(err.message)));
4193
+ answer2(request7).then(reply, (err) => reply(unreadable(err.message)));
4105
4194
  });
4106
4195
  }
4107
- async function listenGuest(path, answer, timeoutMs = REQUEST_TIMEOUT_MS) {
4196
+ async function listenGuest(path, answer2, timeoutMs = REQUEST_TIMEOUT_MS) {
4108
4197
  await closeGuest(path);
4109
4198
  await rm5(path, { force: true });
4110
- const open3 = /* @__PURE__ */ new Set();
4199
+ const open4 = /* @__PURE__ */ new Set();
4111
4200
  const server = createServer((sock) => {
4112
- open3.add(sock);
4113
- sock.once("close", () => open3.delete(sock));
4114
- serve(sock, answer, timeoutMs);
4201
+ open4.add(sock);
4202
+ sock.once("close", () => open4.delete(sock));
4203
+ serve(sock, answer2, timeoutMs);
4115
4204
  });
4116
4205
  server.maxConnections = MAX_OPEN;
4117
4206
  await new Promise((resolve3, reject) => {
@@ -4123,7 +4212,7 @@ async function listenGuest(path, answer, timeoutMs = REQUEST_TIMEOUT_MS) {
4123
4212
  });
4124
4213
  server.unref();
4125
4214
  server.on("error", () => void 0);
4126
- listeners.set(path, { server, open: open3 });
4215
+ listeners.set(path, { server, open: open4 });
4127
4216
  }
4128
4217
  async function closeGuest(path) {
4129
4218
  const l = listeners.get(path);
@@ -4213,11 +4302,11 @@ async function answerGuest(ref, request7, p, now = Date.now()) {
4213
4302
  const probe = await probeConnection(cp, meta, integration, now);
4214
4303
  return refusal("off", `${integration} is not turned on for this box`, probe?.connected);
4215
4304
  }
4216
- const answer = await askCredential(cp, meta, integration);
4217
- if (answer.ok && answer.identity && !(told.has(meta.id) && sameIdentity(told.get(meta.id), answer.identity))) {
4218
- void tellCurrent(ref, p.machine(meta.owner, meta.name).vsock, p, answer.identity).catch(() => void 0);
4305
+ const answer2 = await askCredential(cp, meta, integration);
4306
+ if (answer2.ok && answer2.identity && !(told.has(meta.id) && sameIdentity(told.get(meta.id), answer2.identity))) {
4307
+ void tellCurrent(ref, p.machine(meta.owner, meta.name).vsock, p, answer2.identity).catch(() => void 0);
4219
4308
  }
4220
- return answer;
4309
+ return answer2;
4221
4310
  }
4222
4311
  var told = /* @__PURE__ */ new Map();
4223
4312
  var sameIdentity = (a, b) => a?.name === b?.name && a?.email === b?.email;
@@ -4238,12 +4327,12 @@ async function identityOf(box, p) {
4238
4327
  var sameList = (a, b) => JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
4239
4328
  async function tellCurrent(ref, vsock, p, identity) {
4240
4329
  for (; ; ) {
4241
- const asked2 = await readMachineMeta(ref, p);
4242
- const who = identity !== void 0 && (asked2.integrations ?? []).includes("github") ? identity : await identityOf(asked2, p);
4330
+ const asked3 = await readMachineMeta(ref, p);
4331
+ const who = identity !== void 0 && (asked3.integrations ?? []).includes("github") ? identity : await identityOf(asked3, p);
4243
4332
  if (who === null) return false;
4244
4333
  const done = await withBoxLock(ref, async () => {
4245
4334
  const box = await readMachineMeta(ref, p);
4246
- if (!sameList(box.integrations, asked2.integrations)) return false;
4335
+ if (!sameList(box.integrations, asked3.integrations)) return false;
4247
4336
  const unusable = await tellGuest(box, vsock, who);
4248
4337
  if (unusable.length > 0) log.warn(`box ${shown(box)} has integrations it cannot use: ${tooOldFor(box, unusable)}`);
4249
4338
  return true;
@@ -4362,9 +4451,13 @@ function toMachine(meta, p = paths()) {
4362
4451
  ...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
4363
4452
  ...meta.integrations?.length ? { integrations: [...meta.integrations] } : {},
4364
4453
  ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
4365
- ...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
4454
+ ...linksOf(meta)
4366
4455
  };
4367
4456
  }
4457
+ function linksOf(meta) {
4458
+ const all = [...(meta.links ?? []).filter((l) => !l.stale), ...meta.farLinks ?? []];
4459
+ return all.length > 0 ? { links: all.map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {};
4460
+ }
4368
4461
  var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
4369
4462
  async function listMachines(scope, p = paths()) {
4370
4463
  return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
@@ -4592,8 +4685,326 @@ function pickSshPort(taken) {
4592
4685
  throw new KvboxError(`no free port left between ${SSH_PORT_MIN} and ${SSH_PORT_MAX} on this host`);
4593
4686
  }
4594
4687
 
4688
+ // src/core/farTunnel.ts
4689
+ import { createServer as createServer2 } from "node:net";
4690
+ import { connect as tlsConnect } from "node:tls";
4691
+
4692
+ // ../shared/src/httpHead.ts
4693
+ var END = "\r\n\r\n";
4694
+ var HeadTimeoutError = class extends Error {
4695
+ };
4696
+ function readHead(socket, opts) {
4697
+ return new Promise((resolve3, reject) => {
4698
+ let bytes = Buffer.alloc(0);
4699
+ const done = (err) => {
4700
+ clearTimeout(timer);
4701
+ socket.off("data", onData);
4702
+ socket.off("close", onClose);
4703
+ socket.pause();
4704
+ if (err) return reject(err);
4705
+ const end = bytes.indexOf(END);
4706
+ resolve3({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
4707
+ };
4708
+ const onData = (chunk) => {
4709
+ bytes = Buffer.concat([bytes, chunk]);
4710
+ if (bytes.includes(END)) done();
4711
+ else if (bytes.length > opts.maxBytes) done(new Error("answer head too large"));
4712
+ };
4713
+ const onClose = () => done(new Error("closed before answering"));
4714
+ const timer = setTimeout(() => done(new HeadTimeoutError(`no answer within ${opts.timeoutMs / 1e3} s`)), opts.timeoutMs);
4715
+ socket.on("data", onData);
4716
+ socket.once("close", onClose);
4717
+ });
4718
+ }
4719
+ function headStatus(head) {
4720
+ const m = /^HTTP\/\d(?:\.\d)? (\d{3})(?: |\r|$)/.exec(head);
4721
+ return m ? Number(m[1]) : void 0;
4722
+ }
4723
+ function headHeader(head, name) {
4724
+ const line = head.split("\r\n").slice(1).find((l) => l.slice(0, l.indexOf(":")).trim().toLowerCase() === name);
4725
+ return line?.slice(line.indexOf(":") + 1).trim();
4726
+ }
4727
+ function rewriteHead(head, drop, add = {}) {
4728
+ const [status, ...lines] = head.split("\r\n");
4729
+ const kept = lines.filter((l) => !drop(l.slice(0, l.indexOf(":")).trim().toLowerCase()));
4730
+ const extra = Object.entries(add).map(([k, v]) => `${k}: ${v}`);
4731
+ return Buffer.from(`${[status, ...kept, ...extra].join("\r\n")}${END}`, "latin1");
4732
+ }
4733
+
4734
+ // ../shared/src/names.ts
4735
+ import { createHmac } from "node:crypto";
4736
+ var PROXY_ERROR_HEADER = "x-kvbox-proxy-error";
4737
+ var PROXIED_HEADER = "x-kvbox-proxied";
4738
+ var VISITOR_PATH_HEADER = "x-kvbox-path";
4739
+ var WAKE_HEADER = "x-kvbox-wake";
4740
+ var WAKE_WAIT_MS = 3e4;
4741
+ var REQUEST_TIMEOUT_MS2 = 36e5;
4742
+ var WOKE_HEADER = "x-kvbox-woke";
4743
+ var VISITOR_AUTH_HEADER = "x-kvbox-authorization";
4744
+ var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
4745
+ var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
4746
+ var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
4747
+ function edgeCredential(hostSecret) {
4748
+ return createHmac("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
4749
+ }
4750
+ var BOX_LINK_PATH_RE = /^\/machines\/([^/]+)\/link\/(\d{1,5})\/?$/;
4751
+ var LINK_PROTOCOL = "kvbox-link";
4752
+ var LINK_ERROR_HEADER = "x-kvbox-link-error";
4753
+ var BOX_RUN_PATH_RE = /^\/machines\/([^/]+)\/runs(\/[A-Za-z0-9_-]{1,64})?\/?$/;
4754
+ function cronCredential(hostSecret) {
4755
+ return createHmac("sha256", hostSecret).update("kvbox-cron-v1").digest("base64url");
4756
+ }
4757
+
4758
+ // src/core/farTunnel.ts
4759
+ var FarRefusal = class extends Error {
4760
+ constructor(code, message) {
4761
+ super(message);
4762
+ this.code = code;
4763
+ this.name = "FarRefusal";
4764
+ }
4765
+ code;
4766
+ };
4767
+ var DIAL_TIMEOUT_MS = 1e4;
4768
+ var MAX_HEAD_BYTES = 16 * 1024;
4769
+ var MAX_OPEN2 = 256;
4770
+ var WARN_EVERY_MS = 6e4;
4771
+ var KEEPALIVE_MS = 3e4;
4772
+ function splice(a, b) {
4773
+ for (const s of [a, b]) {
4774
+ s.allowHalfOpen = true;
4775
+ s.setKeepAlive(true, KEEPALIVE_MS);
4776
+ }
4777
+ a.pipe(b);
4778
+ b.pipe(a);
4779
+ const after = (gone, other) => (hadError) => {
4780
+ if (hadError || other.writableFinished || gone.errored) return void other.destroy();
4781
+ other.end(() => other.destroy());
4782
+ };
4783
+ a.once("close", after(a, b));
4784
+ b.once("close", after(b, a));
4785
+ }
4786
+ function connectPinned(url, pin, timeoutMs) {
4787
+ const target = new URL(url);
4788
+ return new Promise((resolve3, reject) => {
4789
+ const socket = tlsConnect({ host: target.hostname, port: Number(target.port || 443), rejectUnauthorized: false, timeout: timeoutMs });
4790
+ socket.allowHalfOpen = true;
4791
+ socket.once("timeout", () => socket.destroy(new Error(`no answer within ${timeoutMs / 1e3} s`)));
4792
+ socket.once("error", reject);
4793
+ socket.once("secureConnect", () => {
4794
+ if (socket.getPeerCertificate().fingerprint256 !== pin) {
4795
+ socket.destroy();
4796
+ return reject(new Error("its certificate is not the one the control plane named (fingerprint mismatch)"));
4797
+ }
4798
+ socket.setTimeout(0);
4799
+ socket.off("error", reject);
4800
+ socket.on("error", () => socket.destroy());
4801
+ resolve3(socket);
4802
+ });
4803
+ });
4804
+ }
4805
+ async function ask2(t, method, timeoutMs) {
4806
+ const socket = await connectPinned(t.url, t.pin, timeoutMs);
4807
+ const slug = t.owner.split("@")[0];
4808
+ socket.write(
4809
+ `${method} /machines/${encodeURIComponent(t.name)}/link/${t.port} HTTP/1.1\r
4810
+ host: ${new URL(t.url).host}\r
4811
+ connection: Upgrade\r
4812
+ upgrade: ${LINK_PROTOCOL}\r
4813
+ authorization: Bearer ${t.key}\r
4814
+ x-kvbox-owner: ${slug}\r
4815
+ \r
4816
+ `
4817
+ );
4818
+ try {
4819
+ return { socket, ...await readHead(socket, { maxBytes: MAX_HEAD_BYTES, timeoutMs }) };
4820
+ } catch (err) {
4821
+ socket.destroy();
4822
+ throw err;
4823
+ }
4824
+ }
4825
+ var refusal2 = (head) => {
4826
+ const code = headHeader(head, LINK_ERROR_HEADER);
4827
+ return new FarRefusal(code === "gone" || code === "down" || code === "unreachable" ? code : "refused", `the other host answered ${headStatus(head) ?? "nothing it should"}${code ? ` (${code})` : ""}`);
4828
+ };
4829
+ async function dialFar(t, timeoutMs = DIAL_TIMEOUT_MS) {
4830
+ const { socket, head, rest } = await ask2(t, "GET", timeoutMs);
4831
+ if (headStatus(head) === 101) return { socket, rest };
4832
+ socket.destroy();
4833
+ throw refusal2(head);
4834
+ }
4835
+ async function dropFar(t, timeoutMs = DIAL_TIMEOUT_MS) {
4836
+ const { socket, head } = await ask2(t, "DELETE", timeoutMs);
4837
+ socket.destroy();
4838
+ if (headStatus(head) === 200) return;
4839
+ const refused = refusal2(head);
4840
+ if (refused.code !== "gone") throw refused;
4841
+ }
4842
+ 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;
4843
+ var listeners2 = /* @__PURE__ */ new Map();
4844
+ async function listenFar(id, opts) {
4845
+ const have = listeners2.get(id);
4846
+ if (have && sameTarget(have.target, opts.target)) return have.port;
4847
+ if (have) await closeFar(id);
4848
+ const open4 = /* @__PURE__ */ new Set();
4849
+ const track = (s) => {
4850
+ open4.add(s);
4851
+ s.once("close", () => open4.delete(s));
4852
+ };
4853
+ let warnedAt = 0;
4854
+ const server = createServer2({ allowHalfOpen: true }, (box) => {
4855
+ track(box);
4856
+ box.on("error", () => box.destroy());
4857
+ if (box.remoteAddress !== opts.fromIp) return void box.destroy();
4858
+ dialFar(opts.target, opts.dialTimeoutMs).then(
4859
+ ({ socket, rest }) => {
4860
+ if (box.destroyed) return void socket.destroy();
4861
+ track(socket);
4862
+ if (rest.length > 0) box.write(rest);
4863
+ splice(box, socket);
4864
+ },
4865
+ (err) => {
4866
+ box.destroy();
4867
+ if (err instanceof FarRefusal && err.code === "gone") return opts.onGone?.();
4868
+ if (err instanceof FarRefusal && err.code !== "refused") return;
4869
+ if (Date.now() - warnedAt < WARN_EVERY_MS) return;
4870
+ warnedAt = Date.now();
4871
+ log.warn(`link to ${opts.target.name} port ${opts.target.port} on another host: ${err.message}`);
4872
+ }
4873
+ );
4874
+ });
4875
+ server.maxConnections = MAX_OPEN2;
4876
+ await new Promise((resolve3, reject) => {
4877
+ server.once("error", reject);
4878
+ server.listen(0, opts.host, () => {
4879
+ server.off("error", reject);
4880
+ resolve3();
4881
+ });
4882
+ });
4883
+ server.unref();
4884
+ server.on("error", () => void 0);
4885
+ const port = server.address().port;
4886
+ listeners2.set(id, { server, open: open4, port, target: { ...opts.target } });
4887
+ return port;
4888
+ }
4889
+ async function closeFar(id) {
4890
+ const l = listeners2.get(id);
4891
+ if (!l) return;
4892
+ listeners2.delete(id);
4893
+ for (const sock of l.open) sock.destroy();
4894
+ await new Promise((resolve3) => l.server.close(() => resolve3()));
4895
+ }
4896
+
4897
+ // src/core/machines/farTargets.ts
4898
+ var listenerId = (boxId, t) => `${boxId}|${t.owner}/${t.name}:${t.port}`;
4899
+ var sameTarget2 = (to, port) => (t) => t.owner === to.owner && t.name === to.name && t.port === port;
4900
+ function targetRef(req, caller) {
4901
+ if (req.toOwner !== void 0) return { owner: ownerFor(req.toOwner, caller), name: req.to, display: `${req.toOwner}/${req.to}` };
4902
+ return parseRef(req.to, caller);
4903
+ }
4904
+ async function open(meta, t, cfg, p) {
4905
+ const ref = { owner: meta.owner, name: meta.name };
4906
+ const via = await listenFar(listenerId(meta.id, t), {
4907
+ host: driver().net.farListenHost(cfg),
4908
+ fromIp: meta.ip,
4909
+ target: t,
4910
+ // The listener was made under the box's lock, and its connections would read as holding it: the forget
4911
+ // waits for the lock like any other change of the box.
4912
+ onGone: () => outsideLocks(() => void forgetFarTarget(ref, t, p).catch((err) => log.warn(`box ${meta.name}: could not forget its link to ${t.name}: ${err.message}`)))
4913
+ });
4914
+ await driver().net.openFarLink({ box: meta.id, fromIp: meta.ip, standIn: t.ip, port: t.port, via }, cfg);
4915
+ }
4916
+ async function close(meta, t, cfg) {
4917
+ try {
4918
+ await driver().net.closeFarLink({ box: meta.id, fromIp: meta.ip, standIn: t.ip, port: t.port }, cfg);
4919
+ } finally {
4920
+ await closeFar(listenerId(meta.id, t));
4921
+ }
4922
+ }
4923
+ async function openFarTargets(meta, cfg, p) {
4924
+ for (const t of meta.farTargets ?? []) {
4925
+ 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}`));
4926
+ }
4927
+ }
4928
+ async function closeFarTargets(meta, cfg) {
4929
+ for (const t of meta.farTargets ?? []) {
4930
+ 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}`));
4931
+ }
4932
+ }
4933
+ async function reopenFarTargets(p = paths()) {
4934
+ const cfg = await loadConfig(p);
4935
+ for (const listed of await readAllMeta(p)) {
4936
+ if (!vmAlive(listed) || !listed.farTargets?.length) continue;
4937
+ await withBoxLock(listed, async () => {
4938
+ const meta = await readMachineMeta(listed, p).catch(() => null);
4939
+ if (meta !== null && vmAlive(meta)) await openFarTargets(meta, cfg, p);
4940
+ });
4941
+ }
4942
+ }
4943
+ var addFarTarget = locked(async function addFarTarget2(ref, req, caller, p = paths()) {
4944
+ const meta = await readMeta(ref, p);
4945
+ const to = targetRef(req, caller);
4946
+ if (realmOf(meta.owner) === null || realmOf(to.owner) !== realmOf(meta.owner)) {
4947
+ 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`);
4948
+ }
4949
+ const cfg = await loadConfig(p);
4950
+ const same = sameTarget2(to, req.port);
4951
+ const before = (meta.farTargets ?? []).find(same);
4952
+ const kept = (meta.farTargets ?? []).filter((t) => !same(t));
4953
+ 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}`);
4954
+ return withHostLock("links", async () => {
4955
+ const taken = (await readAllMeta(p)).flatMap((m) => m.farTargets ?? []);
4956
+ const ip = taken.find((t) => t.owner === to.owner && t.name === to.name)?.ip ?? driver().net.standIn(cfg, taken.map((t) => t.ip));
4957
+ const entry = { owner: to.owner, name: to.name, port: req.port, ip, url: req.url, pin: req.pin, key: req.key };
4958
+ const next = { ...meta, farTargets: [...kept, entry] };
4959
+ if (before) await close(meta, before, cfg);
4960
+ await writeMachineMeta(next, p);
4961
+ boxListChanged();
4962
+ if (vmAlive(meta)) {
4963
+ try {
4964
+ await open(next, entry, cfg, p);
4965
+ } catch (err) {
4966
+ await close(next, entry, cfg).catch(() => void 0);
4967
+ await writeMachineMeta(meta, p);
4968
+ boxListChanged();
4969
+ 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}`));
4970
+ throw err;
4971
+ }
4972
+ }
4973
+ return toMachine(next, p);
4974
+ });
4975
+ });
4976
+ var removeFarTarget = locked(async function removeFarTarget2(ref, req, caller, p = paths()) {
4977
+ const meta = await readMeta(ref, p);
4978
+ const same = sameTarget2(targetRef(req, caller), req.port);
4979
+ const gone = (meta.farTargets ?? []).filter(same);
4980
+ if (gone.length === 0) return toMachine(meta, p);
4981
+ return toMachine(await without(meta, gone, p), p);
4982
+ });
4983
+ async function without(meta, gone, p) {
4984
+ const cfg = await loadConfig(p);
4985
+ for (const t of gone) await close(meta, t, cfg);
4986
+ const kept = (meta.farTargets ?? []).filter((t) => !gone.includes(t));
4987
+ const next = { ...meta, farTargets: kept.length > 0 ? kept : void 0 };
4988
+ await writeMachineMeta(next, p);
4989
+ boxListChanged();
4990
+ return next;
4991
+ }
4992
+ var forgetFarTarget = locked(async function forgetFarTarget2(ref, t, p) {
4993
+ const meta = await readMachineMeta(ref, p).catch(() => null);
4994
+ const gone = (meta?.farTargets ?? []).filter((now) => now.owner === t.owner && now.name === t.name && now.port === t.port && now.key === t.key);
4995
+ if (meta === null || gone.length === 0) return;
4996
+ await without(meta, gone, p);
4997
+ log.info(`box ${meta.name}: its link to ${t.name} port ${t.port} no longer exists on the other host; forgotten here`);
4998
+ });
4999
+ function tellFarTargetsGone(gone) {
5000
+ for (const t of gone.farTargets ?? []) {
5001
+ void dropFar(t).catch((err) => log.warn(`removed box ${gone.name}: its link into ${t.name} on another host stays listed there (${err.message})`));
5002
+ }
5003
+ }
5004
+
4595
5005
  // src/core/machines/ports.ts
4596
5006
  var publicPortsInUse = (metas) => metas.flatMap((m) => [...m.sshPort === void 0 ? [] : [m.sshPort], ...(m.ports ?? []).map((f) => f.hostPort)]);
5007
+ var reaching = (meta) => meta.farTargets?.length && meta.owner !== void 0 && meta.name !== void 0 ? { ...meta, owner: meta.owner, name: meta.name } : null;
4597
5008
  function boxProxies(meta) {
4598
5009
  const ssh = meta.sshPort === void 0 ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];
4599
5010
  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 }))];
@@ -4613,6 +5024,8 @@ async function openPorts(meta, cfg, p) {
4613
5024
  for (const link4 of await standingLinks(meta, p)) {
4614
5025
  await driver().net.openLink(link4, cfg).catch((err) => log.warn(`could not open the link from ${link4.fromIp}: ${err.message}`));
4615
5026
  }
5027
+ const far = reaching(meta);
5028
+ if (far) await openFarTargets(far, cfg, p);
4616
5029
  }
4617
5030
  async function closePorts(meta, cfg) {
4618
5031
  for (const proxy of boxProxies(meta)) {
@@ -4621,6 +5034,8 @@ async function closePorts(meta, cfg) {
4621
5034
  for (const link4 of boxLinks(meta)) {
4622
5035
  await driver().net.closeLink(link4, cfg).catch((err) => log.warn(`could not close the link from ${link4.fromIp}: ${err.message}`));
4623
5036
  }
5037
+ const far = reaching(meta);
5038
+ if (far) await closeFarTargets(far, cfg);
4624
5039
  }
4625
5040
  var reservedPorts = /* @__PURE__ */ new Set();
4626
5041
  async function drawPorts(count, p) {
@@ -4662,15 +5077,15 @@ var addPorts = locked(async function addPorts2(ref, req, p = paths()) {
4662
5077
  const opened = [];
4663
5078
  try {
4664
5079
  const added = fresh.map((w, i) => ({ ...w, hostPort: drawn.ports[i] }));
4665
- const open3 = ({ closed: _closed, ...f }) => f;
4666
- const again = current2.filter((f) => reopened.some(samePort(f))).map(open3);
5080
+ const open4 = ({ closed: _closed, ...f }) => f;
5081
+ const again = current2.filter((f) => reopened.some(samePort(f))).map(open4);
4667
5082
  if (vmAlive(meta)) {
4668
5083
  for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: [...again, ...added] })) {
4669
5084
  await driver().net.openProxy(proxy, cfg);
4670
5085
  opened.push(proxy);
4671
5086
  }
4672
5087
  }
4673
- const next = { ...meta, ports: [...current2.map((f) => reopened.some(samePort(f)) ? open3(f) : f), ...added] };
5088
+ const next = { ...meta, ports: [...current2.map((f) => reopened.some(samePort(f)) ? open4(f) : f), ...added] };
4674
5089
  await writeMachineMeta(next, p);
4675
5090
  return toMachine(next, p);
4676
5091
  } catch (err) {
@@ -4844,6 +5259,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
4844
5259
  import { rm as rm7 } from "node:fs/promises";
4845
5260
 
4846
5261
  // src/core/machines/links.ts
5262
+ import { createHash as createHash3, timingSafeEqual } from "node:crypto";
4847
5263
  function linkSource(req, caller, target) {
4848
5264
  if (req.fromOwner !== void 0) return { owner: ownerFor(req.fromOwner, caller), name: req.from, display: `${req.fromOwner}/${req.from}` };
4849
5265
  const ref = parseRef(req.from, caller);
@@ -4854,6 +5270,7 @@ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
4854
5270
  const meta = await readMeta(ref, p);
4855
5271
  const fromRef = linkSource(req, caller, meta.owner);
4856
5272
  if (fromRef.owner === meta.owner && fromRef.name === meta.name) throw new KvboxError(`box ${shown(ref)} already reaches itself`);
5273
+ if (req.far !== void 0) return addFarLink(meta, fromRef, req.port, req.far.key, p);
4857
5274
  const from = await readMeta(fromRef, p);
4858
5275
  if (realmOf(from.owner) !== realmOf(meta.owner)) {
4859
5276
  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`);
@@ -4861,7 +5278,8 @@ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
4861
5278
  const links = (meta.links ?? []).filter((l) => !(l.stale && l.owner === from.owner && l.name === from.name && l.ip === from.ip && l.port === req.port));
4862
5279
  const same = (l) => !l.stale && l.owner === from.owner && l.name === from.name && l.port === req.port;
4863
5280
  if (links.some(same)) throw new KvboxError(`box ${shown(fromRef)} already reaches box ${shown(ref)} on port ${req.port}`);
4864
- if (links.length >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${shown(ref)} has ${links.length}`);
5281
+ const held2 = links.length + (meta.farLinks?.length ?? 0);
5282
+ if (held2 >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${shown(ref)} has ${held2}`);
4865
5283
  const added = { owner: from.owner, name: from.name, ip: from.ip, port: req.port };
4866
5284
  const cfg = await loadConfig(p);
4867
5285
  if (vmAlive(meta)) await driver().net.openLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg);
@@ -4874,16 +5292,60 @@ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
4874
5292
  }
4875
5293
  return toMachine(next, p);
4876
5294
  });
5295
+ var keyHash = (key) => createHash3("sha256").update(key).digest("hex");
5296
+ async function addFarLink(meta, from, port, key, p) {
5297
+ if (realmOf(meta.owner) === null || realmOf(from.owner) !== realmOf(meta.owner)) {
5298
+ 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`);
5299
+ }
5300
+ const same = (l) => l.owner === from.owner && l.name === from.name && l.port === port;
5301
+ if ((meta.links ?? []).some((l) => !l.stale && same(l)) || (meta.farLinks ?? []).some(same)) {
5302
+ throw new KvboxError(`box ${shown(from)} already reaches box ${meta.name} on port ${port}; to link it again, unlink it first`);
5303
+ }
5304
+ const kept = meta.farLinks ?? [];
5305
+ const held2 = (meta.links ?? []).filter((l) => !l.stale).length + kept.length;
5306
+ if (held2 >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${meta.name} has ${held2}`);
5307
+ const next = { ...meta, farLinks: [...kept, { owner: from.owner, name: from.name, port, key: keyHash(key) }] };
5308
+ await writeMachineMeta(next, p);
5309
+ return toMachine(next, p);
5310
+ }
5311
+ var holdsKey = (key, port) => {
5312
+ const given = Buffer.from(keyHash(key), "hex");
5313
+ return (l) => {
5314
+ const kept = Buffer.from(l.key, "hex");
5315
+ return l.port === port && kept.length === given.length && timingSafeEqual(kept, given);
5316
+ };
5317
+ };
5318
+ async function metaIfAny(ref, p) {
5319
+ return readMachineMeta(ref, p).catch((err) => {
5320
+ if (err.code === "ENOENT") return null;
5321
+ throw err;
5322
+ });
5323
+ }
5324
+ async function farLinkInto(ref, port, key, p = paths()) {
5325
+ const meta = await metaIfAny(ref, p);
5326
+ if (!meta?.farLinks?.some(holdsKey(key, port))) return "gone";
5327
+ return vmAlive(meta) && !meta.paused ? { ip: meta.ip } : "down";
5328
+ }
5329
+ var dropFarLink = locked(async function dropFarLink2(ref, port, key, p = paths()) {
5330
+ const meta = await metaIfAny(ref, p);
5331
+ const holds = holdsKey(key, port);
5332
+ if (!meta?.farLinks?.some(holds)) return false;
5333
+ const kept = meta.farLinks.filter((l) => !holds(l));
5334
+ await writeMachineMeta({ ...meta, farLinks: kept.length > 0 ? kept : void 0 }, p);
5335
+ return true;
5336
+ });
4877
5337
  var removeLink = locked(async function removeLink2(ref, req, caller, p = paths()) {
4878
5338
  const meta = await readMeta(ref, p);
4879
5339
  const fromRef = linkSource(req, caller, meta.owner);
4880
5340
  const links = meta.links ?? [];
4881
5341
  const gone = links.filter((l) => !l.stale && l.owner === fromRef.owner && l.name === fromRef.name && l.port === req.port);
4882
- if (gone.length === 0) throw new KvboxError(`box ${shown(fromRef)} is not linked to box ${shown(ref)} on port ${req.port}`);
5342
+ const far = (meta.farLinks ?? []).filter((l) => !(l.owner === fromRef.owner && l.name === fromRef.name && l.port === req.port));
5343
+ const hadFar = far.length !== (meta.farLinks?.length ?? 0);
5344
+ if (gone.length === 0 && !hadFar) throw new KvboxError(`box ${shown(fromRef)} is not linked to box ${shown(ref)} on port ${req.port}`);
4883
5345
  const cfg = await loadConfig(p);
4884
5346
  for (const l of gone) await driver().net.closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg);
4885
5347
  const kept = links.filter((l) => !gone.includes(l));
4886
- const next = { ...meta, links: kept.length > 0 ? kept : void 0 };
5348
+ const next = { ...meta, links: kept.length > 0 ? kept : void 0, farLinks: far.length > 0 ? far : void 0 };
4887
5349
  await writeMachineMeta(next, p);
4888
5350
  return toMachine(next, p);
4889
5351
  });
@@ -4963,7 +5425,11 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
4963
5425
  });
4964
5426
  async function destroyMachine(ref, p = paths()) {
4965
5427
  const gone = await destroyBox(ref, p);
4966
- await dropLinksFrom(gone, p);
5428
+ try {
5429
+ await dropLinksFrom(gone, p);
5430
+ } finally {
5431
+ tellFarTargetsGone(gone);
5432
+ }
4967
5433
  }
4968
5434
  var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
4969
5435
  const meta = await readMeta(ref, p);
@@ -5662,12 +6128,12 @@ async function replaceVolumeDisk(volume, file, p = paths()) {
5662
6128
  // src/core/backups.ts
5663
6129
  import { randomBytes as randomBytes5 } from "node:crypto";
5664
6130
  import { existsSync as existsSync13 } from "node:fs";
5665
- 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";
6131
+ 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";
5666
6132
  import { basename as basename2, join as join3 } from "node:path";
5667
6133
  import { setTimeout as sleep5 } from "node:timers/promises";
5668
6134
 
5669
6135
  // ../shared/src/backup.ts
5670
- import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes4 } from "node:crypto";
6136
+ import { createCipheriv, createDecipheriv, createHmac as createHmac2, randomBytes as randomBytes4 } from "node:crypto";
5671
6137
  import { promisify as promisify2 } from "node:util";
5672
6138
  import { deflateRaw as deflateRawCb, inflateRaw as inflateRawCb, constants as zlib } from "node:zlib";
5673
6139
  var deflateRaw = promisify2(deflateRawCb);
@@ -5683,8 +6149,8 @@ function backupKeys(dataKeyB64) {
5683
6149
  const dk = Buffer.from(dataKeyB64, "base64");
5684
6150
  if (dk.length !== 32) throw new Error("backup key: expected 32 bytes");
5685
6151
  return {
5686
- name: createHmac("sha256", dk).update("kvbox-backup chunk-name v1").digest(),
5687
- seal: createHmac("sha256", dk).update("kvbox-backup chunk-seal v1").digest()
6152
+ name: createHmac2("sha256", dk).update("kvbox-backup chunk-name v1").digest(),
6153
+ seal: createHmac2("sha256", dk).update("kvbox-backup chunk-seal v1").digest()
5688
6154
  };
5689
6155
  }
5690
6156
  function isZero(buf) {
@@ -5696,7 +6162,7 @@ function zeros(n) {
5696
6162
  return zeroBuf.subarray(0, n);
5697
6163
  }
5698
6164
  function chunkName(keys, plain) {
5699
- return createHmac("sha256", keys.name).update(plain).digest("hex");
6165
+ return createHmac2("sha256", keys.name).update(plain).digest("hex");
5700
6166
  }
5701
6167
  async function sealChunk(keys, name, plain) {
5702
6168
  const packed = await deflateRaw(plain, { level: zlib.Z_BEST_SPEED });
@@ -5751,7 +6217,7 @@ function storeDispatcher(pin, local) {
5751
6217
  const have = dispatchers.get(id);
5752
6218
  if (have) return have;
5753
6219
  const plain = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0, timeout: 1e4 });
5754
- const connect3 = (opts, cb) => {
6220
+ const connect4 = (opts, cb) => {
5755
6221
  plain(local ? { ...opts, hostname: "127.0.0.1" } : opts, (err, socket) => {
5756
6222
  if (err || !socket) return cb(err ?? new Error("no socket"), null);
5757
6223
  const tls = socket;
@@ -5763,7 +6229,7 @@ function storeDispatcher(pin, local) {
5763
6229
  cb(null, socket);
5764
6230
  });
5765
6231
  };
5766
- const agent = new Agent2({ connect: connect3 });
6232
+ const agent = new Agent2({ connect: connect4 });
5767
6233
  dispatchers.set(id, agent);
5768
6234
  return agent;
5769
6235
  }
@@ -5808,7 +6274,7 @@ async function readBox2(ref, p) {
5808
6274
  async function chunkNames(file, keys) {
5809
6275
  const { size: size2 } = await stat5(file);
5810
6276
  const chunks = [];
5811
- const fh = await open(file, "r");
6277
+ const fh = await open2(file, "r");
5812
6278
  try {
5813
6279
  const buf = Buffer.alloc(CHUNK_SIZE);
5814
6280
  for (let i = 0; i < chunkCount(size2); i++) {
@@ -5949,7 +6415,7 @@ async function uploadOnce(id, req, signal, p) {
5949
6415
  });
5950
6416
  const { size: size2 } = await stat5(s.disk);
5951
6417
  const fetchChunk = await chunkFetcher(req.pin, work[0]?.url, p);
5952
- const fh = await open(s.disk, "r");
6418
+ const fh = await open2(s.disk, "r");
5953
6419
  let bytes = 0;
5954
6420
  const sizes = {};
5955
6421
  try {
@@ -5996,7 +6462,7 @@ async function downloadDisk(file, req, p = paths()) {
5996
6462
  }
5997
6463
  const fetchChunk = await chunkFetcher(req.pin, req.chunks[0]?.url, p);
5998
6464
  await writeFile7(file, "", { mode: 384 });
5999
- const fh = await open(file, "r+");
6465
+ const fh = await open2(file, "r+");
6000
6466
  try {
6001
6467
  await fh.truncate(req.sizeBytes);
6002
6468
  await pool(req.chunks, async ({ index, hash, url }) => {
@@ -6688,21 +7154,21 @@ function startRelayWatch(opts = {}) {
6688
7154
 
6689
7155
  // src/daemon.ts
6690
7156
  import { spawn as spawn3 } from "node:child_process";
6691
- import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync6 } from "node:fs";
7157
+ import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync4, statSync as statSync6 } from "node:fs";
6692
7158
  import { mkdir as mkdir11, readFile as readFile11, stat as stat6 } from "node:fs/promises";
6693
7159
  import { userInfo as userInfo3 } from "node:os";
6694
7160
  import { setTimeout as sleep6 } from "node:timers/promises";
6695
7161
 
6696
7162
  // ../shared/src/systemd.ts
6697
7163
  import { spawnSync } from "node:child_process";
6698
- import { readFileSync as readFileSync2 } from "node:fs";
7164
+ import { readFileSync as readFileSync3 } from "node:fs";
6699
7165
  import { resolve } from "node:path";
6700
7166
  var UNIT = "kvbox-server";
6701
7167
  var UNIT_FILE = `/etc/systemd/system/${UNIT}.service`;
6702
7168
  function hasUnitFor(p, file = UNIT_FILE) {
6703
7169
  let text;
6704
7170
  try {
6705
- text = readFileSync2(file, "utf8");
7171
+ text = readFileSync3(file, "utf8");
6706
7172
  } catch {
6707
7173
  return false;
6708
7174
  }
@@ -6808,7 +7274,7 @@ async function refuseSecondDaemon(p = paths()) {
6808
7274
  }
6809
7275
  function isKvboxServer(pid) {
6810
7276
  try {
6811
- return readFileSync3(`/proc/${pid}/cmdline`, "utf8").split("\0").slice(1).some((arg) => arg.includes("kvbox"));
7277
+ return readFileSync4(`/proc/${pid}/cmdline`, "utf8").split("\0").slice(1).some((arg) => arg.includes("kvbox"));
6812
7278
  } catch (err) {
6813
7279
  return err.code !== "ENOENT";
6814
7280
  }
@@ -6939,7 +7405,7 @@ function shellQuote(word) {
6939
7405
  function groupWithMember(gid, user, groupFile) {
6940
7406
  let text;
6941
7407
  try {
6942
- text = readFileSync3(groupFile, "utf8");
7408
+ text = readFileSync4(groupFile, "utf8");
6943
7409
  } catch {
6944
7410
  return void 0;
6945
7411
  }
@@ -6956,27 +7422,6 @@ import { readFile as readFile13, rm as rm16, writeFile as writeFile10 } from "no
6956
7422
  import { createServer as createHttpsServer } from "node:https";
6957
7423
  import { createAdaptorServer } from "@hono/node-server";
6958
7424
 
6959
- // ../shared/src/names.ts
6960
- import { createHmac as createHmac2 } from "node:crypto";
6961
- var PROXY_ERROR_HEADER = "x-kvbox-proxy-error";
6962
- var PROXIED_HEADER = "x-kvbox-proxied";
6963
- var VISITOR_PATH_HEADER = "x-kvbox-path";
6964
- var WAKE_HEADER = "x-kvbox-wake";
6965
- var WAKE_WAIT_MS = 3e4;
6966
- var REQUEST_TIMEOUT_MS2 = 36e5;
6967
- var WOKE_HEADER = "x-kvbox-woke";
6968
- var VISITOR_AUTH_HEADER = "x-kvbox-authorization";
6969
- var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
6970
- var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
6971
- var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
6972
- function edgeCredential(hostSecret) {
6973
- return createHmac2("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
6974
- }
6975
- var BOX_RUN_PATH_RE = /^\/machines\/([^/]+)\/runs(\/[A-Za-z0-9_-]{1,64})?\/?$/;
6976
- function cronCredential(hostSecret) {
6977
- return createHmac2("sha256", hostSecret).update("kvbox-cron-v1").digest("base64url");
6978
- }
6979
-
6980
7425
  // src/app.ts
6981
7426
  import { Hono as Hono12 } from "hono";
6982
7427
 
@@ -6993,10 +7438,10 @@ function versionOf(srcFileUrl, injected) {
6993
7438
  }
6994
7439
 
6995
7440
  // src/version.ts
6996
- var VERSION = versionOf(import.meta.url, true ? "0.6.15" : void 0);
7441
+ var VERSION = versionOf(import.meta.url, true ? "0.6.17" : void 0);
6997
7442
 
6998
7443
  // src/caller.ts
6999
- import { createHash as createHash3, timingSafeEqual } from "node:crypto";
7444
+ import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
7000
7445
  var OWNER_HEADER = "x-kvbox-owner";
7001
7446
  function resolveCaller(opts = {}) {
7002
7447
  const cp = opts.controlPlane;
@@ -7046,11 +7491,11 @@ function bearerCheck(token) {
7046
7491
  const expected = digest(token);
7047
7492
  return (authorization) => {
7048
7493
  const m = /^Bearer\s+(\S+)$/i.exec(authorization ?? "");
7049
- return m !== null && timingSafeEqual(digest(m[1]), expected);
7494
+ return m !== null && timingSafeEqual2(digest(m[1]), expected);
7050
7495
  };
7051
7496
  }
7052
7497
  function digest(secret) {
7053
- return createHash3("sha256").update(secret).digest();
7498
+ return createHash4("sha256").update(secret).digest();
7054
7499
  }
7055
7500
 
7056
7501
  // src/core/update.ts
@@ -7171,42 +7616,6 @@ import { connect as connect2 } from "node:net";
7171
7616
  import { Readable } from "node:stream";
7172
7617
  import { Hono as Hono3 } from "hono";
7173
7618
  import { request as request6 } from "undici";
7174
-
7175
- // ../shared/src/httpHead.ts
7176
- var END = "\r\n\r\n";
7177
- var HeadTimeoutError = class extends Error {
7178
- };
7179
- function readHead(socket, opts) {
7180
- return new Promise((resolve3, reject) => {
7181
- let bytes = Buffer.alloc(0);
7182
- const done = (err) => {
7183
- clearTimeout(timer);
7184
- socket.off("data", onData);
7185
- socket.off("close", onClose);
7186
- socket.pause();
7187
- if (err) return reject(err);
7188
- const end = bytes.indexOf(END);
7189
- resolve3({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
7190
- };
7191
- const onData = (chunk) => {
7192
- bytes = Buffer.concat([bytes, chunk]);
7193
- if (bytes.includes(END)) done();
7194
- else if (bytes.length > opts.maxBytes) done(new Error("answer head too large"));
7195
- };
7196
- const onClose = () => done(new Error("closed before answering"));
7197
- const timer = setTimeout(() => done(new HeadTimeoutError(`no answer within ${opts.timeoutMs / 1e3} s`)), opts.timeoutMs);
7198
- socket.on("data", onData);
7199
- socket.once("close", onClose);
7200
- });
7201
- }
7202
- function rewriteHead(head, drop, add = {}) {
7203
- const [status, ...lines] = head.split("\r\n");
7204
- const kept = lines.filter((l) => !drop(l.slice(0, l.indexOf(":")).trim().toLowerCase()));
7205
- const extra = Object.entries(add).map(([k, v]) => `${k}: ${v}`);
7206
- return Buffer.from(`${[status, ...kept, ...extra].join("\r\n")}${END}`, "latin1");
7207
- }
7208
-
7209
- // src/routes/boxHttp.ts
7210
7619
  var HEADERS_TIMEOUT_MS = 55e3;
7211
7620
  var MAX_HANDSHAKE_BYTES = 16 * 1024;
7212
7621
  var CONNECT_TIMEOUT_MS = 5e3;
@@ -7396,10 +7805,10 @@ ${lines.join("")}\r
7396
7805
  `);
7397
7806
  if (head.length > 0) box.write(head);
7398
7807
  readHead(box, { maxBytes: MAX_HANDSHAKE_BYTES, timeoutMs: headersTimeoutMs }).then(
7399
- (answer) => {
7808
+ (answer2) => {
7400
7809
  if (socket.destroyed) return void box.destroy();
7401
- socket.write(rewriteHead(answer.head, (name) => name.startsWith("x-kvbox-"), { [PROXIED_HEADER]: "1", ...target.woke ? { [WOKE_HEADER]: "1" } : {} }));
7402
- if (answer.rest.length > 0) socket.write(answer.rest);
7810
+ socket.write(rewriteHead(answer2.head, (name) => name.startsWith("x-kvbox-"), { [PROXIED_HEADER]: "1", ...target.woke ? { [WOKE_HEADER]: "1" } : {} }));
7811
+ if (answer2.rest.length > 0) socket.write(answer2.rest);
7403
7812
  piped = true;
7404
7813
  box.pipe(socket);
7405
7814
  socket.pipe(box);
@@ -7549,6 +7958,16 @@ function machineRoutes() {
7549
7958
  };
7550
7959
  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));
7551
7960
  r.delete("/:name/links", async (c) => c.json(await removeLink(parseRef(c.req.param("name"), c.get("owner")), await linkBody(c), c.get("owner"))));
7961
+ r.post("/:name/far-links", async (c) => {
7962
+ const body = FarLinkRequest.safeParse(await c.req.json().catch(() => ({})));
7963
+ if (!body.success) throw new KvboxError("far-links: expected {to, port, url, pin, key}");
7964
+ return c.json(await addFarTarget(parseRef(c.req.param("name"), c.get("owner")), body.data, c.get("owner")), 201);
7965
+ });
7966
+ r.delete("/:name/far-links", async (c) => {
7967
+ const body = FarUnlinkRequest.safeParse(await c.req.json().catch(() => ({})));
7968
+ if (!body.success) throw new KvboxError("far-links: expected {to, port}");
7969
+ return c.json(await removeFarTarget(parseRef(c.req.param("name"), c.get("owner")), body.data, c.get("owner")));
7970
+ });
7552
7971
  r.get("/:name/usage", async (c) => {
7553
7972
  const since = c.req.query("since");
7554
7973
  let from;
@@ -7597,7 +8016,7 @@ function machineRoutes() {
7597
8016
  // src/routes/runs.ts
7598
8017
  import { Hono as Hono7 } from "hono";
7599
8018
  import { z as z9 } from "zod";
7600
- var refusal2 = (c, err) => {
8019
+ var refusal3 = (c, err) => {
7601
8020
  if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
7602
8021
  if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
7603
8022
  if (err instanceof AgentNotAnsweringError) return c.json({ error: err.message, code: "unreachable" }, 503);
@@ -7618,7 +8037,7 @@ function runRoutes(wake = wakeBox) {
7618
8037
  const started = await startBoxRun(ref, body);
7619
8038
  return c.json(StartRunAnswerSchema.parse({ id: body.id, started, woke }), 202);
7620
8039
  } catch (err) {
7621
- return refusal2(c, err);
8040
+ return refusal3(c, err);
7622
8041
  }
7623
8042
  });
7624
8043
  r.get("/:name/runs/:id", async (c) => {
@@ -7626,7 +8045,7 @@ function runRoutes(wake = wakeBox) {
7626
8045
  const { ref } = await runningBox(c.req.param("name"), c.get("owner"), wants(c.req.header(WAKE_HEADER)) ? wake : void 0);
7627
8046
  return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
7628
8047
  } catch (err) {
7629
- return refusal2(c, err);
8048
+ return refusal3(c, err);
7630
8049
  }
7631
8050
  });
7632
8051
  r.get("/:name/runs/:id/output", async (c) => {
@@ -7639,7 +8058,7 @@ function runRoutes(wake = wakeBox) {
7639
8058
  const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
7640
8059
  return c.json(RunOutputSchema.parse(await boxRunOutput(ref, id, stream, offset, limit)));
7641
8060
  } catch (err) {
7642
- return refusal2(c, err);
8061
+ return refusal3(c, err);
7643
8062
  }
7644
8063
  });
7645
8064
  return r;
@@ -7792,6 +8211,94 @@ function createApp(opts = {}) {
7792
8211
  return app;
7793
8212
  }
7794
8213
 
8214
+ // src/routes/boxLink.ts
8215
+ import { connect as connect3 } from "node:net";
8216
+ var CONNECT_TIMEOUT_MS2 = 5e3;
8217
+ function pathOf(url) {
8218
+ try {
8219
+ return new URL(url ?? "/", "https://host").pathname;
8220
+ } catch {
8221
+ return null;
8222
+ }
8223
+ }
8224
+ var isLinkPath = (url) => BOX_LINK_PATH_RE.test(pathOf(url) ?? "");
8225
+ function dispatchUpgrade(toLinked, toBox) {
8226
+ return (req, socket, head) => {
8227
+ try {
8228
+ (isLinkPath(req.url) ? toLinked : toBox)(req, socket, head);
8229
+ } catch {
8230
+ socket.destroy();
8231
+ }
8232
+ };
8233
+ }
8234
+ function answer(socket, status, text, code) {
8235
+ const body = JSON.stringify(status === 200 ? { ok: true } : { error: text });
8236
+ socket.end(
8237
+ `HTTP/1.1 ${status} ${status === 200 ? "OK" : "Error"}\r
8238
+ content-type: application/json\r
8239
+ content-length: ${Buffer.byteLength(body)}\r
8240
+ ${code ? `${LINK_ERROR_HEADER}: ${code}\r
8241
+ ` : ""}connection: close\r
8242
+ \r
8243
+ ${body}`
8244
+ );
8245
+ }
8246
+ function asked2(req, realm) {
8247
+ const m = BOX_LINK_PATH_RE.exec(pathOf(req.url) ?? "");
8248
+ const key = /^Bearer\s+(\S+)$/i.exec(req.headers.authorization ?? "")?.[1];
8249
+ const user = req.headers[OWNER_HEADER];
8250
+ if (!m || key === void 0 || typeof user !== "string" || !LOCAL_OWNER_RE.test(user)) return null;
8251
+ const port = Number(m[2]);
8252
+ let name;
8253
+ try {
8254
+ name = decodeURIComponent(m[1]);
8255
+ } catch {
8256
+ return null;
8257
+ }
8258
+ if (port < 1 || port > 65535 || name.includes("/")) return null;
8259
+ return { ref: parseRef(name, `${user}@${realm}`), port, key };
8260
+ }
8261
+ function linkUpgradeHandler(realm, connectTimeoutMs = CONNECT_TIMEOUT_MS2) {
8262
+ return (req, socket, head) => {
8263
+ socket.on("error", () => socket.destroy());
8264
+ void (async () => {
8265
+ const link4 = asked2(req, realm);
8266
+ if (link4 === null) return answer(socket, 400, "not a link's request");
8267
+ if (req.method !== "GET" && req.method !== "DELETE") return answer(socket, 405, "a link's connection is a GET");
8268
+ const to = await farLinkInto(link4.ref, link4.port, link4.key).catch(() => null);
8269
+ if (to === null) return answer(socket, 500, "the box cannot be read on this host");
8270
+ if (req.method === "DELETE") {
8271
+ if (to === "gone") return answer(socket, 404, "no such link", "gone");
8272
+ return await dropFarLink(link4.ref, link4.port, link4.key) ? answer(socket, 200, "") : answer(socket, 404, "no such link", "gone");
8273
+ }
8274
+ if (to === "gone") return answer(socket, 404, "no such link", "gone");
8275
+ if (to === "down") return answer(socket, 503, "the box is not running", "down");
8276
+ if (socket.destroyed) return;
8277
+ const box = connect3({ host: to.ip, port: link4.port, timeout: connectTimeoutMs, allowHalfOpen: true });
8278
+ let piped = false;
8279
+ box.once("timeout", () => box.destroy(new Error("timed out")));
8280
+ box.on("error", () => {
8281
+ if (!piped && !socket.destroyed) answer(socket, 502, `nothing answers on port ${link4.port} of the box`, "unreachable");
8282
+ else socket.destroy();
8283
+ });
8284
+ const leftEarly = () => box.destroy();
8285
+ socket.once("close", leftEarly);
8286
+ box.once("connect", () => {
8287
+ box.setTimeout(0);
8288
+ socket.write(`HTTP/1.1 101 Switching Protocols\r
8289
+ connection: Upgrade\r
8290
+ upgrade: ${LINK_PROTOCOL}\r
8291
+ \r
8292
+ `);
8293
+ if (head.length > 0) box.write(head);
8294
+ piped = true;
8295
+ socket.off("close", leftEarly);
8296
+ splice(socket, box);
8297
+ });
8298
+ })().catch(() => socket.destroy());
8299
+ };
8300
+ }
8301
+
7795
8302
  // src/listen.ts
7796
8303
  async function listen(opts = {}) {
7797
8304
  const p = await ensureLayout(paths());
@@ -7832,7 +8339,7 @@ async function listen(opts = {}) {
7832
8339
  const edge = edgeCheck(cp);
7833
8340
  const cron = cronCheck(cp);
7834
8341
  limitUntrusted(httpsServer, (req) => secret(req.headers.authorization) || edge(req.headers.authorization) || cron(req.headers.authorization));
7835
- httpsServer.on("upgrade", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));
8342
+ httpsServer.on("upgrade", dispatchUpgrade(linkUpgradeHandler(cp.name), boxUpgradeHandler({ name: cp.name, secret: cp.secret })));
7836
8343
  const port = opts.httpsPort ?? cp.port;
7837
8344
  await new Promise((resolve3, reject) => {
7838
8345
  httpsServer.once("error", reject);
@@ -7846,7 +8353,7 @@ async function listen(opts = {}) {
7846
8353
  const bound = httpsServer.address().port;
7847
8354
  https = { port: bound, url: `https://${cp.advertise}:${bound}` };
7848
8355
  }
7849
- const close = async () => {
8356
+ const close2 = async () => {
7850
8357
  await Promise.all([
7851
8358
  new Promise((resolve3) => server.close(() => resolve3())),
7852
8359
  httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
@@ -7864,7 +8371,7 @@ async function listen(opts = {}) {
7864
8371
  };
7865
8372
  process.once("SIGINT", () => void shutdown3());
7866
8373
  process.once("SIGTERM", () => void shutdown3());
7867
- return https ? { socketPath, server, https, close } : { socketPath, server, close };
8374
+ return https ? { socketPath, server, https, close: close2 } : { socketPath, server, close: close2 };
7868
8375
  }
7869
8376
  var UNTRUSTED_REQUEST_MS = 3e5;
7870
8377
  function limitUntrusted(server, trusted, ms = UNTRUSTED_REQUEST_MS) {
@@ -7910,6 +8417,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
7910
8417
  const state = await driver().net.prepare(cfg);
7911
8418
  log.info(`host network: bridge ${cfg.bridge} ${state}`);
7912
8419
  await pinRunningTaps(paths());
8420
+ await reopenFarTargets(paths()).catch((err) => log.warn(`running boxes cannot reach the boxes they are linked to on other hosts: ${err.message}`));
7913
8421
  } catch (err) {
7914
8422
  log.warn(`host network not ready (${err.message}); run: kvbox-server net up`);
7915
8423
  }
@@ -8031,7 +8539,7 @@ var leaveCommand = new Command6("leave").description("take this host out from be
8031
8539
  });
8032
8540
 
8033
8541
  // src/commands/logs.ts
8034
- import { open as open2, readFile as readFile14, stat as stat7 } from "node:fs/promises";
8542
+ import { open as open3, readFile as readFile14, stat as stat7 } from "node:fs/promises";
8035
8543
  import { setTimeout as sleep7 } from "node:timers/promises";
8036
8544
  import { Command as Command7 } from "commander";
8037
8545
  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) => {
@@ -8063,7 +8571,7 @@ async function follow(path, write, opts = {}) {
8063
8571
  const size2 = await stat7(path).then((s) => s.size, () => 0);
8064
8572
  if (size2 < offset) offset = 0;
8065
8573
  if (size2 > offset) {
8066
- const fh = await open2(path, "r");
8574
+ const fh = await open3(path, "r");
8067
8575
  try {
8068
8576
  const buf = Buffer.alloc(size2 - offset);
8069
8577
  const { bytesRead } = await fh.read(buf, 0, buf.length, offset);
@@ -8157,7 +8665,9 @@ async function plan(from, to, p) {
8157
8665
  ...sshKeys !== void 0 ? { sshKeys } : {},
8158
8666
  // A stopped box reads its lines at boot; any other guest still holds the old ones.
8159
8667
  ...keysChanged ? { sshKeysStale: status === "stopped" ? void 0 : true } : {},
8160
- ...meta.links !== void 0 ? { links: meta.links.map((l) => ({ ...l, owner: owner(l.owner) })) } : {}
8668
+ ...meta.links !== void 0 ? { links: meta.links.map((l) => ({ ...l, owner: owner(l.owner) })) } : {},
8669
+ ...meta.farLinks !== void 0 ? { farLinks: meta.farLinks.map((l) => ({ ...l, owner: owner(l.owner) })) } : {},
8670
+ ...meta.farTargets !== void 0 ? { farTargets: meta.farTargets.map((l) => ({ ...l, owner: owner(l.owner) })) } : {}
8161
8671
  }
8162
8672
  });
8163
8673
  }
@@ -8276,8 +8786,8 @@ async function confirm(question, yes) {
8276
8786
  const { createInterface } = await import("node:readline/promises");
8277
8787
  const rl = createInterface({ input: process.stdin, output: process.stderr });
8278
8788
  try {
8279
- const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
8280
- return answer === "y" || answer === "yes";
8789
+ const answer2 = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
8790
+ return answer2 === "y" || answer2 === "yes";
8281
8791
  } finally {
8282
8792
  rl.close();
8283
8793
  }