@kvbox/server 0.5.43 → 0.5.45
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 +2003 -1423
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
- package/scripts/net-setup.sh +1 -1
package/dist/kvbox-server.js
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
// src/index.ts
|
|
4
|
-
import { spawnSync } from "node:child_process";
|
|
5
|
-
import { Command } from "commander";
|
|
6
|
-
|
|
7
3
|
// ../shared/src/errors.ts
|
|
8
4
|
var KvboxError = class extends Error {
|
|
9
5
|
constructor(message, exitCode = 1) {
|
|
@@ -20,6 +16,9 @@ var NotFoundError = class extends KvboxError {
|
|
|
20
16
|
}
|
|
21
17
|
};
|
|
22
18
|
|
|
19
|
+
// src/commands/start.ts
|
|
20
|
+
import { Command } from "commander";
|
|
21
|
+
|
|
23
22
|
// ../shared/src/paths.ts
|
|
24
23
|
import { homedir } from "node:os";
|
|
25
24
|
import { join } from "node:path";
|
|
@@ -35,6 +34,14 @@ function paths(home = kvboxHome()) {
|
|
|
35
34
|
serverSock: join(home, "server.sock"),
|
|
36
35
|
serverPid: join(home, "server.pid"),
|
|
37
36
|
serverLog: join(home, "server.log"),
|
|
37
|
+
/**
|
|
38
|
+
* The host's self-update (`POST /update`, the control plane's admin): `update.json` is its state
|
|
39
|
+
* (install-server.sh --update writes it), `update/` holds the downloaded script and its log.
|
|
40
|
+
*/
|
|
41
|
+
updateState: join(home, "update.json"),
|
|
42
|
+
updateDir: join(home, "update"),
|
|
43
|
+
updateScript: join(home, "update", "install-server.sh"),
|
|
44
|
+
updateLog: join(home, "update", "update.log"),
|
|
38
45
|
/** The CLI's login to the control plane (`kvbox login`): url, bearer token, user. Mode 600. */
|
|
39
46
|
cli: join(home, "cli.json"),
|
|
40
47
|
/** The CLI's last look at npm for a newer @kvbox/cli: `{checkedAt, latest}`, at most once a day (cli update.ts). */
|
|
@@ -49,7 +56,7 @@ function paths(home = kvboxHome()) {
|
|
|
49
56
|
tls: join(home, "tls"),
|
|
50
57
|
tlsKey: join(home, "tls", "key.pem"),
|
|
51
58
|
tlsCert: join(home, "tls", "cert.pem"),
|
|
52
|
-
/** The host's WireGuard tunnel to its relay (`kvbox
|
|
59
|
+
/** The host's WireGuard tunnel to its relay (`kvbox-server relay`, #50): the conf net-setup.sh installs for wg-quick. Mode 600. */
|
|
53
60
|
relay: join(home, "relay"),
|
|
54
61
|
relayConf: join(home, "relay", "kvbox.conf"),
|
|
55
62
|
bin: join(home, "bin"),
|
|
@@ -454,1435 +461,1232 @@ async function loadConfig(p = paths()) {
|
|
|
454
461
|
}
|
|
455
462
|
}
|
|
456
463
|
|
|
457
|
-
// src/core/
|
|
458
|
-
import {
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
464
|
+
// src/core/kvm.ts
|
|
465
|
+
import { access, constants, readFile as readFile2, stat } from "node:fs/promises";
|
|
466
|
+
var KVM_DEVICE = "/dev/kvm";
|
|
467
|
+
async function groupName(gid, groupFile = "/etc/group") {
|
|
468
|
+
const text = await readFile2(groupFile, "utf8").catch(() => "");
|
|
469
|
+
for (const line of text.split("\n")) {
|
|
470
|
+
const [name, , id] = line.split(":");
|
|
471
|
+
if (id !== void 0 && Number.parseInt(id, 10) === gid && name) return name;
|
|
472
|
+
}
|
|
473
|
+
return "kvm";
|
|
474
|
+
}
|
|
475
|
+
async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
|
|
476
|
+
try {
|
|
477
|
+
await access(device, constants.R_OK | constants.W_OK);
|
|
478
|
+
return;
|
|
479
|
+
} catch (err) {
|
|
480
|
+
const code = err.code;
|
|
481
|
+
if (code === "ENOENT") {
|
|
482
|
+
throw new KvboxError(`${device} is missing: this machine has no KVM, so boxes cannot run here (enable virtualization in the BIOS, then install-server.sh checks the rest)`);
|
|
483
|
+
}
|
|
484
|
+
if (code !== "EACCES" && code !== "EPERM") throw new KvboxError(`cannot open ${device}: ${err.message}`);
|
|
485
|
+
}
|
|
486
|
+
const owner = await stat(device).then((s) => groupName(s.gid, groupFile), () => "kvm");
|
|
487
|
+
throw new KvboxError(
|
|
488
|
+
`cannot start: this process is not allowed to open ${device}, so no box could run. It was started from a shell without the ${owner} group (a login from before you were added to it). Log out and back in, or start it from a shell that has the group: sg ${owner} -c "kvbox-server start -d"`
|
|
489
|
+
);
|
|
490
|
+
}
|
|
462
491
|
|
|
463
|
-
//
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
492
|
+
// src/core/dns.ts
|
|
493
|
+
import { createSocket } from "node:dgram";
|
|
494
|
+
|
|
495
|
+
// src/core/state.ts
|
|
496
|
+
import { randomBytes } from "node:crypto";
|
|
497
|
+
import { readFileSync } from "node:fs";
|
|
498
|
+
import { mkdir, readFile as readFile3, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
499
|
+
import { z as z3 } from "zod";
|
|
500
|
+
|
|
501
|
+
// src/core/db.ts
|
|
502
|
+
import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs";
|
|
503
|
+
import { dirname } from "node:path";
|
|
504
|
+
import { DatabaseSync } from "node:sqlite";
|
|
505
|
+
var MIGRATIONS = [
|
|
506
|
+
`create table usage_events (
|
|
507
|
+
id integer primary key,
|
|
508
|
+
box_id text not null,
|
|
509
|
+
owner text not null,
|
|
510
|
+
name text not null,
|
|
511
|
+
at text not null,
|
|
512
|
+
state text not null,
|
|
513
|
+
vcpu integer not null,
|
|
514
|
+
mem_mib integer not null,
|
|
515
|
+
disk_gib integer not null,
|
|
516
|
+
by text not null
|
|
517
|
+
);
|
|
518
|
+
create index usage_events_box_at on usage_events (box_id, at);`,
|
|
519
|
+
// The ledger's identity (#42): a control plane keys pulled rows by it, so a re-join is recognised
|
|
520
|
+
// and a fresh ledger (KVBOX_HOME wiped) restarts its cursor instead of waiting for ids it already saw.
|
|
521
|
+
`create table ledger (id text not null);
|
|
522
|
+
insert into ledger (id) values (lower(hex(randomblob(16))));
|
|
523
|
+
create index usage_events_at on usage_events (at);`,
|
|
524
|
+
// Volumes (#91): a row per create, resize and rm, the size from that moment on. Its own table and
|
|
525
|
+
// ids, pulled by the control plane like usage_events, in the same ledger.
|
|
526
|
+
`create table volume_events (
|
|
527
|
+
id integer primary key,
|
|
528
|
+
volume_id text not null,
|
|
529
|
+
owner text not null,
|
|
530
|
+
name text not null,
|
|
531
|
+
at text not null,
|
|
532
|
+
size_gib integer not null,
|
|
533
|
+
by text not null
|
|
534
|
+
);
|
|
535
|
+
create index volume_events_volume_at on volume_events (volume_id, at);`
|
|
536
|
+
];
|
|
537
|
+
var handles = /* @__PURE__ */ new Map();
|
|
538
|
+
function openDb(p = paths()) {
|
|
539
|
+
const have = handles.get(p.db);
|
|
540
|
+
if (have !== void 0) return have;
|
|
541
|
+
mkdirSync(dirname(p.db), { recursive: true, mode: 448 });
|
|
542
|
+
closeSync(openSync(p.db, "a", 384));
|
|
543
|
+
chmodSync(p.db, 384);
|
|
544
|
+
const db = new DatabaseSync(p.db);
|
|
545
|
+
db.exec("pragma journal_mode = wal");
|
|
546
|
+
db.exec("pragma busy_timeout = 5000");
|
|
547
|
+
migrate(db);
|
|
548
|
+
handles.set(p.db, db);
|
|
549
|
+
return db;
|
|
550
|
+
}
|
|
551
|
+
function migrate(db) {
|
|
552
|
+
db.exec("create table if not exists schema_version (version integer not null)");
|
|
553
|
+
const row = db.prepare("select version from schema_version").get();
|
|
554
|
+
let version = row?.version ?? 0;
|
|
555
|
+
if (row === void 0) db.prepare("insert into schema_version (version) values (0)").run();
|
|
556
|
+
while (version < MIGRATIONS.length) {
|
|
557
|
+
db.exec("begin");
|
|
558
|
+
try {
|
|
559
|
+
db.exec(MIGRATIONS[version]);
|
|
560
|
+
version += 1;
|
|
561
|
+
db.prepare("update schema_version set version = ?").run(version);
|
|
562
|
+
db.exec("commit");
|
|
563
|
+
} catch (err) {
|
|
564
|
+
db.exec("rollback");
|
|
565
|
+
throw err;
|
|
477
566
|
}
|
|
478
567
|
}
|
|
479
|
-
return byName;
|
|
480
568
|
}
|
|
481
|
-
|
|
482
|
-
|
|
569
|
+
var LIVE_STATES = ["running", "standby"];
|
|
570
|
+
function fromRaw(r) {
|
|
571
|
+
return { boxId: r.box_id, owner: r.owner, name: r.name, at: r.at, state: r.state, vcpu: r.vcpu, memMib: r.mem_mib, diskGib: r.disk_gib, by: r.by };
|
|
483
572
|
}
|
|
484
|
-
function
|
|
485
|
-
|
|
486
|
-
return
|
|
573
|
+
function lastEvent(boxId, db) {
|
|
574
|
+
const raw = db.prepare("select * from usage_events where box_id = ? order by at desc, id desc limit 1").get(boxId);
|
|
575
|
+
return raw === void 0 ? void 0 : fromRaw(raw);
|
|
487
576
|
}
|
|
488
|
-
function
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
577
|
+
function insertRaw(e, db) {
|
|
578
|
+
db.prepare(
|
|
579
|
+
"insert into usage_events (box_id, owner, name, at, state, vcpu, mem_mib, disk_gib, by) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
580
|
+
).run(e.boxId, e.owner, e.name, e.at, e.state, e.vcpu, e.memMib, e.diskGib, e.by);
|
|
581
|
+
}
|
|
582
|
+
function insertUsageEvent(e, p = paths()) {
|
|
583
|
+
const db = openDb(p);
|
|
584
|
+
if (e.state === "running" && e.by !== "resume") closeOpenRun(e.boxId, e.at, p);
|
|
585
|
+
insertRaw(e, db);
|
|
586
|
+
}
|
|
587
|
+
function closeOpenRun(boxId, at, p = paths()) {
|
|
588
|
+
const db = openDb(p);
|
|
589
|
+
const last = lastEvent(boxId, db);
|
|
590
|
+
if (last === void 0 || !LIVE_STATES.includes(last.state)) return false;
|
|
591
|
+
insertRaw({ ...last, at, state: "stopped", by: "server" }, db);
|
|
592
|
+
return true;
|
|
593
|
+
}
|
|
594
|
+
function closeRunCutByBoot(boxId, bootAt, now, p = paths()) {
|
|
595
|
+
const last = lastEvent(boxId, openDb(p));
|
|
596
|
+
return closeOpenRun(boxId, last !== void 0 && last.at < bootAt ? bootAt : now, p);
|
|
597
|
+
}
|
|
598
|
+
function usageEventsFor(boxId, since, p = paths()) {
|
|
599
|
+
const rows = openDb(p).prepare("select * from usage_events where box_id = ? and at >= ? order by at, id").all(boxId, since);
|
|
600
|
+
return rows.map(fromRaw);
|
|
601
|
+
}
|
|
602
|
+
var withId = (r) => ({ ...fromRaw(r), id: r.id });
|
|
603
|
+
function ledgerId(p = paths()) {
|
|
604
|
+
return openDb(p).prepare("select id from ledger").get().id;
|
|
605
|
+
}
|
|
606
|
+
function usageEventsAfter(after, limit, scope, p = paths()) {
|
|
607
|
+
const db = openDb(p);
|
|
608
|
+
const rows = scope === null ? db.prepare("select * from usage_events where id > ? order by id limit ?").all(after, limit) : typeof scope === "string" ? db.prepare("select * from usage_events where id > ? and owner = ? order by id limit ?").all(after, scope, limit) : db.prepare("select * from usage_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?").all(after, `@${scope.realm}`, `@${scope.realm}`, limit);
|
|
609
|
+
return rows.map(withId);
|
|
610
|
+
}
|
|
611
|
+
function usageEventsInScope(scope, window, p = paths()) {
|
|
612
|
+
const rows = openDb(p).prepare(
|
|
613
|
+
`select * from usage_events where at < ? and (at >= ? or id in (select max(id) from usage_events where at < ? group by box_id))
|
|
614
|
+
order by at, id`
|
|
615
|
+
).all(window.to, window.from, window.from);
|
|
616
|
+
return rows.filter((r) => inScope(r.owner, scope)).map(withId);
|
|
617
|
+
}
|
|
618
|
+
var volumeWithId = (r) => ({ id: r.id, volumeId: r.volume_id, owner: r.owner, name: r.name, at: r.at, sizeGib: r.size_gib, by: r.by });
|
|
619
|
+
function insertVolumeEvent(e, p = paths()) {
|
|
620
|
+
openDb(p).prepare("insert into volume_events (volume_id, owner, name, at, size_gib, by) values (?, ?, ?, ?, ?, ?)").run(e.volumeId, e.owner, e.name, e.at, e.sizeGib, e.by);
|
|
621
|
+
}
|
|
622
|
+
function volumeEventsAfter(after, limit, scope, p = paths()) {
|
|
623
|
+
const db = openDb(p);
|
|
624
|
+
const rows = scope === null ? db.prepare("select * from volume_events where id > ? order by id limit ?").all(after, limit) : typeof scope === "string" ? db.prepare("select * from volume_events where id > ? and owner = ? order by id limit ?").all(after, scope, limit) : db.prepare("select * from volume_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?").all(after, `@${scope.realm}`, `@${scope.realm}`, limit);
|
|
625
|
+
return rows.map(volumeWithId);
|
|
626
|
+
}
|
|
627
|
+
function volumeEventsInScope(scope, window, p = paths()) {
|
|
628
|
+
const rows = openDb(p).prepare(
|
|
629
|
+
`select * from volume_events where at < ? and (at >= ? or id in (select max(id) from volume_events where at < ? group by volume_id))
|
|
630
|
+
order by at, id`
|
|
631
|
+
).all(window.to, window.from, window.from);
|
|
632
|
+
return rows.filter((r) => inScope(r.owner, scope)).map(volumeWithId);
|
|
494
633
|
}
|
|
495
634
|
|
|
496
|
-
//
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
var BoxStatusSchema = z3.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
|
|
500
|
-
var PortProtoSchema = z3.enum(["tcp", "udp"]);
|
|
501
|
-
var MAX_BOX_PORTS = 16;
|
|
502
|
-
var PortForwardSchema = z3.object({
|
|
503
|
-
guestPort: z3.number().int().min(1).max(65535),
|
|
504
|
-
hostPort: z3.number().int(),
|
|
505
|
-
proto: PortProtoSchema,
|
|
506
|
-
/** The host's public address; only the control plane fills it in, as for `ssh`. */
|
|
507
|
-
address: z3.string().optional()
|
|
508
|
-
});
|
|
509
|
-
var PortsRequest = z3.object({
|
|
510
|
-
ports: z3.array(z3.object({ guestPort: z3.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
|
|
511
|
-
});
|
|
512
|
-
var BoxPortSchema = z3.number().int().min(1).max(65535);
|
|
513
|
-
var MAX_BOX_LINKS = 32;
|
|
514
|
-
var BoxLinkSchema = z3.object({ from: z3.string(), port: BoxPortSchema });
|
|
515
|
-
var LinkRequest = z3.object({ from: z3.string().min(1), fromOwner: z3.string().optional(), port: BoxPortSchema });
|
|
516
|
-
var ClaimSubdomainRequest = z3.object({ name: z3.string(), port: BoxPortSchema });
|
|
517
|
-
var SubdomainPortRequest = z3.object({ port: BoxPortSchema });
|
|
518
|
-
var SubdomainRouteRequest = z3.object({ name: z3.string(), port: BoxPortSchema });
|
|
519
|
-
var SubdomainSchema = z3.object({
|
|
520
|
-
owner: z3.string(),
|
|
521
|
-
box: z3.string(),
|
|
522
|
-
subdomain: z3.string(),
|
|
523
|
-
port: BoxPortSchema,
|
|
524
|
-
url: z3.string(),
|
|
525
|
-
routes: z3.array(z3.object({ name: z3.string(), port: BoxPortSchema, url: z3.string() }))
|
|
526
|
-
});
|
|
527
|
-
var AddDomainRequest = z3.object({ domain: z3.string(), port: BoxPortSchema.optional() });
|
|
528
|
-
var DomainSchema = z3.object({
|
|
529
|
-
owner: z3.string(),
|
|
530
|
-
box: z3.string(),
|
|
531
|
-
domain: z3.string(),
|
|
532
|
-
port: BoxPortSchema,
|
|
533
|
-
status: z3.enum(["pending", "live"]),
|
|
534
|
-
www: z3.boolean(),
|
|
535
|
-
url: z3.string(),
|
|
536
|
-
error: z3.string().nullable(),
|
|
537
|
-
records: z3.array(z3.object({ type: z3.enum(["A", "TXT", "CNAME"]), name: z3.string(), value: z3.string() })),
|
|
538
|
-
createdAt: z3.string()
|
|
539
|
-
});
|
|
540
|
-
var WakeHookSchema = z3.object({
|
|
541
|
-
id: z3.string(),
|
|
542
|
-
owner: z3.string(),
|
|
543
|
-
box: z3.string(),
|
|
544
|
-
url: z3.string(),
|
|
545
|
-
createdBy: z3.string().nullable(),
|
|
546
|
-
createdAt: z3.string(),
|
|
547
|
-
lastCalledAt: z3.string().nullable()
|
|
548
|
-
});
|
|
549
|
-
var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z3.string() });
|
|
550
|
-
var WakeHookCallSchema = z3.object({
|
|
551
|
-
box: z3.string(),
|
|
552
|
-
action: z3.enum(["wake", "resume", "none"]),
|
|
553
|
-
reason: z3.string().optional()
|
|
554
|
-
});
|
|
555
|
-
var BACKUP_STATUSES = ["running", "ready", "failed"];
|
|
556
|
-
var BackupSchema = z3.object({
|
|
557
|
-
id: z3.string(),
|
|
558
|
-
owner: z3.string(),
|
|
559
|
-
box: z3.string(),
|
|
560
|
-
status: z3.enum(BACKUP_STATUSES),
|
|
561
|
-
/** Why it failed; null otherwise. */
|
|
562
|
-
error: z3.string().nullable(),
|
|
563
|
-
/** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
|
|
564
|
-
base: z3.string().nullable(),
|
|
565
|
-
image: z3.string().optional(),
|
|
566
|
-
vcpu: z3.number().int().nullable(),
|
|
567
|
-
memMib: z3.number().int().nullable(),
|
|
568
|
-
/** The disk's size. */
|
|
569
|
-
diskBytes: z3.number().int().nullable(),
|
|
570
|
-
/** What it holds: the slots that are not all zeros. */
|
|
571
|
-
dataBytes: z3.number().int().nullable(),
|
|
572
|
-
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
573
|
-
uploadedBytes: z3.number().int().nullable(),
|
|
574
|
-
createdBy: z3.string().nullable(),
|
|
575
|
-
createdAt: z3.string(),
|
|
576
|
-
finishedAt: z3.string().nullable()
|
|
577
|
-
});
|
|
578
|
-
var HostBackupRequest = z3.object({ id: z3.string(), key: z3.string() });
|
|
579
|
-
var HostBackupManifestSchema = z3.object({
|
|
580
|
-
id: z3.string(),
|
|
581
|
-
sizeBytes: z3.number().int(),
|
|
582
|
-
chunks: z3.array(z3.string().nullable()),
|
|
583
|
-
env: z3.string().nullable(),
|
|
584
|
-
base: z3.string(),
|
|
585
|
-
image: z3.string().optional(),
|
|
586
|
-
vcpu: z3.number().int(),
|
|
587
|
-
memMib: z3.number().int()
|
|
588
|
-
});
|
|
589
|
-
var HostUploadRequest = z3.object({ key: z3.string(), urls: z3.record(z3.string(), z3.string()) });
|
|
590
|
-
var HostUploadResultSchema = z3.object({ chunks: z3.number().int(), bytes: z3.number().int(), sizes: z3.record(z3.string(), z3.number().int()) });
|
|
591
|
-
var HostRestoreRequest = z3.object({
|
|
592
|
-
/** The backup's id: its variables were sealed under it. */
|
|
593
|
-
id: z3.string(),
|
|
594
|
-
key: z3.string(),
|
|
595
|
-
sizeBytes: z3.number().int().positive(),
|
|
596
|
-
base: z3.string(),
|
|
597
|
-
image: z3.string().optional(),
|
|
598
|
-
env: z3.string().nullable(),
|
|
599
|
-
chunks: z3.array(z3.object({ index: z3.number().int().nonnegative(), hash: z3.string(), url: z3.string() }))
|
|
600
|
-
});
|
|
601
|
-
var MachineSchema = z3.object({
|
|
602
|
-
/** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
|
|
635
|
+
// src/core/state.ts
|
|
636
|
+
var MachineMetaSchema = z3.object({
|
|
637
|
+
/** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */
|
|
603
638
|
id: z3.string(),
|
|
604
639
|
name: z3.string(),
|
|
605
|
-
/**
|
|
640
|
+
/** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */
|
|
606
641
|
owner: z3.string(),
|
|
607
642
|
ip: z3.string(),
|
|
608
643
|
mac: z3.string(),
|
|
609
644
|
pid: z3.number().int().nullable(),
|
|
645
|
+
// null: stopped on purpose, disk kept
|
|
646
|
+
/**
|
|
647
|
+
* The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot
|
|
648
|
+
* the number can name some other process; a pid from another boot is dead whatever `kill -0` says.
|
|
649
|
+
* Absent (boxes launched before #29): the pid alone decides.
|
|
650
|
+
*/
|
|
651
|
+
bootId: z3.string().optional(),
|
|
610
652
|
vcpu: z3.number().int(),
|
|
611
653
|
memMib: z3.number().int(),
|
|
612
|
-
diskBytes: z3.number().int(),
|
|
613
|
-
// the box's own writable disk, as the guest sees it
|
|
614
|
-
diskUsedBytes: z3.number().int(),
|
|
615
|
-
// what the box uses of it: the filesystem's own count, like the guest's `df` (#115)
|
|
616
|
-
/** What the disk's sparse file occupies on the host. Grows while the box runs, `kvbox stop` trims it back. Hosts before 0.5.42 do not send it. */
|
|
617
|
-
diskHostBytes: z3.number().int().optional(),
|
|
618
|
-
base: z3.string(),
|
|
619
|
-
// version of the image the box's overlay stacks on
|
|
620
|
-
/** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
|
|
621
|
-
image: z3.string().optional(),
|
|
622
654
|
createdAt: z3.string(),
|
|
623
655
|
source: z3.string(),
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
/**
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
*/
|
|
630
|
-
sshPort: z3.number().int().optional(),
|
|
631
|
-
/**
|
|
632
|
-
* Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only
|
|
633
|
-
* the control plane fills it in (a host does not know its own public address); absent for a box
|
|
634
|
-
* whose host reported no port or did not answer.
|
|
635
|
-
*/
|
|
636
|
-
ssh: z3.object({ host: z3.string(), port: z3.number().int(), user: z3.string() }).optional(),
|
|
637
|
-
/** Box ports published on the host (#30). Absent: none. */
|
|
638
|
-
ports: z3.array(PortForwardSchema).optional(),
|
|
639
|
-
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
|
|
640
|
-
ownerKind: z3.enum(["user", "org"]).optional(),
|
|
641
|
-
/**
|
|
642
|
-
* The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
|
|
643
|
-
* links to, and a volume attaches to, only a box on the same host.
|
|
644
|
-
*/
|
|
645
|
-
host: z3.string().optional(),
|
|
646
|
-
/** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
|
|
647
|
-
country: z3.string().optional(),
|
|
648
|
-
/** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
|
|
649
|
-
autoHibernateSec: z3.number().int().positive().optional(),
|
|
650
|
-
/** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
|
|
651
|
-
idleCheck: z3.string().optional(),
|
|
652
|
-
/** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
|
|
653
|
-
volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional(),
|
|
654
|
-
/** Boxes that may reach this one, each on one port (#98). Absent: none. */
|
|
655
|
-
links: z3.array(BoxLinkSchema).optional(),
|
|
656
|
-
/** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */
|
|
656
|
+
/** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */
|
|
657
|
+
base: z3.string(),
|
|
658
|
+
/** The image (#87), when not the base one: assets/images/<image>/rootfs-<base>.ext4. `vm update` keeps it. */
|
|
659
|
+
image: z3.string().optional(),
|
|
660
|
+
/** The image's connect line with its secrets masked and `${BOX}` unfilled (#87, `maskedUrl`). Absent: the image declares none. */
|
|
657
661
|
url: z3.string().optional(),
|
|
658
662
|
/**
|
|
659
|
-
*
|
|
660
|
-
*
|
|
661
|
-
|
|
662
|
-
connect: z3.string().optional()
|
|
663
|
-
});
|
|
664
|
-
var VolumeSchema = z3.object({
|
|
665
|
-
/** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
666
|
-
id: z3.string(),
|
|
667
|
-
name: z3.string(),
|
|
668
|
-
owner: z3.string(),
|
|
669
|
-
sizeGib: z3.number().int(),
|
|
670
|
-
/** What the sparse file really occupies on the host. */
|
|
671
|
-
usedBytes: z3.number().int(),
|
|
672
|
-
attachedTo: z3.string().nullable(),
|
|
673
|
-
createdAt: z3.string(),
|
|
674
|
-
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
|
|
675
|
-
ownerKind: z3.enum(["user", "org"]).optional(),
|
|
676
|
-
/** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
|
|
677
|
-
host: z3.string().optional()
|
|
678
|
-
});
|
|
679
|
-
var MAX_VOLUME_GIB = 4096;
|
|
680
|
-
var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
681
|
-
var VOLUME_NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
|
|
682
|
-
var CreateVolumeRequest = z3.object({
|
|
683
|
-
name: z3.string(),
|
|
684
|
-
sizeGib: z3.number().int().min(1).max(MAX_VOLUME_GIB),
|
|
685
|
-
/**
|
|
686
|
-
* Through a control plane (#91): the box this volume is for, so it is made on that box's host; the
|
|
687
|
-
* control plane requires it (a volume attaches only to a box on its own host, so one made for no box
|
|
688
|
-
* could never attach) and the CLI attaches right after. A host ignores it.
|
|
663
|
+
* Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
|
|
664
|
+
* each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
|
|
665
|
+
* is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.
|
|
689
666
|
*/
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
box: z3.string()
|
|
694
|
-
});
|
|
695
|
-
var EnvVarSchema = z3.object({
|
|
696
|
-
name: z3.string(),
|
|
697
|
-
value: z3.string().optional(),
|
|
698
|
-
secret: z3.boolean(),
|
|
699
|
-
updatedAt: z3.string()
|
|
700
|
-
});
|
|
701
|
-
var BoxEnvSchema = z3.object({
|
|
702
|
-
box: z3.string(),
|
|
703
|
-
vars: z3.array(EnvVarSchema)
|
|
704
|
-
});
|
|
705
|
-
var BoxEnvChangeSchema = z3.object({
|
|
706
|
-
box: z3.string(),
|
|
707
|
-
name: z3.string(),
|
|
708
|
-
/** Whether the box is running now: the change waits for its next start. */
|
|
709
|
-
running: z3.boolean()
|
|
710
|
-
});
|
|
711
|
-
var SetEnvRequest = z3.object({
|
|
712
|
-
value: z3.string(),
|
|
713
|
-
secret: z3.boolean().optional()
|
|
714
|
-
});
|
|
715
|
-
var EnvChangeSchema = z3.object({
|
|
716
|
-
owner: z3.string(),
|
|
717
|
-
name: z3.string(),
|
|
718
|
-
boxes: z3.number().int()
|
|
719
|
-
});
|
|
720
|
-
var HostEnvRequest = z3.object({
|
|
721
|
-
version: z3.number().int().min(0),
|
|
722
|
-
vars: z3.array(z3.object({ name: z3.string(), value: z3.string() }))
|
|
723
|
-
});
|
|
724
|
-
var HostEnvVersionsSchema = z3.array(z3.object({ owner: z3.string(), version: z3.number().int() }));
|
|
725
|
-
var CreateMachineRequest = z3.object({
|
|
726
|
-
name: z3.string().optional(),
|
|
727
|
-
/** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
|
|
728
|
-
owner: z3.string().optional(),
|
|
729
|
-
size: SizeSchema.optional(),
|
|
730
|
-
from: z3.string().optional(),
|
|
731
|
-
force: z3.boolean().optional(),
|
|
667
|
+
memSnapshots: z3.number().int().optional(),
|
|
668
|
+
/** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */
|
|
669
|
+
paused: z3.boolean().optional(),
|
|
732
670
|
/**
|
|
733
|
-
*
|
|
734
|
-
*
|
|
735
|
-
*
|
|
671
|
+
* authorized_keys lines the box gets on top of the host's own key, as the control plane sent them
|
|
672
|
+
* at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so
|
|
673
|
+
* `start` has to send the same lines again. Absent: host key only.
|
|
736
674
|
*/
|
|
737
675
|
sshKeys: z3.array(z3.string()).optional(),
|
|
738
|
-
/** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
|
|
739
|
-
autoHibernateSec: z3.number().int().min(0).optional(),
|
|
740
676
|
/**
|
|
741
|
-
*
|
|
742
|
-
*
|
|
677
|
+
* The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,
|
|
678
|
+
* or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.
|
|
743
679
|
*/
|
|
744
|
-
|
|
680
|
+
sshKeysStale: z3.boolean().optional(),
|
|
681
|
+
/** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */
|
|
682
|
+
sshPort: z3.number().int().optional(),
|
|
745
683
|
/**
|
|
746
|
-
*
|
|
747
|
-
*
|
|
684
|
+
* Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,
|
|
685
|
+
* each host port the box's for its life. DNATed while the box runs, rebuilt from here with its
|
|
686
|
+
* current IP every time it comes up. Absent: none.
|
|
748
687
|
*/
|
|
749
|
-
|
|
750
|
-
/**
|
|
751
|
-
|
|
752
|
-
/** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
|
|
753
|
-
env: z3.array(z3.object({ name: z3.string(), value: z3.string() })).optional()
|
|
754
|
-
});
|
|
755
|
-
var ForkMachineRequest = z3.object({
|
|
756
|
-
name: z3.string().optional(),
|
|
688
|
+
ports: z3.array(z3.object({ guestPort: z3.number().int(), hostPort: z3.number().int(), proto: z3.enum(["tcp", "udp"]) })).optional(),
|
|
689
|
+
/** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
|
|
690
|
+
autoHibernateSec: z3.number().int().positive().optional(),
|
|
757
691
|
/**
|
|
758
|
-
*
|
|
759
|
-
*
|
|
692
|
+
* A script inside the box auto-hibernate asks instead of watching the tap (#102, core/idle.ts): run by
|
|
693
|
+
* kvbox-agent, exit 0 = idle. A new box gets its image's `idle` (image.json); `kvbox vm set --idle-check`
|
|
694
|
+
* changes it. The one place the host looks. Absent: the traffic rule.
|
|
760
695
|
*/
|
|
761
|
-
|
|
762
|
-
/** A cold fork only: a warm one keeps the source's vCPU and memory. */
|
|
763
|
-
size: SizeSchema.optional(),
|
|
764
|
-
force: z3.boolean().optional(),
|
|
765
|
-
/** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */
|
|
766
|
-
sshKeys: z3.array(z3.string()).optional(),
|
|
767
|
-
autoHibernateSec: z3.number().int().min(0).optional()
|
|
768
|
-
});
|
|
769
|
-
var SetSshKeysRequest = z3.object({
|
|
770
|
-
sshKeys: z3.array(z3.string())
|
|
771
|
-
});
|
|
772
|
-
var RescaleMachineRequest = z3.object({
|
|
773
|
-
size: SizeSchema.optional(),
|
|
774
|
-
vcpu: z3.number().int().min(1).max(64).optional(),
|
|
775
|
-
memMib: z3.number().int().min(256).optional(),
|
|
776
|
-
diskGib: z3.number().int().min(1).optional(),
|
|
777
|
-
/** Skip the capacity guard when a running box grows (#37). */
|
|
778
|
-
force: z3.boolean().optional()
|
|
779
|
-
});
|
|
780
|
-
var StartMachineRequest = z3.object({
|
|
781
|
-
force: z3.boolean().optional()
|
|
782
|
-
});
|
|
783
|
-
var SetMachineRequest = z3.object({
|
|
784
|
-
/** Seconds without network traffic before the box is hibernated (#47); 0: never. */
|
|
785
|
-
autoHibernateSec: z3.number().int().min(0).optional(),
|
|
786
|
-
/** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
|
|
787
|
-
idleCheck: z3.union([z3.literal(""), z3.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
|
|
788
|
-
});
|
|
789
|
-
var SnapshotSchema = z3.object({
|
|
790
|
-
name: z3.string(),
|
|
791
|
-
owner: z3.string(),
|
|
792
|
-
source: z3.string(),
|
|
793
|
-
// the box it was taken from, as owner/name
|
|
794
|
-
base: z3.string(),
|
|
795
|
-
// version of the image the overlay stacks on; a restore needs the same one
|
|
796
|
-
/** As in MachineSchema: the image when it is not the base one (#87). */
|
|
797
|
-
image: z3.string().optional(),
|
|
798
|
-
vcpu: z3.number().int(),
|
|
799
|
-
memMib: z3.number().int(),
|
|
800
|
-
sizeBytes: z3.number().int(),
|
|
801
|
-
// what vmstate + mem + overlay really occupy on the host
|
|
802
|
-
createdAt: z3.string()
|
|
803
|
-
});
|
|
804
|
-
var CreateSnapshotRequest = z3.object({
|
|
805
|
-
box: z3.string(),
|
|
806
|
-
name: z3.string(),
|
|
807
|
-
/** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
|
|
808
|
-
replace: z3.boolean().optional()
|
|
809
|
-
});
|
|
810
|
-
var DiskCapacitySchema = z3.object({
|
|
811
|
-
totalGib: z3.number().int(),
|
|
812
|
-
freeGib: z3.number().int(),
|
|
813
|
-
volumesGib: z3.number().int(),
|
|
814
|
-
volumesUsedGib: z3.number().int(),
|
|
815
|
-
headroomGib: z3.number().int()
|
|
816
|
-
});
|
|
817
|
-
var CapacitySchema = z3.object({
|
|
818
|
-
hostMemMib: z3.number().int(),
|
|
819
|
-
hostCores: z3.number().int(),
|
|
820
|
-
reservedMemMib: z3.number().int(),
|
|
821
|
-
reservedVcpu: z3.number().int(),
|
|
822
|
-
running: z3.number().int(),
|
|
823
|
-
/** Absent on a host from before volumes (#91): it cannot take one. */
|
|
824
|
-
disk: DiskCapacitySchema.optional(),
|
|
696
|
+
idleCheck: z3.string().optional(),
|
|
825
697
|
/**
|
|
826
|
-
*
|
|
827
|
-
*
|
|
698
|
+
* Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
|
|
699
|
+
* their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
|
|
700
|
+
* volume's meta.json does not say. Absent: none.
|
|
828
701
|
*/
|
|
829
|
-
|
|
830
|
-
});
|
|
831
|
-
var ImageSchema = z3.object({ name: z3.string(), version: z3.string().nullable() });
|
|
832
|
-
var RecoveryReportSchema = z3.object({
|
|
833
|
-
at: z3.string(),
|
|
834
|
-
booted: z3.array(z3.string()),
|
|
835
|
-
leftStopped: z3.array(z3.string()),
|
|
836
|
-
failed: z3.array(z3.object({ box: z3.string(), error: z3.string() }))
|
|
837
|
-
});
|
|
838
|
-
var HealthSchema = z3.object({
|
|
839
|
-
ok: z3.literal(true),
|
|
840
|
-
version: z3.string(),
|
|
841
|
-
pid: z3.number().int(),
|
|
842
|
-
/** Base image version new boxes get (null when the host has no usable base image yet). */
|
|
843
|
-
base: z3.string().nullable(),
|
|
844
|
-
/** Owner that boxes made over the local socket get (the Unix user running the server). */
|
|
845
|
-
owner: z3.string(),
|
|
846
|
-
/** The control plane this host joined (null when none). */
|
|
847
|
-
controlPlane: z3.object({
|
|
848
|
-
/** Realm name, e.g. kvbox.sh. */
|
|
849
|
-
name: z3.string(),
|
|
850
|
-
url: z3.string(),
|
|
851
|
-
/** Where this host answers the control plane. */
|
|
852
|
-
hostUrl: z3.string()
|
|
853
|
-
}).nullable(),
|
|
854
|
-
/** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */
|
|
855
|
-
relay: z3.object({
|
|
856
|
-
name: z3.string(),
|
|
857
|
-
/** The public IP the relay owns for this host. */
|
|
858
|
-
publicIp: z3.string(),
|
|
859
|
-
/** The relay's WireGuard endpoint the tunnel dials. */
|
|
860
|
-
endpoint: z3.string(),
|
|
861
|
-
/** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */
|
|
862
|
-
restarts: z3.number().int().optional(),
|
|
863
|
-
lastRestartAt: z3.string().nullable().optional()
|
|
864
|
-
}).nullable().optional(),
|
|
865
|
-
/** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */
|
|
866
|
-
recovery: RecoveryReportSchema.nullable().optional()
|
|
867
|
-
});
|
|
868
|
-
var MachineUsageSchema = z3.object({
|
|
869
|
-
name: z3.string(),
|
|
870
|
-
owner: z3.string(),
|
|
871
|
-
status: BoxStatusSchema,
|
|
872
|
-
window: z3.object({ from: z3.string(), to: z3.string() }),
|
|
873
|
-
seconds: z3.object({
|
|
874
|
-
running: z3.number().int(),
|
|
875
|
-
standby: z3.number().int(),
|
|
876
|
-
hibernated: z3.number().int(),
|
|
877
|
-
stopped: z3.number().int()
|
|
878
|
-
}),
|
|
879
|
-
vcpuHours: z3.number(),
|
|
880
|
-
ramGibHours: z3.number(),
|
|
881
|
-
diskGibHours: z3.number(),
|
|
882
|
-
cost: z3.object({ amount: z3.number(), currency: z3.string() }).optional(),
|
|
883
|
-
/** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */
|
|
884
|
-
estimatedStops: z3.number().int(),
|
|
885
|
-
historyFrom: z3.string().nullable()
|
|
886
|
-
});
|
|
887
|
-
var GuestStatsSchema = z3.object({
|
|
888
|
-
/** Load average over 1, 5 and 15 minutes. */
|
|
889
|
-
load: z3.tuple([z3.number(), z3.number(), z3.number()]),
|
|
890
|
-
cpus: z3.number().int(),
|
|
891
|
-
memTotalMib: z3.number().int(),
|
|
892
|
-
/** Total minus available: page cache counts as free. */
|
|
893
|
-
memUsedMib: z3.number().int(),
|
|
894
|
-
/** The box's root, which is its overlay disk: the box's own writes, not the shared base. */
|
|
895
|
-
diskTotalBytes: z3.number().int(),
|
|
896
|
-
diskUsedBytes: z3.number().int(),
|
|
897
|
-
uptimeSec: z3.number().int()
|
|
898
|
-
});
|
|
899
|
-
var MachineStatsSchema = z3.object({
|
|
900
|
-
name: z3.string(),
|
|
901
|
-
owner: z3.string(),
|
|
902
|
-
stats: GuestStatsSchema.nullable()
|
|
903
|
-
});
|
|
904
|
-
var UsageStatusSchema = z3.enum([...BoxStatusSchema.options, "removed"]);
|
|
905
|
-
var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({
|
|
906
|
-
/** The host's box id; a name removed and recreated appears twice, with two ids. */
|
|
907
|
-
id: z3.string(),
|
|
908
|
-
status: UsageStatusSchema,
|
|
909
|
-
/** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */
|
|
910
|
-
ownerKind: z3.enum(["user", "org"]).optional(),
|
|
702
|
+
volumes: z3.array(z3.string()).optional(),
|
|
911
703
|
/**
|
|
912
|
-
*
|
|
913
|
-
*
|
|
704
|
+
* Links into this box (#98, `kvbox vm link`): box `owner/name`, at `ip`, may open TCP connections to
|
|
705
|
+
* `port`. The rule is open while this box runs, rebuilt from here at every boot; `ip` is the other
|
|
706
|
+
* box's, fixed for its life, and checked against its meta.json before a rule opens. `stale`: that box
|
|
707
|
+
* was removed but the rule would not close; kept only so this box's next stop closes it, never opened
|
|
708
|
+
* again, never listed (a new box of the same name may get the same IP). Absent: none.
|
|
914
709
|
*/
|
|
915
|
-
|
|
710
|
+
links: z3.array(z3.object({ owner: z3.string(), name: z3.string(), ip: z3.string(), port: z3.number().int(), stale: z3.literal(true).optional() })).optional()
|
|
916
711
|
});
|
|
917
|
-
var
|
|
918
|
-
/**
|
|
712
|
+
var VolumeMetaSchema = z3.object({
|
|
713
|
+
/** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
919
714
|
id: z3.string(),
|
|
920
715
|
name: z3.string(),
|
|
921
716
|
owner: z3.string(),
|
|
922
|
-
ownerKind: z3.enum(["user", "org"]).optional(),
|
|
923
|
-
/** The size at the end of the window (or when removed). */
|
|
924
717
|
sizeGib: z3.number().int(),
|
|
925
|
-
|
|
926
|
-
volumeHours: z3.number(),
|
|
927
|
-
volumeGibHours: z3.number(),
|
|
928
|
-
cost: z3.object({ amount: z3.number(), currency: z3.string() }).optional(),
|
|
929
|
-
historyFrom: z3.string().nullable()
|
|
930
|
-
});
|
|
931
|
-
var UsageReportSchema = z3.object({
|
|
932
|
-
window: z3.object({ from: z3.string(), to: z3.string() }),
|
|
933
|
-
boxes: z3.array(BoxUsageSchema),
|
|
934
|
-
/** Absent from a side older than #91. */
|
|
935
|
-
volumes: z3.array(VolumeUsageSchema).optional(),
|
|
936
|
-
totals: z3.object({
|
|
937
|
-
seconds: MachineUsageSchema.shape.seconds,
|
|
938
|
-
vcpuHours: z3.number(),
|
|
939
|
-
ramGibHours: z3.number(),
|
|
940
|
-
diskGibHours: z3.number(),
|
|
941
|
-
volumeHours: z3.number().optional(),
|
|
942
|
-
volumeGibHours: z3.number().optional(),
|
|
943
|
-
/** Boxes and volumes together. */
|
|
944
|
-
cost: z3.object({ amount: z3.number(), currency: z3.string() }).optional()
|
|
945
|
-
})
|
|
718
|
+
createdAt: z3.string()
|
|
946
719
|
});
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
720
|
+
function newBoxId(taken) {
|
|
721
|
+
for (; ; ) {
|
|
722
|
+
const id = randomBytes(3).toString("hex");
|
|
723
|
+
if (!taken.has(id)) return id;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
var SnapshotMetaSchema = z3.object({
|
|
951
727
|
name: z3.string(),
|
|
952
|
-
|
|
953
|
-
|
|
728
|
+
owner: z3.string(),
|
|
729
|
+
/** The box it was taken from, as owner/name. */
|
|
730
|
+
source: z3.string(),
|
|
731
|
+
base: z3.string(),
|
|
732
|
+
/** As in a box's meta.json (#87). */
|
|
733
|
+
image: z3.string().optional(),
|
|
954
734
|
vcpu: z3.number().int(),
|
|
955
735
|
memMib: z3.number().int(),
|
|
956
|
-
|
|
957
|
-
by: z3.string()
|
|
958
|
-
});
|
|
959
|
-
var UsageEventsResponseSchema = z3.object({
|
|
960
|
-
ledger: z3.string().min(1),
|
|
961
|
-
events: z3.array(UsageEventRowSchema),
|
|
962
|
-
next: z3.number().int()
|
|
963
|
-
});
|
|
964
|
-
var VolumeEventRowSchema = z3.object({
|
|
965
|
-
id: z3.number().int(),
|
|
966
|
-
volumeId: z3.string(),
|
|
967
|
-
owner: z3.string(),
|
|
968
|
-
name: z3.string(),
|
|
969
|
-
at: z3.string(),
|
|
970
|
-
sizeGib: z3.number().int(),
|
|
971
|
-
by: z3.enum(["create", "resize", "rm"])
|
|
972
|
-
});
|
|
973
|
-
var VolumeEventsResponseSchema = z3.object({
|
|
974
|
-
ledger: z3.string().min(1),
|
|
975
|
-
events: z3.array(VolumeEventRowSchema),
|
|
976
|
-
next: z3.number().int()
|
|
977
|
-
});
|
|
978
|
-
var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
|
|
979
|
-
var ApiErrorCodeSchema = z3.enum(API_ERROR_CODES);
|
|
980
|
-
var ApiErrorSchema = z3.object({
|
|
981
|
-
error: z3.string(),
|
|
982
|
-
code: ApiErrorCodeSchema.optional()
|
|
983
|
-
});
|
|
984
|
-
var ACTIVATED_BY = ["card", "admin"];
|
|
985
|
-
var ActivatedBySchema = z3.enum(ACTIVATED_BY);
|
|
986
|
-
var CloudUserSchema = z3.object({
|
|
987
|
-
/** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */
|
|
988
|
-
username: z3.string(),
|
|
989
|
-
/** Display name, free text ("Alexandru Ghiura"). */
|
|
990
|
-
name: z3.string(),
|
|
991
|
-
/** Login identity, unique. */
|
|
992
|
-
email: z3.string(),
|
|
993
|
-
role: z3.enum(["admin", "user"]),
|
|
736
|
+
sizeBytes: z3.number().int(),
|
|
994
737
|
createdAt: z3.string(),
|
|
995
738
|
/**
|
|
996
|
-
*
|
|
997
|
-
*
|
|
998
|
-
*
|
|
739
|
+
* The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
|
|
740
|
+
* and their mounts in the memory image, but their data is not here. A box restored from the snapshot
|
|
741
|
+
* gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
|
|
999
742
|
*/
|
|
1000
|
-
|
|
1001
|
-
activatedBy: ActivatedBySchema.nullable().default(null)
|
|
1002
|
-
});
|
|
1003
|
-
var ORG_ROLES = ["owner", "admin", "member"];
|
|
1004
|
-
var OrgRoleSchema = z3.enum(ORG_ROLES);
|
|
1005
|
-
var CloudOrgSchema = z3.object({
|
|
1006
|
-
slug: z3.string(),
|
|
1007
|
-
/** Display name; the slug never changes, this may. */
|
|
1008
|
-
name: z3.string(),
|
|
1009
|
-
createdAt: z3.string(),
|
|
1010
|
-
/** An org pays for itself (#74): off until it has a card or an admin activates it; its boxes are 402. Defaults as on CloudUser. */
|
|
1011
|
-
active: z3.boolean().default(true),
|
|
1012
|
-
activatedBy: ActivatedBySchema.nullable().default(null)
|
|
1013
|
-
});
|
|
1014
|
-
var OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });
|
|
1015
|
-
var OrgMemberSchema = z3.object({
|
|
1016
|
-
username: z3.string(),
|
|
1017
|
-
name: z3.string(),
|
|
1018
|
-
role: OrgRoleSchema,
|
|
1019
|
-
addedAt: z3.string()
|
|
1020
|
-
});
|
|
1021
|
-
var OrgDetailSchema = CloudOrgSchema.extend({ members: z3.array(OrgMemberSchema) });
|
|
1022
|
-
var CreateOrgRequestSchema = z3.object({
|
|
1023
|
-
slug: z3.string().min(1),
|
|
1024
|
-
name: z3.string().min(1)
|
|
1025
|
-
});
|
|
1026
|
-
var RenameOrgRequestSchema = z3.object({ name: z3.string().min(1) });
|
|
1027
|
-
var AddMemberRequestSchema = z3.object({
|
|
1028
|
-
username: z3.string().min(1),
|
|
1029
|
-
role: OrgRoleSchema.default("member")
|
|
1030
|
-
});
|
|
1031
|
-
var SetRoleRequestSchema = z3.object({ role: OrgRoleSchema });
|
|
1032
|
-
var MeResponseSchema = CloudUserSchema.extend({ orgs: z3.array(OrgMembershipSchema) });
|
|
1033
|
-
var BalanceSchema = z3.object({
|
|
1034
|
-
slug: z3.string(),
|
|
1035
|
-
balance: z3.number(),
|
|
1036
|
-
currency: z3.string(),
|
|
1037
|
-
topUps: z3.number(),
|
|
1038
|
-
spent: z3.number(),
|
|
1039
|
-
/** The first moment usage counts from: the slug's first top-up; null when it has none. */
|
|
1040
|
-
since: z3.string().nullable(),
|
|
1041
|
-
/** When the slug ran out and its boxes were hibernated (the `sweep-credit` job); null in good standing. Absent from a control plane older than this field. */
|
|
1042
|
-
suspendedAt: z3.string().nullable().default(null)
|
|
1043
|
-
});
|
|
1044
|
-
var TopUpRequestSchema = z3.object({
|
|
1045
|
-
slug: z3.string().min(1),
|
|
1046
|
-
/** In the control plane's currency; negative corrects a mistake. */
|
|
1047
|
-
amount: z3.number().finite(),
|
|
1048
|
-
note: z3.string().max(200).optional()
|
|
1049
|
-
});
|
|
1050
|
-
var TopUpSchema = z3.object({
|
|
1051
|
-
id: z3.string(),
|
|
1052
|
-
slug: z3.string(),
|
|
1053
|
-
amount: z3.number(),
|
|
1054
|
-
currency: z3.string(),
|
|
1055
|
-
/** `transfer` (#93): an owner moving credit to an org they own, a negative row on their slug and a positive one on the org's. */
|
|
1056
|
-
source: z3.enum(["admin", "card", "trial", "transfer"]),
|
|
1057
|
-
note: z3.string().nullable(),
|
|
1058
|
-
at: z3.string()
|
|
1059
|
-
});
|
|
1060
|
-
var TOP_UP_AMOUNTS = [10, 25, 50, 100];
|
|
1061
|
-
var BillingInfoSchema = z3.object({
|
|
1062
|
-
card: z3.object({ brand: z3.string(), last4: z3.string() }).nullable(),
|
|
1063
|
-
cardInUse: z3.boolean(),
|
|
1064
|
-
balance: BalanceSchema
|
|
1065
|
-
});
|
|
1066
|
-
var BillingRedirectSchema = z3.object({ url: z3.string() });
|
|
1067
|
-
var TopUpCheckoutRequestSchema = z3.object({
|
|
1068
|
-
amount: z3.literal(TOP_UP_AMOUNTS)
|
|
1069
|
-
});
|
|
1070
|
-
var TransferRequestSchema = z3.object({
|
|
1071
|
-
org: z3.string().min(1),
|
|
1072
|
-
amount: z3.number().positive().multipleOf(0.01, "amount is in cents at most")
|
|
1073
|
-
});
|
|
1074
|
-
var TransferResponseSchema = z3.object({ from: BalanceSchema, to: BalanceSchema, activated: z3.boolean() });
|
|
1075
|
-
var LoginRequestSchema = z3.object({
|
|
1076
|
-
email: z3.string().min(1),
|
|
1077
|
-
password: z3.string().min(1),
|
|
1078
|
-
publicKey: z3.string().optional()
|
|
1079
|
-
});
|
|
1080
|
-
var SignupRequestSchema = z3.object({
|
|
1081
|
-
username: z3.string().min(1),
|
|
1082
|
-
name: z3.string().min(1),
|
|
1083
|
-
email: z3.string().min(1),
|
|
1084
|
-
password: z3.string().min(1)
|
|
743
|
+
volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int() })).optional()
|
|
1085
744
|
});
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
sshCert: z3.string().optional(),
|
|
1090
|
-
sshCertExpires: z3.string().optional(),
|
|
1091
|
-
/** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
|
|
1092
|
-
sshCertPrincipals: z3.array(z3.string()).optional()
|
|
1093
|
-
});
|
|
1094
|
-
var SshCertRequestSchema = z3.object({
|
|
1095
|
-
publicKey: z3.string().min(1)
|
|
1096
|
-
});
|
|
1097
|
-
var SshCertResponseSchema = z3.object({
|
|
1098
|
-
cert: z3.string(),
|
|
1099
|
-
expires: z3.string(),
|
|
1100
|
-
principals: z3.array(z3.string())
|
|
1101
|
-
});
|
|
1102
|
-
var SshCaResponseSchema = z3.object({
|
|
1103
|
-
publicKey: z3.string(),
|
|
1104
|
-
/** CAs replaced by `ca rotate` (#55), newest first; a box still holding one of these has not had `kvbox server trust-ca` run on its host. */
|
|
1105
|
-
retired: z3.array(z3.object({ publicKey: z3.string(), retiredAt: z3.string() })).optional()
|
|
1106
|
-
});
|
|
1107
|
-
var HostSshCaResponseSchema = z3.object({
|
|
1108
|
-
publicKey: z3.string()
|
|
1109
|
-
});
|
|
1110
|
-
var CloudCaSchema = z3.object({
|
|
1111
|
-
controlPlane: z3.string(),
|
|
1112
|
-
publicKey: z3.string(),
|
|
1113
|
-
fingerprint: z3.string()
|
|
1114
|
-
});
|
|
1115
|
-
var TrustCaRequestSchema = z3.object({
|
|
1116
|
-
publicKey: z3.string().min(1)
|
|
1117
|
-
});
|
|
1118
|
-
var SshKeysAppliedSchema = z3.enum(["now", "start", "wake", "resume", "later"]);
|
|
1119
|
-
var TrustCaReportSchema = z3.object({
|
|
1120
|
-
publicKey: z3.string(),
|
|
1121
|
-
fingerprint: z3.string(),
|
|
1122
|
-
/** The guest trusts the CA now. */
|
|
1123
|
-
updated: z3.array(z3.string()),
|
|
1124
|
-
/** meta.json has the line; the guest gets it at `when`. */
|
|
1125
|
-
pending: z3.array(z3.object({ box: z3.string(), when: SshKeysAppliedSchema, why: z3.string().optional() })),
|
|
1126
|
-
failed: z3.array(z3.object({ box: z3.string(), error: z3.string() })),
|
|
1127
|
-
/** Local boxes, untouched: they trust the host's key only. */
|
|
1128
|
-
local: z3.number().int()
|
|
1129
|
-
});
|
|
1130
|
-
var HostJoinRequestSchema = z3.object({
|
|
1131
|
-
token: z3.string().min(1),
|
|
1132
|
-
name: z3.string().min(1),
|
|
1133
|
-
url: z3.string().url(),
|
|
1134
|
-
fingerprint: z3.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
|
|
1135
|
-
publicAddress: z3.string().min(1),
|
|
1136
|
-
/** Where the host is (`kvbox server join --country`): a code or an English name. */
|
|
1137
|
-
country: z3.string().optional()
|
|
1138
|
-
});
|
|
1139
|
-
var HostJoinResponseSchema = z3.object({
|
|
1140
|
-
hostSecret: z3.string(),
|
|
1141
|
-
controlPlane: z3.object({ name: z3.string() })
|
|
1142
|
-
});
|
|
1143
|
-
var CloudHostSchema = z3.object({
|
|
1144
|
-
name: z3.string(),
|
|
1145
|
-
url: z3.string(),
|
|
1146
|
-
publicAddress: z3.string(),
|
|
1147
|
-
joinedAt: z3.string(),
|
|
1148
|
-
lastSeenAt: z3.string().nullable(),
|
|
1149
|
-
capacity: CapacitySchema.nullable(),
|
|
1150
|
-
/** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
|
|
1151
|
-
country: z3.string().nullable()
|
|
1152
|
-
});
|
|
1153
|
-
var HostPatchRequest = z3.object({ country: z3.string().nullable() });
|
|
1154
|
-
var CountrySchema = z3.object({ code: z3.string(), name: z3.string() });
|
|
1155
|
-
|
|
1156
|
-
// ../shared/src/ssh.ts
|
|
1157
|
-
import { createHash } from "node:crypto";
|
|
1158
|
-
var SSH_PUBLIC_KEY_RE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com) ([A-Za-z0-9+/]+=*)(?: [^\r\n]*)?$/;
|
|
1159
|
-
function parseSshPublicKey(text) {
|
|
1160
|
-
const key = text.trim().replace(/^cert-authority\s+/, "");
|
|
1161
|
-
if (!SSH_PUBLIC_KEY_RE.test(key)) {
|
|
1162
|
-
throw new KvboxError("that is not an SSH public key; expected one line like: ssh-ed25519 AAAA\u2026 kvbox-ca@kvbox.sh");
|
|
745
|
+
async function ensureLayout(p = paths()) {
|
|
746
|
+
for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
|
|
747
|
+
await mkdir(dir, { recursive: true, mode: 448 });
|
|
1163
748
|
}
|
|
1164
|
-
return
|
|
1165
|
-
}
|
|
1166
|
-
function sshKeyFingerprint(publicKey) {
|
|
1167
|
-
const m = SSH_PUBLIC_KEY_RE.exec(publicKey.trim());
|
|
1168
|
-
if (!m) throw new KvboxError("cannot fingerprint: not an SSH public key");
|
|
1169
|
-
return `SHA256:${createHash("sha256").update(Buffer.from(m[2], "base64")).digest("base64").replace(/=+$/, "")}`;
|
|
1170
|
-
}
|
|
1171
|
-
function caLineFor(principal, caPublicKey) {
|
|
1172
|
-
return `cert-authority,principals="${principal}" ${caPublicKey}`;
|
|
749
|
+
return p;
|
|
1173
750
|
}
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
// src/core/exec.ts
|
|
1177
|
-
import { execFile } from "node:child_process";
|
|
1178
|
-
import { promisify } from "node:util";
|
|
1179
|
-
|
|
1180
|
-
// src/core/log.ts
|
|
1181
|
-
function formatLine(level, message, at = /* @__PURE__ */ new Date()) {
|
|
1182
|
-
return `[${at.toISOString()}][${level}]: ${message}`;
|
|
751
|
+
async function readJson(file, schema) {
|
|
752
|
+
return schema.parse(JSON.parse(await readFile3(file, "utf8")));
|
|
1183
753
|
}
|
|
1184
|
-
|
|
1185
|
-
debug(message) {
|
|
1186
|
-
console.error(formatLine("debug", message));
|
|
1187
|
-
},
|
|
1188
|
-
info(message) {
|
|
1189
|
-
console.log(formatLine("info", message));
|
|
1190
|
-
},
|
|
1191
|
-
warn(message) {
|
|
1192
|
-
console.error(formatLine("warn", message));
|
|
1193
|
-
},
|
|
1194
|
-
error(message) {
|
|
1195
|
-
console.error(formatLine("error", message));
|
|
1196
|
-
}
|
|
1197
|
-
};
|
|
1198
|
-
|
|
1199
|
-
// src/core/exec.ts
|
|
1200
|
-
var execFileAsync = promisify(execFile);
|
|
1201
|
-
async function run(argv, opts = {}) {
|
|
1202
|
-
const [cmd, ...args] = opts.sudo ? ["sudo", "-n", ...argv] : argv;
|
|
1203
|
-
if (!cmd) throw new KvboxError("run: empty argv");
|
|
1204
|
-
if (process.env["KVBOX_DEBUG"]) log.debug(`exec ${[cmd, ...args].join(" ")}`);
|
|
754
|
+
async function listDirs(dir) {
|
|
1205
755
|
try {
|
|
1206
|
-
const
|
|
1207
|
-
|
|
1208
|
-
env: opts.env ?? process.env,
|
|
1209
|
-
timeout: opts.timeoutMs ?? 3e4,
|
|
1210
|
-
maxBuffer: 8 * 1024 * 1024
|
|
1211
|
-
});
|
|
1212
|
-
return { stdout, stderr };
|
|
756
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
757
|
+
return entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
|
1213
758
|
} catch (err) {
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
const detail = (e.stderr ?? e.message ?? "").trim();
|
|
1217
|
-
throw new KvboxError(`${[cmd, ...args].join(" ")} failed${detail ? `: ${detail}` : ""}`);
|
|
759
|
+
if (err.code === "ENOENT") return [];
|
|
760
|
+
throw err;
|
|
1218
761
|
}
|
|
1219
762
|
}
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
763
|
+
async function readMachineMeta(ref, p = paths()) {
|
|
764
|
+
return readJson(p.machine(ref.owner, ref.name).meta, MachineMetaSchema);
|
|
765
|
+
}
|
|
766
|
+
var boxListVersion = 0;
|
|
767
|
+
var boxListVersionNow = () => boxListVersion;
|
|
768
|
+
var boxListChanged = () => void (boxListVersion += 1);
|
|
769
|
+
async function writeMachineMeta(meta, p = paths()) {
|
|
770
|
+
const m = p.machine(meta.owner, meta.name);
|
|
771
|
+
await mkdir(m.dir, { recursive: true });
|
|
772
|
+
const tmp = `${m.meta}.tmp`;
|
|
773
|
+
await writeFile2(tmp, JSON.stringify(meta, null, 2) + "\n");
|
|
774
|
+
await rename2(tmp, m.meta);
|
|
775
|
+
boxListChanged();
|
|
776
|
+
}
|
|
777
|
+
async function listMachineRefs(p = paths()) {
|
|
778
|
+
return listRefs(p.machines);
|
|
779
|
+
}
|
|
780
|
+
async function readSnapshotMeta(ref, p = paths()) {
|
|
781
|
+
return readJson(p.snapshot(ref.owner, ref.name).meta, SnapshotMetaSchema);
|
|
782
|
+
}
|
|
783
|
+
async function writeSnapshotMeta(meta, p = paths(), s = p.snapshot(meta.owner, meta.name)) {
|
|
784
|
+
await mkdir(s.dir, { recursive: true });
|
|
785
|
+
await writeFile2(s.meta, JSON.stringify(meta, null, 2) + "\n");
|
|
786
|
+
}
|
|
787
|
+
async function listSnapshotRefs(p = paths()) {
|
|
788
|
+
return (await listRefs(p.snapshots)).filter((ref) => !ref.name.startsWith("."));
|
|
789
|
+
}
|
|
790
|
+
async function readVolumeMeta(ref, p = paths()) {
|
|
791
|
+
const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z3.string().optional() }));
|
|
792
|
+
if (raw.id !== void 0) return { ...raw, id: raw.id };
|
|
793
|
+
const taken = /* @__PURE__ */ new Set();
|
|
794
|
+
for (const other of await listVolumeRefs(p)) {
|
|
1228
795
|
try {
|
|
1229
|
-
await
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
"-x509",
|
|
1233
|
-
"-newkey",
|
|
1234
|
-
"ec",
|
|
1235
|
-
"-pkeyopt",
|
|
1236
|
-
"ec_paramgen_curve:prime256v1",
|
|
1237
|
-
"-nodes",
|
|
1238
|
-
"-keyout",
|
|
1239
|
-
p.tlsKey,
|
|
1240
|
-
"-out",
|
|
1241
|
-
p.tlsCert,
|
|
1242
|
-
"-subj",
|
|
1243
|
-
"/CN=kvbox-host",
|
|
1244
|
-
"-days",
|
|
1245
|
-
"3650"
|
|
1246
|
-
]);
|
|
1247
|
-
} catch (err) {
|
|
1248
|
-
throw new KvboxError(`could not make the host's certificate (is openssl installed?): ${err.message}`);
|
|
796
|
+
const j = JSON.parse(await readFile3(p.volume(other.owner, other.name).meta, "utf8"));
|
|
797
|
+
if (typeof j.id === "string") taken.add(j.id);
|
|
798
|
+
} catch {
|
|
1249
799
|
}
|
|
1250
|
-
await chmod2(p.tlsKey, 384);
|
|
1251
800
|
}
|
|
1252
|
-
const
|
|
1253
|
-
|
|
801
|
+
const meta = { ...raw, id: newBoxId(taken) };
|
|
802
|
+
await writeVolumeMeta(meta, p);
|
|
803
|
+
insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: meta.createdAt, sizeGib: meta.sizeGib, by: "create" }, p);
|
|
804
|
+
return meta;
|
|
1254
805
|
}
|
|
1255
|
-
function
|
|
1256
|
-
const
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
return a === 10 || a === 127 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127;
|
|
806
|
+
async function writeVolumeMeta(meta, p = paths()) {
|
|
807
|
+
const v = p.volume(meta.owner, meta.name);
|
|
808
|
+
await mkdir(v.dir, { recursive: true, mode: 448 });
|
|
809
|
+
await writeFile2(v.meta, JSON.stringify(meta, null, 2) + "\n");
|
|
1260
810
|
}
|
|
1261
|
-
async function
|
|
1262
|
-
|
|
1263
|
-
throw new KvboxError(`cannot tell this host's address (${err.message}); pass --advertise <host-or-ip>`);
|
|
1264
|
-
});
|
|
1265
|
-
const m = /\bsrc\s+(\S+)/.exec(stdout);
|
|
1266
|
-
if (!m) throw new KvboxError("cannot tell this host's address from its routes; pass --advertise <host-or-ip>");
|
|
1267
|
-
return m[1];
|
|
811
|
+
async function listVolumeRefs(p = paths()) {
|
|
812
|
+
return listRefs(p.volumes);
|
|
1268
813
|
}
|
|
1269
|
-
async function
|
|
1270
|
-
const
|
|
1271
|
-
const
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
let advertise = opts.advertise;
|
|
1275
|
-
if (advertise === void 0 && cfg.relay) {
|
|
1276
|
-
advertise = cfg.relay.publicIp;
|
|
1277
|
-
} else if (advertise === void 0) {
|
|
1278
|
-
advertise = await guessAddress();
|
|
1279
|
-
if (isPrivateAddress(advertise)) {
|
|
1280
|
-
throw new KvboxError(
|
|
1281
|
-
`${advertise} is a private address: a control plane on the internet cannot reach this host there.
|
|
1282
|
-
Pass --advertise <public host or ip>, or --advertise ${advertise} if the control plane is on the same network.`
|
|
1283
|
-
);
|
|
814
|
+
async function listRefs(root) {
|
|
815
|
+
const out = [];
|
|
816
|
+
for (const owner of await listDirs(root)) {
|
|
817
|
+
for (const name of await listDirs(`${root}/${owner}`)) {
|
|
818
|
+
out.push({ owner, name });
|
|
1284
819
|
}
|
|
1285
820
|
}
|
|
1286
|
-
|
|
1287
|
-
const country = opts.country === void 0 ? void 0 : parseCountry(opts.country);
|
|
1288
|
-
const { fingerprint } = await ensureTlsCert(p);
|
|
1289
|
-
const hostUrl = `https://${advertise}:${port}`;
|
|
1290
|
-
const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
|
|
1291
|
-
const res = await request(`${url}/hosts/join`, {
|
|
1292
|
-
method: "POST",
|
|
1293
|
-
headers: { "content-type": "application/json" },
|
|
1294
|
-
body: JSON.stringify(body),
|
|
1295
|
-
headersTimeout: 1e4,
|
|
1296
|
-
bodyTimeout: 1e4
|
|
1297
|
-
}).catch((err) => {
|
|
1298
|
-
throw new KvboxError(`cannot reach ${url} (${err.message})`);
|
|
1299
|
-
});
|
|
1300
|
-
const text = await res.body.text();
|
|
1301
|
-
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
1302
|
-
throw new KvboxError(errorIn(text) ?? `control plane answered ${res.statusCode}`);
|
|
1303
|
-
}
|
|
1304
|
-
const parsed = HostJoinResponseSchema.safeParse(jsonOrNull(text));
|
|
1305
|
-
if (!parsed.success) throw new KvboxError(`${url} did not answer like a kvbox control plane`);
|
|
1306
|
-
if (!REALM_RE.test(parsed.data.controlPlane.name)) {
|
|
1307
|
-
throw new KvboxError(`${url} calls itself "${parsed.data.controlPlane.name}", which cannot name a realm (letters, digits, '.', '-')`);
|
|
1308
|
-
}
|
|
1309
|
-
await saveConfig({ ...cfg, controlPlane: { url, name: parsed.data.controlPlane.name, secret: parsed.data.hostSecret, advertise, port } }, p);
|
|
1310
|
-
return { hostName: name, controlPlane: parsed.data.controlPlane.name, hostUrl };
|
|
1311
|
-
}
|
|
1312
|
-
async function fetchCloudCa(p = paths()) {
|
|
1313
|
-
const cfg = await loadConfig(p);
|
|
1314
|
-
const cp = cfg.controlPlane;
|
|
1315
|
-
if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no CA to fetch; paste the key instead: kvbox server trust-ca <public-key>");
|
|
1316
|
-
const res = await request(`${cp.url}/hosts/self/ssh-ca`, {
|
|
1317
|
-
headers: { authorization: `Bearer ${cp.secret}` },
|
|
1318
|
-
headersTimeout: 1e4,
|
|
1319
|
-
bodyTimeout: 1e4
|
|
1320
|
-
}).catch((err) => {
|
|
1321
|
-
throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
|
|
1322
|
-
});
|
|
1323
|
-
const text = await res.body.text();
|
|
1324
|
-
if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not answer /hosts/self/ssh-ca: it is older than this host; paste the key instead`);
|
|
1325
|
-
if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(errorIn(text) ?? `${cp.name} answered ${res.statusCode}`);
|
|
1326
|
-
const parsed = HostSshCaResponseSchema.safeParse(jsonOrNull(text));
|
|
1327
|
-
if (!parsed.success) throw new KvboxError(`${cp.name} did not answer with a CA key`);
|
|
1328
|
-
const publicKey = parseSshPublicKey(parsed.data.publicKey);
|
|
1329
|
-
return { controlPlane: cp.name, publicKey, fingerprint: sshKeyFingerprint(publicKey) };
|
|
1330
|
-
}
|
|
1331
|
-
async function leaveControlPlane(p = paths()) {
|
|
1332
|
-
const cfg = await loadConfig(p);
|
|
1333
|
-
const cp = cfg.controlPlane;
|
|
1334
|
-
if (!cp) throw new KvboxError("this host has not joined a control plane");
|
|
1335
|
-
const told = await request(`${cp.url}/hosts/self`, {
|
|
1336
|
-
method: "DELETE",
|
|
1337
|
-
headers: { authorization: `Bearer ${cp.secret}` },
|
|
1338
|
-
headersTimeout: 3e3,
|
|
1339
|
-
bodyTimeout: 3e3
|
|
1340
|
-
}).then(async (res) => {
|
|
1341
|
-
await res.body.dump();
|
|
1342
|
-
return res.statusCode >= 200 && res.statusCode < 300;
|
|
1343
|
-
}).catch(() => false);
|
|
1344
|
-
const { controlPlane: _gone, ...rest } = cfg;
|
|
1345
|
-
await saveConfig(rest, p);
|
|
1346
|
-
return { controlPlane: cp.name, told };
|
|
821
|
+
return out;
|
|
1347
822
|
}
|
|
1348
|
-
function
|
|
823
|
+
function pidAlive(pid) {
|
|
824
|
+
if (pid === null || pid <= 0) return false;
|
|
1349
825
|
try {
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
826
|
+
process.kill(pid, 0);
|
|
827
|
+
return true;
|
|
828
|
+
} catch (err) {
|
|
829
|
+
return err.code === "EPERM";
|
|
1353
830
|
}
|
|
1354
831
|
}
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
if (
|
|
1358
|
-
|
|
1359
|
-
}
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
var KVM_DEVICE = "/dev/kvm";
|
|
1364
|
-
async function groupName(gid, groupFile = "/etc/group") {
|
|
1365
|
-
const text = await readFile3(groupFile, "utf8").catch(() => "");
|
|
1366
|
-
for (const line of text.split("\n")) {
|
|
1367
|
-
const [name, , id] = line.split(":");
|
|
1368
|
-
if (id !== void 0 && Number.parseInt(id, 10) === gid && name) return name;
|
|
832
|
+
var bootId;
|
|
833
|
+
function currentBootId() {
|
|
834
|
+
if (bootId === void 0) {
|
|
835
|
+
try {
|
|
836
|
+
bootId = { id: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() };
|
|
837
|
+
} catch {
|
|
838
|
+
bootId = { id: void 0 };
|
|
839
|
+
}
|
|
1369
840
|
}
|
|
1370
|
-
return
|
|
841
|
+
return bootId.id;
|
|
1371
842
|
}
|
|
1372
|
-
|
|
843
|
+
function vmAlive(meta) {
|
|
844
|
+
if (meta.bootId !== void 0 && meta.bootId !== currentBootId()) return false;
|
|
845
|
+
return pidAlive(meta.pid);
|
|
846
|
+
}
|
|
847
|
+
function hostBootTime() {
|
|
1373
848
|
try {
|
|
1374
|
-
|
|
1375
|
-
return;
|
|
1376
|
-
} catch
|
|
1377
|
-
|
|
1378
|
-
if (code === "ENOENT") {
|
|
1379
|
-
throw new KvboxError(`${device} is missing: this machine has no KVM, so boxes cannot run here (enable virtualization in the BIOS, then install-server.sh checks the rest)`);
|
|
1380
|
-
}
|
|
1381
|
-
if (code !== "EACCES" && code !== "EPERM") throw new KvboxError(`cannot open ${device}: ${err.message}`);
|
|
849
|
+
const m = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
|
|
850
|
+
return m ? new Date(Number(m[1]) * 1e3) : null;
|
|
851
|
+
} catch {
|
|
852
|
+
return null;
|
|
1382
853
|
}
|
|
1383
|
-
const owner = await stat(device).then((s) => groupName(s.gid, groupFile), () => "kvm");
|
|
1384
|
-
throw new KvboxError(
|
|
1385
|
-
`cannot start: this process is not allowed to open ${device}, so no box could run. It was started from a shell without the ${owner} group (a login from before you were added to it). Log out and back in, or start it from a shell that has the group: sg ${owner} -c "kvbox server start"`
|
|
1386
|
-
);
|
|
1387
854
|
}
|
|
1388
855
|
|
|
1389
856
|
// src/core/dns.ts
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
);
|
|
1415
|
-
create index usage_events_box_at on usage_events (box_id, at);`,
|
|
1416
|
-
// The ledger's identity (#42): a control plane keys pulled rows by it, so a re-join is recognised
|
|
1417
|
-
// and a fresh ledger (KVBOX_HOME wiped) restarts its cursor instead of waiting for ids it already saw.
|
|
1418
|
-
`create table ledger (id text not null);
|
|
1419
|
-
insert into ledger (id) values (lower(hex(randomblob(16))));
|
|
1420
|
-
create index usage_events_at on usage_events (at);`,
|
|
1421
|
-
// Volumes (#91): a row per create, resize and rm, the size from that moment on. Its own table and
|
|
1422
|
-
// ids, pulled by the control plane like usage_events, in the same ledger.
|
|
1423
|
-
`create table volume_events (
|
|
1424
|
-
id integer primary key,
|
|
1425
|
-
volume_id text not null,
|
|
1426
|
-
owner text not null,
|
|
1427
|
-
name text not null,
|
|
1428
|
-
at text not null,
|
|
1429
|
-
size_gib integer not null,
|
|
1430
|
-
by text not null
|
|
1431
|
-
);
|
|
1432
|
-
create index volume_events_volume_at on volume_events (volume_id, at);`
|
|
1433
|
-
];
|
|
1434
|
-
var handles = /* @__PURE__ */ new Map();
|
|
1435
|
-
function openDb(p = paths()) {
|
|
1436
|
-
const have = handles.get(p.db);
|
|
1437
|
-
if (have !== void 0) return have;
|
|
1438
|
-
mkdirSync(dirname(p.db), { recursive: true, mode: 448 });
|
|
1439
|
-
closeSync(openSync(p.db, "a", 384));
|
|
1440
|
-
chmodSync(p.db, 384);
|
|
1441
|
-
const db = new DatabaseSync(p.db);
|
|
1442
|
-
db.exec("pragma journal_mode = wal");
|
|
1443
|
-
db.exec("pragma busy_timeout = 5000");
|
|
1444
|
-
migrate(db);
|
|
1445
|
-
handles.set(p.db, db);
|
|
1446
|
-
return db;
|
|
1447
|
-
}
|
|
1448
|
-
function migrate(db) {
|
|
1449
|
-
db.exec("create table if not exists schema_version (version integer not null)");
|
|
1450
|
-
const row = db.prepare("select version from schema_version").get();
|
|
1451
|
-
let version = row?.version ?? 0;
|
|
1452
|
-
if (row === void 0) db.prepare("insert into schema_version (version) values (0)").run();
|
|
1453
|
-
while (version < MIGRATIONS.length) {
|
|
1454
|
-
db.exec("begin");
|
|
1455
|
-
try {
|
|
1456
|
-
db.exec(MIGRATIONS[version]);
|
|
1457
|
-
version += 1;
|
|
1458
|
-
db.prepare("update schema_version set version = ?").run(version);
|
|
1459
|
-
db.exec("commit");
|
|
1460
|
-
} catch (err) {
|
|
1461
|
-
db.exec("rollback");
|
|
1462
|
-
throw err;
|
|
1463
|
-
}
|
|
857
|
+
var DNS_PORT = 10053;
|
|
858
|
+
var DNS_SUFFIX = ".kvbox";
|
|
859
|
+
var DNS_RETRY_MS = 1e4;
|
|
860
|
+
var TTL_SEC = 5;
|
|
861
|
+
var BOXES_FRESH_MS = 6e4;
|
|
862
|
+
var TYPE_A = 1;
|
|
863
|
+
var CLASS_IN = 1;
|
|
864
|
+
var RCODE = { ok: 0, nxDomain: 3, refused: 5 };
|
|
865
|
+
function parseQuery(msg) {
|
|
866
|
+
if (msg.length < 12) return null;
|
|
867
|
+
const flags = msg.readUInt16BE(2);
|
|
868
|
+
const isResponse = flags & 32768;
|
|
869
|
+
const opcode = flags >> 11 & 15;
|
|
870
|
+
if (isResponse || opcode !== 0 || msg.readUInt16BE(4) < 1) return null;
|
|
871
|
+
const labels = [];
|
|
872
|
+
let at = 12;
|
|
873
|
+
for (; ; ) {
|
|
874
|
+
if (at >= msg.length) return null;
|
|
875
|
+
const len = msg[at];
|
|
876
|
+
at += 1;
|
|
877
|
+
if (len === 0) break;
|
|
878
|
+
if (len > 63 || at + len > msg.length) return null;
|
|
879
|
+
labels.push(msg.subarray(at, at + len).toString("latin1"));
|
|
880
|
+
at += len;
|
|
1464
881
|
}
|
|
882
|
+
if (at + 4 > msg.length) return null;
|
|
883
|
+
return {
|
|
884
|
+
id: msg.readUInt16BE(0),
|
|
885
|
+
rd: Boolean(flags & 256),
|
|
886
|
+
name: labels.join(".").toLowerCase(),
|
|
887
|
+
type: msg.readUInt16BE(at),
|
|
888
|
+
class: msg.readUInt16BE(at + 2),
|
|
889
|
+
question: msg.subarray(12, at + 4)
|
|
890
|
+
};
|
|
1465
891
|
}
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
892
|
+
function buildAnswer(q, rcode, ip) {
|
|
893
|
+
const header = Buffer.alloc(12);
|
|
894
|
+
header.writeUInt16BE(q.id, 0);
|
|
895
|
+
header.writeUInt16BE(32768 | 1024 | (q.rd ? 256 : 0) | rcode, 2);
|
|
896
|
+
header.writeUInt16BE(1, 4);
|
|
897
|
+
header.writeUInt16BE(ip ? 1 : 0, 6);
|
|
898
|
+
if (!ip) return Buffer.concat([header, q.question]);
|
|
899
|
+
const rr = Buffer.alloc(16);
|
|
900
|
+
rr.writeUInt16BE(49164, 0);
|
|
901
|
+
rr.writeUInt16BE(TYPE_A, 2);
|
|
902
|
+
rr.writeUInt16BE(CLASS_IN, 4);
|
|
903
|
+
rr.writeUInt32BE(TTL_SEC, 6);
|
|
904
|
+
rr.writeUInt16BE(4, 10);
|
|
905
|
+
ip.split(".").forEach((o, i) => rr.writeUInt8(Number(o), 12 + i));
|
|
906
|
+
return Buffer.concat([header, q.question, rr]);
|
|
1478
907
|
}
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
908
|
+
var slugOf = (owner) => owner.split("@")[0].toLowerCase();
|
|
909
|
+
var isOurs = (q) => q.class === CLASS_IN && q.name.endsWith(DNS_SUFFIX);
|
|
910
|
+
function answerFor(q, asker, boxes) {
|
|
911
|
+
if (!isOurs(q)) return { rcode: RCODE.refused };
|
|
912
|
+
const [name, slug, ...rest] = q.name.slice(0, -DNS_SUFFIX.length).split(".");
|
|
913
|
+
const from = boxes.find((b) => b.ip === asker);
|
|
914
|
+
let box;
|
|
915
|
+
if (from && rest.length === 0) {
|
|
916
|
+
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));
|
|
917
|
+
}
|
|
918
|
+
if (!box) return { rcode: RCODE.nxDomain };
|
|
919
|
+
return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };
|
|
1483
920
|
}
|
|
1484
|
-
function
|
|
1485
|
-
const
|
|
1486
|
-
const
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
921
|
+
async function boxAddresses(p) {
|
|
922
|
+
const out = [];
|
|
923
|
+
for (const ref of await listMachineRefs(p)) {
|
|
924
|
+
const meta = await readMachineMeta(ref, p).catch(() => null);
|
|
925
|
+
if (meta) out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {} });
|
|
926
|
+
}
|
|
927
|
+
return out;
|
|
1490
928
|
}
|
|
1491
|
-
function
|
|
1492
|
-
|
|
1493
|
-
return
|
|
929
|
+
function sharedBoxes(load, freshMs = BOXES_FRESH_MS, version = boxListVersionNow) {
|
|
930
|
+
let last = null;
|
|
931
|
+
return () => {
|
|
932
|
+
if (!last || last.version !== version() || Date.now() - last.at > freshMs) {
|
|
933
|
+
const entry = { at: Date.now(), version: version(), list: load() };
|
|
934
|
+
last = entry;
|
|
935
|
+
entry.list.catch(() => {
|
|
936
|
+
if (last === entry) last = null;
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
return last.list;
|
|
940
|
+
};
|
|
1494
941
|
}
|
|
1495
|
-
function
|
|
1496
|
-
const
|
|
1497
|
-
|
|
942
|
+
async function startDns(opts) {
|
|
943
|
+
const p = opts.p ?? paths();
|
|
944
|
+
const boxes = sharedBoxes(opts.boxes ?? (() => boxAddresses(p)));
|
|
945
|
+
const socket = createSocket("udp4");
|
|
946
|
+
socket.on("message", (msg, rinfo) => {
|
|
947
|
+
const q = parseQuery(msg);
|
|
948
|
+
if (!q) return;
|
|
949
|
+
const reply = (a) => socket.send(buildAnswer(q, a.rcode, a.ip), rinfo.port, rinfo.address);
|
|
950
|
+
if (!isOurs(q)) return reply({ rcode: RCODE.refused });
|
|
951
|
+
void boxes().then((list) => answerFor(q, rinfo.address, list)).catch(() => ({ rcode: RCODE.refused })).then(reply);
|
|
952
|
+
});
|
|
953
|
+
await new Promise((resolve2, reject) => {
|
|
954
|
+
socket.once("error", (err) => {
|
|
955
|
+
socket.close();
|
|
956
|
+
reject(err);
|
|
957
|
+
});
|
|
958
|
+
socket.bind(opts.port ?? DNS_PORT, opts.host, () => {
|
|
959
|
+
socket.removeAllListeners("error");
|
|
960
|
+
socket.on("error", () => {
|
|
961
|
+
});
|
|
962
|
+
resolve2();
|
|
963
|
+
});
|
|
964
|
+
});
|
|
965
|
+
return { socket, close: () => new Promise((resolve2) => socket.close(() => resolve2())) };
|
|
1498
966
|
}
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
}
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
}
|
|
1508
|
-
function
|
|
1509
|
-
const
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
return
|
|
1514
|
-
}
|
|
1515
|
-
var volumeWithId = (r) => ({ id: r.id, volumeId: r.volume_id, owner: r.owner, name: r.name, at: r.at, sizeGib: r.size_gib, by: r.by });
|
|
1516
|
-
function insertVolumeEvent(e, p = paths()) {
|
|
1517
|
-
openDb(p).prepare("insert into volume_events (volume_id, owner, name, at, size_gib, by) values (?, ?, ?, ?, ?, ?)").run(e.volumeId, e.owner, e.name, e.at, e.sizeGib, e.by);
|
|
1518
|
-
}
|
|
1519
|
-
function volumeEventsAfter(after, limit, scope, p = paths()) {
|
|
1520
|
-
const db = openDb(p);
|
|
1521
|
-
const rows = scope === null ? db.prepare("select * from volume_events where id > ? order by id limit ?").all(after, limit) : typeof scope === "string" ? db.prepare("select * from volume_events where id > ? and owner = ? order by id limit ?").all(after, scope, limit) : db.prepare("select * from volume_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?").all(after, `@${scope.realm}`, `@${scope.realm}`, limit);
|
|
1522
|
-
return rows.map(volumeWithId);
|
|
1523
|
-
}
|
|
1524
|
-
function volumeEventsInScope(scope, window, p = paths()) {
|
|
1525
|
-
const rows = openDb(p).prepare(
|
|
1526
|
-
`select * from volume_events where at < ? and (at >= ? or id in (select max(id) from volume_events where at < ? group by volume_id))
|
|
1527
|
-
order by at, id`
|
|
1528
|
-
).all(window.to, window.from, window.from);
|
|
1529
|
-
return rows.filter((r) => inScope(r.owner, scope)).map(volumeWithId);
|
|
967
|
+
|
|
968
|
+
// src/core/machines.ts
|
|
969
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
970
|
+
import { closeSync as closeSync3, existsSync as existsSync6, openSync as openSync4, statSync as statSync2 } from "node:fs";
|
|
971
|
+
import { link as link2, mkdir as mkdir5, readFile as readFile5, rename as rename5, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
|
|
972
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
973
|
+
|
|
974
|
+
// ../shared/src/duration.ts
|
|
975
|
+
var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
|
|
976
|
+
function parseDuration(text) {
|
|
977
|
+
const t = text.trim().toLowerCase();
|
|
978
|
+
if (!/^(\d+[mhd])+$/.test(t)) return void 0;
|
|
979
|
+
let sec = 0;
|
|
980
|
+
for (const [, n, unit] of t.matchAll(/(\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit];
|
|
981
|
+
return sec;
|
|
1530
982
|
}
|
|
1531
983
|
|
|
1532
|
-
// src/
|
|
1533
|
-
|
|
1534
|
-
|
|
984
|
+
// ../shared/src/api.ts
|
|
985
|
+
import { z as z4 } from "zod";
|
|
986
|
+
var SizeSchema = z4.enum(SIZE_NAMES);
|
|
987
|
+
var BoxStatusSchema = z4.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
|
|
988
|
+
var PortProtoSchema = z4.enum(["tcp", "udp"]);
|
|
989
|
+
var MAX_BOX_PORTS = 16;
|
|
990
|
+
var PortForwardSchema = z4.object({
|
|
991
|
+
guestPort: z4.number().int().min(1).max(65535),
|
|
992
|
+
hostPort: z4.number().int(),
|
|
993
|
+
proto: PortProtoSchema,
|
|
994
|
+
/** The host's public address; only the control plane fills it in, as for `ssh`. */
|
|
995
|
+
address: z4.string().optional()
|
|
996
|
+
});
|
|
997
|
+
var PortsRequest = z4.object({
|
|
998
|
+
ports: z4.array(z4.object({ guestPort: z4.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
|
|
999
|
+
});
|
|
1000
|
+
var BoxPortSchema = z4.number().int().min(1).max(65535);
|
|
1001
|
+
var MAX_BOX_LINKS = 32;
|
|
1002
|
+
var BoxLinkSchema = z4.object({ from: z4.string(), port: BoxPortSchema });
|
|
1003
|
+
var LinkRequest = z4.object({ from: z4.string().min(1), fromOwner: z4.string().optional(), port: BoxPortSchema });
|
|
1004
|
+
var ClaimSubdomainRequest = z4.object({ name: z4.string(), port: BoxPortSchema });
|
|
1005
|
+
var SubdomainPortRequest = z4.object({ port: BoxPortSchema });
|
|
1006
|
+
var SubdomainRouteRequest = z4.object({ name: z4.string(), port: BoxPortSchema });
|
|
1007
|
+
var SubdomainSchema = z4.object({
|
|
1008
|
+
owner: z4.string(),
|
|
1009
|
+
box: z4.string(),
|
|
1010
|
+
subdomain: z4.string(),
|
|
1011
|
+
port: BoxPortSchema,
|
|
1012
|
+
url: z4.string(),
|
|
1013
|
+
routes: z4.array(z4.object({ name: z4.string(), port: BoxPortSchema, url: z4.string() }))
|
|
1014
|
+
});
|
|
1015
|
+
var AddDomainRequest = z4.object({ domain: z4.string(), port: BoxPortSchema.optional() });
|
|
1016
|
+
var DomainSchema = z4.object({
|
|
1017
|
+
owner: z4.string(),
|
|
1018
|
+
box: z4.string(),
|
|
1019
|
+
domain: z4.string(),
|
|
1020
|
+
port: BoxPortSchema,
|
|
1021
|
+
status: z4.enum(["pending", "live"]),
|
|
1022
|
+
www: z4.boolean(),
|
|
1023
|
+
url: z4.string(),
|
|
1024
|
+
error: z4.string().nullable(),
|
|
1025
|
+
records: z4.array(z4.object({ type: z4.enum(["A", "TXT", "CNAME"]), name: z4.string(), value: z4.string() })),
|
|
1026
|
+
createdAt: z4.string()
|
|
1027
|
+
});
|
|
1028
|
+
var WakeHookSchema = z4.object({
|
|
1029
|
+
id: z4.string(),
|
|
1030
|
+
owner: z4.string(),
|
|
1031
|
+
box: z4.string(),
|
|
1032
|
+
url: z4.string(),
|
|
1033
|
+
createdBy: z4.string().nullable(),
|
|
1034
|
+
createdAt: z4.string(),
|
|
1035
|
+
lastCalledAt: z4.string().nullable()
|
|
1036
|
+
});
|
|
1037
|
+
var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z4.string() });
|
|
1038
|
+
var WakeHookCallSchema = z4.object({
|
|
1039
|
+
box: z4.string(),
|
|
1040
|
+
action: z4.enum(["wake", "resume", "none"]),
|
|
1041
|
+
reason: z4.string().optional()
|
|
1042
|
+
});
|
|
1043
|
+
var BACKUP_STATUSES = ["running", "ready", "failed"];
|
|
1044
|
+
var BackupSchema = z4.object({
|
|
1045
|
+
id: z4.string(),
|
|
1046
|
+
owner: z4.string(),
|
|
1047
|
+
box: z4.string(),
|
|
1048
|
+
status: z4.enum(BACKUP_STATUSES),
|
|
1049
|
+
/** Why it failed; null otherwise. */
|
|
1050
|
+
error: z4.string().nullable(),
|
|
1051
|
+
/** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
|
|
1052
|
+
base: z4.string().nullable(),
|
|
1053
|
+
image: z4.string().optional(),
|
|
1054
|
+
vcpu: z4.number().int().nullable(),
|
|
1055
|
+
memMib: z4.number().int().nullable(),
|
|
1056
|
+
/** The disk's size. */
|
|
1057
|
+
diskBytes: z4.number().int().nullable(),
|
|
1058
|
+
/** What it holds: the slots that are not all zeros. */
|
|
1059
|
+
dataBytes: z4.number().int().nullable(),
|
|
1060
|
+
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
1061
|
+
uploadedBytes: z4.number().int().nullable(),
|
|
1062
|
+
createdBy: z4.string().nullable(),
|
|
1063
|
+
createdAt: z4.string(),
|
|
1064
|
+
finishedAt: z4.string().nullable()
|
|
1065
|
+
});
|
|
1066
|
+
var HostBackupRequest = z4.object({ id: z4.string(), key: z4.string() });
|
|
1067
|
+
var HostBackupManifestSchema = z4.object({
|
|
1068
|
+
id: z4.string(),
|
|
1069
|
+
sizeBytes: z4.number().int(),
|
|
1070
|
+
chunks: z4.array(z4.string().nullable()),
|
|
1071
|
+
env: z4.string().nullable(),
|
|
1072
|
+
base: z4.string(),
|
|
1073
|
+
image: z4.string().optional(),
|
|
1074
|
+
vcpu: z4.number().int(),
|
|
1075
|
+
memMib: z4.number().int()
|
|
1076
|
+
});
|
|
1077
|
+
var HostUploadRequest = z4.object({ key: z4.string(), urls: z4.record(z4.string(), z4.string()) });
|
|
1078
|
+
var HostUploadResultSchema = z4.object({ chunks: z4.number().int(), bytes: z4.number().int(), sizes: z4.record(z4.string(), z4.number().int()) });
|
|
1079
|
+
var HostRestoreRequest = z4.object({
|
|
1080
|
+
/** The backup's id: its variables were sealed under it. */
|
|
1081
|
+
id: z4.string(),
|
|
1082
|
+
key: z4.string(),
|
|
1083
|
+
sizeBytes: z4.number().int().positive(),
|
|
1084
|
+
base: z4.string(),
|
|
1085
|
+
image: z4.string().optional(),
|
|
1086
|
+
env: z4.string().nullable(),
|
|
1087
|
+
chunks: z4.array(z4.object({ index: z4.number().int().nonnegative(), hash: z4.string(), url: z4.string() }))
|
|
1088
|
+
});
|
|
1089
|
+
var MachineSchema = z4.object({
|
|
1090
|
+
/** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
|
|
1535
1091
|
id: z4.string(),
|
|
1536
1092
|
name: z4.string(),
|
|
1537
|
-
/**
|
|
1093
|
+
/** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */
|
|
1538
1094
|
owner: z4.string(),
|
|
1539
1095
|
ip: z4.string(),
|
|
1540
1096
|
mac: z4.string(),
|
|
1541
1097
|
pid: z4.number().int().nullable(),
|
|
1542
|
-
// null: stopped on purpose, disk kept
|
|
1543
|
-
/**
|
|
1544
|
-
* The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot
|
|
1545
|
-
* the number can name some other process; a pid from another boot is dead whatever `kill -0` says.
|
|
1546
|
-
* Absent (boxes launched before #29): the pid alone decides.
|
|
1547
|
-
*/
|
|
1548
|
-
bootId: z4.string().optional(),
|
|
1549
1098
|
vcpu: z4.number().int(),
|
|
1550
1099
|
memMib: z4.number().int(),
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1100
|
+
diskBytes: z4.number().int(),
|
|
1101
|
+
// the box's own writable disk, as the guest sees it
|
|
1102
|
+
diskUsedBytes: z4.number().int(),
|
|
1103
|
+
// what the box uses of it: the filesystem's own count, like the guest's `df` (#115)
|
|
1104
|
+
/** What the disk's sparse file occupies on the host. Grows while the box runs, `kvbox stop` trims it back. Hosts before 0.5.42 do not send it. */
|
|
1105
|
+
diskHostBytes: z4.number().int().optional(),
|
|
1554
1106
|
base: z4.string(),
|
|
1555
|
-
|
|
1107
|
+
// version of the image the box's overlay stacks on
|
|
1108
|
+
/** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
|
|
1556
1109
|
image: z4.string().optional(),
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
* each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
|
|
1562
|
-
* is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.
|
|
1563
|
-
*/
|
|
1564
|
-
memSnapshots: z4.number().int().optional(),
|
|
1565
|
-
/** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */
|
|
1566
|
-
paused: z4.boolean().optional(),
|
|
1567
|
-
/**
|
|
1568
|
-
* authorized_keys lines the box gets on top of the host's own key, as the control plane sent them
|
|
1569
|
-
* at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so
|
|
1570
|
-
* `start` has to send the same lines again. Absent: host key only.
|
|
1571
|
-
*/
|
|
1572
|
-
sshKeys: z4.array(z4.string()).optional(),
|
|
1110
|
+
createdAt: z4.string(),
|
|
1111
|
+
source: z4.string(),
|
|
1112
|
+
// "base", "snapshot:<owner/name>" or "fork:<owner/name>" (#79)
|
|
1113
|
+
status: BoxStatusSchema,
|
|
1573
1114
|
/**
|
|
1574
|
-
*
|
|
1575
|
-
*
|
|
1115
|
+
* Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made
|
|
1116
|
+
* through a control plane have one; the control plane adds the host's address for `connect` (#21).
|
|
1576
1117
|
*/
|
|
1577
|
-
sshKeysStale: z4.boolean().optional(),
|
|
1578
|
-
/** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */
|
|
1579
1118
|
sshPort: z4.number().int().optional(),
|
|
1580
1119
|
/**
|
|
1581
|
-
*
|
|
1582
|
-
*
|
|
1583
|
-
*
|
|
1120
|
+
* Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only
|
|
1121
|
+
* the control plane fills it in (a host does not know its own public address); absent for a box
|
|
1122
|
+
* whose host reported no port or did not answer.
|
|
1584
1123
|
*/
|
|
1585
|
-
|
|
1586
|
-
/**
|
|
1587
|
-
|
|
1124
|
+
ssh: z4.object({ host: z4.string(), port: z4.number().int(), user: z4.string() }).optional(),
|
|
1125
|
+
/** Box ports published on the host (#30). Absent: none. */
|
|
1126
|
+
ports: z4.array(PortForwardSchema).optional(),
|
|
1127
|
+
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
|
|
1128
|
+
ownerKind: z4.enum(["user", "org"]).optional(),
|
|
1588
1129
|
/**
|
|
1589
|
-
*
|
|
1590
|
-
*
|
|
1591
|
-
* changes it. The one place the host looks. Absent: the traffic rule.
|
|
1130
|
+
* The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
|
|
1131
|
+
* links to, and a volume attaches to, only a box on the same host.
|
|
1592
1132
|
*/
|
|
1133
|
+
host: z4.string().optional(),
|
|
1134
|
+
/** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
|
|
1135
|
+
country: z4.string().optional(),
|
|
1136
|
+
/** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
|
|
1137
|
+
autoHibernateSec: z4.number().int().positive().optional(),
|
|
1138
|
+
/** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
|
|
1593
1139
|
idleCheck: z4.string().optional(),
|
|
1140
|
+
/** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
|
|
1141
|
+
volumes: z4.array(z4.object({ name: z4.string(), sizeGib: z4.number().int(), mountPath: z4.string() })).optional(),
|
|
1142
|
+
/** Boxes that may reach this one, each on one port (#98). Absent: none. */
|
|
1143
|
+
links: z4.array(BoxLinkSchema).optional(),
|
|
1144
|
+
/** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */
|
|
1145
|
+
url: z4.string().optional(),
|
|
1594
1146
|
/**
|
|
1595
|
-
*
|
|
1596
|
-
*
|
|
1597
|
-
* volume's meta.json does not say. Absent: none.
|
|
1598
|
-
*/
|
|
1599
|
-
volumes: z4.array(z4.string()).optional(),
|
|
1600
|
-
/**
|
|
1601
|
-
* Links into this box (#98, `kvbox vm link`): box `owner/name`, at `ip`, may open TCP connections to
|
|
1602
|
-
* `port`. The rule is open while this box runs, rebuilt from here at every boot; `ip` is the other
|
|
1603
|
-
* box's, fixed for its life, and checked against its meta.json before a rule opens. `stale`: that box
|
|
1604
|
-
* was removed but the rule would not close; kept only so this box's next stop closes it, never opened
|
|
1605
|
-
* again, never listed (a new box of the same name may get the same IP). Absent: none.
|
|
1147
|
+
* Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
|
|
1148
|
+
* serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
|
|
1606
1149
|
*/
|
|
1607
|
-
|
|
1150
|
+
connect: z4.string().optional()
|
|
1608
1151
|
});
|
|
1609
|
-
var
|
|
1610
|
-
/**
|
|
1152
|
+
var VolumeSchema = z4.object({
|
|
1153
|
+
/** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
1611
1154
|
id: z4.string(),
|
|
1612
1155
|
name: z4.string(),
|
|
1613
1156
|
owner: z4.string(),
|
|
1614
1157
|
sizeGib: z4.number().int(),
|
|
1615
|
-
|
|
1158
|
+
/** What the sparse file really occupies on the host. */
|
|
1159
|
+
usedBytes: z4.number().int(),
|
|
1160
|
+
attachedTo: z4.string().nullable(),
|
|
1161
|
+
createdAt: z4.string(),
|
|
1162
|
+
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
|
|
1163
|
+
ownerKind: z4.enum(["user", "org"]).optional(),
|
|
1164
|
+
/** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
|
|
1165
|
+
host: z4.string().optional()
|
|
1616
1166
|
});
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1167
|
+
var MAX_VOLUME_GIB = 4096;
|
|
1168
|
+
var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
1169
|
+
var VOLUME_NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
|
|
1170
|
+
var CreateVolumeRequest = z4.object({
|
|
1171
|
+
name: z4.string(),
|
|
1172
|
+
sizeGib: z4.number().int().min(1).max(MAX_VOLUME_GIB),
|
|
1173
|
+
/**
|
|
1174
|
+
* Through a control plane (#91): the box this volume is for, so it is made on that box's host; the
|
|
1175
|
+
* control plane requires it (a volume attaches only to a box on its own host, so one made for no box
|
|
1176
|
+
* could never attach) and the CLI attaches right after. A host ignores it.
|
|
1177
|
+
*/
|
|
1178
|
+
box: z4.string().optional()
|
|
1179
|
+
});
|
|
1180
|
+
var AttachVolumeRequest = z4.object({
|
|
1181
|
+
box: z4.string()
|
|
1182
|
+
});
|
|
1183
|
+
var EnvVarSchema = z4.object({
|
|
1184
|
+
name: z4.string(),
|
|
1185
|
+
value: z4.string().optional(),
|
|
1186
|
+
secret: z4.boolean(),
|
|
1187
|
+
updatedAt: z4.string()
|
|
1188
|
+
});
|
|
1189
|
+
var BoxEnvSchema = z4.object({
|
|
1190
|
+
box: z4.string(),
|
|
1191
|
+
vars: z4.array(EnvVarSchema)
|
|
1192
|
+
});
|
|
1193
|
+
var BoxEnvChangeSchema = z4.object({
|
|
1194
|
+
box: z4.string(),
|
|
1195
|
+
name: z4.string(),
|
|
1196
|
+
/** Whether the box is running now: the change waits for its next start. */
|
|
1197
|
+
running: z4.boolean()
|
|
1198
|
+
});
|
|
1199
|
+
var SetEnvRequest = z4.object({
|
|
1200
|
+
value: z4.string(),
|
|
1201
|
+
secret: z4.boolean().optional()
|
|
1202
|
+
});
|
|
1203
|
+
var EnvChangeSchema = z4.object({
|
|
1204
|
+
owner: z4.string(),
|
|
1205
|
+
name: z4.string(),
|
|
1206
|
+
boxes: z4.number().int()
|
|
1207
|
+
});
|
|
1208
|
+
var HostEnvRequest = z4.object({
|
|
1209
|
+
version: z4.number().int().min(0),
|
|
1210
|
+
vars: z4.array(z4.object({ name: z4.string(), value: z4.string() }))
|
|
1211
|
+
});
|
|
1212
|
+
var HostEnvVersionsSchema = z4.array(z4.object({ owner: z4.string(), version: z4.number().int() }));
|
|
1213
|
+
var CreateMachineRequest = z4.object({
|
|
1214
|
+
name: z4.string().optional(),
|
|
1215
|
+
/** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
|
|
1216
|
+
owner: z4.string().optional(),
|
|
1217
|
+
size: SizeSchema.optional(),
|
|
1218
|
+
from: z4.string().optional(),
|
|
1219
|
+
force: z4.boolean().optional(),
|
|
1220
|
+
/**
|
|
1221
|
+
* Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends
|
|
1222
|
+
* its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every
|
|
1223
|
+
* boot (#49); a host older than that ignores them.
|
|
1224
|
+
*/
|
|
1225
|
+
sshKeys: z4.array(z4.string()).optional(),
|
|
1226
|
+
/** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
|
|
1227
|
+
autoHibernateSec: z4.number().int().min(0).optional(),
|
|
1228
|
+
/**
|
|
1229
|
+
* Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
|
|
1230
|
+
* control plane reads it; a host has one place to put a box.
|
|
1231
|
+
*/
|
|
1232
|
+
near: z4.string().optional(),
|
|
1233
|
+
/**
|
|
1234
|
+
* Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
|
|
1235
|
+
* `@kvbox/shared/country`. Only the control plane reads it.
|
|
1236
|
+
*/
|
|
1237
|
+
country: z4.string().optional(),
|
|
1238
|
+
/** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
|
|
1239
|
+
image: z4.string().optional(),
|
|
1240
|
+
/** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
|
|
1241
|
+
env: z4.array(z4.object({ name: z4.string(), value: z4.string() })).optional()
|
|
1242
|
+
});
|
|
1243
|
+
var ForkMachineRequest = z4.object({
|
|
1244
|
+
name: z4.string().optional(),
|
|
1245
|
+
/**
|
|
1246
|
+
* The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host
|
|
1247
|
+
* qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.
|
|
1248
|
+
*/
|
|
1249
|
+
owner: z4.string().optional(),
|
|
1250
|
+
/** A cold fork only: a warm one keeps the source's vCPU and memory. */
|
|
1251
|
+
size: SizeSchema.optional(),
|
|
1252
|
+
force: z4.boolean().optional(),
|
|
1253
|
+
/** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */
|
|
1254
|
+
sshKeys: z4.array(z4.string()).optional(),
|
|
1255
|
+
autoHibernateSec: z4.number().int().min(0).optional()
|
|
1256
|
+
});
|
|
1257
|
+
var SetSshKeysRequest = z4.object({
|
|
1258
|
+
sshKeys: z4.array(z4.string())
|
|
1259
|
+
});
|
|
1260
|
+
var RescaleMachineRequest = z4.object({
|
|
1261
|
+
size: SizeSchema.optional(),
|
|
1262
|
+
vcpu: z4.number().int().min(1).max(64).optional(),
|
|
1263
|
+
memMib: z4.number().int().min(256).optional(),
|
|
1264
|
+
diskGib: z4.number().int().min(1).optional(),
|
|
1265
|
+
/** Skip the capacity guard when a running box grows (#37). */
|
|
1266
|
+
force: z4.boolean().optional()
|
|
1267
|
+
});
|
|
1268
|
+
var StartMachineRequest = z4.object({
|
|
1269
|
+
force: z4.boolean().optional()
|
|
1270
|
+
});
|
|
1271
|
+
var SetMachineRequest = z4.object({
|
|
1272
|
+
/** Seconds without network traffic before the box is hibernated (#47); 0: never. */
|
|
1273
|
+
autoHibernateSec: z4.number().int().min(0).optional(),
|
|
1274
|
+
/** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
|
|
1275
|
+
idleCheck: z4.union([z4.literal(""), z4.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
|
|
1276
|
+
});
|
|
1277
|
+
var SnapshotSchema = z4.object({
|
|
1624
1278
|
name: z4.string(),
|
|
1625
1279
|
owner: z4.string(),
|
|
1626
|
-
/** The box it was taken from, as owner/name. */
|
|
1627
1280
|
source: z4.string(),
|
|
1281
|
+
// the box it was taken from, as owner/name
|
|
1628
1282
|
base: z4.string(),
|
|
1629
|
-
|
|
1283
|
+
// version of the image the overlay stacks on; a restore needs the same one
|
|
1284
|
+
/** As in MachineSchema: the image when it is not the base one (#87). */
|
|
1630
1285
|
image: z4.string().optional(),
|
|
1631
1286
|
vcpu: z4.number().int(),
|
|
1632
1287
|
memMib: z4.number().int(),
|
|
1633
1288
|
sizeBytes: z4.number().int(),
|
|
1634
|
-
|
|
1289
|
+
// what vmstate + mem + overlay really occupy on the host
|
|
1290
|
+
createdAt: z4.string()
|
|
1291
|
+
});
|
|
1292
|
+
var CreateSnapshotRequest = z4.object({
|
|
1293
|
+
box: z4.string(),
|
|
1294
|
+
name: z4.string(),
|
|
1295
|
+
/** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
|
|
1296
|
+
replace: z4.boolean().optional()
|
|
1297
|
+
});
|
|
1298
|
+
var DiskCapacitySchema = z4.object({
|
|
1299
|
+
totalGib: z4.number().int(),
|
|
1300
|
+
freeGib: z4.number().int(),
|
|
1301
|
+
volumesGib: z4.number().int(),
|
|
1302
|
+
volumesUsedGib: z4.number().int(),
|
|
1303
|
+
headroomGib: z4.number().int()
|
|
1304
|
+
});
|
|
1305
|
+
var CapacitySchema = z4.object({
|
|
1306
|
+
hostMemMib: z4.number().int(),
|
|
1307
|
+
hostCores: z4.number().int(),
|
|
1308
|
+
reservedMemMib: z4.number().int(),
|
|
1309
|
+
reservedVcpu: z4.number().int(),
|
|
1310
|
+
running: z4.number().int(),
|
|
1311
|
+
/** Absent on a host from before volumes (#91): it cannot take one. */
|
|
1312
|
+
disk: DiskCapacitySchema.optional(),
|
|
1635
1313
|
/**
|
|
1636
|
-
* The
|
|
1637
|
-
*
|
|
1638
|
-
* gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
|
|
1314
|
+
* The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
|
|
1315
|
+
* Absent on a host from before images: it has only the base.
|
|
1639
1316
|
*/
|
|
1640
|
-
|
|
1317
|
+
images: z4.array(z4.object({ name: z4.string(), version: z4.string() })).optional(),
|
|
1318
|
+
/** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */
|
|
1319
|
+
version: z4.string().optional()
|
|
1641
1320
|
});
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
}
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
}
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
}
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
}
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
var
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
}
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1321
|
+
var ImageSchema = z4.object({ name: z4.string(), version: z4.string().nullable() });
|
|
1322
|
+
var RecoveryReportSchema = z4.object({
|
|
1323
|
+
at: z4.string(),
|
|
1324
|
+
booted: z4.array(z4.string()),
|
|
1325
|
+
leftStopped: z4.array(z4.string()),
|
|
1326
|
+
failed: z4.array(z4.object({ box: z4.string(), error: z4.string() }))
|
|
1327
|
+
});
|
|
1328
|
+
var HostUpdateSchema = z4.object({
|
|
1329
|
+
state: z4.enum(["running", "done", "failed"]),
|
|
1330
|
+
startedAt: z4.string(),
|
|
1331
|
+
finishedAt: z4.string().nullable(),
|
|
1332
|
+
/** kvbox-server's version when the update started, and when it ended (null while running or when it failed before). */
|
|
1333
|
+
from: z4.string(),
|
|
1334
|
+
to: z4.string().nullable(),
|
|
1335
|
+
error: z4.string().nullable(),
|
|
1336
|
+
needsManual: z4.array(z4.string())
|
|
1337
|
+
});
|
|
1338
|
+
var HealthSchema = z4.object({
|
|
1339
|
+
ok: z4.literal(true),
|
|
1340
|
+
version: z4.string(),
|
|
1341
|
+
pid: z4.number().int(),
|
|
1342
|
+
/** Base image version new boxes get (null when the host has no usable base image yet). */
|
|
1343
|
+
base: z4.string().nullable(),
|
|
1344
|
+
/** Owner that boxes made over the local socket get (the Unix user running the server). */
|
|
1345
|
+
owner: z4.string(),
|
|
1346
|
+
/** The control plane this host joined (null when none). */
|
|
1347
|
+
controlPlane: z4.object({
|
|
1348
|
+
/** Realm name, e.g. kvbox.sh. */
|
|
1349
|
+
name: z4.string(),
|
|
1350
|
+
url: z4.string(),
|
|
1351
|
+
/** Where this host answers the control plane. */
|
|
1352
|
+
hostUrl: z4.string()
|
|
1353
|
+
}).nullable(),
|
|
1354
|
+
/** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */
|
|
1355
|
+
relay: z4.object({
|
|
1356
|
+
name: z4.string(),
|
|
1357
|
+
/** The public IP the relay owns for this host. */
|
|
1358
|
+
publicIp: z4.string(),
|
|
1359
|
+
/** The relay's WireGuard endpoint the tunnel dials. */
|
|
1360
|
+
endpoint: z4.string(),
|
|
1361
|
+
/** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */
|
|
1362
|
+
restarts: z4.number().int().optional(),
|
|
1363
|
+
lastRestartAt: z4.string().nullable().optional()
|
|
1364
|
+
}).nullable().optional(),
|
|
1365
|
+
/** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */
|
|
1366
|
+
recovery: RecoveryReportSchema.nullable().optional(),
|
|
1367
|
+
/** The last self-update; null when none ran. Older servers omit it. */
|
|
1368
|
+
update: HostUpdateSchema.nullable().optional()
|
|
1369
|
+
});
|
|
1370
|
+
var MachineUsageSchema = z4.object({
|
|
1371
|
+
name: z4.string(),
|
|
1372
|
+
owner: z4.string(),
|
|
1373
|
+
status: BoxStatusSchema,
|
|
1374
|
+
window: z4.object({ from: z4.string(), to: z4.string() }),
|
|
1375
|
+
seconds: z4.object({
|
|
1376
|
+
running: z4.number().int(),
|
|
1377
|
+
standby: z4.number().int(),
|
|
1378
|
+
hibernated: z4.number().int(),
|
|
1379
|
+
stopped: z4.number().int()
|
|
1380
|
+
}),
|
|
1381
|
+
vcpuHours: z4.number(),
|
|
1382
|
+
ramGibHours: z4.number(),
|
|
1383
|
+
diskGibHours: z4.number(),
|
|
1384
|
+
cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
|
|
1385
|
+
/** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */
|
|
1386
|
+
estimatedStops: z4.number().int(),
|
|
1387
|
+
historyFrom: z4.string().nullable()
|
|
1388
|
+
});
|
|
1389
|
+
var GuestStatsSchema = z4.object({
|
|
1390
|
+
/** Load average over 1, 5 and 15 minutes. */
|
|
1391
|
+
load: z4.tuple([z4.number(), z4.number(), z4.number()]),
|
|
1392
|
+
cpus: z4.number().int(),
|
|
1393
|
+
memTotalMib: z4.number().int(),
|
|
1394
|
+
/** Total minus available: page cache counts as free. */
|
|
1395
|
+
memUsedMib: z4.number().int(),
|
|
1396
|
+
/** The box's root, which is its overlay disk: the box's own writes, not the shared base. */
|
|
1397
|
+
diskTotalBytes: z4.number().int(),
|
|
1398
|
+
diskUsedBytes: z4.number().int(),
|
|
1399
|
+
uptimeSec: z4.number().int()
|
|
1400
|
+
});
|
|
1401
|
+
var MachineStatsSchema = z4.object({
|
|
1402
|
+
name: z4.string(),
|
|
1403
|
+
owner: z4.string(),
|
|
1404
|
+
stats: GuestStatsSchema.nullable()
|
|
1405
|
+
});
|
|
1406
|
+
var UsageStatusSchema = z4.enum([...BoxStatusSchema.options, "removed"]);
|
|
1407
|
+
var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({
|
|
1408
|
+
/** The host's box id; a name removed and recreated appears twice, with two ids. */
|
|
1409
|
+
id: z4.string(),
|
|
1410
|
+
status: UsageStatusSchema,
|
|
1411
|
+
/** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */
|
|
1412
|
+
ownerKind: z4.enum(["user", "org"]).optional(),
|
|
1413
|
+
/**
|
|
1414
|
+
* Through a control plane: the username that made the box (#60), absent when the box is gone from
|
|
1415
|
+
* the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.
|
|
1416
|
+
*/
|
|
1417
|
+
createdBy: z4.string().optional()
|
|
1418
|
+
});
|
|
1419
|
+
var VolumeUsageSchema = z4.object({
|
|
1420
|
+
/** The host's volume id; a name removed and made again appears twice, with two ids. */
|
|
1421
|
+
id: z4.string(),
|
|
1422
|
+
name: z4.string(),
|
|
1423
|
+
owner: z4.string(),
|
|
1424
|
+
ownerKind: z4.enum(["user", "org"]).optional(),
|
|
1425
|
+
/** The size at the end of the window (or when removed). */
|
|
1426
|
+
sizeGib: z4.number().int(),
|
|
1427
|
+
status: z4.enum(["present", "removed"]),
|
|
1428
|
+
volumeHours: z4.number(),
|
|
1429
|
+
volumeGibHours: z4.number(),
|
|
1430
|
+
cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
|
|
1431
|
+
historyFrom: z4.string().nullable()
|
|
1432
|
+
});
|
|
1433
|
+
var UsageReportSchema = z4.object({
|
|
1434
|
+
window: z4.object({ from: z4.string(), to: z4.string() }),
|
|
1435
|
+
boxes: z4.array(BoxUsageSchema),
|
|
1436
|
+
/** Absent from a side older than #91. */
|
|
1437
|
+
volumes: z4.array(VolumeUsageSchema).optional(),
|
|
1438
|
+
totals: z4.object({
|
|
1439
|
+
seconds: MachineUsageSchema.shape.seconds,
|
|
1440
|
+
vcpuHours: z4.number(),
|
|
1441
|
+
ramGibHours: z4.number(),
|
|
1442
|
+
diskGibHours: z4.number(),
|
|
1443
|
+
volumeHours: z4.number().optional(),
|
|
1444
|
+
volumeGibHours: z4.number().optional(),
|
|
1445
|
+
/** Boxes and volumes together. */
|
|
1446
|
+
cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional()
|
|
1447
|
+
})
|
|
1448
|
+
});
|
|
1449
|
+
var UsageEventRowSchema = z4.object({
|
|
1450
|
+
id: z4.number().int(),
|
|
1451
|
+
boxId: z4.string(),
|
|
1452
|
+
owner: z4.string(),
|
|
1453
|
+
name: z4.string(),
|
|
1454
|
+
at: z4.string(),
|
|
1455
|
+
state: z4.enum(["running", "standby", "hibernated", "stopped"]),
|
|
1456
|
+
vcpu: z4.number().int(),
|
|
1457
|
+
memMib: z4.number().int(),
|
|
1458
|
+
diskGib: z4.number().int(),
|
|
1459
|
+
by: z4.string()
|
|
1460
|
+
});
|
|
1461
|
+
var UsageEventsResponseSchema = z4.object({
|
|
1462
|
+
ledger: z4.string().min(1),
|
|
1463
|
+
events: z4.array(UsageEventRowSchema),
|
|
1464
|
+
next: z4.number().int()
|
|
1465
|
+
});
|
|
1466
|
+
var VolumeEventRowSchema = z4.object({
|
|
1467
|
+
id: z4.number().int(),
|
|
1468
|
+
volumeId: z4.string(),
|
|
1469
|
+
owner: z4.string(),
|
|
1470
|
+
name: z4.string(),
|
|
1471
|
+
at: z4.string(),
|
|
1472
|
+
sizeGib: z4.number().int(),
|
|
1473
|
+
by: z4.enum(["create", "resize", "rm"])
|
|
1474
|
+
});
|
|
1475
|
+
var VolumeEventsResponseSchema = z4.object({
|
|
1476
|
+
ledger: z4.string().min(1),
|
|
1477
|
+
events: z4.array(VolumeEventRowSchema),
|
|
1478
|
+
next: z4.number().int()
|
|
1479
|
+
});
|
|
1480
|
+
var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
|
|
1481
|
+
var ApiErrorCodeSchema = z4.enum(API_ERROR_CODES);
|
|
1482
|
+
var ApiErrorSchema = z4.object({
|
|
1483
|
+
error: z4.string(),
|
|
1484
|
+
code: ApiErrorCodeSchema.optional()
|
|
1485
|
+
});
|
|
1486
|
+
var ACTIVATED_BY = ["card", "admin"];
|
|
1487
|
+
var ActivatedBySchema = z4.enum(ACTIVATED_BY);
|
|
1488
|
+
var CloudUserSchema = z4.object({
|
|
1489
|
+
/** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */
|
|
1490
|
+
username: z4.string(),
|
|
1491
|
+
/** Display name, free text ("Alexandru Ghiura"). */
|
|
1492
|
+
name: z4.string(),
|
|
1493
|
+
/** Login identity, unique. */
|
|
1494
|
+
email: z4.string(),
|
|
1495
|
+
role: z4.enum(["admin", "user"]),
|
|
1496
|
+
createdAt: z4.string(),
|
|
1497
|
+
/**
|
|
1498
|
+
* False until a card is on file or an admin activates the account (#74): then only `/me` and
|
|
1499
|
+
* `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and
|
|
1500
|
+
* gates nobody, hence the defaults: a newer CLI must still parse its answers.
|
|
1501
|
+
*/
|
|
1502
|
+
active: z4.boolean().default(true),
|
|
1503
|
+
activatedBy: ActivatedBySchema.nullable().default(null)
|
|
1504
|
+
});
|
|
1505
|
+
var ORG_ROLES = ["owner", "admin", "member"];
|
|
1506
|
+
var OrgRoleSchema = z4.enum(ORG_ROLES);
|
|
1507
|
+
var CloudOrgSchema = z4.object({
|
|
1508
|
+
slug: z4.string(),
|
|
1509
|
+
/** Display name; the slug never changes, this may. */
|
|
1510
|
+
name: z4.string(),
|
|
1511
|
+
createdAt: z4.string(),
|
|
1512
|
+
/** An org pays for itself (#74): off until it has a card or an admin activates it; its boxes are 402. Defaults as on CloudUser. */
|
|
1513
|
+
active: z4.boolean().default(true),
|
|
1514
|
+
activatedBy: ActivatedBySchema.nullable().default(null)
|
|
1515
|
+
});
|
|
1516
|
+
var OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });
|
|
1517
|
+
var OrgMemberSchema = z4.object({
|
|
1518
|
+
username: z4.string(),
|
|
1519
|
+
name: z4.string(),
|
|
1520
|
+
role: OrgRoleSchema,
|
|
1521
|
+
addedAt: z4.string()
|
|
1522
|
+
});
|
|
1523
|
+
var OrgDetailSchema = CloudOrgSchema.extend({ members: z4.array(OrgMemberSchema) });
|
|
1524
|
+
var CreateOrgRequestSchema = z4.object({
|
|
1525
|
+
slug: z4.string().min(1),
|
|
1526
|
+
name: z4.string().min(1)
|
|
1527
|
+
});
|
|
1528
|
+
var RenameOrgRequestSchema = z4.object({ name: z4.string().min(1) });
|
|
1529
|
+
var AddMemberRequestSchema = z4.object({
|
|
1530
|
+
username: z4.string().min(1),
|
|
1531
|
+
role: OrgRoleSchema.default("member")
|
|
1532
|
+
});
|
|
1533
|
+
var SetRoleRequestSchema = z4.object({ role: OrgRoleSchema });
|
|
1534
|
+
var MeResponseSchema = CloudUserSchema.extend({ orgs: z4.array(OrgMembershipSchema) });
|
|
1535
|
+
var BalanceSchema = z4.object({
|
|
1536
|
+
slug: z4.string(),
|
|
1537
|
+
balance: z4.number(),
|
|
1538
|
+
currency: z4.string(),
|
|
1539
|
+
topUps: z4.number(),
|
|
1540
|
+
spent: z4.number(),
|
|
1541
|
+
/** The first moment usage counts from: the slug's first top-up; null when it has none. */
|
|
1542
|
+
since: z4.string().nullable(),
|
|
1543
|
+
/** When the slug ran out and its boxes were hibernated (the `sweep-credit` job); null in good standing. Absent from a control plane older than this field. */
|
|
1544
|
+
suspendedAt: z4.string().nullable().default(null)
|
|
1545
|
+
});
|
|
1546
|
+
var TopUpRequestSchema = z4.object({
|
|
1547
|
+
slug: z4.string().min(1),
|
|
1548
|
+
/** In the control plane's currency; negative corrects a mistake. */
|
|
1549
|
+
amount: z4.number().finite(),
|
|
1550
|
+
note: z4.string().max(200).optional()
|
|
1551
|
+
});
|
|
1552
|
+
var TopUpSchema = z4.object({
|
|
1553
|
+
id: z4.string(),
|
|
1554
|
+
slug: z4.string(),
|
|
1555
|
+
amount: z4.number(),
|
|
1556
|
+
currency: z4.string(),
|
|
1557
|
+
/** `transfer` (#93): an owner moving credit to an org they own, a negative row on their slug and a positive one on the org's. */
|
|
1558
|
+
source: z4.enum(["admin", "card", "trial", "transfer"]),
|
|
1559
|
+
note: z4.string().nullable(),
|
|
1560
|
+
at: z4.string()
|
|
1561
|
+
});
|
|
1562
|
+
var TOP_UP_AMOUNTS = [10, 25, 50, 100];
|
|
1563
|
+
var BillingInfoSchema = z4.object({
|
|
1564
|
+
card: z4.object({ brand: z4.string(), last4: z4.string() }).nullable(),
|
|
1565
|
+
cardInUse: z4.boolean(),
|
|
1566
|
+
balance: BalanceSchema
|
|
1567
|
+
});
|
|
1568
|
+
var BillingRedirectSchema = z4.object({ url: z4.string() });
|
|
1569
|
+
var TopUpCheckoutRequestSchema = z4.object({
|
|
1570
|
+
amount: z4.literal(TOP_UP_AMOUNTS)
|
|
1571
|
+
});
|
|
1572
|
+
var TransferRequestSchema = z4.object({
|
|
1573
|
+
org: z4.string().min(1),
|
|
1574
|
+
amount: z4.number().positive().multipleOf(0.01, "amount is in cents at most")
|
|
1575
|
+
});
|
|
1576
|
+
var TransferResponseSchema = z4.object({ from: BalanceSchema, to: BalanceSchema, activated: z4.boolean() });
|
|
1577
|
+
var LoginRequestSchema = z4.object({
|
|
1578
|
+
email: z4.string().min(1),
|
|
1579
|
+
password: z4.string().min(1),
|
|
1580
|
+
publicKey: z4.string().optional()
|
|
1581
|
+
});
|
|
1582
|
+
var SignupRequestSchema = z4.object({
|
|
1583
|
+
username: z4.string().min(1),
|
|
1584
|
+
name: z4.string().min(1),
|
|
1585
|
+
email: z4.string().min(1),
|
|
1586
|
+
password: z4.string().min(1)
|
|
1587
|
+
});
|
|
1588
|
+
var LoginResponseSchema = z4.object({
|
|
1589
|
+
token: z4.string(),
|
|
1590
|
+
user: CloudUserSchema,
|
|
1591
|
+
sshCert: z4.string().optional(),
|
|
1592
|
+
sshCertExpires: z4.string().optional(),
|
|
1593
|
+
/** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
|
|
1594
|
+
sshCertPrincipals: z4.array(z4.string()).optional()
|
|
1595
|
+
});
|
|
1596
|
+
var SshCertRequestSchema = z4.object({
|
|
1597
|
+
publicKey: z4.string().min(1)
|
|
1598
|
+
});
|
|
1599
|
+
var SshCertResponseSchema = z4.object({
|
|
1600
|
+
cert: z4.string(),
|
|
1601
|
+
expires: z4.string(),
|
|
1602
|
+
principals: z4.array(z4.string())
|
|
1603
|
+
});
|
|
1604
|
+
var SshCaResponseSchema = z4.object({
|
|
1605
|
+
publicKey: z4.string(),
|
|
1606
|
+
/** CAs replaced by `ca rotate` (#55), newest first; a box still holding one of these has not had `kvbox-server trust-ca` run on its host. */
|
|
1607
|
+
retired: z4.array(z4.object({ publicKey: z4.string(), retiredAt: z4.string() })).optional()
|
|
1608
|
+
});
|
|
1609
|
+
var HostSshCaResponseSchema = z4.object({
|
|
1610
|
+
publicKey: z4.string()
|
|
1611
|
+
});
|
|
1612
|
+
var CloudCaSchema = z4.object({
|
|
1613
|
+
controlPlane: z4.string(),
|
|
1614
|
+
publicKey: z4.string(),
|
|
1615
|
+
fingerprint: z4.string()
|
|
1616
|
+
});
|
|
1617
|
+
var TrustCaRequestSchema = z4.object({
|
|
1618
|
+
publicKey: z4.string().min(1)
|
|
1619
|
+
});
|
|
1620
|
+
var SshKeysAppliedSchema = z4.enum(["now", "start", "wake", "resume", "later"]);
|
|
1621
|
+
var TrustCaReportSchema = z4.object({
|
|
1622
|
+
publicKey: z4.string(),
|
|
1623
|
+
fingerprint: z4.string(),
|
|
1624
|
+
/** The guest trusts the CA now. */
|
|
1625
|
+
updated: z4.array(z4.string()),
|
|
1626
|
+
/** meta.json has the line; the guest gets it at `when`. */
|
|
1627
|
+
pending: z4.array(z4.object({ box: z4.string(), when: SshKeysAppliedSchema, why: z4.string().optional() })),
|
|
1628
|
+
failed: z4.array(z4.object({ box: z4.string(), error: z4.string() })),
|
|
1629
|
+
/** Local boxes, untouched: they trust the host's key only. */
|
|
1630
|
+
local: z4.number().int()
|
|
1631
|
+
});
|
|
1632
|
+
var HostJoinRequestSchema = z4.object({
|
|
1633
|
+
token: z4.string().min(1),
|
|
1634
|
+
name: z4.string().min(1),
|
|
1635
|
+
url: z4.string().url(),
|
|
1636
|
+
fingerprint: z4.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
|
|
1637
|
+
publicAddress: z4.string().min(1),
|
|
1638
|
+
/** Where the host is (`kvbox-server join --country`): a code or an English name. */
|
|
1639
|
+
country: z4.string().optional()
|
|
1640
|
+
});
|
|
1641
|
+
var HostJoinResponseSchema = z4.object({
|
|
1642
|
+
hostSecret: z4.string(),
|
|
1643
|
+
controlPlane: z4.object({ name: z4.string() })
|
|
1644
|
+
});
|
|
1645
|
+
var CloudHostSchema = z4.object({
|
|
1646
|
+
name: z4.string(),
|
|
1647
|
+
url: z4.string(),
|
|
1648
|
+
publicAddress: z4.string(),
|
|
1649
|
+
joinedAt: z4.string(),
|
|
1650
|
+
lastSeenAt: z4.string().nullable(),
|
|
1651
|
+
capacity: CapacitySchema.nullable(),
|
|
1652
|
+
/** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
|
|
1653
|
+
country: z4.string().nullable(),
|
|
1654
|
+
/** kvbox-server's version as of the poller's last look (`capacity.version`); null before one, or for a server older than 0.5.45. */
|
|
1655
|
+
version: z4.string().nullable()
|
|
1656
|
+
});
|
|
1657
|
+
var HostInfoSchema = z4.object({
|
|
1658
|
+
host: CloudHostSchema,
|
|
1659
|
+
health: HealthSchema.nullable(),
|
|
1660
|
+
error: z4.string().nullable()
|
|
1661
|
+
});
|
|
1662
|
+
var HostPatchRequest = z4.object({ country: z4.string().nullable() });
|
|
1663
|
+
var CountrySchema = z4.object({ code: z4.string(), name: z4.string() });
|
|
1870
1664
|
|
|
1871
|
-
// ../shared/src/
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1665
|
+
// ../shared/src/ssh.ts
|
|
1666
|
+
import { createHash } from "node:crypto";
|
|
1667
|
+
var SSH_PUBLIC_KEY_RE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com) ([A-Za-z0-9+/]+=*)(?: [^\r\n]*)?$/;
|
|
1668
|
+
function parseSshPublicKey(text) {
|
|
1669
|
+
const key = text.trim().replace(/^cert-authority\s+/, "");
|
|
1670
|
+
if (!SSH_PUBLIC_KEY_RE.test(key)) {
|
|
1671
|
+
throw new KvboxError("that is not an SSH public key; expected one line like: ssh-ed25519 AAAA\u2026 kvbox-ca@kvbox.sh");
|
|
1672
|
+
}
|
|
1673
|
+
return key;
|
|
1674
|
+
}
|
|
1675
|
+
function sshKeyFingerprint(publicKey) {
|
|
1676
|
+
const m = SSH_PUBLIC_KEY_RE.exec(publicKey.trim());
|
|
1677
|
+
if (!m) throw new KvboxError("cannot fingerprint: not an SSH public key");
|
|
1678
|
+
return `SHA256:${createHash("sha256").update(Buffer.from(m[2], "base64")).digest("base64").replace(/=+$/, "")}`;
|
|
1679
|
+
}
|
|
1680
|
+
function caLineFor(principal, caPublicKey) {
|
|
1681
|
+
return `cert-authority,principals="${principal}" ${caPublicKey}`;
|
|
1879
1682
|
}
|
|
1683
|
+
var isCaLine = (line) => /^cert-authority(,|\s)/.test(line.trim());
|
|
1880
1684
|
|
|
1881
1685
|
// src/core/agent.ts
|
|
1882
1686
|
import { connect } from "node:net";
|
|
1883
1687
|
var AGENT_PORT = 52;
|
|
1884
1688
|
async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
1885
|
-
const reply = await new Promise((
|
|
1689
|
+
const reply = await new Promise((resolve2, reject) => {
|
|
1886
1690
|
const sock = connect(udsPath);
|
|
1887
1691
|
let buf = "";
|
|
1888
1692
|
let handshaken = false;
|
|
@@ -1906,7 +1710,7 @@ async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
|
1906
1710
|
sock.write(JSON.stringify(req) + "\n");
|
|
1907
1711
|
} else {
|
|
1908
1712
|
sock.end();
|
|
1909
|
-
return
|
|
1713
|
+
return resolve2(line);
|
|
1910
1714
|
}
|
|
1911
1715
|
}
|
|
1912
1716
|
});
|
|
@@ -1951,7 +1755,7 @@ var isNoAgent = (err) => /vsock connect refused|vsock connection closed before t
|
|
|
1951
1755
|
|
|
1952
1756
|
// src/core/env.ts
|
|
1953
1757
|
import { existsSync } from "node:fs";
|
|
1954
|
-
import { copyFile, mkdir as
|
|
1758
|
+
import { copyFile, mkdir as mkdir2, readFile as readFile4, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
|
|
1955
1759
|
import { z as z5 } from "zod";
|
|
1956
1760
|
|
|
1957
1761
|
// ../shared/src/env.ts
|
|
@@ -1989,7 +1793,7 @@ async function withLock(key, fn) {
|
|
|
1989
1793
|
if (mine?.has(key)) return fn();
|
|
1990
1794
|
const previous = tails.get(key);
|
|
1991
1795
|
let release;
|
|
1992
|
-
const tail = new Promise((
|
|
1796
|
+
const tail = new Promise((resolve2) => release = resolve2);
|
|
1993
1797
|
tails.set(key, tail);
|
|
1994
1798
|
try {
|
|
1995
1799
|
await previous;
|
|
@@ -2006,6 +1810,25 @@ function locked(fn) {
|
|
|
2006
1810
|
return (...args) => withBoxLock(args[0], () => fn(...args));
|
|
2007
1811
|
}
|
|
2008
1812
|
|
|
1813
|
+
// src/core/log.ts
|
|
1814
|
+
function formatLine(level, message, at = /* @__PURE__ */ new Date()) {
|
|
1815
|
+
return `[${at.toISOString()}][${level}]: ${message}`;
|
|
1816
|
+
}
|
|
1817
|
+
var log = {
|
|
1818
|
+
debug(message) {
|
|
1819
|
+
console.error(formatLine("debug", message));
|
|
1820
|
+
},
|
|
1821
|
+
info(message) {
|
|
1822
|
+
console.log(formatLine("info", message));
|
|
1823
|
+
},
|
|
1824
|
+
warn(message) {
|
|
1825
|
+
console.error(formatLine("warn", message));
|
|
1826
|
+
},
|
|
1827
|
+
error(message) {
|
|
1828
|
+
console.error(formatLine("error", message));
|
|
1829
|
+
}
|
|
1830
|
+
};
|
|
1831
|
+
|
|
2009
1832
|
// src/core/env.ts
|
|
2010
1833
|
var OwnerEnvSchema = z5.object({
|
|
2011
1834
|
/** The control plane's counter for the list; only ever grows. */
|
|
@@ -2014,7 +1837,7 @@ var OwnerEnvSchema = z5.object({
|
|
|
2014
1837
|
});
|
|
2015
1838
|
async function readOwnerEnv(owner, p = paths()) {
|
|
2016
1839
|
try {
|
|
2017
|
-
return OwnerEnvSchema.parse(JSON.parse(await
|
|
1840
|
+
return OwnerEnvSchema.parse(JSON.parse(await readFile4(p.ownerEnv(owner), "utf8")));
|
|
2018
1841
|
} catch (err) {
|
|
2019
1842
|
if (err.code === "ENOENT") return null;
|
|
2020
1843
|
throw err;
|
|
@@ -2039,7 +1862,7 @@ async function readBoxEnv(box, p = paths()) {
|
|
|
2039
1862
|
}
|
|
2040
1863
|
async function readBoxEnvFile(file) {
|
|
2041
1864
|
try {
|
|
2042
|
-
return BoxEnvFileSchema.parse(JSON.parse(await
|
|
1865
|
+
return BoxEnvFileSchema.parse(JSON.parse(await readFile4(file, "utf8"))).vars;
|
|
2043
1866
|
} catch (err) {
|
|
2044
1867
|
if (err.code === "ENOENT") return [];
|
|
2045
1868
|
throw err;
|
|
@@ -2104,7 +1927,7 @@ async function setOwnerEnv(owner, req, p = paths()) {
|
|
|
2104
1927
|
const have = await readOwnerEnv(owner, p);
|
|
2105
1928
|
if (have !== null && have.version > req.version) return { version: have.version };
|
|
2106
1929
|
const file = p.ownerEnv(owner);
|
|
2107
|
-
await
|
|
1930
|
+
await mkdir2(p.env, { recursive: true, mode: 448 });
|
|
2108
1931
|
const tmp = `${file}.tmp`;
|
|
2109
1932
|
await writeFile3(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
|
|
2110
1933
|
await rename3(tmp, file);
|
|
@@ -2135,6 +1958,46 @@ import { existsSync as existsSync2 } from "node:fs";
|
|
|
2135
1958
|
import { readdir as readdir3, realpath } from "node:fs/promises";
|
|
2136
1959
|
import { basename } from "node:path";
|
|
2137
1960
|
import { z as z6 } from "zod";
|
|
1961
|
+
|
|
1962
|
+
// src/core/exec.ts
|
|
1963
|
+
import { execFile, spawn } from "node:child_process";
|
|
1964
|
+
import { openSync as openSync2 } from "node:fs";
|
|
1965
|
+
import { promisify } from "node:util";
|
|
1966
|
+
var execFileAsync = promisify(execFile);
|
|
1967
|
+
async function run(argv, opts = {}) {
|
|
1968
|
+
const [cmd, ...args] = opts.sudo ? ["sudo", "-n", ...argv] : argv;
|
|
1969
|
+
if (!cmd) throw new KvboxError("run: empty argv");
|
|
1970
|
+
if (process.env["KVBOX_DEBUG"]) log.debug(`exec ${[cmd, ...args].join(" ")}`);
|
|
1971
|
+
try {
|
|
1972
|
+
const { stdout, stderr } = await execFileAsync(cmd, args, {
|
|
1973
|
+
cwd: opts.cwd,
|
|
1974
|
+
env: opts.env ?? process.env,
|
|
1975
|
+
timeout: opts.timeoutMs ?? 3e4,
|
|
1976
|
+
maxBuffer: 8 * 1024 * 1024
|
|
1977
|
+
});
|
|
1978
|
+
return { stdout, stderr };
|
|
1979
|
+
} catch (err) {
|
|
1980
|
+
const e = err;
|
|
1981
|
+
if (typeof e.code === "number" && opts.okExitCodes?.includes(e.code)) return { stdout: e.stdout ?? "", stderr: e.stderr ?? "" };
|
|
1982
|
+
const detail = (e.stderr ?? e.message ?? "").trim();
|
|
1983
|
+
throw new KvboxError(`${[cmd, ...args].join(" ")} failed${detail ? `: ${detail}` : ""}`);
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
function spawnDetached(argv, logFile, env = process.env) {
|
|
1987
|
+
const [cmd, ...args] = argv;
|
|
1988
|
+
if (!cmd) throw new KvboxError("spawnDetached: empty argv");
|
|
1989
|
+
const out = openSync2(logFile, "a");
|
|
1990
|
+
const child = spawn(cmd, args, { detached: true, stdio: ["ignore", out, out], env });
|
|
1991
|
+
return new Promise((resolve2, reject) => {
|
|
1992
|
+
child.once("error", (err) => reject(new KvboxError(`${cmd} could not start: ${err.message}`)));
|
|
1993
|
+
child.once("spawn", () => {
|
|
1994
|
+
child.unref();
|
|
1995
|
+
resolve2(child.pid ?? -1);
|
|
1996
|
+
});
|
|
1997
|
+
});
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
// src/core/images.ts
|
|
2138
2001
|
var BASE_IMAGE = "base";
|
|
2139
2002
|
var IMAGE_RE = /^[a-z][a-z0-9-]{0,30}$/;
|
|
2140
2003
|
function baseVersionOf(file) {
|
|
@@ -2291,7 +2154,7 @@ function namesIn(text) {
|
|
|
2291
2154
|
|
|
2292
2155
|
// src/core/volumes.ts
|
|
2293
2156
|
import { existsSync as existsSync3, statSync } from "node:fs";
|
|
2294
|
-
import { lstat, mkdir as
|
|
2157
|
+
import { lstat, mkdir as mkdir3, readdir as readdir4, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
|
|
2295
2158
|
|
|
2296
2159
|
// ../shared/src/capacity.ts
|
|
2297
2160
|
var MEM_HEADROOM_MIB = 2048;
|
|
@@ -2397,7 +2260,7 @@ async function createVolume(req, owner, p = paths()) {
|
|
|
2397
2260
|
async function makeVolume(req, owner, p) {
|
|
2398
2261
|
const v = p.volume(owner, req.name);
|
|
2399
2262
|
if (existsSync3(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
|
|
2400
|
-
await
|
|
2263
|
+
await mkdir3(p.ownerVolumes(owner), { recursive: true, mode: 448 });
|
|
2401
2264
|
const disk = await diskCapacity(p);
|
|
2402
2265
|
if (!hasDiskRoom(disk, req.sizeGib)) {
|
|
2403
2266
|
throw new KvboxError(
|
|
@@ -2412,7 +2275,7 @@ async function makeVolume(req, owner, p) {
|
|
|
2412
2275
|
}
|
|
2413
2276
|
}
|
|
2414
2277
|
try {
|
|
2415
|
-
await
|
|
2278
|
+
await mkdir3(v.dir, { mode: 448 });
|
|
2416
2279
|
} catch (err) {
|
|
2417
2280
|
if (err.code === "EEXIST") throw new KvboxError(`volume ${req.name} already exists`);
|
|
2418
2281
|
throw err;
|
|
@@ -2592,7 +2455,7 @@ async function assertRoomFor(vcpu, memMib, force, box, by, p = paths()) {
|
|
|
2592
2455
|
}
|
|
2593
2456
|
|
|
2594
2457
|
// src/core/ext4.ts
|
|
2595
|
-
import { closeSync as closeSync2, openSync as
|
|
2458
|
+
import { closeSync as closeSync2, openSync as openSync3, readSync } from "node:fs";
|
|
2596
2459
|
var SUPERBLOCK_OFFSET = 1024;
|
|
2597
2460
|
var EXT4_MAGIC = 61267;
|
|
2598
2461
|
var INCOMPAT_META_BG = 16;
|
|
@@ -2600,7 +2463,7 @@ var INCOMPAT_64BIT = 128;
|
|
|
2600
2463
|
function ext4Usage(file) {
|
|
2601
2464
|
let fd;
|
|
2602
2465
|
try {
|
|
2603
|
-
fd =
|
|
2466
|
+
fd = openSync3(file, "r");
|
|
2604
2467
|
const sb = Buffer.alloc(1024);
|
|
2605
2468
|
if (readSync(fd, sb, 0, sb.length, SUPERBLOCK_OFFSET) !== sb.length) return null;
|
|
2606
2469
|
if (sb.readUInt16LE(56) !== EXT4_MAGIC) return null;
|
|
@@ -2631,10 +2494,10 @@ function ext4Usage(file) {
|
|
|
2631
2494
|
|
|
2632
2495
|
// src/core/snapshots.ts
|
|
2633
2496
|
import { existsSync as existsSync4 } from "node:fs";
|
|
2634
|
-
import { link, mkdir as
|
|
2497
|
+
import { link, mkdir as mkdir4, readdir as readdir5, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
|
|
2635
2498
|
|
|
2636
2499
|
// src/core/firecracker.ts
|
|
2637
|
-
import { Agent, request
|
|
2500
|
+
import { Agent, request } from "undici";
|
|
2638
2501
|
var FirecrackerClient = class {
|
|
2639
2502
|
constructor(socketPath) {
|
|
2640
2503
|
this.socketPath = socketPath;
|
|
@@ -2643,7 +2506,7 @@ var FirecrackerClient = class {
|
|
|
2643
2506
|
socketPath;
|
|
2644
2507
|
agent;
|
|
2645
2508
|
async call(method, path, body) {
|
|
2646
|
-
const res = await
|
|
2509
|
+
const res = await request(`http://localhost${path}`, {
|
|
2647
2510
|
dispatcher: this.agent,
|
|
2648
2511
|
method,
|
|
2649
2512
|
headers: body === void 0 ? {} : { "content-type": "application/json" },
|
|
@@ -2808,7 +2671,7 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
2808
2671
|
const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
|
|
2809
2672
|
const cfg = await loadConfig(p);
|
|
2810
2673
|
if (s !== final) await rm2(s.dir, { recursive: true, force: true });
|
|
2811
|
-
await
|
|
2674
|
+
await mkdir4(s.dir, { recursive: true, mode: 448 });
|
|
2812
2675
|
try {
|
|
2813
2676
|
const volumes = await captureDrivesOf(box, p);
|
|
2814
2677
|
await captureBox(box, s, cfg, p);
|
|
@@ -3111,8 +2974,8 @@ function stateMessage(ref, status) {
|
|
|
3111
2974
|
return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
|
|
3112
2975
|
}
|
|
3113
2976
|
function toMachine(meta, p = paths()) {
|
|
3114
|
-
const
|
|
3115
|
-
if (!
|
|
2977
|
+
const alive2 = vmAlive(meta);
|
|
2978
|
+
if (!alive2 && meta.pid !== null) {
|
|
3116
2979
|
try {
|
|
3117
2980
|
closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
|
|
3118
2981
|
} catch (err) {
|
|
@@ -3125,7 +2988,7 @@ function toMachine(meta, p = paths()) {
|
|
|
3125
2988
|
owner: meta.owner,
|
|
3126
2989
|
ip: meta.ip,
|
|
3127
2990
|
mac: meta.mac,
|
|
3128
|
-
pid:
|
|
2991
|
+
pid: alive2 ? meta.pid : null,
|
|
3129
2992
|
vcpu: meta.vcpu,
|
|
3130
2993
|
memMib: meta.memMib,
|
|
3131
2994
|
...diskStats(p.machine(meta.owner, meta.name).overlay),
|
|
@@ -3217,7 +3080,7 @@ async function waitFor(pred, timeoutMs, stepMs = 50) {
|
|
|
3217
3080
|
}
|
|
3218
3081
|
async function tailOf(file, lines = 5) {
|
|
3219
3082
|
try {
|
|
3220
|
-
return (await
|
|
3083
|
+
return (await readFile5(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
|
|
3221
3084
|
} catch {
|
|
3222
3085
|
return "";
|
|
3223
3086
|
}
|
|
@@ -3226,10 +3089,10 @@ async function spawnFirecracker(ref, cfg, p) {
|
|
|
3226
3089
|
const m = p.machine(ref.owner, ref.name);
|
|
3227
3090
|
await rm3(m.sock, { force: true });
|
|
3228
3091
|
await rm3(m.vsock, { force: true });
|
|
3229
|
-
const logFd =
|
|
3092
|
+
const logFd = openSync4(m.log, "a");
|
|
3230
3093
|
let child;
|
|
3231
3094
|
try {
|
|
3232
|
-
child =
|
|
3095
|
+
child = spawn2(cfg.firecracker, ["--api-sock", m.sock, "--id", ref.name, "--level", "Error"], {
|
|
3233
3096
|
cwd: m.dir,
|
|
3234
3097
|
detached: true,
|
|
3235
3098
|
stdio: ["ignore", logFd, logFd]
|
|
@@ -3306,7 +3169,7 @@ async function currentBaseVersion(p = paths()) {
|
|
|
3306
3169
|
}
|
|
3307
3170
|
async function readHostPubkey(p) {
|
|
3308
3171
|
try {
|
|
3309
|
-
return (await
|
|
3172
|
+
return (await readFile5(`${p.sshKey}.pub`, "utf8")).trim();
|
|
3310
3173
|
} catch {
|
|
3311
3174
|
throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);
|
|
3312
3175
|
}
|
|
@@ -3356,7 +3219,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
3356
3219
|
const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
|
|
3357
3220
|
const m = p.machine(owner, name);
|
|
3358
3221
|
await ensureHostNetwork(cfg);
|
|
3359
|
-
await
|
|
3222
|
+
await mkdir5(m.dir, { recursive: true, mode: 448 });
|
|
3360
3223
|
let tapCreated = false;
|
|
3361
3224
|
let pid;
|
|
3362
3225
|
let sshPort;
|
|
@@ -3444,7 +3307,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
3444
3307
|
const { id, ip, owner, name } = box;
|
|
3445
3308
|
const m = p.machine(owner, name);
|
|
3446
3309
|
await ensureHostNetwork(cfg);
|
|
3447
|
-
await
|
|
3310
|
+
await mkdir5(m.dir, { recursive: true, mode: 448 });
|
|
3448
3311
|
let tapCreated = false;
|
|
3449
3312
|
let pid;
|
|
3450
3313
|
let sshPort;
|
|
@@ -3793,7 +3656,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
3793
3656
|
if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
|
|
3794
3657
|
const m = p.machine(ref.owner, ref.name);
|
|
3795
3658
|
await rm3(m.hibernateDir, { recursive: true, force: true });
|
|
3796
|
-
await
|
|
3659
|
+
await mkdir5(m.hibernateDir, { recursive: true, mode: 448 });
|
|
3797
3660
|
const fc = new FirecrackerClient(m.sock);
|
|
3798
3661
|
try {
|
|
3799
3662
|
try {
|
|
@@ -4184,7 +4047,7 @@ async function bootRecovered(settled, p = paths()) {
|
|
|
4184
4047
|
// src/core/backups.ts
|
|
4185
4048
|
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
4186
4049
|
import { existsSync as existsSync7 } from "node:fs";
|
|
4187
|
-
import { mkdir as
|
|
4050
|
+
import { mkdir as mkdir6, open, readdir as readdir6, readFile as readFile6, rm as rm4, stat as stat3, statfs as statfs2, writeFile as writeFile6 } from "node:fs/promises";
|
|
4188
4051
|
import { basename as basename2, join as join2 } from "node:path";
|
|
4189
4052
|
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
4190
4053
|
|
|
@@ -4319,7 +4182,7 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4319
4182
|
const keys = backupKeys(req.key);
|
|
4320
4183
|
const s = p.backup(req.id);
|
|
4321
4184
|
await rm4(s.dir, { recursive: true, force: true });
|
|
4322
|
-
await
|
|
4185
|
+
await mkdir6(s.dir, { recursive: true, mode: 448 });
|
|
4323
4186
|
try {
|
|
4324
4187
|
const { meta, envText } = await withBoxLock(ref, async () => {
|
|
4325
4188
|
const meta2 = await readBox2(ref, p);
|
|
@@ -4341,7 +4204,7 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4341
4204
|
} else {
|
|
4342
4205
|
await copy();
|
|
4343
4206
|
}
|
|
4344
|
-
const envText2 = existsSync7(m.env) ? await
|
|
4207
|
+
const envText2 = existsSync7(m.env) ? await readFile6(m.env, "utf8") : null;
|
|
4345
4208
|
return { meta: meta2, envText: envText2 };
|
|
4346
4209
|
});
|
|
4347
4210
|
const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
|
|
@@ -4393,7 +4256,7 @@ async function uploadOnce(id, req, signal, p) {
|
|
|
4393
4256
|
const s = p.backup(id);
|
|
4394
4257
|
if (!existsSync7(s.chunks)) throw new NotFoundError(`backup ${id}`);
|
|
4395
4258
|
const keys = backupKeys(req.key);
|
|
4396
|
-
const { chunks } = JSON.parse(await
|
|
4259
|
+
const { chunks } = JSON.parse(await readFile6(s.chunks, "utf8"));
|
|
4397
4260
|
const slotOf = /* @__PURE__ */ new Map();
|
|
4398
4261
|
chunks.forEach((name, i) => {
|
|
4399
4262
|
if (name !== null && !slotOf.has(name)) slotOf.set(name, i);
|
|
@@ -4526,59 +4389,238 @@ async function pool(items, fn) {
|
|
|
4526
4389
|
await Promise.all(Array.from({ length: Math.min(PARALLEL, items.length) }, worker));
|
|
4527
4390
|
if (failed !== void 0) throw failed;
|
|
4528
4391
|
}
|
|
4529
|
-
async function withTries(what, fn, signal) {
|
|
4530
|
-
let last;
|
|
4531
|
-
for (let i = 0; i < TRIES; i++) {
|
|
4532
|
-
if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
|
|
4533
|
-
try {
|
|
4534
|
-
return await fn();
|
|
4535
|
-
} catch (err) {
|
|
4536
|
-
if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
|
|
4537
|
-
last = err;
|
|
4538
|
-
await sleep2(250 * 2 ** i);
|
|
4539
|
-
}
|
|
4540
|
-
}
|
|
4541
|
-
throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
|
|
4392
|
+
async function withTries(what, fn, signal) {
|
|
4393
|
+
let last;
|
|
4394
|
+
for (let i = 0; i < TRIES; i++) {
|
|
4395
|
+
if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
|
|
4396
|
+
try {
|
|
4397
|
+
return await fn();
|
|
4398
|
+
} catch (err) {
|
|
4399
|
+
if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
|
|
4400
|
+
last = err;
|
|
4401
|
+
await sleep2(250 * 2 ** i);
|
|
4402
|
+
}
|
|
4403
|
+
}
|
|
4404
|
+
throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
|
|
4405
|
+
}
|
|
4406
|
+
|
|
4407
|
+
// src/core/relay.ts
|
|
4408
|
+
import { access as access2, chmod as chmod3, mkdir as mkdir8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
|
|
4409
|
+
|
|
4410
|
+
// ../shared/src/relay.ts
|
|
4411
|
+
import { z as z7 } from "zod";
|
|
4412
|
+
var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
|
|
4413
|
+
var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
|
|
4414
|
+
var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
4415
|
+
var RelayJoinSchema = z7.object({
|
|
4416
|
+
v: z7.literal(1),
|
|
4417
|
+
/** How the relay lists this host. */
|
|
4418
|
+
name: z7.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
|
|
4419
|
+
/** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
|
|
4420
|
+
relay: z7.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
|
|
4421
|
+
/** The relay's WireGuard public key. */
|
|
4422
|
+
relayKey: z7.string().regex(WG_KEY_RE),
|
|
4423
|
+
/** This host's address inside the tunnel. */
|
|
4424
|
+
tunnelIp: z7.string().regex(IPV4_RE),
|
|
4425
|
+
/** This host's WireGuard private key, generated on the relay, kept nowhere else. */
|
|
4426
|
+
privateKey: z7.string().regex(WG_KEY_RE),
|
|
4427
|
+
/** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
|
|
4428
|
+
publicIp: z7.string().regex(IPV4_RE)
|
|
4429
|
+
});
|
|
4430
|
+
function decodeRelayJoin(text) {
|
|
4431
|
+
let parsed;
|
|
4432
|
+
try {
|
|
4433
|
+
parsed = JSON.parse(Buffer.from(text.trim(), "base64url").toString("utf8"));
|
|
4434
|
+
} catch {
|
|
4435
|
+
return null;
|
|
4436
|
+
}
|
|
4437
|
+
const res = RelayJoinSchema.safeParse(parsed);
|
|
4438
|
+
return res.success ? res.data : null;
|
|
4439
|
+
}
|
|
4440
|
+
|
|
4441
|
+
// src/core/controlPlane.ts
|
|
4442
|
+
import { X509Certificate } from "node:crypto";
|
|
4443
|
+
import { chmod as chmod2, mkdir as mkdir7, readFile as readFile7 } from "node:fs/promises";
|
|
4444
|
+
import { hostname as osHostname } from "node:os";
|
|
4445
|
+
import { request as request2 } from "undici";
|
|
4446
|
+
|
|
4447
|
+
// ../shared/src/country.ts
|
|
4448
|
+
var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
|
|
4449
|
+
var NOT_COUNTRIES = /* @__PURE__ */ new Set(["EU", "EZ", "UN", "QO", "XA", "XB", "ZZ"]);
|
|
4450
|
+
var ALIASES = { usa: "US", america: "US", uk: "GB", britain: "GB", england: "GB", holland: "NL" };
|
|
4451
|
+
var fold = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z]/g, "");
|
|
4452
|
+
var byName;
|
|
4453
|
+
function nameIndex() {
|
|
4454
|
+
if (byName) return byName;
|
|
4455
|
+
byName = new Map(Object.entries(ALIASES));
|
|
4456
|
+
for (let a = 65; a <= 90; a++) {
|
|
4457
|
+
for (let b = 65; b <= 90; b++) {
|
|
4458
|
+
const code = String.fromCharCode(a, b);
|
|
4459
|
+
const name = countryName(code);
|
|
4460
|
+
if (name !== void 0 && canonical(code) === code) byName.set(fold(name), code);
|
|
4461
|
+
}
|
|
4462
|
+
}
|
|
4463
|
+
return byName;
|
|
4464
|
+
}
|
|
4465
|
+
function canonical(code) {
|
|
4466
|
+
return /-([A-Z]{2})$/.exec(Intl.getCanonicalLocales(`und-${code}`)[0] ?? "")?.[1] ?? code;
|
|
4467
|
+
}
|
|
4468
|
+
function countryName(code) {
|
|
4469
|
+
if (!/^[A-Z]{2}$/.test(code) || NOT_COUNTRIES.has(code)) return void 0;
|
|
4470
|
+
return names.of(code);
|
|
4471
|
+
}
|
|
4472
|
+
function parseCountry(input) {
|
|
4473
|
+
const t = input.trim();
|
|
4474
|
+
const upper = t.toUpperCase();
|
|
4475
|
+
const code = countryName(upper) !== void 0 ? canonical(upper) : nameIndex().get(fold(t));
|
|
4476
|
+
if (code !== void 0) return code;
|
|
4477
|
+
throw new KvboxError(`unknown country "${input}": give its name or its two-letter code, e.g. RO or US`);
|
|
4478
|
+
}
|
|
4479
|
+
|
|
4480
|
+
// src/core/controlPlane.ts
|
|
4481
|
+
var DEFAULT_HTTPS_PORT = 7777;
|
|
4482
|
+
async function ensureTlsCert(p = paths()) {
|
|
4483
|
+
const have = await readFile7(p.tlsCert, "utf8").catch(() => null);
|
|
4484
|
+
const haveKey = await readFile7(p.tlsKey).then(() => true, () => false);
|
|
4485
|
+
if (have === null || !haveKey) {
|
|
4486
|
+
await mkdir7(p.tls, { recursive: true, mode: 448 });
|
|
4487
|
+
try {
|
|
4488
|
+
await run([
|
|
4489
|
+
"openssl",
|
|
4490
|
+
"req",
|
|
4491
|
+
"-x509",
|
|
4492
|
+
"-newkey",
|
|
4493
|
+
"ec",
|
|
4494
|
+
"-pkeyopt",
|
|
4495
|
+
"ec_paramgen_curve:prime256v1",
|
|
4496
|
+
"-nodes",
|
|
4497
|
+
"-keyout",
|
|
4498
|
+
p.tlsKey,
|
|
4499
|
+
"-out",
|
|
4500
|
+
p.tlsCert,
|
|
4501
|
+
"-subj",
|
|
4502
|
+
"/CN=kvbox-host",
|
|
4503
|
+
"-days",
|
|
4504
|
+
"3650"
|
|
4505
|
+
]);
|
|
4506
|
+
} catch (err) {
|
|
4507
|
+
throw new KvboxError(`could not make the host's certificate (is openssl installed?): ${err.message}`);
|
|
4508
|
+
}
|
|
4509
|
+
await chmod2(p.tlsKey, 384);
|
|
4510
|
+
}
|
|
4511
|
+
const pem = await readFile7(p.tlsCert, "utf8");
|
|
4512
|
+
return { fingerprint: new X509Certificate(pem).fingerprint256 };
|
|
4513
|
+
}
|
|
4514
|
+
function isPrivateAddress(ip) {
|
|
4515
|
+
const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(ip);
|
|
4516
|
+
if (!m) return false;
|
|
4517
|
+
const [a, b] = [Number(m[1]), Number(m[2])];
|
|
4518
|
+
return a === 10 || a === 127 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127;
|
|
4519
|
+
}
|
|
4520
|
+
async function defaultAdvertise() {
|
|
4521
|
+
const { stdout } = await run(["ip", "-4", "route", "get", "1.1.1.1"]).catch((err) => {
|
|
4522
|
+
throw new KvboxError(`cannot tell this host's address (${err.message}); pass --advertise <host-or-ip>`);
|
|
4523
|
+
});
|
|
4524
|
+
const m = /\bsrc\s+(\S+)/.exec(stdout);
|
|
4525
|
+
if (!m) throw new KvboxError("cannot tell this host's address from its routes; pass --advertise <host-or-ip>");
|
|
4526
|
+
return m[1];
|
|
4527
|
+
}
|
|
4528
|
+
async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdvertise) {
|
|
4529
|
+
const url = opts.url.replace(/\/+$/, "");
|
|
4530
|
+
const port = opts.port ?? DEFAULT_HTTPS_PORT;
|
|
4531
|
+
const cfg = await loadConfig(p);
|
|
4532
|
+
if (cfg.controlPlane) throw new KvboxError(`this host has already joined ${cfg.controlPlane.name} (${cfg.controlPlane.url}); run kvbox-server leave first`);
|
|
4533
|
+
let advertise = opts.advertise;
|
|
4534
|
+
if (advertise === void 0 && cfg.relay) {
|
|
4535
|
+
advertise = cfg.relay.publicIp;
|
|
4536
|
+
} else if (advertise === void 0) {
|
|
4537
|
+
advertise = await guessAddress();
|
|
4538
|
+
if (isPrivateAddress(advertise)) {
|
|
4539
|
+
throw new KvboxError(
|
|
4540
|
+
`${advertise} is a private address: a control plane on the internet cannot reach this host there.
|
|
4541
|
+
Pass --advertise <public host or ip>, or --advertise ${advertise} if the control plane is on the same network.`
|
|
4542
|
+
);
|
|
4543
|
+
}
|
|
4544
|
+
}
|
|
4545
|
+
const name = opts.name ?? osHostname();
|
|
4546
|
+
const country = opts.country === void 0 ? void 0 : parseCountry(opts.country);
|
|
4547
|
+
const { fingerprint } = await ensureTlsCert(p);
|
|
4548
|
+
const hostUrl = `https://${advertise}:${port}`;
|
|
4549
|
+
const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
|
|
4550
|
+
const res = await request2(`${url}/hosts/join`, {
|
|
4551
|
+
method: "POST",
|
|
4552
|
+
headers: { "content-type": "application/json" },
|
|
4553
|
+
body: JSON.stringify(body),
|
|
4554
|
+
headersTimeout: 1e4,
|
|
4555
|
+
bodyTimeout: 1e4
|
|
4556
|
+
}).catch((err) => {
|
|
4557
|
+
throw new KvboxError(`cannot reach ${url} (${err.message})`);
|
|
4558
|
+
});
|
|
4559
|
+
const text = await res.body.text();
|
|
4560
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
4561
|
+
throw new KvboxError(errorIn(text) ?? `control plane answered ${res.statusCode}`);
|
|
4562
|
+
}
|
|
4563
|
+
const parsed = HostJoinResponseSchema.safeParse(jsonOrNull(text));
|
|
4564
|
+
if (!parsed.success) throw new KvboxError(`${url} did not answer like a kvbox control plane`);
|
|
4565
|
+
if (!REALM_RE.test(parsed.data.controlPlane.name)) {
|
|
4566
|
+
throw new KvboxError(`${url} calls itself "${parsed.data.controlPlane.name}", which cannot name a realm (letters, digits, '.', '-')`);
|
|
4567
|
+
}
|
|
4568
|
+
await saveConfig({ ...cfg, controlPlane: { url, name: parsed.data.controlPlane.name, secret: parsed.data.hostSecret, advertise, port } }, p);
|
|
4569
|
+
return { hostName: name, controlPlane: parsed.data.controlPlane.name, hostUrl };
|
|
4570
|
+
}
|
|
4571
|
+
async function fetchCloudCa(p = paths()) {
|
|
4572
|
+
const cfg = await loadConfig(p);
|
|
4573
|
+
const cp = cfg.controlPlane;
|
|
4574
|
+
if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no CA to fetch; paste the key instead: kvbox-server trust-ca <public-key>");
|
|
4575
|
+
const res = await request2(`${cp.url}/hosts/self/ssh-ca`, {
|
|
4576
|
+
headers: { authorization: `Bearer ${cp.secret}` },
|
|
4577
|
+
headersTimeout: 1e4,
|
|
4578
|
+
bodyTimeout: 1e4
|
|
4579
|
+
}).catch((err) => {
|
|
4580
|
+
throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
|
|
4581
|
+
});
|
|
4582
|
+
const text = await res.body.text();
|
|
4583
|
+
if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not answer /hosts/self/ssh-ca: it is older than this host; paste the key instead`);
|
|
4584
|
+
if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(errorIn(text) ?? `${cp.name} answered ${res.statusCode}`);
|
|
4585
|
+
const parsed = HostSshCaResponseSchema.safeParse(jsonOrNull(text));
|
|
4586
|
+
if (!parsed.success) throw new KvboxError(`${cp.name} did not answer with a CA key`);
|
|
4587
|
+
const publicKey = parseSshPublicKey(parsed.data.publicKey);
|
|
4588
|
+
return { controlPlane: cp.name, publicKey, fingerprint: sshKeyFingerprint(publicKey) };
|
|
4589
|
+
}
|
|
4590
|
+
async function leaveControlPlane(p = paths()) {
|
|
4591
|
+
const cfg = await loadConfig(p);
|
|
4592
|
+
const cp = cfg.controlPlane;
|
|
4593
|
+
if (!cp) throw new KvboxError("this host has not joined a control plane");
|
|
4594
|
+
const told = await request2(`${cp.url}/hosts/self`, {
|
|
4595
|
+
method: "DELETE",
|
|
4596
|
+
headers: { authorization: `Bearer ${cp.secret}` },
|
|
4597
|
+
headersTimeout: 3e3,
|
|
4598
|
+
bodyTimeout: 3e3
|
|
4599
|
+
}).then(async (res) => {
|
|
4600
|
+
await res.body.dump();
|
|
4601
|
+
return res.statusCode >= 200 && res.statusCode < 300;
|
|
4602
|
+
}).catch(() => false);
|
|
4603
|
+
const { controlPlane: _gone, ...rest } = cfg;
|
|
4604
|
+
await saveConfig(rest, p);
|
|
4605
|
+
return { controlPlane: cp.name, told };
|
|
4542
4606
|
}
|
|
4543
|
-
|
|
4544
|
-
// src/core/relay.ts
|
|
4545
|
-
import { access as access2, chmod as chmod3, mkdir as mkdir8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
|
|
4546
|
-
|
|
4547
|
-
// ../shared/src/relay.ts
|
|
4548
|
-
import { z as z7 } from "zod";
|
|
4549
|
-
var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
|
|
4550
|
-
var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
|
|
4551
|
-
var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
4552
|
-
var RelayJoinSchema = z7.object({
|
|
4553
|
-
v: z7.literal(1),
|
|
4554
|
-
/** How the relay lists this host. */
|
|
4555
|
-
name: z7.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
|
|
4556
|
-
/** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
|
|
4557
|
-
relay: z7.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
|
|
4558
|
-
/** The relay's WireGuard public key. */
|
|
4559
|
-
relayKey: z7.string().regex(WG_KEY_RE),
|
|
4560
|
-
/** This host's address inside the tunnel. */
|
|
4561
|
-
tunnelIp: z7.string().regex(IPV4_RE),
|
|
4562
|
-
/** This host's WireGuard private key, generated on the relay, kept nowhere else. */
|
|
4563
|
-
privateKey: z7.string().regex(WG_KEY_RE),
|
|
4564
|
-
/** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
|
|
4565
|
-
publicIp: z7.string().regex(IPV4_RE)
|
|
4566
|
-
});
|
|
4567
|
-
function decodeRelayJoin(text) {
|
|
4568
|
-
let parsed;
|
|
4607
|
+
function jsonOrNull(text) {
|
|
4569
4608
|
try {
|
|
4570
|
-
|
|
4609
|
+
return JSON.parse(text);
|
|
4571
4610
|
} catch {
|
|
4572
4611
|
return null;
|
|
4573
4612
|
}
|
|
4574
|
-
|
|
4575
|
-
|
|
4613
|
+
}
|
|
4614
|
+
function errorIn(text) {
|
|
4615
|
+
const v = jsonOrNull(text);
|
|
4616
|
+
if (v && typeof v === "object" && typeof v.error === "string") return v.error;
|
|
4617
|
+
return void 0;
|
|
4576
4618
|
}
|
|
4577
4619
|
|
|
4578
4620
|
// src/core/relay.ts
|
|
4579
4621
|
function relayConf(join3) {
|
|
4580
4622
|
return [
|
|
4581
|
-
"# kvbox relay tunnel: made by `kvbox
|
|
4623
|
+
"# kvbox relay tunnel: made by `kvbox-server relay`, installed by net-setup.sh. Do not edit.",
|
|
4582
4624
|
"[Interface]",
|
|
4583
4625
|
`PrivateKey = ${join3.privateKey}`,
|
|
4584
4626
|
`Address = ${join3.tunnelIp}/32`,
|
|
@@ -4599,11 +4641,11 @@ async function useRelay(joinString, p = paths()) {
|
|
|
4599
4641
|
if (!join3) throw new KvboxError("that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay");
|
|
4600
4642
|
const cfg = await loadConfig(p);
|
|
4601
4643
|
if (cfg.relay && cfg.relay.name !== join3.name) {
|
|
4602
|
-
throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox
|
|
4644
|
+
throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox-server relay off first`);
|
|
4603
4645
|
}
|
|
4604
4646
|
if (cfg.relay && cfg.relay.publicIp !== join3.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {
|
|
4605
4647
|
throw new KvboxError(
|
|
4606
|
-
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join3.publicIp}; run kvbox
|
|
4648
|
+
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join3.publicIp}; run kvbox-server leave first, then join again`
|
|
4607
4649
|
);
|
|
4608
4650
|
}
|
|
4609
4651
|
await mkdir8(p.relay, { recursive: true, mode: 448 });
|
|
@@ -4626,7 +4668,7 @@ async function dropRelay(p = paths()) {
|
|
|
4626
4668
|
const relay = cfg.relay;
|
|
4627
4669
|
if (!relay) throw new KvboxError("this host does not go through a relay");
|
|
4628
4670
|
if (cfg.controlPlane?.advertise === relay.publicIp) {
|
|
4629
|
-
throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox
|
|
4671
|
+
throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
|
|
4630
4672
|
}
|
|
4631
4673
|
await netSetup(cfg, ["relay", "down"]);
|
|
4632
4674
|
await rm5(p.relayConf, { force: true });
|
|
@@ -4802,8 +4844,264 @@ function startRelayWatch(opts = {}) {
|
|
|
4802
4844
|
};
|
|
4803
4845
|
}
|
|
4804
4846
|
|
|
4847
|
+
// src/daemon.ts
|
|
4848
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
4849
|
+
import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
|
|
4850
|
+
import { mkdir as mkdir9, readFile as readFile9, stat as stat4 } from "node:fs/promises";
|
|
4851
|
+
import { userInfo as userInfo2 } from "node:os";
|
|
4852
|
+
import { setTimeout as sleep3 } from "node:timers/promises";
|
|
4853
|
+
|
|
4854
|
+
// ../shared/src/systemd.ts
|
|
4855
|
+
import { spawnSync } from "node:child_process";
|
|
4856
|
+
import { readFileSync as readFileSync2 } from "node:fs";
|
|
4857
|
+
import { resolve } from "node:path";
|
|
4858
|
+
var UNIT = "kvbox-server";
|
|
4859
|
+
var UNIT_FILE = `/etc/systemd/system/${UNIT}.service`;
|
|
4860
|
+
function hasUnitFor(p, file = UNIT_FILE) {
|
|
4861
|
+
let text;
|
|
4862
|
+
try {
|
|
4863
|
+
text = readFileSync2(file, "utf8");
|
|
4864
|
+
} catch {
|
|
4865
|
+
return false;
|
|
4866
|
+
}
|
|
4867
|
+
const home = /^Environment="?KVBOX_HOME=([^"\n]+)"?$/m.exec(text)?.[1];
|
|
4868
|
+
return home !== void 0 && resolve(home) === resolve(p.home);
|
|
4869
|
+
}
|
|
4870
|
+
function startUnitProcess() {
|
|
4871
|
+
const res = spawnSync("sudo", ["-n", "systemctl", "start", UNIT], { encoding: "utf8" });
|
|
4872
|
+
return { ok: res.status === 0, out: `${res.stdout ?? ""}${res.stderr ?? ""}`.trim() };
|
|
4873
|
+
}
|
|
4874
|
+
function unitActive() {
|
|
4875
|
+
const res = spawnSync("systemctl", ["is-active", UNIT], { encoding: "utf8" });
|
|
4876
|
+
return (res.stdout ?? "").trim() === "active";
|
|
4877
|
+
}
|
|
4878
|
+
function unitPid() {
|
|
4879
|
+
const res = spawnSync("systemctl", ["show", UNIT, "-p", "MainPID", "--value"], { encoding: "utf8" });
|
|
4880
|
+
const pid = Number.parseInt((res.stdout ?? "").trim(), 10);
|
|
4881
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
4882
|
+
}
|
|
4883
|
+
function startsAtBoot(p) {
|
|
4884
|
+
return hasUnitFor(p) && spawnSync("systemctl", ["is-enabled", "--quiet", UNIT]).status === 0;
|
|
4885
|
+
}
|
|
4886
|
+
|
|
4887
|
+
// src/socketClient.ts
|
|
4888
|
+
import { Agent as Agent2, request as request3 } from "undici";
|
|
4889
|
+
var SocketClient = class {
|
|
4890
|
+
agent;
|
|
4891
|
+
constructor(socketPath) {
|
|
4892
|
+
this.agent = new Agent2({ connect: { socketPath } });
|
|
4893
|
+
}
|
|
4894
|
+
health() {
|
|
4895
|
+
return this.call("GET", "/health", HealthSchema);
|
|
4896
|
+
}
|
|
4897
|
+
cloudCa() {
|
|
4898
|
+
return this.call("GET", "/ssh/cloud-ca", CloudCaSchema);
|
|
4899
|
+
}
|
|
4900
|
+
trustCa(req) {
|
|
4901
|
+
return this.call("POST", "/ssh/trust-ca", TrustCaReportSchema, req);
|
|
4902
|
+
}
|
|
4903
|
+
async close() {
|
|
4904
|
+
await this.agent.close();
|
|
4905
|
+
}
|
|
4906
|
+
async call(method, path, schema, body) {
|
|
4907
|
+
let res;
|
|
4908
|
+
try {
|
|
4909
|
+
res = await request3(`http://kvbox-server${path}`, {
|
|
4910
|
+
method,
|
|
4911
|
+
dispatcher: this.agent,
|
|
4912
|
+
...body === void 0 ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }
|
|
4913
|
+
});
|
|
4914
|
+
} catch (err) {
|
|
4915
|
+
const code = err.code ?? "";
|
|
4916
|
+
if (code === "ENOENT" || code === "ECONNREFUSED") throw new KvboxError("kvbox-server is not running; start it with: kvbox-server start -d");
|
|
4917
|
+
throw new KvboxError(`cannot reach kvbox-server: ${err.message}`);
|
|
4918
|
+
}
|
|
4919
|
+
const text = await res.body.text();
|
|
4920
|
+
if (res.statusCode >= 300) {
|
|
4921
|
+
const parsed = ApiErrorSchema.safeParse(safeJson(text) ?? {});
|
|
4922
|
+
if (!parsed.success) throw new KvboxError(`kvbox-server answered ${res.statusCode}`);
|
|
4923
|
+
throw new KvboxError(parsed.data.error, res.statusCode === 501 ? 2 : 1);
|
|
4924
|
+
}
|
|
4925
|
+
const json = safeJson(text);
|
|
4926
|
+
if (json === void 0) throw new KvboxError(`kvbox-server answered ${res.statusCode} with something that is not JSON`);
|
|
4927
|
+
return schema.parse(json);
|
|
4928
|
+
}
|
|
4929
|
+
};
|
|
4930
|
+
function safeJson(text) {
|
|
4931
|
+
try {
|
|
4932
|
+
return JSON.parse(text);
|
|
4933
|
+
} catch {
|
|
4934
|
+
return void 0;
|
|
4935
|
+
}
|
|
4936
|
+
}
|
|
4937
|
+
|
|
4938
|
+
// src/daemon.ts
|
|
4939
|
+
async function runningPid(p = paths()) {
|
|
4940
|
+
let pid;
|
|
4941
|
+
try {
|
|
4942
|
+
pid = Number.parseInt(await readFile9(p.serverPid, "utf8"), 10);
|
|
4943
|
+
} catch {
|
|
4944
|
+
return null;
|
|
4945
|
+
}
|
|
4946
|
+
return Number.isInteger(pid) && alive(pid) ? pid : null;
|
|
4947
|
+
}
|
|
4948
|
+
async function daemonPid(p = paths()) {
|
|
4949
|
+
return await runningPid(p) ?? (hasUnitFor(p) ? unitPid() : null);
|
|
4950
|
+
}
|
|
4951
|
+
async function refuseSecondDaemon(p = paths()) {
|
|
4952
|
+
const live = await answering(p);
|
|
4953
|
+
if (live) throw new KvboxError(`kvbox-server is already running (pid ${live.pid}); kvbox-server status shows it`);
|
|
4954
|
+
const pid = await daemonPid(p);
|
|
4955
|
+
if (pid !== null && pid !== process.pid && isKvboxServer(pid)) {
|
|
4956
|
+
throw new KvboxError(`kvbox-server is already running (pid ${pid}) but its socket is gone, so nothing can reach it; restart it: kvbox-server stop, then kvbox-server start -d`);
|
|
4957
|
+
}
|
|
4958
|
+
}
|
|
4959
|
+
function isKvboxServer(pid) {
|
|
4960
|
+
try {
|
|
4961
|
+
return readFileSync3(`/proc/${pid}/cmdline`, "utf8").split("\0").slice(1).some((arg) => arg.includes("kvbox"));
|
|
4962
|
+
} catch (err) {
|
|
4963
|
+
return err.code !== "ENOENT";
|
|
4964
|
+
}
|
|
4965
|
+
}
|
|
4966
|
+
function alive(pid) {
|
|
4967
|
+
try {
|
|
4968
|
+
process.kill(pid, 0);
|
|
4969
|
+
return true;
|
|
4970
|
+
} catch {
|
|
4971
|
+
return false;
|
|
4972
|
+
}
|
|
4973
|
+
}
|
|
4974
|
+
async function stopDaemon(pid, timeoutMs = 1e4) {
|
|
4975
|
+
process.kill(pid, "SIGTERM");
|
|
4976
|
+
const deadline = Date.now() + timeoutMs;
|
|
4977
|
+
while (alive(pid)) {
|
|
4978
|
+
if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1e3}s`);
|
|
4979
|
+
await sleep3(100);
|
|
4980
|
+
}
|
|
4981
|
+
}
|
|
4982
|
+
async function answering(p = paths()) {
|
|
4983
|
+
if (!await stat4(p.serverSock).then(() => true, () => false)) return null;
|
|
4984
|
+
const probe = new SocketClient(p.serverSock);
|
|
4985
|
+
try {
|
|
4986
|
+
const health = await probe.health();
|
|
4987
|
+
return { pid: health.pid, version: health.version };
|
|
4988
|
+
} catch {
|
|
4989
|
+
return null;
|
|
4990
|
+
} finally {
|
|
4991
|
+
await probe.close();
|
|
4992
|
+
}
|
|
4993
|
+
}
|
|
4994
|
+
async function startDetached(p = paths(), timeoutMs = 5e3) {
|
|
4995
|
+
await mkdir9(p.home, { recursive: true });
|
|
4996
|
+
const running = await answering(p);
|
|
4997
|
+
if (running) return { pid: running.pid, socketPath: p.serverSock, viaGroup: void 0, viaUnit: false, alreadyRunning: running.version };
|
|
4998
|
+
if (hasUnitFor(p)) return startUnit(p, timeoutMs);
|
|
4999
|
+
const log2 = openSync5(p.serverLog, "a");
|
|
5000
|
+
const launcher = selfLauncher();
|
|
5001
|
+
const child = spawn3(launcher.cmd, launcher.args, { detached: true, stdio: ["ignore", log2, log2], env: { ...process.env, KVBOX_HOME: p.home } });
|
|
5002
|
+
const failed = new Promise((_, reject) => {
|
|
5003
|
+
child.once("error", (err) => reject(new KvboxError(`could not start kvbox-server: ${err.message}`)));
|
|
5004
|
+
child.once("exit", (code) => {
|
|
5005
|
+
void lastErrorLine(p.serverLog).then((why) => {
|
|
5006
|
+
reject(new KvboxError(why === void 0 ? `kvbox-server exited with code ${String(code)} before listening; see ${p.serverLog}` : `kvbox-server could not start: ${why}`));
|
|
5007
|
+
});
|
|
5008
|
+
});
|
|
5009
|
+
});
|
|
5010
|
+
await Promise.race([serving(p, timeoutMs), failed]);
|
|
5011
|
+
child.removeAllListeners("exit");
|
|
5012
|
+
child.unref();
|
|
5013
|
+
return { pid: await pidFile(p, child.pid ?? -1), socketPath: p.serverSock, viaGroup: launcher.viaGroup, viaUnit: false };
|
|
5014
|
+
}
|
|
5015
|
+
async function restartDaemon(p = paths()) {
|
|
5016
|
+
const pid = await runningPid(p);
|
|
5017
|
+
if (pid !== null) await stopDaemon(pid);
|
|
5018
|
+
return startDetached(p);
|
|
5019
|
+
}
|
|
5020
|
+
async function startUnit(p, timeoutMs) {
|
|
5021
|
+
const logFrom = await stat4(p.serverLog).then((s) => s.size, () => 0);
|
|
5022
|
+
const res = startUnitProcess();
|
|
5023
|
+
if (!res.ok) {
|
|
5024
|
+
const why = res.out || await lastErrorLine(p.serverLog, logFrom) || "systemctl start failed";
|
|
5025
|
+
throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT}; rerun install-server.sh if sudo asked for a password)`);
|
|
5026
|
+
}
|
|
5027
|
+
await serving(p, timeoutMs, async () => {
|
|
5028
|
+
if (unitActive()) return;
|
|
5029
|
+
const why = await lastErrorLine(p.serverLog, logFrom) ?? "it exited right after starting";
|
|
5030
|
+
throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT})`);
|
|
5031
|
+
});
|
|
5032
|
+
return { pid: await pidFile(p, -1), socketPath: p.serverSock, viaGroup: void 0, viaUnit: true };
|
|
5033
|
+
}
|
|
5034
|
+
async function pidFile(p, fallback) {
|
|
5035
|
+
const pid = Number.parseInt(await readFile9(p.serverPid, "utf8").catch(() => ""), 10);
|
|
5036
|
+
return Number.isNaN(pid) ? fallback : pid;
|
|
5037
|
+
}
|
|
5038
|
+
async function serving(p, timeoutMs, check) {
|
|
5039
|
+
const deadline = Date.now() + timeoutMs;
|
|
5040
|
+
while (Date.now() < deadline) {
|
|
5041
|
+
await check?.();
|
|
5042
|
+
if (await stat4(p.serverSock).then(() => true, () => false)) {
|
|
5043
|
+
const probe = new SocketClient(p.serverSock);
|
|
5044
|
+
try {
|
|
5045
|
+
await probe.health();
|
|
5046
|
+
return;
|
|
5047
|
+
} catch {
|
|
5048
|
+
} finally {
|
|
5049
|
+
await probe.close();
|
|
5050
|
+
}
|
|
5051
|
+
}
|
|
5052
|
+
await sleep3(100);
|
|
5053
|
+
}
|
|
5054
|
+
throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
|
|
5055
|
+
}
|
|
5056
|
+
async function lastErrorLine(logPath, from = 0) {
|
|
5057
|
+
const text = (await readFile9(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
|
|
5058
|
+
for (const line of text.trimEnd().split("\n").slice(-20).reverse()) {
|
|
5059
|
+
const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
|
|
5060
|
+
if (m?.[1] !== void 0) return m[1];
|
|
5061
|
+
}
|
|
5062
|
+
return void 0;
|
|
5063
|
+
}
|
|
5064
|
+
function selfLauncher(opts = {}) {
|
|
5065
|
+
const device = opts.device ?? KVM_DEVICE;
|
|
5066
|
+
const argv = [process.execPath, ...process.execArgv, process.argv[1] ?? "kvbox-server", "start"];
|
|
5067
|
+
const plain = { cmd: argv[0], args: argv.slice(1) };
|
|
5068
|
+
try {
|
|
5069
|
+
accessSync(device, constants2.R_OK | constants2.W_OK);
|
|
5070
|
+
return plain;
|
|
5071
|
+
} catch (err) {
|
|
5072
|
+
const code = err.code;
|
|
5073
|
+
if (code !== "EACCES" && code !== "EPERM") return plain;
|
|
5074
|
+
}
|
|
5075
|
+
let gid;
|
|
5076
|
+
try {
|
|
5077
|
+
gid = statSync3(device).gid;
|
|
5078
|
+
} catch {
|
|
5079
|
+
return plain;
|
|
5080
|
+
}
|
|
5081
|
+
const group = groupWithMember(gid, opts.user ?? userInfo2().username, opts.groupFile ?? "/etc/group");
|
|
5082
|
+
if (group === void 0) return plain;
|
|
5083
|
+
return { cmd: "sg", args: [group, "-c", argv.map(shellQuote).join(" ")], viaGroup: group };
|
|
5084
|
+
}
|
|
5085
|
+
function shellQuote(word) {
|
|
5086
|
+
return `'${word.replaceAll("'", `'\\''`)}'`;
|
|
5087
|
+
}
|
|
5088
|
+
function groupWithMember(gid, user, groupFile) {
|
|
5089
|
+
let text;
|
|
5090
|
+
try {
|
|
5091
|
+
text = readFileSync3(groupFile, "utf8");
|
|
5092
|
+
} catch {
|
|
5093
|
+
return void 0;
|
|
5094
|
+
}
|
|
5095
|
+
for (const line of text.split("\n")) {
|
|
5096
|
+
const [name, , id, members = ""] = line.split(":");
|
|
5097
|
+
if (name === void 0 || id === void 0 || Number.parseInt(id, 10) !== gid) continue;
|
|
5098
|
+
return members.split(",").includes(user) ? name : void 0;
|
|
5099
|
+
}
|
|
5100
|
+
return void 0;
|
|
5101
|
+
}
|
|
5102
|
+
|
|
4805
5103
|
// src/listen.ts
|
|
4806
|
-
import { readFile as
|
|
5104
|
+
import { readFile as readFile11, rm as rm6, writeFile as writeFile9 } from "node:fs/promises";
|
|
4807
5105
|
import { createServer as createHttpsServer } from "node:https";
|
|
4808
5106
|
import { createAdaptorServer } from "@hono/node-server";
|
|
4809
5107
|
|
|
@@ -4823,7 +5121,7 @@ function versionOf(srcFileUrl, injected) {
|
|
|
4823
5121
|
}
|
|
4824
5122
|
|
|
4825
5123
|
// src/version.ts
|
|
4826
|
-
var VERSION = versionOf(import.meta.url, true ? "0.5.
|
|
5124
|
+
var VERSION = versionOf(import.meta.url, true ? "0.5.45" : void 0);
|
|
4827
5125
|
|
|
4828
5126
|
// src/caller.ts
|
|
4829
5127
|
import { createHash as createHash2, timingSafeEqual } from "node:crypto";
|
|
@@ -4896,6 +5194,53 @@ function digest(secret) {
|
|
|
4896
5194
|
return createHash2("sha256").update(secret).digest();
|
|
4897
5195
|
}
|
|
4898
5196
|
|
|
5197
|
+
// src/core/update.ts
|
|
5198
|
+
import { mkdir as mkdir10, readFile as readFile10, writeFile as writeFile8 } from "node:fs/promises";
|
|
5199
|
+
var INSTALL_SERVER_URL = "https://kvbox.sh/install-server.sh";
|
|
5200
|
+
var UPDATE_STALE_MS = 60 * 6e4;
|
|
5201
|
+
async function readUpdateState(p = paths(), now = Date.now()) {
|
|
5202
|
+
let raw;
|
|
5203
|
+
try {
|
|
5204
|
+
raw = JSON.parse(await readFile10(p.updateState, "utf8"));
|
|
5205
|
+
} catch {
|
|
5206
|
+
return null;
|
|
5207
|
+
}
|
|
5208
|
+
const parsed = HostUpdateSchema.safeParse(raw);
|
|
5209
|
+
if (!parsed.success) return null;
|
|
5210
|
+
const u = parsed.data;
|
|
5211
|
+
if (u.state === "running" && now - Date.parse(u.startedAt) > UPDATE_STALE_MS) {
|
|
5212
|
+
return { ...u, state: "failed", error: `never finished; see ${p.updateLog}` };
|
|
5213
|
+
}
|
|
5214
|
+
return u;
|
|
5215
|
+
}
|
|
5216
|
+
async function startUpdate(version, p = paths(), deps = {}) {
|
|
5217
|
+
const current = await readUpdateState(p);
|
|
5218
|
+
if (current?.state === "running") throw new KvboxError(`an update is already running since ${current.startedAt}`);
|
|
5219
|
+
const url = deps.url ?? process.env["KVBOX_INSTALL_SERVER_URL"] ?? INSTALL_SERVER_URL;
|
|
5220
|
+
const res = await (deps.fetch ?? fetch)(url, { signal: AbortSignal.timeout(2e4) });
|
|
5221
|
+
if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);
|
|
5222
|
+
const script = await res.text();
|
|
5223
|
+
if (!script.startsWith("#!") || !script.includes("--update")) throw new KvboxError(`${url} is not an install-server.sh that knows --update`);
|
|
5224
|
+
await mkdir10(p.updateDir, { recursive: true });
|
|
5225
|
+
await writeFile8(p.updateScript, script, { mode: 448 });
|
|
5226
|
+
const state = { state: "running", startedAt: (/* @__PURE__ */ new Date()).toISOString(), finishedAt: null, from: version, to: null, error: null, needsManual: [] };
|
|
5227
|
+
await writeFile8(p.updateState, `${JSON.stringify(state, null, 2)}
|
|
5228
|
+
`);
|
|
5229
|
+
await writeFile8(p.updateLog, `--- ${state.startedAt} update from ${version}, ${url}
|
|
5230
|
+
`, { flag: "a" });
|
|
5231
|
+
const env = { ...process.env, KVBOX_HOME: p.home, KVBOX_YES: "1" };
|
|
5232
|
+
try {
|
|
5233
|
+
await (deps.spawn ?? spawnDetached)(["bash", p.updateScript, "--update"], p.updateLog, env);
|
|
5234
|
+
} catch (err) {
|
|
5235
|
+
const failed = { ...state, state: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error: err.message };
|
|
5236
|
+
await writeFile8(p.updateState, `${JSON.stringify(failed, null, 2)}
|
|
5237
|
+
`);
|
|
5238
|
+
throw err;
|
|
5239
|
+
}
|
|
5240
|
+
log.info(`update started from ${version}: install-server.sh --update, log in ${p.updateLog}`);
|
|
5241
|
+
return state;
|
|
5242
|
+
}
|
|
5243
|
+
|
|
4899
5244
|
// src/routes/backups.ts
|
|
4900
5245
|
import { Hono } from "hono";
|
|
4901
5246
|
function backupMachineRoutes() {
|
|
@@ -4930,14 +5275,14 @@ function backupRoutes() {
|
|
|
4930
5275
|
import { connect as connect2 } from "node:net";
|
|
4931
5276
|
import { Readable } from "node:stream";
|
|
4932
5277
|
import { Hono as Hono2 } from "hono";
|
|
4933
|
-
import { request as
|
|
5278
|
+
import { request as request4 } from "undici";
|
|
4934
5279
|
|
|
4935
5280
|
// ../shared/src/httpHead.ts
|
|
4936
5281
|
var END = "\r\n\r\n";
|
|
4937
5282
|
var HeadTimeoutError = class extends Error {
|
|
4938
5283
|
};
|
|
4939
5284
|
function readHead(socket, opts) {
|
|
4940
|
-
return new Promise((
|
|
5285
|
+
return new Promise((resolve2, reject) => {
|
|
4941
5286
|
let bytes = Buffer.alloc(0);
|
|
4942
5287
|
const done = (err) => {
|
|
4943
5288
|
clearTimeout(timer);
|
|
@@ -4946,7 +5291,7 @@ function readHead(socket, opts) {
|
|
|
4946
5291
|
socket.pause();
|
|
4947
5292
|
if (err) return reject(err);
|
|
4948
5293
|
const end = bytes.indexOf(END);
|
|
4949
|
-
|
|
5294
|
+
resolve2({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
|
|
4950
5295
|
};
|
|
4951
5296
|
const onData = (chunk) => {
|
|
4952
5297
|
bytes = Buffer.concat([bytes, chunk]);
|
|
@@ -5072,7 +5417,7 @@ async function forward(c, wake) {
|
|
|
5072
5417
|
raw.headers.forEach((value, name) => pairs.push([name, value]));
|
|
5073
5418
|
let res;
|
|
5074
5419
|
try {
|
|
5075
|
-
res = await
|
|
5420
|
+
res = await request4(`http://${target.ip}:${target.port}${target.path}`, {
|
|
5076
5421
|
method: raw.method,
|
|
5077
5422
|
headers: boxHeaders(pairs, target).flat(),
|
|
5078
5423
|
body: raw.body === null ? null : Readable.fromWeb(raw.body),
|
|
@@ -5177,7 +5522,7 @@ ${lines.join("")}\r
|
|
|
5177
5522
|
import { Hono as Hono3 } from "hono";
|
|
5178
5523
|
function capacityRoutes() {
|
|
5179
5524
|
const r = new Hono3();
|
|
5180
|
-
r.get("/", async (c) => c.json(await capacity()));
|
|
5525
|
+
r.get("/", async (c) => c.json({ ...await capacity(), version: VERSION }));
|
|
5181
5526
|
return r;
|
|
5182
5527
|
}
|
|
5183
5528
|
|
|
@@ -5347,7 +5692,7 @@ import { Hono as Hono7 } from "hono";
|
|
|
5347
5692
|
function sshRoutes(opts = {}) {
|
|
5348
5693
|
const r = new Hono7();
|
|
5349
5694
|
if (opts.controlPlane) {
|
|
5350
|
-
r.all("/*", (c) => c.json({ error: "trusting a CA is done on the host itself (kvbox
|
|
5695
|
+
r.all("/*", (c) => c.json({ error: "trusting a CA is done on the host itself (kvbox-server trust-ca there); the control plane cannot ask a host to" }, 403));
|
|
5351
5696
|
return r;
|
|
5352
5697
|
}
|
|
5353
5698
|
r.get("/cloud-ca", async (c) => c.json(await fetchCloudCa()));
|
|
@@ -5437,9 +5782,11 @@ function createApp(opts = {}) {
|
|
|
5437
5782
|
owner: cfg.owner,
|
|
5438
5783
|
controlPlane: cp ? { name: cp.name, url: cp.url, hostUrl: `https://${cp.advertise}:${cp.port}` } : null,
|
|
5439
5784
|
relay: cfg.relay ? { name: cfg.relay.name, publicIp: cfg.relay.publicIp, endpoint: cfg.relay.endpoint, ...relayWatchReport() } : null,
|
|
5440
|
-
recovery: lastRecovery()
|
|
5785
|
+
recovery: lastRecovery(),
|
|
5786
|
+
update: await readUpdateState()
|
|
5441
5787
|
});
|
|
5442
5788
|
});
|
|
5789
|
+
if (opts.controlPlane) app.post("/update", async (c) => c.json(await startUpdate(VERSION), 202));
|
|
5443
5790
|
if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
|
|
5444
5791
|
if (opts.controlPlane) {
|
|
5445
5792
|
app.route("/machines", backupMachineRoutes());
|
|
@@ -5472,19 +5819,20 @@ async function listen(opts = {}) {
|
|
|
5472
5819
|
if (Buffer.byteLength(socketPath) > 100) {
|
|
5473
5820
|
throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
|
|
5474
5821
|
}
|
|
5822
|
+
if (socketPath === p.serverSock) await refuseSecondDaemon(p);
|
|
5475
5823
|
await rm6(socketPath, { force: true });
|
|
5476
5824
|
const server = createAdaptorServer({ fetch: createApp().fetch });
|
|
5477
|
-
await new Promise((
|
|
5825
|
+
await new Promise((resolve2, reject) => {
|
|
5478
5826
|
server.once("error", reject);
|
|
5479
|
-
server.listen(socketPath, () =>
|
|
5827
|
+
server.listen(socketPath, () => resolve2());
|
|
5480
5828
|
});
|
|
5481
|
-
await
|
|
5829
|
+
await writeFile9(p.serverPid, `${process.pid}
|
|
5482
5830
|
`);
|
|
5483
5831
|
let https;
|
|
5484
5832
|
let httpsServer;
|
|
5485
5833
|
const cp = cfg.controlPlane;
|
|
5486
5834
|
if (cp) {
|
|
5487
|
-
const [key, cert] = await Promise.all([
|
|
5835
|
+
const [key, cert] = await Promise.all([readFile11(p.tlsKey), readFile11(p.tlsCert)]).catch((err) => {
|
|
5488
5836
|
throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
|
|
5489
5837
|
});
|
|
5490
5838
|
httpsServer = createAdaptorServer({
|
|
@@ -5494,9 +5842,9 @@ async function listen(opts = {}) {
|
|
|
5494
5842
|
});
|
|
5495
5843
|
httpsServer.on("upgrade", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));
|
|
5496
5844
|
const port = opts.httpsPort ?? cp.port;
|
|
5497
|
-
await new Promise((
|
|
5845
|
+
await new Promise((resolve2, reject) => {
|
|
5498
5846
|
httpsServer.once("error", reject);
|
|
5499
|
-
httpsServer.listen(port, "0.0.0.0", () =>
|
|
5847
|
+
httpsServer.listen(port, "0.0.0.0", () => resolve2());
|
|
5500
5848
|
}).catch(async (err) => {
|
|
5501
5849
|
server.close();
|
|
5502
5850
|
await rm6(socketPath, { force: true });
|
|
@@ -5508,8 +5856,8 @@ async function listen(opts = {}) {
|
|
|
5508
5856
|
}
|
|
5509
5857
|
const close = async () => {
|
|
5510
5858
|
await Promise.all([
|
|
5511
|
-
new Promise((
|
|
5512
|
-
httpsServer ? new Promise((
|
|
5859
|
+
new Promise((resolve2) => server.close(() => resolve2())),
|
|
5860
|
+
httpsServer ? new Promise((resolve2) => httpsServer.close(() => resolve2())) : void 0
|
|
5513
5861
|
]);
|
|
5514
5862
|
await rm6(socketPath, { force: true });
|
|
5515
5863
|
await rm6(p.serverPid, { force: true });
|
|
@@ -5527,10 +5875,21 @@ async function listen(opts = {}) {
|
|
|
5527
5875
|
return https ? { socketPath, server, https, close } : { socketPath, server, close };
|
|
5528
5876
|
}
|
|
5529
5877
|
|
|
5530
|
-
// src/
|
|
5878
|
+
// src/commands/start.ts
|
|
5531
5879
|
var daemon = false;
|
|
5532
|
-
var
|
|
5533
|
-
|
|
5880
|
+
var isDaemon = () => daemon;
|
|
5881
|
+
var startCommand = new Command("start").description("run the daemon in the foreground; -d starts it in the background and returns").option("-d, --detach", "start the daemon in the background (through systemd when install-server.sh set it up) and return once it answers").option("--socket <path>", "socket to listen on (default: $KVBOX_HOME/server.sock)").action(async (opts) => {
|
|
5882
|
+
if (opts.detach) {
|
|
5883
|
+
const started = await startDetached(paths());
|
|
5884
|
+
if (started.alreadyRunning !== void 0) {
|
|
5885
|
+
console.log(`kvbox-server ${started.alreadyRunning} is already running (pid ${started.pid})`);
|
|
5886
|
+
return;
|
|
5887
|
+
}
|
|
5888
|
+
console.log(`kvbox-server started (pid ${started.pid}), listening on ${started.socketPath}${started.viaUnit ? " (through systemd)" : ""}`);
|
|
5889
|
+
if (started.viaGroup !== void 0) console.log(`started through the ${started.viaGroup} group, which this shell does not have yet (log out and back in to get it)`);
|
|
5890
|
+
return;
|
|
5891
|
+
}
|
|
5892
|
+
if (opts.socket === void 0) await refuseSecondDaemon(paths());
|
|
5534
5893
|
daemon = true;
|
|
5535
5894
|
await requireKvm();
|
|
5536
5895
|
const settled = await settleDeadBoxes(paths());
|
|
@@ -5553,7 +5912,7 @@ program.command("start", { isDefault: true }).description("serve the API on the
|
|
|
5553
5912
|
const relay = await restoreRelay(paths());
|
|
5554
5913
|
if (relay) log.info(`relay ${relay.name}: the control plane may reach this host through the tunnel again`);
|
|
5555
5914
|
} catch (err) {
|
|
5556
|
-
log.warn(`the control plane may not reach this host through its relay (${err.message}); run: kvbox
|
|
5915
|
+
log.warn(`the control plane may not reach this host through its relay (${err.message}); run: kvbox-server relay <join string>`);
|
|
5557
5916
|
}
|
|
5558
5917
|
let dnsWarned = false;
|
|
5559
5918
|
const bindDns = () => {
|
|
@@ -5576,45 +5935,266 @@ program.command("start", { isDefault: true }).description("serve the API on the
|
|
|
5576
5935
|
for (const f of recovery2.failed) log.warn(`box ${f.box} was running when it went down and did not come back: ${f.error}`);
|
|
5577
5936
|
}
|
|
5578
5937
|
});
|
|
5579
|
-
|
|
5580
|
-
|
|
5938
|
+
|
|
5939
|
+
// src/program.ts
|
|
5940
|
+
import { Command as Command10 } from "commander";
|
|
5941
|
+
|
|
5942
|
+
// src/commands/join.ts
|
|
5943
|
+
import { Command as Command2 } from "commander";
|
|
5944
|
+
var joinCommand = new Command2("join").description("put this host behind a control plane (needs a one-time token minted there) and restart the daemon").argument("<control-plane-url>", "the control plane, e.g. https://api.kvbox.sh").requiredOption("--token <token>", "one-time join token from the control plane").option("--advertise <host-or-ip>", "address the control plane reaches this host at (default: this host's default-route address)").option("--name <name>", "how the control plane lists this host (default: hostname)").option("--country <country>", "where this host is, a name or a code (romania, US); kvbox new --country places boxes by it").action(async (url, opts) => {
|
|
5945
|
+
const p = paths();
|
|
5946
|
+
const joined = await joinControlPlane({ url, ...opts }, p);
|
|
5581
5947
|
console.log(`joined ${joined.controlPlane} as host ${joined.hostName}`);
|
|
5582
|
-
console.log(`it answers the control plane on ${joined.hostUrl} once its server restarts`);
|
|
5583
5948
|
console.log(`make sure port ${new URL(joined.hostUrl).port} is reachable from the control plane`);
|
|
5949
|
+
if (await runningPid(p) === null) {
|
|
5950
|
+
console.log(`it answers the control plane on ${joined.hostUrl} once the daemon starts (kvbox-server start -d)`);
|
|
5951
|
+
return;
|
|
5952
|
+
}
|
|
5953
|
+
const started = await restartDaemon(p);
|
|
5954
|
+
console.log(`kvbox-server restarted (pid ${started.pid}); it answers the control plane on ${joined.hostUrl} now`);
|
|
5584
5955
|
});
|
|
5585
|
-
|
|
5586
|
-
|
|
5587
|
-
|
|
5956
|
+
|
|
5957
|
+
// src/commands/leave.ts
|
|
5958
|
+
import { Command as Command3 } from "commander";
|
|
5959
|
+
var leaveCommand = new Command3("leave").description("take this host out from behind its control plane and restart the daemon").action(async () => {
|
|
5960
|
+
const p = paths();
|
|
5961
|
+
const left = await leaveControlPlane(p);
|
|
5962
|
+
console.log(`left ${left.controlPlane}`);
|
|
5588
5963
|
if (!left.told) console.log(`(the control plane could not be told; remove this host there)`);
|
|
5589
|
-
|
|
5590
|
-
|
|
5591
|
-
if (joinString === "off") {
|
|
5592
|
-
const relay2 = await dropRelay(paths());
|
|
5593
|
-
console.log(`tunnel to relay ${relay2.name} is down; this host no longer answers at ${relay2.publicIp}`);
|
|
5964
|
+
if (await runningPid(p) === null) {
|
|
5965
|
+
console.log("the HTTPS port stays closed from the daemon's next start");
|
|
5594
5966
|
return;
|
|
5595
5967
|
}
|
|
5596
|
-
const
|
|
5597
|
-
console.log(`
|
|
5598
|
-
|
|
5968
|
+
const started = await restartDaemon(p);
|
|
5969
|
+
console.log(`kvbox-server restarted (pid ${started.pid}); only this machine talks to it now`);
|
|
5970
|
+
});
|
|
5971
|
+
|
|
5972
|
+
// src/commands/logs.ts
|
|
5973
|
+
import { open as open2, readFile as readFile12, stat as stat5 } from "node:fs/promises";
|
|
5974
|
+
import { setTimeout as sleep4 } from "node:timers/promises";
|
|
5975
|
+
import { Command as Command4 } from "commander";
|
|
5976
|
+
var logsCommand = new Command4("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) => {
|
|
5977
|
+
const n = Number.parseInt(opts.lines, 10);
|
|
5978
|
+
if (!Number.isInteger(n) || n < 0) throw new KvboxError(`--lines: expected a number, got ${opts.lines}`);
|
|
5979
|
+
const p = paths();
|
|
5980
|
+
const text = await readFile12(p.serverLog, "utf8").catch((err) => {
|
|
5981
|
+
if (err.code === "ENOENT") throw new KvboxError(`no log yet at ${p.serverLog} (the daemon writes it once it has run)`);
|
|
5982
|
+
throw err;
|
|
5983
|
+
});
|
|
5984
|
+
const tail = tailLines(text, n);
|
|
5985
|
+
if (tail !== "") process.stdout.write(`${tail}
|
|
5986
|
+
`);
|
|
5987
|
+
if (!opts.follow) return;
|
|
5988
|
+
const ac = new AbortController();
|
|
5989
|
+
process.once("SIGINT", () => ac.abort());
|
|
5990
|
+
process.once("SIGTERM", () => ac.abort());
|
|
5991
|
+
await follow(p.serverLog, (chunk) => process.stdout.write(chunk), { from: Buffer.byteLength(text), signal: ac.signal });
|
|
5599
5992
|
});
|
|
5600
|
-
|
|
5993
|
+
function tailLines(text, n) {
|
|
5994
|
+
if (n === 0) return "";
|
|
5995
|
+
const lines = text.endsWith("\n") ? text.slice(0, -1).split("\n") : text.split("\n");
|
|
5996
|
+
return lines.slice(-n).join("\n");
|
|
5997
|
+
}
|
|
5998
|
+
async function follow(path, write, opts = {}) {
|
|
5999
|
+
const intervalMs = opts.intervalMs ?? 250;
|
|
6000
|
+
let offset = opts.from ?? await stat5(path).then((s) => s.size, () => 0);
|
|
6001
|
+
while (!opts.signal?.aborted) {
|
|
6002
|
+
const size = await stat5(path).then((s) => s.size, () => 0);
|
|
6003
|
+
if (size < offset) offset = 0;
|
|
6004
|
+
if (size > offset) {
|
|
6005
|
+
const fh = await open2(path, "r");
|
|
6006
|
+
try {
|
|
6007
|
+
const buf = Buffer.alloc(size - offset);
|
|
6008
|
+
const { bytesRead } = await fh.read(buf, 0, buf.length, offset);
|
|
6009
|
+
write(buf.subarray(0, bytesRead).toString("utf8"));
|
|
6010
|
+
offset += bytesRead;
|
|
6011
|
+
} finally {
|
|
6012
|
+
await fh.close();
|
|
6013
|
+
}
|
|
6014
|
+
}
|
|
6015
|
+
await sleep4(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
|
|
6016
|
+
}
|
|
6017
|
+
}
|
|
6018
|
+
|
|
6019
|
+
// src/commands/net.ts
|
|
6020
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
6021
|
+
import { Command as Command5 } from "commander";
|
|
6022
|
+
var netCommand = new Command5("net").description("host network: up | down | status (bridge, forwarding, NAT; uses sudo)").argument("<action>", "up, down or status").action(async (action) => {
|
|
5601
6023
|
if (!["up", "down", "status"].includes(action)) throw new KvboxError("net: expected up, down or status");
|
|
5602
6024
|
const cfg = await loadConfig(paths());
|
|
5603
|
-
const res =
|
|
6025
|
+
const res = spawnSync2(netSetupScript(), [action], {
|
|
5604
6026
|
stdio: "inherit",
|
|
5605
6027
|
env: { ...process.env, KVBOX_BRIDGE: cfg.bridge, KVBOX_SUBNET: cfg.subnet, KVBOX_GATEWAY: cfg.gateway }
|
|
5606
6028
|
});
|
|
5607
6029
|
process.exit(res.status ?? 1);
|
|
5608
6030
|
});
|
|
6031
|
+
|
|
6032
|
+
// src/commands/relay.ts
|
|
6033
|
+
import { Command as Command6 } from "commander";
|
|
6034
|
+
var relayCommand = new Command6("relay").description("reach the internet through a relay (paste what `kvbox-relay add` printed on the relay VM); `off` takes the tunnel down").argument("<join-string>", "the line `kvbox-relay add` printed, or `off`").action(async (joinString) => {
|
|
6035
|
+
if (joinString === "off") {
|
|
6036
|
+
const relay2 = await dropRelay(paths());
|
|
6037
|
+
console.log(`tunnel to relay ${relay2.name} is down; this host no longer answers at ${relay2.publicIp}`);
|
|
6038
|
+
return;
|
|
6039
|
+
}
|
|
6040
|
+
const relay = await useRelay(joinString, paths());
|
|
6041
|
+
console.log(`tunnel to relay ${relay.name} (${relay.endpoint}) is up`);
|
|
6042
|
+
console.log(`this host is reachable at ${relay.publicIp}; kvbox-server join advertises it by default`);
|
|
6043
|
+
});
|
|
6044
|
+
|
|
6045
|
+
// src/commands/status.ts
|
|
6046
|
+
import { homedir as homedir2 } from "node:os";
|
|
6047
|
+
import { styleText } from "node:util";
|
|
6048
|
+
import { Command as Command7 } from "commander";
|
|
6049
|
+
var statusCommand = new Command7("status").description("show whether the daemon is running, its control plane and which base image new boxes get").option("--json", "print as JSON").action(async (opts) => {
|
|
6050
|
+
const p = paths();
|
|
6051
|
+
const atBoot = startsAtBoot(p);
|
|
6052
|
+
const pid = await daemonPid(p);
|
|
6053
|
+
if (pid === null) {
|
|
6054
|
+
if (opts.json) {
|
|
6055
|
+
console.log(JSON.stringify({ running: false, startsAtBoot: atBoot }, null, 2));
|
|
6056
|
+
process.exitCode = 1;
|
|
6057
|
+
return;
|
|
6058
|
+
}
|
|
6059
|
+
throw new KvboxError(`kvbox-server is not running (start it with: kvbox-server start -d)${atBoot ? "; it starts at boot" : ""}`);
|
|
6060
|
+
}
|
|
6061
|
+
if (!await answering(p)) {
|
|
6062
|
+
if (opts.json) {
|
|
6063
|
+
console.log(JSON.stringify({ running: true, reachable: false, pid, startsAtBoot: atBoot }, null, 2));
|
|
6064
|
+
process.exitCode = 1;
|
|
6065
|
+
return;
|
|
6066
|
+
}
|
|
6067
|
+
throw new KvboxError(`kvbox-server is running (pid ${pid}) but its socket is gone, so nothing can reach it; restart it: kvbox-server stop, then kvbox-server start -d`);
|
|
6068
|
+
}
|
|
6069
|
+
const client = new SocketClient(p.serverSock);
|
|
6070
|
+
try {
|
|
6071
|
+
const health = await client.health();
|
|
6072
|
+
if (opts.json) {
|
|
6073
|
+
console.log(JSON.stringify({ running: true, ...health, startsAtBoot: atBoot }, null, 2));
|
|
6074
|
+
return;
|
|
6075
|
+
}
|
|
6076
|
+
printStatus(health, atBoot, p.serverLog);
|
|
6077
|
+
} finally {
|
|
6078
|
+
await client.close();
|
|
6079
|
+
}
|
|
6080
|
+
});
|
|
6081
|
+
function printStatus(health, atBoot, logPath) {
|
|
6082
|
+
const dim = (t) => styleText("dim", t, { stream: process.stdout });
|
|
6083
|
+
const rows = [];
|
|
6084
|
+
rows.push(["starts at boot", atBoot ? "yes, and brings back the boxes that were running" : `no ${dim("(install-server.sh sets that up)")}`]);
|
|
6085
|
+
if (health.controlPlane) {
|
|
6086
|
+
rows.push(["control plane", `${health.controlPlane.name} ${dim(`(${health.controlPlane.url})`)}`]);
|
|
6087
|
+
rows.push(["answers it on", health.controlPlane.hostUrl]);
|
|
6088
|
+
} else {
|
|
6089
|
+
rows.push(["control plane", `none ${dim("(kvbox-server join <url> --token <token>)")}`]);
|
|
6090
|
+
}
|
|
6091
|
+
if (health.relay) {
|
|
6092
|
+
rows.push(["relay", `${health.relay.name} lends this host ${health.relay.publicIp} ${dim(`(tunnel to ${health.relay.endpoint})`)}`]);
|
|
6093
|
+
if (health.relay.restarts && health.relay.lastRestartAt) {
|
|
6094
|
+
rows.push(["tunnel redialed", `${health.relay.restarts} time(s) since the server started, last at ${health.relay.lastRestartAt}`]);
|
|
6095
|
+
}
|
|
6096
|
+
}
|
|
6097
|
+
rows.push(["base image", health.base === null ? "none usable yet (run install-server.sh)" : `${health.base} ${dim("(what kvbox new uses)")}`]);
|
|
6098
|
+
const home = homedir2();
|
|
6099
|
+
rows.push(["log", `${logPath.startsWith(`${home}/`) ? `~${logPath.slice(home.length)}` : logPath} ${dim("(kvbox-server logs -f)")}`]);
|
|
6100
|
+
const r = health.recovery;
|
|
6101
|
+
const after = [];
|
|
6102
|
+
if (r) {
|
|
6103
|
+
if (r.booted.length > 0) after.push(["booted again", r.booted.join(", ")]);
|
|
6104
|
+
if (r.leftStopped.length > 0) after.push(["left stopped", `${r.leftStopped.join(", ")} ${dim("(were in standby, their memory was lost)")}`]);
|
|
6105
|
+
for (const f of r.failed) after.push(["did not come back", `${f.box} ${dim(`(${f.error})`)}`]);
|
|
6106
|
+
}
|
|
6107
|
+
const width = Math.max(...rows.map(([k]) => k.length));
|
|
6108
|
+
const line = ([k, v]) => console.log(` ${dim(k.padEnd(width))} ${v}`);
|
|
6109
|
+
console.log(`${styleText("bold", `kvbox-server ${health.version}`, { stream: process.stdout })} ${styleText("green", "\u25CF running", { stream: process.stdout })} ${dim(`(pid ${health.pid})`)}`);
|
|
6110
|
+
console.log();
|
|
6111
|
+
rows.forEach(line);
|
|
6112
|
+
if (after.length > 0) {
|
|
6113
|
+
console.log();
|
|
6114
|
+
console.log(" after the last restart");
|
|
6115
|
+
const w = Math.max(...after.map(([k]) => k.length));
|
|
6116
|
+
for (const [k, v] of after) console.log(` ${dim(k.padEnd(w))} ${v}`);
|
|
6117
|
+
}
|
|
6118
|
+
}
|
|
6119
|
+
|
|
6120
|
+
// src/commands/stop.ts
|
|
6121
|
+
import { Command as Command8 } from "commander";
|
|
6122
|
+
var stopCommand = new Command8("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
|
|
6123
|
+
const pid = await daemonPid(paths());
|
|
6124
|
+
if (pid === null) throw new KvboxError("kvbox-server is not running");
|
|
6125
|
+
await stopDaemon(pid);
|
|
6126
|
+
console.log(`kvbox-server stopped (pid ${pid}); boxes keep running`);
|
|
6127
|
+
});
|
|
6128
|
+
|
|
6129
|
+
// src/commands/trust-ca.ts
|
|
6130
|
+
import { Command as Command9 } from "commander";
|
|
6131
|
+
var trustCaCommand = new Command9("trust-ca").description("make every cloud box on this host trust a new SSH CA (after `ca rotate` on the control plane)").argument("[public-key]", "the CA public key (or its cert-authority line); or --from-cloud").option("--from-cloud", "ask the control plane this host joined for its current CA, show the fingerprint, then ask").option("-y, --yes", "do not ask for confirmation").option("--json", "print the report as JSON").action(async (publicKey, opts) => {
|
|
6132
|
+
if (publicKey === void 0 && !opts.fromCloud) throw new KvboxError("give the CA public key, or --from-cloud to fetch it from the control plane this host joined");
|
|
6133
|
+
if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
|
|
6134
|
+
const client = new SocketClient(paths().serverSock);
|
|
6135
|
+
try {
|
|
6136
|
+
let key = publicKey;
|
|
6137
|
+
if (key === void 0) {
|
|
6138
|
+
const ca = await client.cloudCa();
|
|
6139
|
+
console.log(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);
|
|
6140
|
+
if (!await confirm("make every cloud box on this host trust it (in place of the CA it trusts now)?", opts.yes ?? false)) {
|
|
6141
|
+
throw new KvboxError("cancelled", 130);
|
|
6142
|
+
}
|
|
6143
|
+
key = ca.publicKey;
|
|
6144
|
+
}
|
|
6145
|
+
const report2 = await client.trustCa({ publicKey: key });
|
|
6146
|
+
if (opts.json) console.log(JSON.stringify(report2, null, 2));
|
|
6147
|
+
else describeReport(report2);
|
|
6148
|
+
} finally {
|
|
6149
|
+
await client.close();
|
|
6150
|
+
}
|
|
6151
|
+
});
|
|
6152
|
+
async function confirm(question, yes) {
|
|
6153
|
+
if (yes) return true;
|
|
6154
|
+
if (!process.stdin.isTTY) {
|
|
6155
|
+
console.error("refusing without -y when stdin is not a terminal");
|
|
6156
|
+
return false;
|
|
6157
|
+
}
|
|
6158
|
+
const { createInterface } = await import("node:readline/promises");
|
|
6159
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
6160
|
+
try {
|
|
6161
|
+
const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
|
|
6162
|
+
return answer === "y" || answer === "yes";
|
|
6163
|
+
} finally {
|
|
6164
|
+
rl.close();
|
|
6165
|
+
}
|
|
6166
|
+
}
|
|
6167
|
+
var WHEN = {
|
|
6168
|
+
start: "is stopped: it trusts the CA from its next start",
|
|
6169
|
+
wake: "is hibernated: it trusts the CA from its next wake",
|
|
6170
|
+
resume: "is in standby: it trusts the CA from its next resume",
|
|
6171
|
+
later: "is running but could not take it now; it trusts the CA from its next stop and start"
|
|
6172
|
+
};
|
|
6173
|
+
function describeReport(report2) {
|
|
6174
|
+
console.log(`CA ${report2.fingerprint}`);
|
|
6175
|
+
for (const box of report2.updated) console.log(`box ${box} now trusts the CA`);
|
|
6176
|
+
for (const p of report2.pending) console.log(`box ${p.box} ${WHEN[p.when]}${p.why ? ` (${p.why})` : ""}`);
|
|
6177
|
+
for (const f of report2.failed) console.error(`box ${f.box}: ${f.error}`);
|
|
6178
|
+
const parts = [`${report2.updated.length} box(es) updated now`, `${report2.pending.length} pending`, `${report2.failed.length} failed`];
|
|
6179
|
+
if (report2.local > 0) parts.push(`${report2.local} local box(es) untouched (they trust this host's key only)`);
|
|
6180
|
+
console.log(parts.join(", "));
|
|
6181
|
+
}
|
|
6182
|
+
|
|
6183
|
+
// src/program.ts
|
|
6184
|
+
function buildProgram() {
|
|
6185
|
+
return new Command10("kvbox-server").description("kvbox host daemon: owns Firecracker and $KVBOX_HOME (~/.kvbox), serves the kvbox API").version(VERSION, "-v, --version").showHelpAfterError().addCommand(startCommand).addCommand(stopCommand).addCommand(statusCommand).addCommand(logsCommand).addCommand(joinCommand).addCommand(leaveCommand).addCommand(relayCommand).addCommand(trustCaCommand).addCommand(netCommand);
|
|
6186
|
+
}
|
|
6187
|
+
|
|
6188
|
+
// src/index.ts
|
|
5609
6189
|
try {
|
|
5610
|
-
await
|
|
6190
|
+
await buildProgram().parseAsync(process.argv);
|
|
5611
6191
|
} catch (err) {
|
|
5612
6192
|
if (err instanceof KvboxError) {
|
|
5613
|
-
if (
|
|
6193
|
+
if (isDaemon()) log.error(err.message);
|
|
5614
6194
|
else console.error(`error: ${err.message}`);
|
|
5615
6195
|
process.exit(err.exitCode);
|
|
5616
6196
|
}
|
|
5617
|
-
if (
|
|
6197
|
+
if (isDaemon()) {
|
|
5618
6198
|
log.error(err.stack ?? String(err));
|
|
5619
6199
|
process.exit(1);
|
|
5620
6200
|
}
|