@kvbox/server 0.6.16 → 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.
- package/dist/kvbox-server.js +628 -131
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
- package/scripts/net-setup.sh +66 -3
package/dist/kvbox-server.js
CHANGED
|
@@ -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:
|
|
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(
|
|
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)
|
|
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
|
|
1750
|
-
return { vars: [...given, ...added], generated, secrets: [...generated, ...secrets], connect:
|
|
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) {
|
|
@@ -1923,7 +1970,25 @@ var PortsRequest = z6.object({
|
|
|
1923
1970
|
var BoxPortSchema = z6.number().int().min(1).max(65535);
|
|
1924
1971
|
var MAX_BOX_LINKS = 32;
|
|
1925
1972
|
var BoxLinkSchema = z6.object({ from: z6.string(), port: BoxPortSchema });
|
|
1926
|
-
var LinkRequest = z6.object({
|
|
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 });
|
|
1927
1992
|
var ClaimSubdomainRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
|
|
1928
1993
|
var SubdomainPortRequest = z6.object({ port: BoxPortSchema });
|
|
1929
1994
|
var SubdomainRouteRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
|
|
@@ -1989,7 +2054,10 @@ var BackupSchema = z6.object({
|
|
|
1989
2054
|
dataBytes: z6.number().int().nullable(),
|
|
1990
2055
|
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
1991
2056
|
uploadedBytes: z6.number().int().nullable(),
|
|
2057
|
+
/** Who asked for it; for a scheduled one, whoever made the thing it is of. */
|
|
1992
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),
|
|
1993
2061
|
createdAt: z6.string(),
|
|
1994
2062
|
finishedAt: z6.string().nullable()
|
|
1995
2063
|
});
|
|
@@ -2039,7 +2107,10 @@ var VolumeBackupSchema = z6.object({
|
|
|
2039
2107
|
dataBytes: z6.number().int().nullable(),
|
|
2040
2108
|
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
2041
2109
|
uploadedBytes: z6.number().int().nullable(),
|
|
2110
|
+
/** Who asked for it; for a scheduled one, whoever made the thing it is of. */
|
|
2042
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),
|
|
2043
2114
|
createdAt: z6.string(),
|
|
2044
2115
|
finishedAt: z6.string().nullable()
|
|
2045
2116
|
});
|
|
@@ -2181,7 +2252,7 @@ var MachineSchema = z6.object({
|
|
|
2181
2252
|
ownerKind: z6.enum(["user", "org"]).optional(),
|
|
2182
2253
|
/**
|
|
2183
2254
|
* The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
|
|
2184
|
-
*
|
|
2255
|
+
* a volume attaches only to a box on the same host, and a link between two boxes of one host stays on it.
|
|
2185
2256
|
*/
|
|
2186
2257
|
host: z6.string().optional(),
|
|
2187
2258
|
/** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
|
|
@@ -2481,6 +2552,8 @@ var CapacitySchema = z6.object({
|
|
|
2481
2552
|
fromBackup: z6.boolean().optional(),
|
|
2482
2553
|
/** True on a kvbox-server that keeps a box's `integrations` (#205); an older one drops the field without a word. */
|
|
2483
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(),
|
|
2484
2557
|
/** The integrations this kvbox-server knows (`hostKnowsIntegrations`). Absent with `integrations`: the first one's, `github` alone. */
|
|
2485
2558
|
integrationIds: z6.array(z6.string()).optional()
|
|
2486
2559
|
});
|
|
@@ -3562,9 +3635,9 @@ function forStore(url, p = paths()) {
|
|
|
3562
3635
|
return isStoreRequest(url) && existsSync6(p.backupStore.conf);
|
|
3563
3636
|
}
|
|
3564
3637
|
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 }, (
|
|
3566
|
-
res.writeHead(
|
|
3567
|
-
pipeline(
|
|
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) => {
|
|
3568
3641
|
if (err) res.destroy();
|
|
3569
3642
|
});
|
|
3570
3643
|
});
|
|
@@ -3613,6 +3686,9 @@ async function capacity(p = paths()) {
|
|
|
3613
3686
|
storeClient: true,
|
|
3614
3687
|
// A new box on a backup's disk (#141): the control plane places `new --from-backup` only here.
|
|
3615
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(),
|
|
3616
3692
|
// A box's integrations are kept here (#205): the control plane sends a list only to such a host.
|
|
3617
3693
|
integrations: true,
|
|
3618
3694
|
// ...and which (the control plane places a box with `claude` only on a host that names it).
|
|
@@ -4051,15 +4127,15 @@ async function ask(cp, body) {
|
|
|
4051
4127
|
}
|
|
4052
4128
|
}
|
|
4053
4129
|
async function askCredential(cp, box, integration) {
|
|
4054
|
-
let
|
|
4130
|
+
let answer2;
|
|
4055
4131
|
try {
|
|
4056
|
-
|
|
4132
|
+
answer2 = await ask(cp, { owner: box.owner, box: box.name, integration });
|
|
4057
4133
|
} catch (err) {
|
|
4058
4134
|
return unavailable(`${cp.name} could not be reached (${err.message}); try again shortly`);
|
|
4059
4135
|
}
|
|
4060
|
-
if (
|
|
4061
|
-
const parsed = CredentialAnswerSchema.safeParse(
|
|
4062
|
-
if (!parsed.success) return unavailable(`${cp.name} answered ${
|
|
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`);
|
|
4063
4139
|
return parsed.data;
|
|
4064
4140
|
}
|
|
4065
4141
|
var probes = /* @__PURE__ */ new Map();
|
|
@@ -4088,7 +4164,7 @@ var REQUEST_TIMEOUT_MS = 5e3;
|
|
|
4088
4164
|
var MAX_OPEN = 32;
|
|
4089
4165
|
var listeners = /* @__PURE__ */ new Map();
|
|
4090
4166
|
var unreadable = (message) => ({ ok: false, code: "unavailable", message });
|
|
4091
|
-
function serve(sock,
|
|
4167
|
+
function serve(sock, answer2, timeoutMs) {
|
|
4092
4168
|
let buf = "";
|
|
4093
4169
|
let taken = false;
|
|
4094
4170
|
const reply = (body) => {
|
|
@@ -4114,17 +4190,17 @@ function serve(sock, answer, timeoutMs) {
|
|
|
4114
4190
|
} catch {
|
|
4115
4191
|
return reply(unreadable("the request is not JSON"));
|
|
4116
4192
|
}
|
|
4117
|
-
|
|
4193
|
+
answer2(request7).then(reply, (err) => reply(unreadable(err.message)));
|
|
4118
4194
|
});
|
|
4119
4195
|
}
|
|
4120
|
-
async function listenGuest(path,
|
|
4196
|
+
async function listenGuest(path, answer2, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
4121
4197
|
await closeGuest(path);
|
|
4122
4198
|
await rm5(path, { force: true });
|
|
4123
|
-
const
|
|
4199
|
+
const open4 = /* @__PURE__ */ new Set();
|
|
4124
4200
|
const server = createServer((sock) => {
|
|
4125
|
-
|
|
4126
|
-
sock.once("close", () =>
|
|
4127
|
-
serve(sock,
|
|
4201
|
+
open4.add(sock);
|
|
4202
|
+
sock.once("close", () => open4.delete(sock));
|
|
4203
|
+
serve(sock, answer2, timeoutMs);
|
|
4128
4204
|
});
|
|
4129
4205
|
server.maxConnections = MAX_OPEN;
|
|
4130
4206
|
await new Promise((resolve3, reject) => {
|
|
@@ -4136,7 +4212,7 @@ async function listenGuest(path, answer, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
|
4136
4212
|
});
|
|
4137
4213
|
server.unref();
|
|
4138
4214
|
server.on("error", () => void 0);
|
|
4139
|
-
listeners.set(path, { server, open:
|
|
4215
|
+
listeners.set(path, { server, open: open4 });
|
|
4140
4216
|
}
|
|
4141
4217
|
async function closeGuest(path) {
|
|
4142
4218
|
const l = listeners.get(path);
|
|
@@ -4226,11 +4302,11 @@ async function answerGuest(ref, request7, p, now = Date.now()) {
|
|
|
4226
4302
|
const probe = await probeConnection(cp, meta, integration, now);
|
|
4227
4303
|
return refusal("off", `${integration} is not turned on for this box`, probe?.connected);
|
|
4228
4304
|
}
|
|
4229
|
-
const
|
|
4230
|
-
if (
|
|
4231
|
-
void tellCurrent(ref, p.machine(meta.owner, meta.name).vsock, p,
|
|
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);
|
|
4232
4308
|
}
|
|
4233
|
-
return
|
|
4309
|
+
return answer2;
|
|
4234
4310
|
}
|
|
4235
4311
|
var told = /* @__PURE__ */ new Map();
|
|
4236
4312
|
var sameIdentity = (a, b) => a?.name === b?.name && a?.email === b?.email;
|
|
@@ -4251,12 +4327,12 @@ async function identityOf(box, p) {
|
|
|
4251
4327
|
var sameList = (a, b) => JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
|
|
4252
4328
|
async function tellCurrent(ref, vsock, p, identity) {
|
|
4253
4329
|
for (; ; ) {
|
|
4254
|
-
const
|
|
4255
|
-
const who = identity !== void 0 && (
|
|
4330
|
+
const asked3 = await readMachineMeta(ref, p);
|
|
4331
|
+
const who = identity !== void 0 && (asked3.integrations ?? []).includes("github") ? identity : await identityOf(asked3, p);
|
|
4256
4332
|
if (who === null) return false;
|
|
4257
4333
|
const done = await withBoxLock(ref, async () => {
|
|
4258
4334
|
const box = await readMachineMeta(ref, p);
|
|
4259
|
-
if (!sameList(box.integrations,
|
|
4335
|
+
if (!sameList(box.integrations, asked3.integrations)) return false;
|
|
4260
4336
|
const unusable = await tellGuest(box, vsock, who);
|
|
4261
4337
|
if (unusable.length > 0) log.warn(`box ${shown(box)} has integrations it cannot use: ${tooOldFor(box, unusable)}`);
|
|
4262
4338
|
return true;
|
|
@@ -4375,9 +4451,13 @@ function toMachine(meta, p = paths()) {
|
|
|
4375
4451
|
...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
|
|
4376
4452
|
...meta.integrations?.length ? { integrations: [...meta.integrations] } : {},
|
|
4377
4453
|
...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
|
|
4378
|
-
...
|
|
4454
|
+
...linksOf(meta)
|
|
4379
4455
|
};
|
|
4380
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
|
+
}
|
|
4381
4461
|
var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
|
|
4382
4462
|
async function listMachines(scope, p = paths()) {
|
|
4383
4463
|
return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
|
|
@@ -4605,8 +4685,326 @@ function pickSshPort(taken) {
|
|
|
4605
4685
|
throw new KvboxError(`no free port left between ${SSH_PORT_MIN} and ${SSH_PORT_MAX} on this host`);
|
|
4606
4686
|
}
|
|
4607
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
|
+
|
|
4608
5005
|
// src/core/machines/ports.ts
|
|
4609
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;
|
|
4610
5008
|
function boxProxies(meta) {
|
|
4611
5009
|
const ssh = meta.sshPort === void 0 ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];
|
|
4612
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 }))];
|
|
@@ -4626,6 +5024,8 @@ async function openPorts(meta, cfg, p) {
|
|
|
4626
5024
|
for (const link4 of await standingLinks(meta, p)) {
|
|
4627
5025
|
await driver().net.openLink(link4, cfg).catch((err) => log.warn(`could not open the link from ${link4.fromIp}: ${err.message}`));
|
|
4628
5026
|
}
|
|
5027
|
+
const far = reaching(meta);
|
|
5028
|
+
if (far) await openFarTargets(far, cfg, p);
|
|
4629
5029
|
}
|
|
4630
5030
|
async function closePorts(meta, cfg) {
|
|
4631
5031
|
for (const proxy of boxProxies(meta)) {
|
|
@@ -4634,6 +5034,8 @@ async function closePorts(meta, cfg) {
|
|
|
4634
5034
|
for (const link4 of boxLinks(meta)) {
|
|
4635
5035
|
await driver().net.closeLink(link4, cfg).catch((err) => log.warn(`could not close the link from ${link4.fromIp}: ${err.message}`));
|
|
4636
5036
|
}
|
|
5037
|
+
const far = reaching(meta);
|
|
5038
|
+
if (far) await closeFarTargets(far, cfg);
|
|
4637
5039
|
}
|
|
4638
5040
|
var reservedPorts = /* @__PURE__ */ new Set();
|
|
4639
5041
|
async function drawPorts(count, p) {
|
|
@@ -4675,15 +5077,15 @@ var addPorts = locked(async function addPorts2(ref, req, p = paths()) {
|
|
|
4675
5077
|
const opened = [];
|
|
4676
5078
|
try {
|
|
4677
5079
|
const added = fresh.map((w, i) => ({ ...w, hostPort: drawn.ports[i] }));
|
|
4678
|
-
const
|
|
4679
|
-
const again = current2.filter((f) => reopened.some(samePort(f))).map(
|
|
5080
|
+
const open4 = ({ closed: _closed, ...f }) => f;
|
|
5081
|
+
const again = current2.filter((f) => reopened.some(samePort(f))).map(open4);
|
|
4680
5082
|
if (vmAlive(meta)) {
|
|
4681
5083
|
for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: [...again, ...added] })) {
|
|
4682
5084
|
await driver().net.openProxy(proxy, cfg);
|
|
4683
5085
|
opened.push(proxy);
|
|
4684
5086
|
}
|
|
4685
5087
|
}
|
|
4686
|
-
const next = { ...meta, ports: [...current2.map((f) => reopened.some(samePort(f)) ?
|
|
5088
|
+
const next = { ...meta, ports: [...current2.map((f) => reopened.some(samePort(f)) ? open4(f) : f), ...added] };
|
|
4687
5089
|
await writeMachineMeta(next, p);
|
|
4688
5090
|
return toMachine(next, p);
|
|
4689
5091
|
} catch (err) {
|
|
@@ -4857,6 +5259,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
4857
5259
|
import { rm as rm7 } from "node:fs/promises";
|
|
4858
5260
|
|
|
4859
5261
|
// src/core/machines/links.ts
|
|
5262
|
+
import { createHash as createHash3, timingSafeEqual } from "node:crypto";
|
|
4860
5263
|
function linkSource(req, caller, target) {
|
|
4861
5264
|
if (req.fromOwner !== void 0) return { owner: ownerFor(req.fromOwner, caller), name: req.from, display: `${req.fromOwner}/${req.from}` };
|
|
4862
5265
|
const ref = parseRef(req.from, caller);
|
|
@@ -4867,6 +5270,7 @@ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
|
|
|
4867
5270
|
const meta = await readMeta(ref, p);
|
|
4868
5271
|
const fromRef = linkSource(req, caller, meta.owner);
|
|
4869
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);
|
|
4870
5274
|
const from = await readMeta(fromRef, p);
|
|
4871
5275
|
if (realmOf(from.owner) !== realmOf(meta.owner)) {
|
|
4872
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`);
|
|
@@ -4874,7 +5278,8 @@ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
|
|
|
4874
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));
|
|
4875
5279
|
const same = (l) => !l.stale && l.owner === from.owner && l.name === from.name && l.port === req.port;
|
|
4876
5280
|
if (links.some(same)) throw new KvboxError(`box ${shown(fromRef)} already reaches box ${shown(ref)} on port ${req.port}`);
|
|
4877
|
-
|
|
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}`);
|
|
4878
5283
|
const added = { owner: from.owner, name: from.name, ip: from.ip, port: req.port };
|
|
4879
5284
|
const cfg = await loadConfig(p);
|
|
4880
5285
|
if (vmAlive(meta)) await driver().net.openLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg);
|
|
@@ -4887,16 +5292,60 @@ var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
|
|
|
4887
5292
|
}
|
|
4888
5293
|
return toMachine(next, p);
|
|
4889
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
|
+
});
|
|
4890
5337
|
var removeLink = locked(async function removeLink2(ref, req, caller, p = paths()) {
|
|
4891
5338
|
const meta = await readMeta(ref, p);
|
|
4892
5339
|
const fromRef = linkSource(req, caller, meta.owner);
|
|
4893
5340
|
const links = meta.links ?? [];
|
|
4894
5341
|
const gone = links.filter((l) => !l.stale && l.owner === fromRef.owner && l.name === fromRef.name && l.port === req.port);
|
|
4895
|
-
|
|
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}`);
|
|
4896
5345
|
const cfg = await loadConfig(p);
|
|
4897
5346
|
for (const l of gone) await driver().net.closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg);
|
|
4898
5347
|
const kept = links.filter((l) => !gone.includes(l));
|
|
4899
|
-
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 };
|
|
4900
5349
|
await writeMachineMeta(next, p);
|
|
4901
5350
|
return toMachine(next, p);
|
|
4902
5351
|
});
|
|
@@ -4976,7 +5425,11 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
|
|
|
4976
5425
|
});
|
|
4977
5426
|
async function destroyMachine(ref, p = paths()) {
|
|
4978
5427
|
const gone = await destroyBox(ref, p);
|
|
4979
|
-
|
|
5428
|
+
try {
|
|
5429
|
+
await dropLinksFrom(gone, p);
|
|
5430
|
+
} finally {
|
|
5431
|
+
tellFarTargetsGone(gone);
|
|
5432
|
+
}
|
|
4980
5433
|
}
|
|
4981
5434
|
var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
|
|
4982
5435
|
const meta = await readMeta(ref, p);
|
|
@@ -5675,12 +6128,12 @@ async function replaceVolumeDisk(volume, file, p = paths()) {
|
|
|
5675
6128
|
// src/core/backups.ts
|
|
5676
6129
|
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
5677
6130
|
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";
|
|
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";
|
|
5679
6132
|
import { basename as basename2, join as join3 } from "node:path";
|
|
5680
6133
|
import { setTimeout as sleep5 } from "node:timers/promises";
|
|
5681
6134
|
|
|
5682
6135
|
// ../shared/src/backup.ts
|
|
5683
|
-
import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes4 } from "node:crypto";
|
|
6136
|
+
import { createCipheriv, createDecipheriv, createHmac as createHmac2, randomBytes as randomBytes4 } from "node:crypto";
|
|
5684
6137
|
import { promisify as promisify2 } from "node:util";
|
|
5685
6138
|
import { deflateRaw as deflateRawCb, inflateRaw as inflateRawCb, constants as zlib } from "node:zlib";
|
|
5686
6139
|
var deflateRaw = promisify2(deflateRawCb);
|
|
@@ -5696,8 +6149,8 @@ function backupKeys(dataKeyB64) {
|
|
|
5696
6149
|
const dk = Buffer.from(dataKeyB64, "base64");
|
|
5697
6150
|
if (dk.length !== 32) throw new Error("backup key: expected 32 bytes");
|
|
5698
6151
|
return {
|
|
5699
|
-
name:
|
|
5700
|
-
seal:
|
|
6152
|
+
name: createHmac2("sha256", dk).update("kvbox-backup chunk-name v1").digest(),
|
|
6153
|
+
seal: createHmac2("sha256", dk).update("kvbox-backup chunk-seal v1").digest()
|
|
5701
6154
|
};
|
|
5702
6155
|
}
|
|
5703
6156
|
function isZero(buf) {
|
|
@@ -5709,7 +6162,7 @@ function zeros(n) {
|
|
|
5709
6162
|
return zeroBuf.subarray(0, n);
|
|
5710
6163
|
}
|
|
5711
6164
|
function chunkName(keys, plain) {
|
|
5712
|
-
return
|
|
6165
|
+
return createHmac2("sha256", keys.name).update(plain).digest("hex");
|
|
5713
6166
|
}
|
|
5714
6167
|
async function sealChunk(keys, name, plain) {
|
|
5715
6168
|
const packed = await deflateRaw(plain, { level: zlib.Z_BEST_SPEED });
|
|
@@ -5764,7 +6217,7 @@ function storeDispatcher(pin, local) {
|
|
|
5764
6217
|
const have = dispatchers.get(id);
|
|
5765
6218
|
if (have) return have;
|
|
5766
6219
|
const plain = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0, timeout: 1e4 });
|
|
5767
|
-
const
|
|
6220
|
+
const connect4 = (opts, cb) => {
|
|
5768
6221
|
plain(local ? { ...opts, hostname: "127.0.0.1" } : opts, (err, socket) => {
|
|
5769
6222
|
if (err || !socket) return cb(err ?? new Error("no socket"), null);
|
|
5770
6223
|
const tls = socket;
|
|
@@ -5776,7 +6229,7 @@ function storeDispatcher(pin, local) {
|
|
|
5776
6229
|
cb(null, socket);
|
|
5777
6230
|
});
|
|
5778
6231
|
};
|
|
5779
|
-
const agent = new Agent2({ connect:
|
|
6232
|
+
const agent = new Agent2({ connect: connect4 });
|
|
5780
6233
|
dispatchers.set(id, agent);
|
|
5781
6234
|
return agent;
|
|
5782
6235
|
}
|
|
@@ -5821,7 +6274,7 @@ async function readBox2(ref, p) {
|
|
|
5821
6274
|
async function chunkNames(file, keys) {
|
|
5822
6275
|
const { size: size2 } = await stat5(file);
|
|
5823
6276
|
const chunks = [];
|
|
5824
|
-
const fh = await
|
|
6277
|
+
const fh = await open2(file, "r");
|
|
5825
6278
|
try {
|
|
5826
6279
|
const buf = Buffer.alloc(CHUNK_SIZE);
|
|
5827
6280
|
for (let i = 0; i < chunkCount(size2); i++) {
|
|
@@ -5962,7 +6415,7 @@ async function uploadOnce(id, req, signal, p) {
|
|
|
5962
6415
|
});
|
|
5963
6416
|
const { size: size2 } = await stat5(s.disk);
|
|
5964
6417
|
const fetchChunk = await chunkFetcher(req.pin, work[0]?.url, p);
|
|
5965
|
-
const fh = await
|
|
6418
|
+
const fh = await open2(s.disk, "r");
|
|
5966
6419
|
let bytes = 0;
|
|
5967
6420
|
const sizes = {};
|
|
5968
6421
|
try {
|
|
@@ -6009,7 +6462,7 @@ async function downloadDisk(file, req, p = paths()) {
|
|
|
6009
6462
|
}
|
|
6010
6463
|
const fetchChunk = await chunkFetcher(req.pin, req.chunks[0]?.url, p);
|
|
6011
6464
|
await writeFile7(file, "", { mode: 384 });
|
|
6012
|
-
const fh = await
|
|
6465
|
+
const fh = await open2(file, "r+");
|
|
6013
6466
|
try {
|
|
6014
6467
|
await fh.truncate(req.sizeBytes);
|
|
6015
6468
|
await pool(req.chunks, async ({ index, hash, url }) => {
|
|
@@ -6701,21 +7154,21 @@ function startRelayWatch(opts = {}) {
|
|
|
6701
7154
|
|
|
6702
7155
|
// src/daemon.ts
|
|
6703
7156
|
import { spawn as spawn3 } from "node:child_process";
|
|
6704
|
-
import { accessSync, constants as constants2, openSync as openSync5, readFileSync as
|
|
7157
|
+
import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync4, statSync as statSync6 } from "node:fs";
|
|
6705
7158
|
import { mkdir as mkdir11, readFile as readFile11, stat as stat6 } from "node:fs/promises";
|
|
6706
7159
|
import { userInfo as userInfo3 } from "node:os";
|
|
6707
7160
|
import { setTimeout as sleep6 } from "node:timers/promises";
|
|
6708
7161
|
|
|
6709
7162
|
// ../shared/src/systemd.ts
|
|
6710
7163
|
import { spawnSync } from "node:child_process";
|
|
6711
|
-
import { readFileSync as
|
|
7164
|
+
import { readFileSync as readFileSync3 } from "node:fs";
|
|
6712
7165
|
import { resolve } from "node:path";
|
|
6713
7166
|
var UNIT = "kvbox-server";
|
|
6714
7167
|
var UNIT_FILE = `/etc/systemd/system/${UNIT}.service`;
|
|
6715
7168
|
function hasUnitFor(p, file = UNIT_FILE) {
|
|
6716
7169
|
let text;
|
|
6717
7170
|
try {
|
|
6718
|
-
text =
|
|
7171
|
+
text = readFileSync3(file, "utf8");
|
|
6719
7172
|
} catch {
|
|
6720
7173
|
return false;
|
|
6721
7174
|
}
|
|
@@ -6821,7 +7274,7 @@ async function refuseSecondDaemon(p = paths()) {
|
|
|
6821
7274
|
}
|
|
6822
7275
|
function isKvboxServer(pid) {
|
|
6823
7276
|
try {
|
|
6824
|
-
return
|
|
7277
|
+
return readFileSync4(`/proc/${pid}/cmdline`, "utf8").split("\0").slice(1).some((arg) => arg.includes("kvbox"));
|
|
6825
7278
|
} catch (err) {
|
|
6826
7279
|
return err.code !== "ENOENT";
|
|
6827
7280
|
}
|
|
@@ -6952,7 +7405,7 @@ function shellQuote(word) {
|
|
|
6952
7405
|
function groupWithMember(gid, user, groupFile) {
|
|
6953
7406
|
let text;
|
|
6954
7407
|
try {
|
|
6955
|
-
text =
|
|
7408
|
+
text = readFileSync4(groupFile, "utf8");
|
|
6956
7409
|
} catch {
|
|
6957
7410
|
return void 0;
|
|
6958
7411
|
}
|
|
@@ -6969,27 +7422,6 @@ import { readFile as readFile13, rm as rm16, writeFile as writeFile10 } from "no
|
|
|
6969
7422
|
import { createServer as createHttpsServer } from "node:https";
|
|
6970
7423
|
import { createAdaptorServer } from "@hono/node-server";
|
|
6971
7424
|
|
|
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
7425
|
// src/app.ts
|
|
6994
7426
|
import { Hono as Hono12 } from "hono";
|
|
6995
7427
|
|
|
@@ -7006,10 +7438,10 @@ function versionOf(srcFileUrl, injected) {
|
|
|
7006
7438
|
}
|
|
7007
7439
|
|
|
7008
7440
|
// src/version.ts
|
|
7009
|
-
var VERSION = versionOf(import.meta.url, true ? "0.6.
|
|
7441
|
+
var VERSION = versionOf(import.meta.url, true ? "0.6.17" : void 0);
|
|
7010
7442
|
|
|
7011
7443
|
// src/caller.ts
|
|
7012
|
-
import { createHash as
|
|
7444
|
+
import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
7013
7445
|
var OWNER_HEADER = "x-kvbox-owner";
|
|
7014
7446
|
function resolveCaller(opts = {}) {
|
|
7015
7447
|
const cp = opts.controlPlane;
|
|
@@ -7059,11 +7491,11 @@ function bearerCheck(token) {
|
|
|
7059
7491
|
const expected = digest(token);
|
|
7060
7492
|
return (authorization) => {
|
|
7061
7493
|
const m = /^Bearer\s+(\S+)$/i.exec(authorization ?? "");
|
|
7062
|
-
return m !== null &&
|
|
7494
|
+
return m !== null && timingSafeEqual2(digest(m[1]), expected);
|
|
7063
7495
|
};
|
|
7064
7496
|
}
|
|
7065
7497
|
function digest(secret) {
|
|
7066
|
-
return
|
|
7498
|
+
return createHash4("sha256").update(secret).digest();
|
|
7067
7499
|
}
|
|
7068
7500
|
|
|
7069
7501
|
// src/core/update.ts
|
|
@@ -7184,42 +7616,6 @@ import { connect as connect2 } from "node:net";
|
|
|
7184
7616
|
import { Readable } from "node:stream";
|
|
7185
7617
|
import { Hono as Hono3 } from "hono";
|
|
7186
7618
|
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
7619
|
var HEADERS_TIMEOUT_MS = 55e3;
|
|
7224
7620
|
var MAX_HANDSHAKE_BYTES = 16 * 1024;
|
|
7225
7621
|
var CONNECT_TIMEOUT_MS = 5e3;
|
|
@@ -7409,10 +7805,10 @@ ${lines.join("")}\r
|
|
|
7409
7805
|
`);
|
|
7410
7806
|
if (head.length > 0) box.write(head);
|
|
7411
7807
|
readHead(box, { maxBytes: MAX_HANDSHAKE_BYTES, timeoutMs: headersTimeoutMs }).then(
|
|
7412
|
-
(
|
|
7808
|
+
(answer2) => {
|
|
7413
7809
|
if (socket.destroyed) return void box.destroy();
|
|
7414
|
-
socket.write(rewriteHead(
|
|
7415
|
-
if (
|
|
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);
|
|
7416
7812
|
piped = true;
|
|
7417
7813
|
box.pipe(socket);
|
|
7418
7814
|
socket.pipe(box);
|
|
@@ -7562,6 +7958,16 @@ function machineRoutes() {
|
|
|
7562
7958
|
};
|
|
7563
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));
|
|
7564
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
|
+
});
|
|
7565
7971
|
r.get("/:name/usage", async (c) => {
|
|
7566
7972
|
const since = c.req.query("since");
|
|
7567
7973
|
let from;
|
|
@@ -7610,7 +8016,7 @@ function machineRoutes() {
|
|
|
7610
8016
|
// src/routes/runs.ts
|
|
7611
8017
|
import { Hono as Hono7 } from "hono";
|
|
7612
8018
|
import { z as z9 } from "zod";
|
|
7613
|
-
var
|
|
8019
|
+
var refusal3 = (c, err) => {
|
|
7614
8020
|
if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
|
|
7615
8021
|
if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
|
|
7616
8022
|
if (err instanceof AgentNotAnsweringError) return c.json({ error: err.message, code: "unreachable" }, 503);
|
|
@@ -7631,7 +8037,7 @@ function runRoutes(wake = wakeBox) {
|
|
|
7631
8037
|
const started = await startBoxRun(ref, body);
|
|
7632
8038
|
return c.json(StartRunAnswerSchema.parse({ id: body.id, started, woke }), 202);
|
|
7633
8039
|
} catch (err) {
|
|
7634
|
-
return
|
|
8040
|
+
return refusal3(c, err);
|
|
7635
8041
|
}
|
|
7636
8042
|
});
|
|
7637
8043
|
r.get("/:name/runs/:id", async (c) => {
|
|
@@ -7639,7 +8045,7 @@ function runRoutes(wake = wakeBox) {
|
|
|
7639
8045
|
const { ref } = await runningBox(c.req.param("name"), c.get("owner"), wants(c.req.header(WAKE_HEADER)) ? wake : void 0);
|
|
7640
8046
|
return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
|
|
7641
8047
|
} catch (err) {
|
|
7642
|
-
return
|
|
8048
|
+
return refusal3(c, err);
|
|
7643
8049
|
}
|
|
7644
8050
|
});
|
|
7645
8051
|
r.get("/:name/runs/:id/output", async (c) => {
|
|
@@ -7652,7 +8058,7 @@ function runRoutes(wake = wakeBox) {
|
|
|
7652
8058
|
const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
|
|
7653
8059
|
return c.json(RunOutputSchema.parse(await boxRunOutput(ref, id, stream, offset, limit)));
|
|
7654
8060
|
} catch (err) {
|
|
7655
|
-
return
|
|
8061
|
+
return refusal3(c, err);
|
|
7656
8062
|
}
|
|
7657
8063
|
});
|
|
7658
8064
|
return r;
|
|
@@ -7805,6 +8211,94 @@ function createApp(opts = {}) {
|
|
|
7805
8211
|
return app;
|
|
7806
8212
|
}
|
|
7807
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
|
+
|
|
7808
8302
|
// src/listen.ts
|
|
7809
8303
|
async function listen(opts = {}) {
|
|
7810
8304
|
const p = await ensureLayout(paths());
|
|
@@ -7845,7 +8339,7 @@ async function listen(opts = {}) {
|
|
|
7845
8339
|
const edge = edgeCheck(cp);
|
|
7846
8340
|
const cron = cronCheck(cp);
|
|
7847
8341
|
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 }));
|
|
8342
|
+
httpsServer.on("upgrade", dispatchUpgrade(linkUpgradeHandler(cp.name), boxUpgradeHandler({ name: cp.name, secret: cp.secret })));
|
|
7849
8343
|
const port = opts.httpsPort ?? cp.port;
|
|
7850
8344
|
await new Promise((resolve3, reject) => {
|
|
7851
8345
|
httpsServer.once("error", reject);
|
|
@@ -7859,7 +8353,7 @@ async function listen(opts = {}) {
|
|
|
7859
8353
|
const bound = httpsServer.address().port;
|
|
7860
8354
|
https = { port: bound, url: `https://${cp.advertise}:${bound}` };
|
|
7861
8355
|
}
|
|
7862
|
-
const
|
|
8356
|
+
const close2 = async () => {
|
|
7863
8357
|
await Promise.all([
|
|
7864
8358
|
new Promise((resolve3) => server.close(() => resolve3())),
|
|
7865
8359
|
httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
|
|
@@ -7877,7 +8371,7 @@ async function listen(opts = {}) {
|
|
|
7877
8371
|
};
|
|
7878
8372
|
process.once("SIGINT", () => void shutdown3());
|
|
7879
8373
|
process.once("SIGTERM", () => void shutdown3());
|
|
7880
|
-
return https ? { socketPath, server, https, close } : { socketPath, server, close };
|
|
8374
|
+
return https ? { socketPath, server, https, close: close2 } : { socketPath, server, close: close2 };
|
|
7881
8375
|
}
|
|
7882
8376
|
var UNTRUSTED_REQUEST_MS = 3e5;
|
|
7883
8377
|
function limitUntrusted(server, trusted, ms = UNTRUSTED_REQUEST_MS) {
|
|
@@ -7923,6 +8417,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
|
|
|
7923
8417
|
const state = await driver().net.prepare(cfg);
|
|
7924
8418
|
log.info(`host network: bridge ${cfg.bridge} ${state}`);
|
|
7925
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}`));
|
|
7926
8421
|
} catch (err) {
|
|
7927
8422
|
log.warn(`host network not ready (${err.message}); run: kvbox-server net up`);
|
|
7928
8423
|
}
|
|
@@ -8044,7 +8539,7 @@ var leaveCommand = new Command6("leave").description("take this host out from be
|
|
|
8044
8539
|
});
|
|
8045
8540
|
|
|
8046
8541
|
// src/commands/logs.ts
|
|
8047
|
-
import { open as
|
|
8542
|
+
import { open as open3, readFile as readFile14, stat as stat7 } from "node:fs/promises";
|
|
8048
8543
|
import { setTimeout as sleep7 } from "node:timers/promises";
|
|
8049
8544
|
import { Command as Command7 } from "commander";
|
|
8050
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) => {
|
|
@@ -8076,7 +8571,7 @@ async function follow(path, write, opts = {}) {
|
|
|
8076
8571
|
const size2 = await stat7(path).then((s) => s.size, () => 0);
|
|
8077
8572
|
if (size2 < offset) offset = 0;
|
|
8078
8573
|
if (size2 > offset) {
|
|
8079
|
-
const fh = await
|
|
8574
|
+
const fh = await open3(path, "r");
|
|
8080
8575
|
try {
|
|
8081
8576
|
const buf = Buffer.alloc(size2 - offset);
|
|
8082
8577
|
const { bytesRead } = await fh.read(buf, 0, buf.length, offset);
|
|
@@ -8170,7 +8665,9 @@ async function plan(from, to, p) {
|
|
|
8170
8665
|
...sshKeys !== void 0 ? { sshKeys } : {},
|
|
8171
8666
|
// A stopped box reads its lines at boot; any other guest still holds the old ones.
|
|
8172
8667
|
...keysChanged ? { sshKeysStale: status === "stopped" ? void 0 : true } : {},
|
|
8173
|
-
...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) })) } : {}
|
|
8174
8671
|
}
|
|
8175
8672
|
});
|
|
8176
8673
|
}
|
|
@@ -8289,8 +8786,8 @@ async function confirm(question, yes) {
|
|
|
8289
8786
|
const { createInterface } = await import("node:readline/promises");
|
|
8290
8787
|
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
8291
8788
|
try {
|
|
8292
|
-
const
|
|
8293
|
-
return
|
|
8789
|
+
const answer2 = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
|
|
8790
|
+
return answer2 === "y" || answer2 === "yes";
|
|
8294
8791
|
} finally {
|
|
8295
8792
|
rl.close();
|
|
8296
8793
|
}
|