@kvbox/server 0.5.43 → 0.5.44
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 +1835 -1402
- 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";
|
|
@@ -49,7 +48,7 @@ function paths(home = kvboxHome()) {
|
|
|
49
48
|
tls: join(home, "tls"),
|
|
50
49
|
tlsKey: join(home, "tls", "key.pem"),
|
|
51
50
|
tlsCert: join(home, "tls", "cert.pem"),
|
|
52
|
-
/** The host's WireGuard tunnel to its relay (`kvbox
|
|
51
|
+
/** The host's WireGuard tunnel to its relay (`kvbox-server relay`, #50): the conf net-setup.sh installs for wg-quick. Mode 600. */
|
|
53
52
|
relay: join(home, "relay"),
|
|
54
53
|
relayConf: join(home, "relay", "kvbox.conf"),
|
|
55
54
|
bin: join(home, "bin"),
|
|
@@ -454,1435 +453,1211 @@ async function loadConfig(p = paths()) {
|
|
|
454
453
|
}
|
|
455
454
|
}
|
|
456
455
|
|
|
457
|
-
// src/core/
|
|
458
|
-
import {
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
456
|
+
// src/core/kvm.ts
|
|
457
|
+
import { access, constants, readFile as readFile2, stat } from "node:fs/promises";
|
|
458
|
+
var KVM_DEVICE = "/dev/kvm";
|
|
459
|
+
async function groupName(gid, groupFile = "/etc/group") {
|
|
460
|
+
const text = await readFile2(groupFile, "utf8").catch(() => "");
|
|
461
|
+
for (const line of text.split("\n")) {
|
|
462
|
+
const [name, , id] = line.split(":");
|
|
463
|
+
if (id !== void 0 && Number.parseInt(id, 10) === gid && name) return name;
|
|
464
|
+
}
|
|
465
|
+
return "kvm";
|
|
466
|
+
}
|
|
467
|
+
async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
|
|
468
|
+
try {
|
|
469
|
+
await access(device, constants.R_OK | constants.W_OK);
|
|
470
|
+
return;
|
|
471
|
+
} catch (err) {
|
|
472
|
+
const code = err.code;
|
|
473
|
+
if (code === "ENOENT") {
|
|
474
|
+
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)`);
|
|
475
|
+
}
|
|
476
|
+
if (code !== "EACCES" && code !== "EPERM") throw new KvboxError(`cannot open ${device}: ${err.message}`);
|
|
477
|
+
}
|
|
478
|
+
const owner = await stat(device).then((s) => groupName(s.gid, groupFile), () => "kvm");
|
|
479
|
+
throw new KvboxError(
|
|
480
|
+
`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"`
|
|
481
|
+
);
|
|
482
|
+
}
|
|
462
483
|
|
|
463
|
-
//
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
484
|
+
// src/core/dns.ts
|
|
485
|
+
import { createSocket } from "node:dgram";
|
|
486
|
+
|
|
487
|
+
// src/core/state.ts
|
|
488
|
+
import { randomBytes } from "node:crypto";
|
|
489
|
+
import { readFileSync } from "node:fs";
|
|
490
|
+
import { mkdir, readFile as readFile3, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
491
|
+
import { z as z3 } from "zod";
|
|
492
|
+
|
|
493
|
+
// src/core/db.ts
|
|
494
|
+
import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs";
|
|
495
|
+
import { dirname } from "node:path";
|
|
496
|
+
import { DatabaseSync } from "node:sqlite";
|
|
497
|
+
var MIGRATIONS = [
|
|
498
|
+
`create table usage_events (
|
|
499
|
+
id integer primary key,
|
|
500
|
+
box_id text not null,
|
|
501
|
+
owner text not null,
|
|
502
|
+
name text not null,
|
|
503
|
+
at text not null,
|
|
504
|
+
state text not null,
|
|
505
|
+
vcpu integer not null,
|
|
506
|
+
mem_mib integer not null,
|
|
507
|
+
disk_gib integer not null,
|
|
508
|
+
by text not null
|
|
509
|
+
);
|
|
510
|
+
create index usage_events_box_at on usage_events (box_id, at);`,
|
|
511
|
+
// The ledger's identity (#42): a control plane keys pulled rows by it, so a re-join is recognised
|
|
512
|
+
// and a fresh ledger (KVBOX_HOME wiped) restarts its cursor instead of waiting for ids it already saw.
|
|
513
|
+
`create table ledger (id text not null);
|
|
514
|
+
insert into ledger (id) values (lower(hex(randomblob(16))));
|
|
515
|
+
create index usage_events_at on usage_events (at);`,
|
|
516
|
+
// Volumes (#91): a row per create, resize and rm, the size from that moment on. Its own table and
|
|
517
|
+
// ids, pulled by the control plane like usage_events, in the same ledger.
|
|
518
|
+
`create table volume_events (
|
|
519
|
+
id integer primary key,
|
|
520
|
+
volume_id text not null,
|
|
521
|
+
owner text not null,
|
|
522
|
+
name text not null,
|
|
523
|
+
at text not null,
|
|
524
|
+
size_gib integer not null,
|
|
525
|
+
by text not null
|
|
526
|
+
);
|
|
527
|
+
create index volume_events_volume_at on volume_events (volume_id, at);`
|
|
528
|
+
];
|
|
529
|
+
var handles = /* @__PURE__ */ new Map();
|
|
530
|
+
function openDb(p = paths()) {
|
|
531
|
+
const have = handles.get(p.db);
|
|
532
|
+
if (have !== void 0) return have;
|
|
533
|
+
mkdirSync(dirname(p.db), { recursive: true, mode: 448 });
|
|
534
|
+
closeSync(openSync(p.db, "a", 384));
|
|
535
|
+
chmodSync(p.db, 384);
|
|
536
|
+
const db = new DatabaseSync(p.db);
|
|
537
|
+
db.exec("pragma journal_mode = wal");
|
|
538
|
+
db.exec("pragma busy_timeout = 5000");
|
|
539
|
+
migrate(db);
|
|
540
|
+
handles.set(p.db, db);
|
|
541
|
+
return db;
|
|
542
|
+
}
|
|
543
|
+
function migrate(db) {
|
|
544
|
+
db.exec("create table if not exists schema_version (version integer not null)");
|
|
545
|
+
const row = db.prepare("select version from schema_version").get();
|
|
546
|
+
let version = row?.version ?? 0;
|
|
547
|
+
if (row === void 0) db.prepare("insert into schema_version (version) values (0)").run();
|
|
548
|
+
while (version < MIGRATIONS.length) {
|
|
549
|
+
db.exec("begin");
|
|
550
|
+
try {
|
|
551
|
+
db.exec(MIGRATIONS[version]);
|
|
552
|
+
version += 1;
|
|
553
|
+
db.prepare("update schema_version set version = ?").run(version);
|
|
554
|
+
db.exec("commit");
|
|
555
|
+
} catch (err) {
|
|
556
|
+
db.exec("rollback");
|
|
557
|
+
throw err;
|
|
477
558
|
}
|
|
478
559
|
}
|
|
479
|
-
return byName;
|
|
480
560
|
}
|
|
481
|
-
|
|
482
|
-
|
|
561
|
+
var LIVE_STATES = ["running", "standby"];
|
|
562
|
+
function fromRaw(r) {
|
|
563
|
+
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
564
|
}
|
|
484
|
-
function
|
|
485
|
-
|
|
486
|
-
return
|
|
565
|
+
function lastEvent(boxId, db) {
|
|
566
|
+
const raw = db.prepare("select * from usage_events where box_id = ? order by at desc, id desc limit 1").get(boxId);
|
|
567
|
+
return raw === void 0 ? void 0 : fromRaw(raw);
|
|
487
568
|
}
|
|
488
|
-
function
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
569
|
+
function insertRaw(e, db) {
|
|
570
|
+
db.prepare(
|
|
571
|
+
"insert into usage_events (box_id, owner, name, at, state, vcpu, mem_mib, disk_gib, by) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
572
|
+
).run(e.boxId, e.owner, e.name, e.at, e.state, e.vcpu, e.memMib, e.diskGib, e.by);
|
|
573
|
+
}
|
|
574
|
+
function insertUsageEvent(e, p = paths()) {
|
|
575
|
+
const db = openDb(p);
|
|
576
|
+
if (e.state === "running" && e.by !== "resume") closeOpenRun(e.boxId, e.at, p);
|
|
577
|
+
insertRaw(e, db);
|
|
578
|
+
}
|
|
579
|
+
function closeOpenRun(boxId, at, p = paths()) {
|
|
580
|
+
const db = openDb(p);
|
|
581
|
+
const last = lastEvent(boxId, db);
|
|
582
|
+
if (last === void 0 || !LIVE_STATES.includes(last.state)) return false;
|
|
583
|
+
insertRaw({ ...last, at, state: "stopped", by: "server" }, db);
|
|
584
|
+
return true;
|
|
585
|
+
}
|
|
586
|
+
function closeRunCutByBoot(boxId, bootAt, now, p = paths()) {
|
|
587
|
+
const last = lastEvent(boxId, openDb(p));
|
|
588
|
+
return closeOpenRun(boxId, last !== void 0 && last.at < bootAt ? bootAt : now, p);
|
|
589
|
+
}
|
|
590
|
+
function usageEventsFor(boxId, since, p = paths()) {
|
|
591
|
+
const rows = openDb(p).prepare("select * from usage_events where box_id = ? and at >= ? order by at, id").all(boxId, since);
|
|
592
|
+
return rows.map(fromRaw);
|
|
593
|
+
}
|
|
594
|
+
var withId = (r) => ({ ...fromRaw(r), id: r.id });
|
|
595
|
+
function ledgerId(p = paths()) {
|
|
596
|
+
return openDb(p).prepare("select id from ledger").get().id;
|
|
597
|
+
}
|
|
598
|
+
function usageEventsAfter(after, limit, scope, p = paths()) {
|
|
599
|
+
const db = openDb(p);
|
|
600
|
+
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);
|
|
601
|
+
return rows.map(withId);
|
|
602
|
+
}
|
|
603
|
+
function usageEventsInScope(scope, window, p = paths()) {
|
|
604
|
+
const rows = openDb(p).prepare(
|
|
605
|
+
`select * from usage_events where at < ? and (at >= ? or id in (select max(id) from usage_events where at < ? group by box_id))
|
|
606
|
+
order by at, id`
|
|
607
|
+
).all(window.to, window.from, window.from);
|
|
608
|
+
return rows.filter((r) => inScope(r.owner, scope)).map(withId);
|
|
609
|
+
}
|
|
610
|
+
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 });
|
|
611
|
+
function insertVolumeEvent(e, p = paths()) {
|
|
612
|
+
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);
|
|
613
|
+
}
|
|
614
|
+
function volumeEventsAfter(after, limit, scope, p = paths()) {
|
|
615
|
+
const db = openDb(p);
|
|
616
|
+
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);
|
|
617
|
+
return rows.map(volumeWithId);
|
|
618
|
+
}
|
|
619
|
+
function volumeEventsInScope(scope, window, p = paths()) {
|
|
620
|
+
const rows = openDb(p).prepare(
|
|
621
|
+
`select * from volume_events where at < ? and (at >= ? or id in (select max(id) from volume_events where at < ? group by volume_id))
|
|
622
|
+
order by at, id`
|
|
623
|
+
).all(window.to, window.from, window.from);
|
|
624
|
+
return rows.filter((r) => inScope(r.owner, scope)).map(volumeWithId);
|
|
494
625
|
}
|
|
495
626
|
|
|
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. */
|
|
627
|
+
// src/core/state.ts
|
|
628
|
+
var MachineMetaSchema = z3.object({
|
|
629
|
+
/** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */
|
|
603
630
|
id: z3.string(),
|
|
604
631
|
name: z3.string(),
|
|
605
|
-
/**
|
|
632
|
+
/** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */
|
|
606
633
|
owner: z3.string(),
|
|
607
634
|
ip: z3.string(),
|
|
608
635
|
mac: z3.string(),
|
|
609
636
|
pid: z3.number().int().nullable(),
|
|
637
|
+
// null: stopped on purpose, disk kept
|
|
638
|
+
/**
|
|
639
|
+
* The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot
|
|
640
|
+
* the number can name some other process; a pid from another boot is dead whatever `kill -0` says.
|
|
641
|
+
* Absent (boxes launched before #29): the pid alone decides.
|
|
642
|
+
*/
|
|
643
|
+
bootId: z3.string().optional(),
|
|
610
644
|
vcpu: z3.number().int(),
|
|
611
645
|
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
646
|
createdAt: z3.string(),
|
|
623
647
|
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`. */
|
|
648
|
+
/** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */
|
|
649
|
+
base: z3.string(),
|
|
650
|
+
/** The image (#87), when not the base one: assets/images/<image>/rootfs-<base>.ext4. `vm update` keeps it. */
|
|
651
|
+
image: z3.string().optional(),
|
|
652
|
+
/** The image's connect line with its secrets masked and `${BOX}` unfilled (#87, `maskedUrl`). Absent: the image declares none. */
|
|
657
653
|
url: z3.string().optional(),
|
|
658
654
|
/**
|
|
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.
|
|
655
|
+
* Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
|
|
656
|
+
* each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
|
|
657
|
+
* is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.
|
|
689
658
|
*/
|
|
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(),
|
|
659
|
+
memSnapshots: z3.number().int().optional(),
|
|
660
|
+
/** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */
|
|
661
|
+
paused: z3.boolean().optional(),
|
|
732
662
|
/**
|
|
733
|
-
*
|
|
734
|
-
*
|
|
735
|
-
*
|
|
663
|
+
* authorized_keys lines the box gets on top of the host's own key, as the control plane sent them
|
|
664
|
+
* at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so
|
|
665
|
+
* `start` has to send the same lines again. Absent: host key only.
|
|
736
666
|
*/
|
|
737
667
|
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
668
|
/**
|
|
741
|
-
*
|
|
742
|
-
*
|
|
669
|
+
* The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,
|
|
670
|
+
* or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.
|
|
743
671
|
*/
|
|
744
|
-
|
|
672
|
+
sshKeysStale: z3.boolean().optional(),
|
|
673
|
+
/** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */
|
|
674
|
+
sshPort: z3.number().int().optional(),
|
|
745
675
|
/**
|
|
746
|
-
*
|
|
747
|
-
*
|
|
676
|
+
* Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,
|
|
677
|
+
* each host port the box's for its life. DNATed while the box runs, rebuilt from here with its
|
|
678
|
+
* current IP every time it comes up. Absent: none.
|
|
748
679
|
*/
|
|
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(),
|
|
680
|
+
ports: z3.array(z3.object({ guestPort: z3.number().int(), hostPort: z3.number().int(), proto: z3.enum(["tcp", "udp"]) })).optional(),
|
|
681
|
+
/** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
|
|
682
|
+
autoHibernateSec: z3.number().int().positive().optional(),
|
|
757
683
|
/**
|
|
758
|
-
*
|
|
759
|
-
*
|
|
684
|
+
* A script inside the box auto-hibernate asks instead of watching the tap (#102, core/idle.ts): run by
|
|
685
|
+
* kvbox-agent, exit 0 = idle. A new box gets its image's `idle` (image.json); `kvbox vm set --idle-check`
|
|
686
|
+
* changes it. The one place the host looks. Absent: the traffic rule.
|
|
760
687
|
*/
|
|
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(),
|
|
688
|
+
idleCheck: z3.string().optional(),
|
|
825
689
|
/**
|
|
826
|
-
*
|
|
827
|
-
*
|
|
690
|
+
* Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
|
|
691
|
+
* their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
|
|
692
|
+
* volume's meta.json does not say. Absent: none.
|
|
828
693
|
*/
|
|
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(),
|
|
694
|
+
volumes: z3.array(z3.string()).optional(),
|
|
911
695
|
/**
|
|
912
|
-
*
|
|
913
|
-
*
|
|
696
|
+
* Links into this box (#98, `kvbox vm link`): box `owner/name`, at `ip`, may open TCP connections to
|
|
697
|
+
* `port`. The rule is open while this box runs, rebuilt from here at every boot; `ip` is the other
|
|
698
|
+
* box's, fixed for its life, and checked against its meta.json before a rule opens. `stale`: that box
|
|
699
|
+
* was removed but the rule would not close; kept only so this box's next stop closes it, never opened
|
|
700
|
+
* again, never listed (a new box of the same name may get the same IP). Absent: none.
|
|
914
701
|
*/
|
|
915
|
-
|
|
702
|
+
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
703
|
});
|
|
917
|
-
var
|
|
918
|
-
/**
|
|
704
|
+
var VolumeMetaSchema = z3.object({
|
|
705
|
+
/** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
919
706
|
id: z3.string(),
|
|
920
707
|
name: z3.string(),
|
|
921
708
|
owner: z3.string(),
|
|
922
|
-
ownerKind: z3.enum(["user", "org"]).optional(),
|
|
923
|
-
/** The size at the end of the window (or when removed). */
|
|
924
709
|
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
|
-
})
|
|
710
|
+
createdAt: z3.string()
|
|
946
711
|
});
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
712
|
+
function newBoxId(taken) {
|
|
713
|
+
for (; ; ) {
|
|
714
|
+
const id = randomBytes(3).toString("hex");
|
|
715
|
+
if (!taken.has(id)) return id;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
var SnapshotMetaSchema = z3.object({
|
|
951
719
|
name: z3.string(),
|
|
952
|
-
|
|
953
|
-
|
|
720
|
+
owner: z3.string(),
|
|
721
|
+
/** The box it was taken from, as owner/name. */
|
|
722
|
+
source: z3.string(),
|
|
723
|
+
base: z3.string(),
|
|
724
|
+
/** As in a box's meta.json (#87). */
|
|
725
|
+
image: z3.string().optional(),
|
|
954
726
|
vcpu: z3.number().int(),
|
|
955
727
|
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"]),
|
|
728
|
+
sizeBytes: z3.number().int(),
|
|
994
729
|
createdAt: z3.string(),
|
|
995
730
|
/**
|
|
996
|
-
*
|
|
997
|
-
*
|
|
998
|
-
*
|
|
731
|
+
* The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
|
|
732
|
+
* and their mounts in the memory image, but their data is not here. A box restored from the snapshot
|
|
733
|
+
* gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
|
|
999
734
|
*/
|
|
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")
|
|
735
|
+
volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int() })).optional()
|
|
1030
736
|
});
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
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)
|
|
1085
|
-
});
|
|
1086
|
-
var LoginResponseSchema = z3.object({
|
|
1087
|
-
token: z3.string(),
|
|
1088
|
-
user: CloudUserSchema,
|
|
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");
|
|
737
|
+
async function ensureLayout(p = paths()) {
|
|
738
|
+
for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
|
|
739
|
+
await mkdir(dir, { recursive: true, mode: 448 });
|
|
1163
740
|
}
|
|
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}`;
|
|
741
|
+
return p;
|
|
1173
742
|
}
|
|
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}`;
|
|
743
|
+
async function readJson(file, schema) {
|
|
744
|
+
return schema.parse(JSON.parse(await readFile3(file, "utf8")));
|
|
1183
745
|
}
|
|
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(" ")}`);
|
|
746
|
+
async function listDirs(dir) {
|
|
1205
747
|
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 };
|
|
748
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
749
|
+
return entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
|
1213
750
|
} catch (err) {
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
const detail = (e.stderr ?? e.message ?? "").trim();
|
|
1217
|
-
throw new KvboxError(`${[cmd, ...args].join(" ")} failed${detail ? `: ${detail}` : ""}`);
|
|
751
|
+
if (err.code === "ENOENT") return [];
|
|
752
|
+
throw err;
|
|
1218
753
|
}
|
|
1219
754
|
}
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
755
|
+
async function readMachineMeta(ref, p = paths()) {
|
|
756
|
+
return readJson(p.machine(ref.owner, ref.name).meta, MachineMetaSchema);
|
|
757
|
+
}
|
|
758
|
+
var boxListVersion = 0;
|
|
759
|
+
var boxListVersionNow = () => boxListVersion;
|
|
760
|
+
var boxListChanged = () => void (boxListVersion += 1);
|
|
761
|
+
async function writeMachineMeta(meta, p = paths()) {
|
|
762
|
+
const m = p.machine(meta.owner, meta.name);
|
|
763
|
+
await mkdir(m.dir, { recursive: true });
|
|
764
|
+
const tmp = `${m.meta}.tmp`;
|
|
765
|
+
await writeFile2(tmp, JSON.stringify(meta, null, 2) + "\n");
|
|
766
|
+
await rename2(tmp, m.meta);
|
|
767
|
+
boxListChanged();
|
|
768
|
+
}
|
|
769
|
+
async function listMachineRefs(p = paths()) {
|
|
770
|
+
return listRefs(p.machines);
|
|
771
|
+
}
|
|
772
|
+
async function readSnapshotMeta(ref, p = paths()) {
|
|
773
|
+
return readJson(p.snapshot(ref.owner, ref.name).meta, SnapshotMetaSchema);
|
|
774
|
+
}
|
|
775
|
+
async function writeSnapshotMeta(meta, p = paths(), s = p.snapshot(meta.owner, meta.name)) {
|
|
776
|
+
await mkdir(s.dir, { recursive: true });
|
|
777
|
+
await writeFile2(s.meta, JSON.stringify(meta, null, 2) + "\n");
|
|
778
|
+
}
|
|
779
|
+
async function listSnapshotRefs(p = paths()) {
|
|
780
|
+
return (await listRefs(p.snapshots)).filter((ref) => !ref.name.startsWith("."));
|
|
781
|
+
}
|
|
782
|
+
async function readVolumeMeta(ref, p = paths()) {
|
|
783
|
+
const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z3.string().optional() }));
|
|
784
|
+
if (raw.id !== void 0) return { ...raw, id: raw.id };
|
|
785
|
+
const taken = /* @__PURE__ */ new Set();
|
|
786
|
+
for (const other of await listVolumeRefs(p)) {
|
|
1228
787
|
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}`);
|
|
788
|
+
const j = JSON.parse(await readFile3(p.volume(other.owner, other.name).meta, "utf8"));
|
|
789
|
+
if (typeof j.id === "string") taken.add(j.id);
|
|
790
|
+
} catch {
|
|
1249
791
|
}
|
|
1250
|
-
await chmod2(p.tlsKey, 384);
|
|
1251
792
|
}
|
|
1252
|
-
const
|
|
1253
|
-
|
|
793
|
+
const meta = { ...raw, id: newBoxId(taken) };
|
|
794
|
+
await writeVolumeMeta(meta, p);
|
|
795
|
+
insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: meta.createdAt, sizeGib: meta.sizeGib, by: "create" }, p);
|
|
796
|
+
return meta;
|
|
1254
797
|
}
|
|
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;
|
|
798
|
+
async function writeVolumeMeta(meta, p = paths()) {
|
|
799
|
+
const v = p.volume(meta.owner, meta.name);
|
|
800
|
+
await mkdir(v.dir, { recursive: true, mode: 448 });
|
|
801
|
+
await writeFile2(v.meta, JSON.stringify(meta, null, 2) + "\n");
|
|
1260
802
|
}
|
|
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];
|
|
803
|
+
async function listVolumeRefs(p = paths()) {
|
|
804
|
+
return listRefs(p.volumes);
|
|
1268
805
|
}
|
|
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
|
-
);
|
|
806
|
+
async function listRefs(root) {
|
|
807
|
+
const out = [];
|
|
808
|
+
for (const owner of await listDirs(root)) {
|
|
809
|
+
for (const name of await listDirs(`${root}/${owner}`)) {
|
|
810
|
+
out.push({ owner, name });
|
|
1284
811
|
}
|
|
1285
812
|
}
|
|
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 };
|
|
813
|
+
return out;
|
|
1347
814
|
}
|
|
1348
|
-
function
|
|
815
|
+
function pidAlive(pid) {
|
|
816
|
+
if (pid === null || pid <= 0) return false;
|
|
1349
817
|
try {
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
818
|
+
process.kill(pid, 0);
|
|
819
|
+
return true;
|
|
820
|
+
} catch (err) {
|
|
821
|
+
return err.code === "EPERM";
|
|
1353
822
|
}
|
|
1354
823
|
}
|
|
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;
|
|
824
|
+
var bootId;
|
|
825
|
+
function currentBootId() {
|
|
826
|
+
if (bootId === void 0) {
|
|
827
|
+
try {
|
|
828
|
+
bootId = { id: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() };
|
|
829
|
+
} catch {
|
|
830
|
+
bootId = { id: void 0 };
|
|
831
|
+
}
|
|
1369
832
|
}
|
|
1370
|
-
return
|
|
833
|
+
return bootId.id;
|
|
1371
834
|
}
|
|
1372
|
-
|
|
835
|
+
function vmAlive(meta) {
|
|
836
|
+
if (meta.bootId !== void 0 && meta.bootId !== currentBootId()) return false;
|
|
837
|
+
return pidAlive(meta.pid);
|
|
838
|
+
}
|
|
839
|
+
function hostBootTime() {
|
|
1373
840
|
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}`);
|
|
841
|
+
const m = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
|
|
842
|
+
return m ? new Date(Number(m[1]) * 1e3) : null;
|
|
843
|
+
} catch {
|
|
844
|
+
return null;
|
|
1382
845
|
}
|
|
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
846
|
}
|
|
1388
847
|
|
|
1389
848
|
// 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
|
-
}
|
|
849
|
+
var DNS_PORT = 10053;
|
|
850
|
+
var DNS_SUFFIX = ".kvbox";
|
|
851
|
+
var DNS_RETRY_MS = 1e4;
|
|
852
|
+
var TTL_SEC = 5;
|
|
853
|
+
var BOXES_FRESH_MS = 6e4;
|
|
854
|
+
var TYPE_A = 1;
|
|
855
|
+
var CLASS_IN = 1;
|
|
856
|
+
var RCODE = { ok: 0, nxDomain: 3, refused: 5 };
|
|
857
|
+
function parseQuery(msg) {
|
|
858
|
+
if (msg.length < 12) return null;
|
|
859
|
+
const flags = msg.readUInt16BE(2);
|
|
860
|
+
const isResponse = flags & 32768;
|
|
861
|
+
const opcode = flags >> 11 & 15;
|
|
862
|
+
if (isResponse || opcode !== 0 || msg.readUInt16BE(4) < 1) return null;
|
|
863
|
+
const labels = [];
|
|
864
|
+
let at = 12;
|
|
865
|
+
for (; ; ) {
|
|
866
|
+
if (at >= msg.length) return null;
|
|
867
|
+
const len = msg[at];
|
|
868
|
+
at += 1;
|
|
869
|
+
if (len === 0) break;
|
|
870
|
+
if (len > 63 || at + len > msg.length) return null;
|
|
871
|
+
labels.push(msg.subarray(at, at + len).toString("latin1"));
|
|
872
|
+
at += len;
|
|
1464
873
|
}
|
|
874
|
+
if (at + 4 > msg.length) return null;
|
|
875
|
+
return {
|
|
876
|
+
id: msg.readUInt16BE(0),
|
|
877
|
+
rd: Boolean(flags & 256),
|
|
878
|
+
name: labels.join(".").toLowerCase(),
|
|
879
|
+
type: msg.readUInt16BE(at),
|
|
880
|
+
class: msg.readUInt16BE(at + 2),
|
|
881
|
+
question: msg.subarray(12, at + 4)
|
|
882
|
+
};
|
|
1465
883
|
}
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
884
|
+
function buildAnswer(q, rcode, ip) {
|
|
885
|
+
const header = Buffer.alloc(12);
|
|
886
|
+
header.writeUInt16BE(q.id, 0);
|
|
887
|
+
header.writeUInt16BE(32768 | 1024 | (q.rd ? 256 : 0) | rcode, 2);
|
|
888
|
+
header.writeUInt16BE(1, 4);
|
|
889
|
+
header.writeUInt16BE(ip ? 1 : 0, 6);
|
|
890
|
+
if (!ip) return Buffer.concat([header, q.question]);
|
|
891
|
+
const rr = Buffer.alloc(16);
|
|
892
|
+
rr.writeUInt16BE(49164, 0);
|
|
893
|
+
rr.writeUInt16BE(TYPE_A, 2);
|
|
894
|
+
rr.writeUInt16BE(CLASS_IN, 4);
|
|
895
|
+
rr.writeUInt32BE(TTL_SEC, 6);
|
|
896
|
+
rr.writeUInt16BE(4, 10);
|
|
897
|
+
ip.split(".").forEach((o, i) => rr.writeUInt8(Number(o), 12 + i));
|
|
898
|
+
return Buffer.concat([header, q.question, rr]);
|
|
1478
899
|
}
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
900
|
+
var slugOf = (owner) => owner.split("@")[0].toLowerCase();
|
|
901
|
+
var isOurs = (q) => q.class === CLASS_IN && q.name.endsWith(DNS_SUFFIX);
|
|
902
|
+
function answerFor(q, asker, boxes) {
|
|
903
|
+
if (!isOurs(q)) return { rcode: RCODE.refused };
|
|
904
|
+
const [name, slug, ...rest] = q.name.slice(0, -DNS_SUFFIX.length).split(".");
|
|
905
|
+
const from = boxes.find((b) => b.ip === asker);
|
|
906
|
+
let box;
|
|
907
|
+
if (from && rest.length === 0) {
|
|
908
|
+
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));
|
|
909
|
+
}
|
|
910
|
+
if (!box) return { rcode: RCODE.nxDomain };
|
|
911
|
+
return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };
|
|
1483
912
|
}
|
|
1484
|
-
function
|
|
1485
|
-
const
|
|
1486
|
-
const
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
913
|
+
async function boxAddresses(p) {
|
|
914
|
+
const out = [];
|
|
915
|
+
for (const ref of await listMachineRefs(p)) {
|
|
916
|
+
const meta = await readMachineMeta(ref, p).catch(() => null);
|
|
917
|
+
if (meta) out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {} });
|
|
918
|
+
}
|
|
919
|
+
return out;
|
|
1490
920
|
}
|
|
1491
|
-
function
|
|
1492
|
-
|
|
1493
|
-
return
|
|
921
|
+
function sharedBoxes(load, freshMs = BOXES_FRESH_MS, version = boxListVersionNow) {
|
|
922
|
+
let last = null;
|
|
923
|
+
return () => {
|
|
924
|
+
if (!last || last.version !== version() || Date.now() - last.at > freshMs) {
|
|
925
|
+
const entry = { at: Date.now(), version: version(), list: load() };
|
|
926
|
+
last = entry;
|
|
927
|
+
entry.list.catch(() => {
|
|
928
|
+
if (last === entry) last = null;
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
return last.list;
|
|
932
|
+
};
|
|
1494
933
|
}
|
|
1495
|
-
function
|
|
1496
|
-
const
|
|
1497
|
-
|
|
934
|
+
async function startDns(opts) {
|
|
935
|
+
const p = opts.p ?? paths();
|
|
936
|
+
const boxes = sharedBoxes(opts.boxes ?? (() => boxAddresses(p)));
|
|
937
|
+
const socket = createSocket("udp4");
|
|
938
|
+
socket.on("message", (msg, rinfo) => {
|
|
939
|
+
const q = parseQuery(msg);
|
|
940
|
+
if (!q) return;
|
|
941
|
+
const reply = (a) => socket.send(buildAnswer(q, a.rcode, a.ip), rinfo.port, rinfo.address);
|
|
942
|
+
if (!isOurs(q)) return reply({ rcode: RCODE.refused });
|
|
943
|
+
void boxes().then((list) => answerFor(q, rinfo.address, list)).catch(() => ({ rcode: RCODE.refused })).then(reply);
|
|
944
|
+
});
|
|
945
|
+
await new Promise((resolve2, reject) => {
|
|
946
|
+
socket.once("error", (err) => {
|
|
947
|
+
socket.close();
|
|
948
|
+
reject(err);
|
|
949
|
+
});
|
|
950
|
+
socket.bind(opts.port ?? DNS_PORT, opts.host, () => {
|
|
951
|
+
socket.removeAllListeners("error");
|
|
952
|
+
socket.on("error", () => {
|
|
953
|
+
});
|
|
954
|
+
resolve2();
|
|
955
|
+
});
|
|
956
|
+
});
|
|
957
|
+
return { socket, close: () => new Promise((resolve2) => socket.close(() => resolve2())) };
|
|
1498
958
|
}
|
|
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);
|
|
959
|
+
|
|
960
|
+
// src/core/machines.ts
|
|
961
|
+
import { spawn } from "node:child_process";
|
|
962
|
+
import { closeSync as closeSync3, existsSync as existsSync6, openSync as openSync3, statSync as statSync2 } from "node:fs";
|
|
963
|
+
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";
|
|
964
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
965
|
+
|
|
966
|
+
// ../shared/src/duration.ts
|
|
967
|
+
var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
|
|
968
|
+
function parseDuration(text) {
|
|
969
|
+
const t = text.trim().toLowerCase();
|
|
970
|
+
if (!/^(\d+[mhd])+$/.test(t)) return void 0;
|
|
971
|
+
let sec = 0;
|
|
972
|
+
for (const [, n, unit] of t.matchAll(/(\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit];
|
|
973
|
+
return sec;
|
|
1530
974
|
}
|
|
1531
975
|
|
|
1532
|
-
// src/
|
|
1533
|
-
|
|
1534
|
-
|
|
976
|
+
// ../shared/src/api.ts
|
|
977
|
+
import { z as z4 } from "zod";
|
|
978
|
+
var SizeSchema = z4.enum(SIZE_NAMES);
|
|
979
|
+
var BoxStatusSchema = z4.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
|
|
980
|
+
var PortProtoSchema = z4.enum(["tcp", "udp"]);
|
|
981
|
+
var MAX_BOX_PORTS = 16;
|
|
982
|
+
var PortForwardSchema = z4.object({
|
|
983
|
+
guestPort: z4.number().int().min(1).max(65535),
|
|
984
|
+
hostPort: z4.number().int(),
|
|
985
|
+
proto: PortProtoSchema,
|
|
986
|
+
/** The host's public address; only the control plane fills it in, as for `ssh`. */
|
|
987
|
+
address: z4.string().optional()
|
|
988
|
+
});
|
|
989
|
+
var PortsRequest = z4.object({
|
|
990
|
+
ports: z4.array(z4.object({ guestPort: z4.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
|
|
991
|
+
});
|
|
992
|
+
var BoxPortSchema = z4.number().int().min(1).max(65535);
|
|
993
|
+
var MAX_BOX_LINKS = 32;
|
|
994
|
+
var BoxLinkSchema = z4.object({ from: z4.string(), port: BoxPortSchema });
|
|
995
|
+
var LinkRequest = z4.object({ from: z4.string().min(1), fromOwner: z4.string().optional(), port: BoxPortSchema });
|
|
996
|
+
var ClaimSubdomainRequest = z4.object({ name: z4.string(), port: BoxPortSchema });
|
|
997
|
+
var SubdomainPortRequest = z4.object({ port: BoxPortSchema });
|
|
998
|
+
var SubdomainRouteRequest = z4.object({ name: z4.string(), port: BoxPortSchema });
|
|
999
|
+
var SubdomainSchema = z4.object({
|
|
1000
|
+
owner: z4.string(),
|
|
1001
|
+
box: z4.string(),
|
|
1002
|
+
subdomain: z4.string(),
|
|
1003
|
+
port: BoxPortSchema,
|
|
1004
|
+
url: z4.string(),
|
|
1005
|
+
routes: z4.array(z4.object({ name: z4.string(), port: BoxPortSchema, url: z4.string() }))
|
|
1006
|
+
});
|
|
1007
|
+
var AddDomainRequest = z4.object({ domain: z4.string(), port: BoxPortSchema.optional() });
|
|
1008
|
+
var DomainSchema = z4.object({
|
|
1009
|
+
owner: z4.string(),
|
|
1010
|
+
box: z4.string(),
|
|
1011
|
+
domain: z4.string(),
|
|
1012
|
+
port: BoxPortSchema,
|
|
1013
|
+
status: z4.enum(["pending", "live"]),
|
|
1014
|
+
www: z4.boolean(),
|
|
1015
|
+
url: z4.string(),
|
|
1016
|
+
error: z4.string().nullable(),
|
|
1017
|
+
records: z4.array(z4.object({ type: z4.enum(["A", "TXT", "CNAME"]), name: z4.string(), value: z4.string() })),
|
|
1018
|
+
createdAt: z4.string()
|
|
1019
|
+
});
|
|
1020
|
+
var WakeHookSchema = z4.object({
|
|
1021
|
+
id: z4.string(),
|
|
1022
|
+
owner: z4.string(),
|
|
1023
|
+
box: z4.string(),
|
|
1024
|
+
url: z4.string(),
|
|
1025
|
+
createdBy: z4.string().nullable(),
|
|
1026
|
+
createdAt: z4.string(),
|
|
1027
|
+
lastCalledAt: z4.string().nullable()
|
|
1028
|
+
});
|
|
1029
|
+
var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z4.string() });
|
|
1030
|
+
var WakeHookCallSchema = z4.object({
|
|
1031
|
+
box: z4.string(),
|
|
1032
|
+
action: z4.enum(["wake", "resume", "none"]),
|
|
1033
|
+
reason: z4.string().optional()
|
|
1034
|
+
});
|
|
1035
|
+
var BACKUP_STATUSES = ["running", "ready", "failed"];
|
|
1036
|
+
var BackupSchema = z4.object({
|
|
1037
|
+
id: z4.string(),
|
|
1038
|
+
owner: z4.string(),
|
|
1039
|
+
box: z4.string(),
|
|
1040
|
+
status: z4.enum(BACKUP_STATUSES),
|
|
1041
|
+
/** Why it failed; null otherwise. */
|
|
1042
|
+
error: z4.string().nullable(),
|
|
1043
|
+
/** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
|
|
1044
|
+
base: z4.string().nullable(),
|
|
1045
|
+
image: z4.string().optional(),
|
|
1046
|
+
vcpu: z4.number().int().nullable(),
|
|
1047
|
+
memMib: z4.number().int().nullable(),
|
|
1048
|
+
/** The disk's size. */
|
|
1049
|
+
diskBytes: z4.number().int().nullable(),
|
|
1050
|
+
/** What it holds: the slots that are not all zeros. */
|
|
1051
|
+
dataBytes: z4.number().int().nullable(),
|
|
1052
|
+
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
1053
|
+
uploadedBytes: z4.number().int().nullable(),
|
|
1054
|
+
createdBy: z4.string().nullable(),
|
|
1055
|
+
createdAt: z4.string(),
|
|
1056
|
+
finishedAt: z4.string().nullable()
|
|
1057
|
+
});
|
|
1058
|
+
var HostBackupRequest = z4.object({ id: z4.string(), key: z4.string() });
|
|
1059
|
+
var HostBackupManifestSchema = z4.object({
|
|
1060
|
+
id: z4.string(),
|
|
1061
|
+
sizeBytes: z4.number().int(),
|
|
1062
|
+
chunks: z4.array(z4.string().nullable()),
|
|
1063
|
+
env: z4.string().nullable(),
|
|
1064
|
+
base: z4.string(),
|
|
1065
|
+
image: z4.string().optional(),
|
|
1066
|
+
vcpu: z4.number().int(),
|
|
1067
|
+
memMib: z4.number().int()
|
|
1068
|
+
});
|
|
1069
|
+
var HostUploadRequest = z4.object({ key: z4.string(), urls: z4.record(z4.string(), z4.string()) });
|
|
1070
|
+
var HostUploadResultSchema = z4.object({ chunks: z4.number().int(), bytes: z4.number().int(), sizes: z4.record(z4.string(), z4.number().int()) });
|
|
1071
|
+
var HostRestoreRequest = z4.object({
|
|
1072
|
+
/** The backup's id: its variables were sealed under it. */
|
|
1073
|
+
id: z4.string(),
|
|
1074
|
+
key: z4.string(),
|
|
1075
|
+
sizeBytes: z4.number().int().positive(),
|
|
1076
|
+
base: z4.string(),
|
|
1077
|
+
image: z4.string().optional(),
|
|
1078
|
+
env: z4.string().nullable(),
|
|
1079
|
+
chunks: z4.array(z4.object({ index: z4.number().int().nonnegative(), hash: z4.string(), url: z4.string() }))
|
|
1080
|
+
});
|
|
1081
|
+
var MachineSchema = z4.object({
|
|
1082
|
+
/** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
|
|
1535
1083
|
id: z4.string(),
|
|
1536
1084
|
name: z4.string(),
|
|
1537
|
-
/**
|
|
1085
|
+
/** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */
|
|
1538
1086
|
owner: z4.string(),
|
|
1539
1087
|
ip: z4.string(),
|
|
1540
1088
|
mac: z4.string(),
|
|
1541
1089
|
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
1090
|
vcpu: z4.number().int(),
|
|
1550
1091
|
memMib: z4.number().int(),
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1092
|
+
diskBytes: z4.number().int(),
|
|
1093
|
+
// the box's own writable disk, as the guest sees it
|
|
1094
|
+
diskUsedBytes: z4.number().int(),
|
|
1095
|
+
// what the box uses of it: the filesystem's own count, like the guest's `df` (#115)
|
|
1096
|
+
/** 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. */
|
|
1097
|
+
diskHostBytes: z4.number().int().optional(),
|
|
1554
1098
|
base: z4.string(),
|
|
1555
|
-
|
|
1099
|
+
// version of the image the box's overlay stacks on
|
|
1100
|
+
/** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
|
|
1556
1101
|
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(),
|
|
1102
|
+
createdAt: z4.string(),
|
|
1103
|
+
source: z4.string(),
|
|
1104
|
+
// "base", "snapshot:<owner/name>" or "fork:<owner/name>" (#79)
|
|
1105
|
+
status: BoxStatusSchema,
|
|
1573
1106
|
/**
|
|
1574
|
-
*
|
|
1575
|
-
*
|
|
1107
|
+
* Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made
|
|
1108
|
+
* through a control plane have one; the control plane adds the host's address for `connect` (#21).
|
|
1576
1109
|
*/
|
|
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
1110
|
sshPort: z4.number().int().optional(),
|
|
1580
1111
|
/**
|
|
1581
|
-
*
|
|
1582
|
-
*
|
|
1583
|
-
*
|
|
1112
|
+
* Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only
|
|
1113
|
+
* the control plane fills it in (a host does not know its own public address); absent for a box
|
|
1114
|
+
* whose host reported no port or did not answer.
|
|
1584
1115
|
*/
|
|
1585
|
-
|
|
1586
|
-
/**
|
|
1587
|
-
|
|
1116
|
+
ssh: z4.object({ host: z4.string(), port: z4.number().int(), user: z4.string() }).optional(),
|
|
1117
|
+
/** Box ports published on the host (#30). Absent: none. */
|
|
1118
|
+
ports: z4.array(PortForwardSchema).optional(),
|
|
1119
|
+
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
|
|
1120
|
+
ownerKind: z4.enum(["user", "org"]).optional(),
|
|
1588
1121
|
/**
|
|
1589
|
-
*
|
|
1590
|
-
*
|
|
1591
|
-
* changes it. The one place the host looks. Absent: the traffic rule.
|
|
1122
|
+
* The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
|
|
1123
|
+
* links to, and a volume attaches to, only a box on the same host.
|
|
1592
1124
|
*/
|
|
1125
|
+
host: z4.string().optional(),
|
|
1126
|
+
/** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
|
|
1127
|
+
country: z4.string().optional(),
|
|
1128
|
+
/** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
|
|
1129
|
+
autoHibernateSec: z4.number().int().positive().optional(),
|
|
1130
|
+
/** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
|
|
1593
1131
|
idleCheck: z4.string().optional(),
|
|
1132
|
+
/** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
|
|
1133
|
+
volumes: z4.array(z4.object({ name: z4.string(), sizeGib: z4.number().int(), mountPath: z4.string() })).optional(),
|
|
1134
|
+
/** Boxes that may reach this one, each on one port (#98). Absent: none. */
|
|
1135
|
+
links: z4.array(BoxLinkSchema).optional(),
|
|
1136
|
+
/** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */
|
|
1137
|
+
url: z4.string().optional(),
|
|
1594
1138
|
/**
|
|
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.
|
|
1139
|
+
* Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
|
|
1140
|
+
* serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
|
|
1606
1141
|
*/
|
|
1607
|
-
|
|
1142
|
+
connect: z4.string().optional()
|
|
1608
1143
|
});
|
|
1609
|
-
var
|
|
1610
|
-
/**
|
|
1144
|
+
var VolumeSchema = z4.object({
|
|
1145
|
+
/** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
1611
1146
|
id: z4.string(),
|
|
1612
1147
|
name: z4.string(),
|
|
1613
1148
|
owner: z4.string(),
|
|
1614
1149
|
sizeGib: z4.number().int(),
|
|
1615
|
-
|
|
1150
|
+
/** What the sparse file really occupies on the host. */
|
|
1151
|
+
usedBytes: z4.number().int(),
|
|
1152
|
+
attachedTo: z4.string().nullable(),
|
|
1153
|
+
createdAt: z4.string(),
|
|
1154
|
+
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
|
|
1155
|
+
ownerKind: z4.enum(["user", "org"]).optional(),
|
|
1156
|
+
/** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
|
|
1157
|
+
host: z4.string().optional()
|
|
1616
1158
|
});
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1159
|
+
var MAX_VOLUME_GIB = 4096;
|
|
1160
|
+
var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
1161
|
+
var VOLUME_NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
|
|
1162
|
+
var CreateVolumeRequest = z4.object({
|
|
1163
|
+
name: z4.string(),
|
|
1164
|
+
sizeGib: z4.number().int().min(1).max(MAX_VOLUME_GIB),
|
|
1165
|
+
/**
|
|
1166
|
+
* Through a control plane (#91): the box this volume is for, so it is made on that box's host; the
|
|
1167
|
+
* control plane requires it (a volume attaches only to a box on its own host, so one made for no box
|
|
1168
|
+
* could never attach) and the CLI attaches right after. A host ignores it.
|
|
1169
|
+
*/
|
|
1170
|
+
box: z4.string().optional()
|
|
1171
|
+
});
|
|
1172
|
+
var AttachVolumeRequest = z4.object({
|
|
1173
|
+
box: z4.string()
|
|
1174
|
+
});
|
|
1175
|
+
var EnvVarSchema = z4.object({
|
|
1176
|
+
name: z4.string(),
|
|
1177
|
+
value: z4.string().optional(),
|
|
1178
|
+
secret: z4.boolean(),
|
|
1179
|
+
updatedAt: z4.string()
|
|
1180
|
+
});
|
|
1181
|
+
var BoxEnvSchema = z4.object({
|
|
1182
|
+
box: z4.string(),
|
|
1183
|
+
vars: z4.array(EnvVarSchema)
|
|
1184
|
+
});
|
|
1185
|
+
var BoxEnvChangeSchema = z4.object({
|
|
1186
|
+
box: z4.string(),
|
|
1187
|
+
name: z4.string(),
|
|
1188
|
+
/** Whether the box is running now: the change waits for its next start. */
|
|
1189
|
+
running: z4.boolean()
|
|
1190
|
+
});
|
|
1191
|
+
var SetEnvRequest = z4.object({
|
|
1192
|
+
value: z4.string(),
|
|
1193
|
+
secret: z4.boolean().optional()
|
|
1194
|
+
});
|
|
1195
|
+
var EnvChangeSchema = z4.object({
|
|
1196
|
+
owner: z4.string(),
|
|
1197
|
+
name: z4.string(),
|
|
1198
|
+
boxes: z4.number().int()
|
|
1199
|
+
});
|
|
1200
|
+
var HostEnvRequest = z4.object({
|
|
1201
|
+
version: z4.number().int().min(0),
|
|
1202
|
+
vars: z4.array(z4.object({ name: z4.string(), value: z4.string() }))
|
|
1203
|
+
});
|
|
1204
|
+
var HostEnvVersionsSchema = z4.array(z4.object({ owner: z4.string(), version: z4.number().int() }));
|
|
1205
|
+
var CreateMachineRequest = z4.object({
|
|
1206
|
+
name: z4.string().optional(),
|
|
1207
|
+
/** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
|
|
1208
|
+
owner: z4.string().optional(),
|
|
1209
|
+
size: SizeSchema.optional(),
|
|
1210
|
+
from: z4.string().optional(),
|
|
1211
|
+
force: z4.boolean().optional(),
|
|
1212
|
+
/**
|
|
1213
|
+
* Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends
|
|
1214
|
+
* its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every
|
|
1215
|
+
* boot (#49); a host older than that ignores them.
|
|
1216
|
+
*/
|
|
1217
|
+
sshKeys: z4.array(z4.string()).optional(),
|
|
1218
|
+
/** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
|
|
1219
|
+
autoHibernateSec: z4.number().int().min(0).optional(),
|
|
1220
|
+
/**
|
|
1221
|
+
* Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
|
|
1222
|
+
* control plane reads it; a host has one place to put a box.
|
|
1223
|
+
*/
|
|
1224
|
+
near: z4.string().optional(),
|
|
1225
|
+
/**
|
|
1226
|
+
* Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
|
|
1227
|
+
* `@kvbox/shared/country`. Only the control plane reads it.
|
|
1228
|
+
*/
|
|
1229
|
+
country: z4.string().optional(),
|
|
1230
|
+
/** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
|
|
1231
|
+
image: z4.string().optional(),
|
|
1232
|
+
/** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
|
|
1233
|
+
env: z4.array(z4.object({ name: z4.string(), value: z4.string() })).optional()
|
|
1234
|
+
});
|
|
1235
|
+
var ForkMachineRequest = z4.object({
|
|
1236
|
+
name: z4.string().optional(),
|
|
1237
|
+
/**
|
|
1238
|
+
* The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host
|
|
1239
|
+
* qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.
|
|
1240
|
+
*/
|
|
1241
|
+
owner: z4.string().optional(),
|
|
1242
|
+
/** A cold fork only: a warm one keeps the source's vCPU and memory. */
|
|
1243
|
+
size: SizeSchema.optional(),
|
|
1244
|
+
force: z4.boolean().optional(),
|
|
1245
|
+
/** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */
|
|
1246
|
+
sshKeys: z4.array(z4.string()).optional(),
|
|
1247
|
+
autoHibernateSec: z4.number().int().min(0).optional()
|
|
1248
|
+
});
|
|
1249
|
+
var SetSshKeysRequest = z4.object({
|
|
1250
|
+
sshKeys: z4.array(z4.string())
|
|
1251
|
+
});
|
|
1252
|
+
var RescaleMachineRequest = z4.object({
|
|
1253
|
+
size: SizeSchema.optional(),
|
|
1254
|
+
vcpu: z4.number().int().min(1).max(64).optional(),
|
|
1255
|
+
memMib: z4.number().int().min(256).optional(),
|
|
1256
|
+
diskGib: z4.number().int().min(1).optional(),
|
|
1257
|
+
/** Skip the capacity guard when a running box grows (#37). */
|
|
1258
|
+
force: z4.boolean().optional()
|
|
1259
|
+
});
|
|
1260
|
+
var StartMachineRequest = z4.object({
|
|
1261
|
+
force: z4.boolean().optional()
|
|
1262
|
+
});
|
|
1263
|
+
var SetMachineRequest = z4.object({
|
|
1264
|
+
/** Seconds without network traffic before the box is hibernated (#47); 0: never. */
|
|
1265
|
+
autoHibernateSec: z4.number().int().min(0).optional(),
|
|
1266
|
+
/** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
|
|
1267
|
+
idleCheck: z4.union([z4.literal(""), z4.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
|
|
1268
|
+
});
|
|
1269
|
+
var SnapshotSchema = z4.object({
|
|
1624
1270
|
name: z4.string(),
|
|
1625
1271
|
owner: z4.string(),
|
|
1626
|
-
/** The box it was taken from, as owner/name. */
|
|
1627
1272
|
source: z4.string(),
|
|
1273
|
+
// the box it was taken from, as owner/name
|
|
1628
1274
|
base: z4.string(),
|
|
1629
|
-
|
|
1275
|
+
// version of the image the overlay stacks on; a restore needs the same one
|
|
1276
|
+
/** As in MachineSchema: the image when it is not the base one (#87). */
|
|
1630
1277
|
image: z4.string().optional(),
|
|
1631
1278
|
vcpu: z4.number().int(),
|
|
1632
1279
|
memMib: z4.number().int(),
|
|
1633
1280
|
sizeBytes: z4.number().int(),
|
|
1634
|
-
|
|
1281
|
+
// what vmstate + mem + overlay really occupy on the host
|
|
1282
|
+
createdAt: z4.string()
|
|
1283
|
+
});
|
|
1284
|
+
var CreateSnapshotRequest = z4.object({
|
|
1285
|
+
box: z4.string(),
|
|
1286
|
+
name: z4.string(),
|
|
1287
|
+
/** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
|
|
1288
|
+
replace: z4.boolean().optional()
|
|
1289
|
+
});
|
|
1290
|
+
var DiskCapacitySchema = z4.object({
|
|
1291
|
+
totalGib: z4.number().int(),
|
|
1292
|
+
freeGib: z4.number().int(),
|
|
1293
|
+
volumesGib: z4.number().int(),
|
|
1294
|
+
volumesUsedGib: z4.number().int(),
|
|
1295
|
+
headroomGib: z4.number().int()
|
|
1296
|
+
});
|
|
1297
|
+
var CapacitySchema = z4.object({
|
|
1298
|
+
hostMemMib: z4.number().int(),
|
|
1299
|
+
hostCores: z4.number().int(),
|
|
1300
|
+
reservedMemMib: z4.number().int(),
|
|
1301
|
+
reservedVcpu: z4.number().int(),
|
|
1302
|
+
running: z4.number().int(),
|
|
1303
|
+
/** Absent on a host from before volumes (#91): it cannot take one. */
|
|
1304
|
+
disk: DiskCapacitySchema.optional(),
|
|
1635
1305
|
/**
|
|
1636
|
-
* The
|
|
1637
|
-
*
|
|
1638
|
-
* gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
|
|
1306
|
+
* The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
|
|
1307
|
+
* Absent on a host from before images: it has only the base.
|
|
1639
1308
|
*/
|
|
1640
|
-
|
|
1309
|
+
images: z4.array(z4.object({ name: z4.string(), version: z4.string() })).optional()
|
|
1641
1310
|
});
|
|
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
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
var
|
|
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
|
-
|
|
1311
|
+
var ImageSchema = z4.object({ name: z4.string(), version: z4.string().nullable() });
|
|
1312
|
+
var RecoveryReportSchema = z4.object({
|
|
1313
|
+
at: z4.string(),
|
|
1314
|
+
booted: z4.array(z4.string()),
|
|
1315
|
+
leftStopped: z4.array(z4.string()),
|
|
1316
|
+
failed: z4.array(z4.object({ box: z4.string(), error: z4.string() }))
|
|
1317
|
+
});
|
|
1318
|
+
var HealthSchema = z4.object({
|
|
1319
|
+
ok: z4.literal(true),
|
|
1320
|
+
version: z4.string(),
|
|
1321
|
+
pid: z4.number().int(),
|
|
1322
|
+
/** Base image version new boxes get (null when the host has no usable base image yet). */
|
|
1323
|
+
base: z4.string().nullable(),
|
|
1324
|
+
/** Owner that boxes made over the local socket get (the Unix user running the server). */
|
|
1325
|
+
owner: z4.string(),
|
|
1326
|
+
/** The control plane this host joined (null when none). */
|
|
1327
|
+
controlPlane: z4.object({
|
|
1328
|
+
/** Realm name, e.g. kvbox.sh. */
|
|
1329
|
+
name: z4.string(),
|
|
1330
|
+
url: z4.string(),
|
|
1331
|
+
/** Where this host answers the control plane. */
|
|
1332
|
+
hostUrl: z4.string()
|
|
1333
|
+
}).nullable(),
|
|
1334
|
+
/** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */
|
|
1335
|
+
relay: z4.object({
|
|
1336
|
+
name: z4.string(),
|
|
1337
|
+
/** The public IP the relay owns for this host. */
|
|
1338
|
+
publicIp: z4.string(),
|
|
1339
|
+
/** The relay's WireGuard endpoint the tunnel dials. */
|
|
1340
|
+
endpoint: z4.string(),
|
|
1341
|
+
/** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */
|
|
1342
|
+
restarts: z4.number().int().optional(),
|
|
1343
|
+
lastRestartAt: z4.string().nullable().optional()
|
|
1344
|
+
}).nullable().optional(),
|
|
1345
|
+
/** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */
|
|
1346
|
+
recovery: RecoveryReportSchema.nullable().optional()
|
|
1347
|
+
});
|
|
1348
|
+
var MachineUsageSchema = z4.object({
|
|
1349
|
+
name: z4.string(),
|
|
1350
|
+
owner: z4.string(),
|
|
1351
|
+
status: BoxStatusSchema,
|
|
1352
|
+
window: z4.object({ from: z4.string(), to: z4.string() }),
|
|
1353
|
+
seconds: z4.object({
|
|
1354
|
+
running: z4.number().int(),
|
|
1355
|
+
standby: z4.number().int(),
|
|
1356
|
+
hibernated: z4.number().int(),
|
|
1357
|
+
stopped: z4.number().int()
|
|
1358
|
+
}),
|
|
1359
|
+
vcpuHours: z4.number(),
|
|
1360
|
+
ramGibHours: z4.number(),
|
|
1361
|
+
diskGibHours: z4.number(),
|
|
1362
|
+
cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
|
|
1363
|
+
/** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */
|
|
1364
|
+
estimatedStops: z4.number().int(),
|
|
1365
|
+
historyFrom: z4.string().nullable()
|
|
1366
|
+
});
|
|
1367
|
+
var GuestStatsSchema = z4.object({
|
|
1368
|
+
/** Load average over 1, 5 and 15 minutes. */
|
|
1369
|
+
load: z4.tuple([z4.number(), z4.number(), z4.number()]),
|
|
1370
|
+
cpus: z4.number().int(),
|
|
1371
|
+
memTotalMib: z4.number().int(),
|
|
1372
|
+
/** Total minus available: page cache counts as free. */
|
|
1373
|
+
memUsedMib: z4.number().int(),
|
|
1374
|
+
/** The box's root, which is its overlay disk: the box's own writes, not the shared base. */
|
|
1375
|
+
diskTotalBytes: z4.number().int(),
|
|
1376
|
+
diskUsedBytes: z4.number().int(),
|
|
1377
|
+
uptimeSec: z4.number().int()
|
|
1378
|
+
});
|
|
1379
|
+
var MachineStatsSchema = z4.object({
|
|
1380
|
+
name: z4.string(),
|
|
1381
|
+
owner: z4.string(),
|
|
1382
|
+
stats: GuestStatsSchema.nullable()
|
|
1383
|
+
});
|
|
1384
|
+
var UsageStatusSchema = z4.enum([...BoxStatusSchema.options, "removed"]);
|
|
1385
|
+
var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({
|
|
1386
|
+
/** The host's box id; a name removed and recreated appears twice, with two ids. */
|
|
1387
|
+
id: z4.string(),
|
|
1388
|
+
status: UsageStatusSchema,
|
|
1389
|
+
/** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */
|
|
1390
|
+
ownerKind: z4.enum(["user", "org"]).optional(),
|
|
1391
|
+
/**
|
|
1392
|
+
* Through a control plane: the username that made the box (#60), absent when the box is gone from
|
|
1393
|
+
* the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.
|
|
1394
|
+
*/
|
|
1395
|
+
createdBy: z4.string().optional()
|
|
1396
|
+
});
|
|
1397
|
+
var VolumeUsageSchema = z4.object({
|
|
1398
|
+
/** The host's volume id; a name removed and made again appears twice, with two ids. */
|
|
1399
|
+
id: z4.string(),
|
|
1400
|
+
name: z4.string(),
|
|
1401
|
+
owner: z4.string(),
|
|
1402
|
+
ownerKind: z4.enum(["user", "org"]).optional(),
|
|
1403
|
+
/** The size at the end of the window (or when removed). */
|
|
1404
|
+
sizeGib: z4.number().int(),
|
|
1405
|
+
status: z4.enum(["present", "removed"]),
|
|
1406
|
+
volumeHours: z4.number(),
|
|
1407
|
+
volumeGibHours: z4.number(),
|
|
1408
|
+
cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional(),
|
|
1409
|
+
historyFrom: z4.string().nullable()
|
|
1410
|
+
});
|
|
1411
|
+
var UsageReportSchema = z4.object({
|
|
1412
|
+
window: z4.object({ from: z4.string(), to: z4.string() }),
|
|
1413
|
+
boxes: z4.array(BoxUsageSchema),
|
|
1414
|
+
/** Absent from a side older than #91. */
|
|
1415
|
+
volumes: z4.array(VolumeUsageSchema).optional(),
|
|
1416
|
+
totals: z4.object({
|
|
1417
|
+
seconds: MachineUsageSchema.shape.seconds,
|
|
1418
|
+
vcpuHours: z4.number(),
|
|
1419
|
+
ramGibHours: z4.number(),
|
|
1420
|
+
diskGibHours: z4.number(),
|
|
1421
|
+
volumeHours: z4.number().optional(),
|
|
1422
|
+
volumeGibHours: z4.number().optional(),
|
|
1423
|
+
/** Boxes and volumes together. */
|
|
1424
|
+
cost: z4.object({ amount: z4.number(), currency: z4.string() }).optional()
|
|
1425
|
+
})
|
|
1426
|
+
});
|
|
1427
|
+
var UsageEventRowSchema = z4.object({
|
|
1428
|
+
id: z4.number().int(),
|
|
1429
|
+
boxId: z4.string(),
|
|
1430
|
+
owner: z4.string(),
|
|
1431
|
+
name: z4.string(),
|
|
1432
|
+
at: z4.string(),
|
|
1433
|
+
state: z4.enum(["running", "standby", "hibernated", "stopped"]),
|
|
1434
|
+
vcpu: z4.number().int(),
|
|
1435
|
+
memMib: z4.number().int(),
|
|
1436
|
+
diskGib: z4.number().int(),
|
|
1437
|
+
by: z4.string()
|
|
1438
|
+
});
|
|
1439
|
+
var UsageEventsResponseSchema = z4.object({
|
|
1440
|
+
ledger: z4.string().min(1),
|
|
1441
|
+
events: z4.array(UsageEventRowSchema),
|
|
1442
|
+
next: z4.number().int()
|
|
1443
|
+
});
|
|
1444
|
+
var VolumeEventRowSchema = z4.object({
|
|
1445
|
+
id: z4.number().int(),
|
|
1446
|
+
volumeId: z4.string(),
|
|
1447
|
+
owner: z4.string(),
|
|
1448
|
+
name: z4.string(),
|
|
1449
|
+
at: z4.string(),
|
|
1450
|
+
sizeGib: z4.number().int(),
|
|
1451
|
+
by: z4.enum(["create", "resize", "rm"])
|
|
1452
|
+
});
|
|
1453
|
+
var VolumeEventsResponseSchema = z4.object({
|
|
1454
|
+
ledger: z4.string().min(1),
|
|
1455
|
+
events: z4.array(VolumeEventRowSchema),
|
|
1456
|
+
next: z4.number().int()
|
|
1457
|
+
});
|
|
1458
|
+
var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
|
|
1459
|
+
var ApiErrorCodeSchema = z4.enum(API_ERROR_CODES);
|
|
1460
|
+
var ApiErrorSchema = z4.object({
|
|
1461
|
+
error: z4.string(),
|
|
1462
|
+
code: ApiErrorCodeSchema.optional()
|
|
1463
|
+
});
|
|
1464
|
+
var ACTIVATED_BY = ["card", "admin"];
|
|
1465
|
+
var ActivatedBySchema = z4.enum(ACTIVATED_BY);
|
|
1466
|
+
var CloudUserSchema = z4.object({
|
|
1467
|
+
/** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */
|
|
1468
|
+
username: z4.string(),
|
|
1469
|
+
/** Display name, free text ("Alexandru Ghiura"). */
|
|
1470
|
+
name: z4.string(),
|
|
1471
|
+
/** Login identity, unique. */
|
|
1472
|
+
email: z4.string(),
|
|
1473
|
+
role: z4.enum(["admin", "user"]),
|
|
1474
|
+
createdAt: z4.string(),
|
|
1475
|
+
/**
|
|
1476
|
+
* False until a card is on file or an admin activates the account (#74): then only `/me` and
|
|
1477
|
+
* `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and
|
|
1478
|
+
* gates nobody, hence the defaults: a newer CLI must still parse its answers.
|
|
1479
|
+
*/
|
|
1480
|
+
active: z4.boolean().default(true),
|
|
1481
|
+
activatedBy: ActivatedBySchema.nullable().default(null)
|
|
1482
|
+
});
|
|
1483
|
+
var ORG_ROLES = ["owner", "admin", "member"];
|
|
1484
|
+
var OrgRoleSchema = z4.enum(ORG_ROLES);
|
|
1485
|
+
var CloudOrgSchema = z4.object({
|
|
1486
|
+
slug: z4.string(),
|
|
1487
|
+
/** Display name; the slug never changes, this may. */
|
|
1488
|
+
name: z4.string(),
|
|
1489
|
+
createdAt: z4.string(),
|
|
1490
|
+
/** 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. */
|
|
1491
|
+
active: z4.boolean().default(true),
|
|
1492
|
+
activatedBy: ActivatedBySchema.nullable().default(null)
|
|
1493
|
+
});
|
|
1494
|
+
var OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });
|
|
1495
|
+
var OrgMemberSchema = z4.object({
|
|
1496
|
+
username: z4.string(),
|
|
1497
|
+
name: z4.string(),
|
|
1498
|
+
role: OrgRoleSchema,
|
|
1499
|
+
addedAt: z4.string()
|
|
1500
|
+
});
|
|
1501
|
+
var OrgDetailSchema = CloudOrgSchema.extend({ members: z4.array(OrgMemberSchema) });
|
|
1502
|
+
var CreateOrgRequestSchema = z4.object({
|
|
1503
|
+
slug: z4.string().min(1),
|
|
1504
|
+
name: z4.string().min(1)
|
|
1505
|
+
});
|
|
1506
|
+
var RenameOrgRequestSchema = z4.object({ name: z4.string().min(1) });
|
|
1507
|
+
var AddMemberRequestSchema = z4.object({
|
|
1508
|
+
username: z4.string().min(1),
|
|
1509
|
+
role: OrgRoleSchema.default("member")
|
|
1510
|
+
});
|
|
1511
|
+
var SetRoleRequestSchema = z4.object({ role: OrgRoleSchema });
|
|
1512
|
+
var MeResponseSchema = CloudUserSchema.extend({ orgs: z4.array(OrgMembershipSchema) });
|
|
1513
|
+
var BalanceSchema = z4.object({
|
|
1514
|
+
slug: z4.string(),
|
|
1515
|
+
balance: z4.number(),
|
|
1516
|
+
currency: z4.string(),
|
|
1517
|
+
topUps: z4.number(),
|
|
1518
|
+
spent: z4.number(),
|
|
1519
|
+
/** The first moment usage counts from: the slug's first top-up; null when it has none. */
|
|
1520
|
+
since: z4.string().nullable(),
|
|
1521
|
+
/** 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. */
|
|
1522
|
+
suspendedAt: z4.string().nullable().default(null)
|
|
1523
|
+
});
|
|
1524
|
+
var TopUpRequestSchema = z4.object({
|
|
1525
|
+
slug: z4.string().min(1),
|
|
1526
|
+
/** In the control plane's currency; negative corrects a mistake. */
|
|
1527
|
+
amount: z4.number().finite(),
|
|
1528
|
+
note: z4.string().max(200).optional()
|
|
1529
|
+
});
|
|
1530
|
+
var TopUpSchema = z4.object({
|
|
1531
|
+
id: z4.string(),
|
|
1532
|
+
slug: z4.string(),
|
|
1533
|
+
amount: z4.number(),
|
|
1534
|
+
currency: z4.string(),
|
|
1535
|
+
/** `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. */
|
|
1536
|
+
source: z4.enum(["admin", "card", "trial", "transfer"]),
|
|
1537
|
+
note: z4.string().nullable(),
|
|
1538
|
+
at: z4.string()
|
|
1539
|
+
});
|
|
1540
|
+
var TOP_UP_AMOUNTS = [10, 25, 50, 100];
|
|
1541
|
+
var BillingInfoSchema = z4.object({
|
|
1542
|
+
card: z4.object({ brand: z4.string(), last4: z4.string() }).nullable(),
|
|
1543
|
+
cardInUse: z4.boolean(),
|
|
1544
|
+
balance: BalanceSchema
|
|
1545
|
+
});
|
|
1546
|
+
var BillingRedirectSchema = z4.object({ url: z4.string() });
|
|
1547
|
+
var TopUpCheckoutRequestSchema = z4.object({
|
|
1548
|
+
amount: z4.literal(TOP_UP_AMOUNTS)
|
|
1549
|
+
});
|
|
1550
|
+
var TransferRequestSchema = z4.object({
|
|
1551
|
+
org: z4.string().min(1),
|
|
1552
|
+
amount: z4.number().positive().multipleOf(0.01, "amount is in cents at most")
|
|
1553
|
+
});
|
|
1554
|
+
var TransferResponseSchema = z4.object({ from: BalanceSchema, to: BalanceSchema, activated: z4.boolean() });
|
|
1555
|
+
var LoginRequestSchema = z4.object({
|
|
1556
|
+
email: z4.string().min(1),
|
|
1557
|
+
password: z4.string().min(1),
|
|
1558
|
+
publicKey: z4.string().optional()
|
|
1559
|
+
});
|
|
1560
|
+
var SignupRequestSchema = z4.object({
|
|
1561
|
+
username: z4.string().min(1),
|
|
1562
|
+
name: z4.string().min(1),
|
|
1563
|
+
email: z4.string().min(1),
|
|
1564
|
+
password: z4.string().min(1)
|
|
1565
|
+
});
|
|
1566
|
+
var LoginResponseSchema = z4.object({
|
|
1567
|
+
token: z4.string(),
|
|
1568
|
+
user: CloudUserSchema,
|
|
1569
|
+
sshCert: z4.string().optional(),
|
|
1570
|
+
sshCertExpires: z4.string().optional(),
|
|
1571
|
+
/** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
|
|
1572
|
+
sshCertPrincipals: z4.array(z4.string()).optional()
|
|
1573
|
+
});
|
|
1574
|
+
var SshCertRequestSchema = z4.object({
|
|
1575
|
+
publicKey: z4.string().min(1)
|
|
1576
|
+
});
|
|
1577
|
+
var SshCertResponseSchema = z4.object({
|
|
1578
|
+
cert: z4.string(),
|
|
1579
|
+
expires: z4.string(),
|
|
1580
|
+
principals: z4.array(z4.string())
|
|
1581
|
+
});
|
|
1582
|
+
var SshCaResponseSchema = z4.object({
|
|
1583
|
+
publicKey: z4.string(),
|
|
1584
|
+
/** 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. */
|
|
1585
|
+
retired: z4.array(z4.object({ publicKey: z4.string(), retiredAt: z4.string() })).optional()
|
|
1586
|
+
});
|
|
1587
|
+
var HostSshCaResponseSchema = z4.object({
|
|
1588
|
+
publicKey: z4.string()
|
|
1589
|
+
});
|
|
1590
|
+
var CloudCaSchema = z4.object({
|
|
1591
|
+
controlPlane: z4.string(),
|
|
1592
|
+
publicKey: z4.string(),
|
|
1593
|
+
fingerprint: z4.string()
|
|
1594
|
+
});
|
|
1595
|
+
var TrustCaRequestSchema = z4.object({
|
|
1596
|
+
publicKey: z4.string().min(1)
|
|
1597
|
+
});
|
|
1598
|
+
var SshKeysAppliedSchema = z4.enum(["now", "start", "wake", "resume", "later"]);
|
|
1599
|
+
var TrustCaReportSchema = z4.object({
|
|
1600
|
+
publicKey: z4.string(),
|
|
1601
|
+
fingerprint: z4.string(),
|
|
1602
|
+
/** The guest trusts the CA now. */
|
|
1603
|
+
updated: z4.array(z4.string()),
|
|
1604
|
+
/** meta.json has the line; the guest gets it at `when`. */
|
|
1605
|
+
pending: z4.array(z4.object({ box: z4.string(), when: SshKeysAppliedSchema, why: z4.string().optional() })),
|
|
1606
|
+
failed: z4.array(z4.object({ box: z4.string(), error: z4.string() })),
|
|
1607
|
+
/** Local boxes, untouched: they trust the host's key only. */
|
|
1608
|
+
local: z4.number().int()
|
|
1609
|
+
});
|
|
1610
|
+
var HostJoinRequestSchema = z4.object({
|
|
1611
|
+
token: z4.string().min(1),
|
|
1612
|
+
name: z4.string().min(1),
|
|
1613
|
+
url: z4.string().url(),
|
|
1614
|
+
fingerprint: z4.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
|
|
1615
|
+
publicAddress: z4.string().min(1),
|
|
1616
|
+
/** Where the host is (`kvbox-server join --country`): a code or an English name. */
|
|
1617
|
+
country: z4.string().optional()
|
|
1618
|
+
});
|
|
1619
|
+
var HostJoinResponseSchema = z4.object({
|
|
1620
|
+
hostSecret: z4.string(),
|
|
1621
|
+
controlPlane: z4.object({ name: z4.string() })
|
|
1622
|
+
});
|
|
1623
|
+
var CloudHostSchema = z4.object({
|
|
1624
|
+
name: z4.string(),
|
|
1625
|
+
url: z4.string(),
|
|
1626
|
+
publicAddress: z4.string(),
|
|
1627
|
+
joinedAt: z4.string(),
|
|
1628
|
+
lastSeenAt: z4.string().nullable(),
|
|
1629
|
+
capacity: CapacitySchema.nullable(),
|
|
1630
|
+
/** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
|
|
1631
|
+
country: z4.string().nullable()
|
|
1632
|
+
});
|
|
1633
|
+
var HostPatchRequest = z4.object({ country: z4.string().nullable() });
|
|
1634
|
+
var CountrySchema = z4.object({ code: z4.string(), name: z4.string() });
|
|
1635
|
+
|
|
1636
|
+
// ../shared/src/ssh.ts
|
|
1637
|
+
import { createHash } from "node:crypto";
|
|
1638
|
+
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]*)?$/;
|
|
1639
|
+
function parseSshPublicKey(text) {
|
|
1640
|
+
const key = text.trim().replace(/^cert-authority\s+/, "");
|
|
1641
|
+
if (!SSH_PUBLIC_KEY_RE.test(key)) {
|
|
1642
|
+
throw new KvboxError("that is not an SSH public key; expected one line like: ssh-ed25519 AAAA\u2026 kvbox-ca@kvbox.sh");
|
|
1823
1643
|
}
|
|
1824
|
-
return
|
|
1825
|
-
}
|
|
1826
|
-
function sharedBoxes(load, freshMs = BOXES_FRESH_MS, version = boxListVersionNow) {
|
|
1827
|
-
let last = null;
|
|
1828
|
-
return () => {
|
|
1829
|
-
if (!last || last.version !== version() || Date.now() - last.at > freshMs) {
|
|
1830
|
-
const entry = { at: Date.now(), version: version(), list: load() };
|
|
1831
|
-
last = entry;
|
|
1832
|
-
entry.list.catch(() => {
|
|
1833
|
-
if (last === entry) last = null;
|
|
1834
|
-
});
|
|
1835
|
-
}
|
|
1836
|
-
return last.list;
|
|
1837
|
-
};
|
|
1644
|
+
return key;
|
|
1838
1645
|
}
|
|
1839
|
-
|
|
1840
|
-
const
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
socket.on("message", (msg, rinfo) => {
|
|
1844
|
-
const q = parseQuery(msg);
|
|
1845
|
-
if (!q) return;
|
|
1846
|
-
const reply = (a) => socket.send(buildAnswer(q, a.rcode, a.ip), rinfo.port, rinfo.address);
|
|
1847
|
-
if (!isOurs(q)) return reply({ rcode: RCODE.refused });
|
|
1848
|
-
void boxes().then((list) => answerFor(q, rinfo.address, list)).catch(() => ({ rcode: RCODE.refused })).then(reply);
|
|
1849
|
-
});
|
|
1850
|
-
await new Promise((resolve, reject) => {
|
|
1851
|
-
socket.once("error", (err) => {
|
|
1852
|
-
socket.close();
|
|
1853
|
-
reject(err);
|
|
1854
|
-
});
|
|
1855
|
-
socket.bind(opts.port ?? DNS_PORT, opts.host, () => {
|
|
1856
|
-
socket.removeAllListeners("error");
|
|
1857
|
-
socket.on("error", () => {
|
|
1858
|
-
});
|
|
1859
|
-
resolve();
|
|
1860
|
-
});
|
|
1861
|
-
});
|
|
1862
|
-
return { socket, close: () => new Promise((resolve) => socket.close(() => resolve())) };
|
|
1646
|
+
function sshKeyFingerprint(publicKey) {
|
|
1647
|
+
const m = SSH_PUBLIC_KEY_RE.exec(publicKey.trim());
|
|
1648
|
+
if (!m) throw new KvboxError("cannot fingerprint: not an SSH public key");
|
|
1649
|
+
return `SHA256:${createHash("sha256").update(Buffer.from(m[2], "base64")).digest("base64").replace(/=+$/, "")}`;
|
|
1863
1650
|
}
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
import { spawn } from "node:child_process";
|
|
1867
|
-
import { closeSync as closeSync3, existsSync as existsSync6, openSync as openSync3, statSync as statSync2 } from "node:fs";
|
|
1868
|
-
import { link as link2, mkdir as mkdir6, readFile as readFile6, rename as rename5, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
|
|
1869
|
-
import { setTimeout as sleep } from "node:timers/promises";
|
|
1870
|
-
|
|
1871
|
-
// ../shared/src/duration.ts
|
|
1872
|
-
var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
|
|
1873
|
-
function parseDuration(text) {
|
|
1874
|
-
const t = text.trim().toLowerCase();
|
|
1875
|
-
if (!/^(\d+[mhd])+$/.test(t)) return void 0;
|
|
1876
|
-
let sec = 0;
|
|
1877
|
-
for (const [, n, unit] of t.matchAll(/(\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit];
|
|
1878
|
-
return sec;
|
|
1651
|
+
function caLineFor(principal, caPublicKey) {
|
|
1652
|
+
return `cert-authority,principals="${principal}" ${caPublicKey}`;
|
|
1879
1653
|
}
|
|
1654
|
+
var isCaLine = (line) => /^cert-authority(,|\s)/.test(line.trim());
|
|
1880
1655
|
|
|
1881
1656
|
// src/core/agent.ts
|
|
1882
1657
|
import { connect } from "node:net";
|
|
1883
1658
|
var AGENT_PORT = 52;
|
|
1884
1659
|
async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
1885
|
-
const reply = await new Promise((
|
|
1660
|
+
const reply = await new Promise((resolve2, reject) => {
|
|
1886
1661
|
const sock = connect(udsPath);
|
|
1887
1662
|
let buf = "";
|
|
1888
1663
|
let handshaken = false;
|
|
@@ -1906,7 +1681,7 @@ async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
|
1906
1681
|
sock.write(JSON.stringify(req) + "\n");
|
|
1907
1682
|
} else {
|
|
1908
1683
|
sock.end();
|
|
1909
|
-
return
|
|
1684
|
+
return resolve2(line);
|
|
1910
1685
|
}
|
|
1911
1686
|
}
|
|
1912
1687
|
});
|
|
@@ -1951,7 +1726,7 @@ var isNoAgent = (err) => /vsock connect refused|vsock connection closed before t
|
|
|
1951
1726
|
|
|
1952
1727
|
// src/core/env.ts
|
|
1953
1728
|
import { existsSync } from "node:fs";
|
|
1954
|
-
import { copyFile, mkdir as
|
|
1729
|
+
import { copyFile, mkdir as mkdir2, readFile as readFile4, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
|
|
1955
1730
|
import { z as z5 } from "zod";
|
|
1956
1731
|
|
|
1957
1732
|
// ../shared/src/env.ts
|
|
@@ -1989,7 +1764,7 @@ async function withLock(key, fn) {
|
|
|
1989
1764
|
if (mine?.has(key)) return fn();
|
|
1990
1765
|
const previous = tails.get(key);
|
|
1991
1766
|
let release;
|
|
1992
|
-
const tail = new Promise((
|
|
1767
|
+
const tail = new Promise((resolve2) => release = resolve2);
|
|
1993
1768
|
tails.set(key, tail);
|
|
1994
1769
|
try {
|
|
1995
1770
|
await previous;
|
|
@@ -2006,6 +1781,25 @@ function locked(fn) {
|
|
|
2006
1781
|
return (...args) => withBoxLock(args[0], () => fn(...args));
|
|
2007
1782
|
}
|
|
2008
1783
|
|
|
1784
|
+
// src/core/log.ts
|
|
1785
|
+
function formatLine(level, message, at = /* @__PURE__ */ new Date()) {
|
|
1786
|
+
return `[${at.toISOString()}][${level}]: ${message}`;
|
|
1787
|
+
}
|
|
1788
|
+
var log = {
|
|
1789
|
+
debug(message) {
|
|
1790
|
+
console.error(formatLine("debug", message));
|
|
1791
|
+
},
|
|
1792
|
+
info(message) {
|
|
1793
|
+
console.log(formatLine("info", message));
|
|
1794
|
+
},
|
|
1795
|
+
warn(message) {
|
|
1796
|
+
console.error(formatLine("warn", message));
|
|
1797
|
+
},
|
|
1798
|
+
error(message) {
|
|
1799
|
+
console.error(formatLine("error", message));
|
|
1800
|
+
}
|
|
1801
|
+
};
|
|
1802
|
+
|
|
2009
1803
|
// src/core/env.ts
|
|
2010
1804
|
var OwnerEnvSchema = z5.object({
|
|
2011
1805
|
/** The control plane's counter for the list; only ever grows. */
|
|
@@ -2014,7 +1808,7 @@ var OwnerEnvSchema = z5.object({
|
|
|
2014
1808
|
});
|
|
2015
1809
|
async function readOwnerEnv(owner, p = paths()) {
|
|
2016
1810
|
try {
|
|
2017
|
-
return OwnerEnvSchema.parse(JSON.parse(await
|
|
1811
|
+
return OwnerEnvSchema.parse(JSON.parse(await readFile4(p.ownerEnv(owner), "utf8")));
|
|
2018
1812
|
} catch (err) {
|
|
2019
1813
|
if (err.code === "ENOENT") return null;
|
|
2020
1814
|
throw err;
|
|
@@ -2039,7 +1833,7 @@ async function readBoxEnv(box, p = paths()) {
|
|
|
2039
1833
|
}
|
|
2040
1834
|
async function readBoxEnvFile(file) {
|
|
2041
1835
|
try {
|
|
2042
|
-
return BoxEnvFileSchema.parse(JSON.parse(await
|
|
1836
|
+
return BoxEnvFileSchema.parse(JSON.parse(await readFile4(file, "utf8"))).vars;
|
|
2043
1837
|
} catch (err) {
|
|
2044
1838
|
if (err.code === "ENOENT") return [];
|
|
2045
1839
|
throw err;
|
|
@@ -2104,7 +1898,7 @@ async function setOwnerEnv(owner, req, p = paths()) {
|
|
|
2104
1898
|
const have = await readOwnerEnv(owner, p);
|
|
2105
1899
|
if (have !== null && have.version > req.version) return { version: have.version };
|
|
2106
1900
|
const file = p.ownerEnv(owner);
|
|
2107
|
-
await
|
|
1901
|
+
await mkdir2(p.env, { recursive: true, mode: 448 });
|
|
2108
1902
|
const tmp = `${file}.tmp`;
|
|
2109
1903
|
await writeFile3(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
|
|
2110
1904
|
await rename3(tmp, file);
|
|
@@ -2135,6 +1929,32 @@ import { existsSync as existsSync2 } from "node:fs";
|
|
|
2135
1929
|
import { readdir as readdir3, realpath } from "node:fs/promises";
|
|
2136
1930
|
import { basename } from "node:path";
|
|
2137
1931
|
import { z as z6 } from "zod";
|
|
1932
|
+
|
|
1933
|
+
// src/core/exec.ts
|
|
1934
|
+
import { execFile } from "node:child_process";
|
|
1935
|
+
import { promisify } from "node:util";
|
|
1936
|
+
var execFileAsync = promisify(execFile);
|
|
1937
|
+
async function run(argv, opts = {}) {
|
|
1938
|
+
const [cmd, ...args] = opts.sudo ? ["sudo", "-n", ...argv] : argv;
|
|
1939
|
+
if (!cmd) throw new KvboxError("run: empty argv");
|
|
1940
|
+
if (process.env["KVBOX_DEBUG"]) log.debug(`exec ${[cmd, ...args].join(" ")}`);
|
|
1941
|
+
try {
|
|
1942
|
+
const { stdout, stderr } = await execFileAsync(cmd, args, {
|
|
1943
|
+
cwd: opts.cwd,
|
|
1944
|
+
env: opts.env ?? process.env,
|
|
1945
|
+
timeout: opts.timeoutMs ?? 3e4,
|
|
1946
|
+
maxBuffer: 8 * 1024 * 1024
|
|
1947
|
+
});
|
|
1948
|
+
return { stdout, stderr };
|
|
1949
|
+
} catch (err) {
|
|
1950
|
+
const e = err;
|
|
1951
|
+
if (typeof e.code === "number" && opts.okExitCodes?.includes(e.code)) return { stdout: e.stdout ?? "", stderr: e.stderr ?? "" };
|
|
1952
|
+
const detail = (e.stderr ?? e.message ?? "").trim();
|
|
1953
|
+
throw new KvboxError(`${[cmd, ...args].join(" ")} failed${detail ? `: ${detail}` : ""}`);
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
// src/core/images.ts
|
|
2138
1958
|
var BASE_IMAGE = "base";
|
|
2139
1959
|
var IMAGE_RE = /^[a-z][a-z0-9-]{0,30}$/;
|
|
2140
1960
|
function baseVersionOf(file) {
|
|
@@ -2291,7 +2111,7 @@ function namesIn(text) {
|
|
|
2291
2111
|
|
|
2292
2112
|
// src/core/volumes.ts
|
|
2293
2113
|
import { existsSync as existsSync3, statSync } from "node:fs";
|
|
2294
|
-
import { lstat, mkdir as
|
|
2114
|
+
import { lstat, mkdir as mkdir3, readdir as readdir4, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
|
|
2295
2115
|
|
|
2296
2116
|
// ../shared/src/capacity.ts
|
|
2297
2117
|
var MEM_HEADROOM_MIB = 2048;
|
|
@@ -2397,7 +2217,7 @@ async function createVolume(req, owner, p = paths()) {
|
|
|
2397
2217
|
async function makeVolume(req, owner, p) {
|
|
2398
2218
|
const v = p.volume(owner, req.name);
|
|
2399
2219
|
if (existsSync3(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
|
|
2400
|
-
await
|
|
2220
|
+
await mkdir3(p.ownerVolumes(owner), { recursive: true, mode: 448 });
|
|
2401
2221
|
const disk = await diskCapacity(p);
|
|
2402
2222
|
if (!hasDiskRoom(disk, req.sizeGib)) {
|
|
2403
2223
|
throw new KvboxError(
|
|
@@ -2412,7 +2232,7 @@ async function makeVolume(req, owner, p) {
|
|
|
2412
2232
|
}
|
|
2413
2233
|
}
|
|
2414
2234
|
try {
|
|
2415
|
-
await
|
|
2235
|
+
await mkdir3(v.dir, { mode: 448 });
|
|
2416
2236
|
} catch (err) {
|
|
2417
2237
|
if (err.code === "EEXIST") throw new KvboxError(`volume ${req.name} already exists`);
|
|
2418
2238
|
throw err;
|
|
@@ -2631,10 +2451,10 @@ function ext4Usage(file) {
|
|
|
2631
2451
|
|
|
2632
2452
|
// src/core/snapshots.ts
|
|
2633
2453
|
import { existsSync as existsSync4 } from "node:fs";
|
|
2634
|
-
import { link, mkdir as
|
|
2454
|
+
import { link, mkdir as mkdir4, readdir as readdir5, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
|
|
2635
2455
|
|
|
2636
2456
|
// src/core/firecracker.ts
|
|
2637
|
-
import { Agent, request
|
|
2457
|
+
import { Agent, request } from "undici";
|
|
2638
2458
|
var FirecrackerClient = class {
|
|
2639
2459
|
constructor(socketPath) {
|
|
2640
2460
|
this.socketPath = socketPath;
|
|
@@ -2643,7 +2463,7 @@ var FirecrackerClient = class {
|
|
|
2643
2463
|
socketPath;
|
|
2644
2464
|
agent;
|
|
2645
2465
|
async call(method, path, body) {
|
|
2646
|
-
const res = await
|
|
2466
|
+
const res = await request(`http://localhost${path}`, {
|
|
2647
2467
|
dispatcher: this.agent,
|
|
2648
2468
|
method,
|
|
2649
2469
|
headers: body === void 0 ? {} : { "content-type": "application/json" },
|
|
@@ -2808,7 +2628,7 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
2808
2628
|
const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
|
|
2809
2629
|
const cfg = await loadConfig(p);
|
|
2810
2630
|
if (s !== final) await rm2(s.dir, { recursive: true, force: true });
|
|
2811
|
-
await
|
|
2631
|
+
await mkdir4(s.dir, { recursive: true, mode: 448 });
|
|
2812
2632
|
try {
|
|
2813
2633
|
const volumes = await captureDrivesOf(box, p);
|
|
2814
2634
|
await captureBox(box, s, cfg, p);
|
|
@@ -3111,8 +2931,8 @@ function stateMessage(ref, status) {
|
|
|
3111
2931
|
return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
|
|
3112
2932
|
}
|
|
3113
2933
|
function toMachine(meta, p = paths()) {
|
|
3114
|
-
const
|
|
3115
|
-
if (!
|
|
2934
|
+
const alive2 = vmAlive(meta);
|
|
2935
|
+
if (!alive2 && meta.pid !== null) {
|
|
3116
2936
|
try {
|
|
3117
2937
|
closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
|
|
3118
2938
|
} catch (err) {
|
|
@@ -3125,7 +2945,7 @@ function toMachine(meta, p = paths()) {
|
|
|
3125
2945
|
owner: meta.owner,
|
|
3126
2946
|
ip: meta.ip,
|
|
3127
2947
|
mac: meta.mac,
|
|
3128
|
-
pid:
|
|
2948
|
+
pid: alive2 ? meta.pid : null,
|
|
3129
2949
|
vcpu: meta.vcpu,
|
|
3130
2950
|
memMib: meta.memMib,
|
|
3131
2951
|
...diskStats(p.machine(meta.owner, meta.name).overlay),
|
|
@@ -3217,7 +3037,7 @@ async function waitFor(pred, timeoutMs, stepMs = 50) {
|
|
|
3217
3037
|
}
|
|
3218
3038
|
async function tailOf(file, lines = 5) {
|
|
3219
3039
|
try {
|
|
3220
|
-
return (await
|
|
3040
|
+
return (await readFile5(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
|
|
3221
3041
|
} catch {
|
|
3222
3042
|
return "";
|
|
3223
3043
|
}
|
|
@@ -3306,7 +3126,7 @@ async function currentBaseVersion(p = paths()) {
|
|
|
3306
3126
|
}
|
|
3307
3127
|
async function readHostPubkey(p) {
|
|
3308
3128
|
try {
|
|
3309
|
-
return (await
|
|
3129
|
+
return (await readFile5(`${p.sshKey}.pub`, "utf8")).trim();
|
|
3310
3130
|
} catch {
|
|
3311
3131
|
throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);
|
|
3312
3132
|
}
|
|
@@ -3356,7 +3176,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
3356
3176
|
const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
|
|
3357
3177
|
const m = p.machine(owner, name);
|
|
3358
3178
|
await ensureHostNetwork(cfg);
|
|
3359
|
-
await
|
|
3179
|
+
await mkdir5(m.dir, { recursive: true, mode: 448 });
|
|
3360
3180
|
let tapCreated = false;
|
|
3361
3181
|
let pid;
|
|
3362
3182
|
let sshPort;
|
|
@@ -3444,7 +3264,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
3444
3264
|
const { id, ip, owner, name } = box;
|
|
3445
3265
|
const m = p.machine(owner, name);
|
|
3446
3266
|
await ensureHostNetwork(cfg);
|
|
3447
|
-
await
|
|
3267
|
+
await mkdir5(m.dir, { recursive: true, mode: 448 });
|
|
3448
3268
|
let tapCreated = false;
|
|
3449
3269
|
let pid;
|
|
3450
3270
|
let sshPort;
|
|
@@ -3793,7 +3613,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
3793
3613
|
if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
|
|
3794
3614
|
const m = p.machine(ref.owner, ref.name);
|
|
3795
3615
|
await rm3(m.hibernateDir, { recursive: true, force: true });
|
|
3796
|
-
await
|
|
3616
|
+
await mkdir5(m.hibernateDir, { recursive: true, mode: 448 });
|
|
3797
3617
|
const fc = new FirecrackerClient(m.sock);
|
|
3798
3618
|
try {
|
|
3799
3619
|
try {
|
|
@@ -4184,7 +4004,7 @@ async function bootRecovered(settled, p = paths()) {
|
|
|
4184
4004
|
// src/core/backups.ts
|
|
4185
4005
|
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
4186
4006
|
import { existsSync as existsSync7 } from "node:fs";
|
|
4187
|
-
import { mkdir as
|
|
4007
|
+
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
4008
|
import { basename as basename2, join as join2 } from "node:path";
|
|
4189
4009
|
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
4190
4010
|
|
|
@@ -4319,7 +4139,7 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4319
4139
|
const keys = backupKeys(req.key);
|
|
4320
4140
|
const s = p.backup(req.id);
|
|
4321
4141
|
await rm4(s.dir, { recursive: true, force: true });
|
|
4322
|
-
await
|
|
4142
|
+
await mkdir6(s.dir, { recursive: true, mode: 448 });
|
|
4323
4143
|
try {
|
|
4324
4144
|
const { meta, envText } = await withBoxLock(ref, async () => {
|
|
4325
4145
|
const meta2 = await readBox2(ref, p);
|
|
@@ -4341,7 +4161,7 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4341
4161
|
} else {
|
|
4342
4162
|
await copy();
|
|
4343
4163
|
}
|
|
4344
|
-
const envText2 = existsSync7(m.env) ? await
|
|
4164
|
+
const envText2 = existsSync7(m.env) ? await readFile6(m.env, "utf8") : null;
|
|
4345
4165
|
return { meta: meta2, envText: envText2 };
|
|
4346
4166
|
});
|
|
4347
4167
|
const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
|
|
@@ -4393,7 +4213,7 @@ async function uploadOnce(id, req, signal, p) {
|
|
|
4393
4213
|
const s = p.backup(id);
|
|
4394
4214
|
if (!existsSync7(s.chunks)) throw new NotFoundError(`backup ${id}`);
|
|
4395
4215
|
const keys = backupKeys(req.key);
|
|
4396
|
-
const { chunks } = JSON.parse(await
|
|
4216
|
+
const { chunks } = JSON.parse(await readFile6(s.chunks, "utf8"));
|
|
4397
4217
|
const slotOf = /* @__PURE__ */ new Map();
|
|
4398
4218
|
chunks.forEach((name, i) => {
|
|
4399
4219
|
if (name !== null && !slotOf.has(name)) slotOf.set(name, i);
|
|
@@ -4538,47 +4358,226 @@ async function withTries(what, fn, signal) {
|
|
|
4538
4358
|
await sleep2(250 * 2 ** i);
|
|
4539
4359
|
}
|
|
4540
4360
|
}
|
|
4541
|
-
throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
|
|
4361
|
+
throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
|
|
4362
|
+
}
|
|
4363
|
+
|
|
4364
|
+
// src/core/relay.ts
|
|
4365
|
+
import { access as access2, chmod as chmod3, mkdir as mkdir8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
|
|
4366
|
+
|
|
4367
|
+
// ../shared/src/relay.ts
|
|
4368
|
+
import { z as z7 } from "zod";
|
|
4369
|
+
var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
|
|
4370
|
+
var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
|
|
4371
|
+
var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
4372
|
+
var RelayJoinSchema = z7.object({
|
|
4373
|
+
v: z7.literal(1),
|
|
4374
|
+
/** How the relay lists this host. */
|
|
4375
|
+
name: z7.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
|
|
4376
|
+
/** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
|
|
4377
|
+
relay: z7.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
|
|
4378
|
+
/** The relay's WireGuard public key. */
|
|
4379
|
+
relayKey: z7.string().regex(WG_KEY_RE),
|
|
4380
|
+
/** This host's address inside the tunnel. */
|
|
4381
|
+
tunnelIp: z7.string().regex(IPV4_RE),
|
|
4382
|
+
/** This host's WireGuard private key, generated on the relay, kept nowhere else. */
|
|
4383
|
+
privateKey: z7.string().regex(WG_KEY_RE),
|
|
4384
|
+
/** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
|
|
4385
|
+
publicIp: z7.string().regex(IPV4_RE)
|
|
4386
|
+
});
|
|
4387
|
+
function decodeRelayJoin(text) {
|
|
4388
|
+
let parsed;
|
|
4389
|
+
try {
|
|
4390
|
+
parsed = JSON.parse(Buffer.from(text.trim(), "base64url").toString("utf8"));
|
|
4391
|
+
} catch {
|
|
4392
|
+
return null;
|
|
4393
|
+
}
|
|
4394
|
+
const res = RelayJoinSchema.safeParse(parsed);
|
|
4395
|
+
return res.success ? res.data : null;
|
|
4396
|
+
}
|
|
4397
|
+
|
|
4398
|
+
// src/core/controlPlane.ts
|
|
4399
|
+
import { X509Certificate } from "node:crypto";
|
|
4400
|
+
import { chmod as chmod2, mkdir as mkdir7, readFile as readFile7 } from "node:fs/promises";
|
|
4401
|
+
import { hostname as osHostname } from "node:os";
|
|
4402
|
+
import { request as request2 } from "undici";
|
|
4403
|
+
|
|
4404
|
+
// ../shared/src/country.ts
|
|
4405
|
+
var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
|
|
4406
|
+
var NOT_COUNTRIES = /* @__PURE__ */ new Set(["EU", "EZ", "UN", "QO", "XA", "XB", "ZZ"]);
|
|
4407
|
+
var ALIASES = { usa: "US", america: "US", uk: "GB", britain: "GB", england: "GB", holland: "NL" };
|
|
4408
|
+
var fold = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z]/g, "");
|
|
4409
|
+
var byName;
|
|
4410
|
+
function nameIndex() {
|
|
4411
|
+
if (byName) return byName;
|
|
4412
|
+
byName = new Map(Object.entries(ALIASES));
|
|
4413
|
+
for (let a = 65; a <= 90; a++) {
|
|
4414
|
+
for (let b = 65; b <= 90; b++) {
|
|
4415
|
+
const code = String.fromCharCode(a, b);
|
|
4416
|
+
const name = countryName(code);
|
|
4417
|
+
if (name !== void 0 && canonical(code) === code) byName.set(fold(name), code);
|
|
4418
|
+
}
|
|
4419
|
+
}
|
|
4420
|
+
return byName;
|
|
4421
|
+
}
|
|
4422
|
+
function canonical(code) {
|
|
4423
|
+
return /-([A-Z]{2})$/.exec(Intl.getCanonicalLocales(`und-${code}`)[0] ?? "")?.[1] ?? code;
|
|
4424
|
+
}
|
|
4425
|
+
function countryName(code) {
|
|
4426
|
+
if (!/^[A-Z]{2}$/.test(code) || NOT_COUNTRIES.has(code)) return void 0;
|
|
4427
|
+
return names.of(code);
|
|
4428
|
+
}
|
|
4429
|
+
function parseCountry(input) {
|
|
4430
|
+
const t = input.trim();
|
|
4431
|
+
const upper = t.toUpperCase();
|
|
4432
|
+
const code = countryName(upper) !== void 0 ? canonical(upper) : nameIndex().get(fold(t));
|
|
4433
|
+
if (code !== void 0) return code;
|
|
4434
|
+
throw new KvboxError(`unknown country "${input}": give its name or its two-letter code, e.g. RO or US`);
|
|
4435
|
+
}
|
|
4436
|
+
|
|
4437
|
+
// src/core/controlPlane.ts
|
|
4438
|
+
var DEFAULT_HTTPS_PORT = 7777;
|
|
4439
|
+
async function ensureTlsCert(p = paths()) {
|
|
4440
|
+
const have = await readFile7(p.tlsCert, "utf8").catch(() => null);
|
|
4441
|
+
const haveKey = await readFile7(p.tlsKey).then(() => true, () => false);
|
|
4442
|
+
if (have === null || !haveKey) {
|
|
4443
|
+
await mkdir7(p.tls, { recursive: true, mode: 448 });
|
|
4444
|
+
try {
|
|
4445
|
+
await run([
|
|
4446
|
+
"openssl",
|
|
4447
|
+
"req",
|
|
4448
|
+
"-x509",
|
|
4449
|
+
"-newkey",
|
|
4450
|
+
"ec",
|
|
4451
|
+
"-pkeyopt",
|
|
4452
|
+
"ec_paramgen_curve:prime256v1",
|
|
4453
|
+
"-nodes",
|
|
4454
|
+
"-keyout",
|
|
4455
|
+
p.tlsKey,
|
|
4456
|
+
"-out",
|
|
4457
|
+
p.tlsCert,
|
|
4458
|
+
"-subj",
|
|
4459
|
+
"/CN=kvbox-host",
|
|
4460
|
+
"-days",
|
|
4461
|
+
"3650"
|
|
4462
|
+
]);
|
|
4463
|
+
} catch (err) {
|
|
4464
|
+
throw new KvboxError(`could not make the host's certificate (is openssl installed?): ${err.message}`);
|
|
4465
|
+
}
|
|
4466
|
+
await chmod2(p.tlsKey, 384);
|
|
4467
|
+
}
|
|
4468
|
+
const pem = await readFile7(p.tlsCert, "utf8");
|
|
4469
|
+
return { fingerprint: new X509Certificate(pem).fingerprint256 };
|
|
4470
|
+
}
|
|
4471
|
+
function isPrivateAddress(ip) {
|
|
4472
|
+
const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(ip);
|
|
4473
|
+
if (!m) return false;
|
|
4474
|
+
const [a, b] = [Number(m[1]), Number(m[2])];
|
|
4475
|
+
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;
|
|
4476
|
+
}
|
|
4477
|
+
async function defaultAdvertise() {
|
|
4478
|
+
const { stdout } = await run(["ip", "-4", "route", "get", "1.1.1.1"]).catch((err) => {
|
|
4479
|
+
throw new KvboxError(`cannot tell this host's address (${err.message}); pass --advertise <host-or-ip>`);
|
|
4480
|
+
});
|
|
4481
|
+
const m = /\bsrc\s+(\S+)/.exec(stdout);
|
|
4482
|
+
if (!m) throw new KvboxError("cannot tell this host's address from its routes; pass --advertise <host-or-ip>");
|
|
4483
|
+
return m[1];
|
|
4484
|
+
}
|
|
4485
|
+
async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdvertise) {
|
|
4486
|
+
const url = opts.url.replace(/\/+$/, "");
|
|
4487
|
+
const port = opts.port ?? DEFAULT_HTTPS_PORT;
|
|
4488
|
+
const cfg = await loadConfig(p);
|
|
4489
|
+
if (cfg.controlPlane) throw new KvboxError(`this host has already joined ${cfg.controlPlane.name} (${cfg.controlPlane.url}); run kvbox-server leave first`);
|
|
4490
|
+
let advertise = opts.advertise;
|
|
4491
|
+
if (advertise === void 0 && cfg.relay) {
|
|
4492
|
+
advertise = cfg.relay.publicIp;
|
|
4493
|
+
} else if (advertise === void 0) {
|
|
4494
|
+
advertise = await guessAddress();
|
|
4495
|
+
if (isPrivateAddress(advertise)) {
|
|
4496
|
+
throw new KvboxError(
|
|
4497
|
+
`${advertise} is a private address: a control plane on the internet cannot reach this host there.
|
|
4498
|
+
Pass --advertise <public host or ip>, or --advertise ${advertise} if the control plane is on the same network.`
|
|
4499
|
+
);
|
|
4500
|
+
}
|
|
4501
|
+
}
|
|
4502
|
+
const name = opts.name ?? osHostname();
|
|
4503
|
+
const country = opts.country === void 0 ? void 0 : parseCountry(opts.country);
|
|
4504
|
+
const { fingerprint } = await ensureTlsCert(p);
|
|
4505
|
+
const hostUrl = `https://${advertise}:${port}`;
|
|
4506
|
+
const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
|
|
4507
|
+
const res = await request2(`${url}/hosts/join`, {
|
|
4508
|
+
method: "POST",
|
|
4509
|
+
headers: { "content-type": "application/json" },
|
|
4510
|
+
body: JSON.stringify(body),
|
|
4511
|
+
headersTimeout: 1e4,
|
|
4512
|
+
bodyTimeout: 1e4
|
|
4513
|
+
}).catch((err) => {
|
|
4514
|
+
throw new KvboxError(`cannot reach ${url} (${err.message})`);
|
|
4515
|
+
});
|
|
4516
|
+
const text = await res.body.text();
|
|
4517
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
4518
|
+
throw new KvboxError(errorIn(text) ?? `control plane answered ${res.statusCode}`);
|
|
4519
|
+
}
|
|
4520
|
+
const parsed = HostJoinResponseSchema.safeParse(jsonOrNull(text));
|
|
4521
|
+
if (!parsed.success) throw new KvboxError(`${url} did not answer like a kvbox control plane`);
|
|
4522
|
+
if (!REALM_RE.test(parsed.data.controlPlane.name)) {
|
|
4523
|
+
throw new KvboxError(`${url} calls itself "${parsed.data.controlPlane.name}", which cannot name a realm (letters, digits, '.', '-')`);
|
|
4524
|
+
}
|
|
4525
|
+
await saveConfig({ ...cfg, controlPlane: { url, name: parsed.data.controlPlane.name, secret: parsed.data.hostSecret, advertise, port } }, p);
|
|
4526
|
+
return { hostName: name, controlPlane: parsed.data.controlPlane.name, hostUrl };
|
|
4542
4527
|
}
|
|
4543
|
-
|
|
4544
|
-
|
|
4545
|
-
|
|
4546
|
-
|
|
4547
|
-
|
|
4548
|
-
|
|
4549
|
-
|
|
4550
|
-
|
|
4551
|
-
|
|
4552
|
-
|
|
4553
|
-
|
|
4554
|
-
|
|
4555
|
-
|
|
4556
|
-
|
|
4557
|
-
|
|
4558
|
-
|
|
4559
|
-
|
|
4560
|
-
|
|
4561
|
-
|
|
4562
|
-
|
|
4563
|
-
|
|
4564
|
-
|
|
4565
|
-
|
|
4566
|
-
}
|
|
4567
|
-
|
|
4568
|
-
|
|
4528
|
+
async function fetchCloudCa(p = paths()) {
|
|
4529
|
+
const cfg = await loadConfig(p);
|
|
4530
|
+
const cp = cfg.controlPlane;
|
|
4531
|
+
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>");
|
|
4532
|
+
const res = await request2(`${cp.url}/hosts/self/ssh-ca`, {
|
|
4533
|
+
headers: { authorization: `Bearer ${cp.secret}` },
|
|
4534
|
+
headersTimeout: 1e4,
|
|
4535
|
+
bodyTimeout: 1e4
|
|
4536
|
+
}).catch((err) => {
|
|
4537
|
+
throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
|
|
4538
|
+
});
|
|
4539
|
+
const text = await res.body.text();
|
|
4540
|
+
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`);
|
|
4541
|
+
if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(errorIn(text) ?? `${cp.name} answered ${res.statusCode}`);
|
|
4542
|
+
const parsed = HostSshCaResponseSchema.safeParse(jsonOrNull(text));
|
|
4543
|
+
if (!parsed.success) throw new KvboxError(`${cp.name} did not answer with a CA key`);
|
|
4544
|
+
const publicKey = parseSshPublicKey(parsed.data.publicKey);
|
|
4545
|
+
return { controlPlane: cp.name, publicKey, fingerprint: sshKeyFingerprint(publicKey) };
|
|
4546
|
+
}
|
|
4547
|
+
async function leaveControlPlane(p = paths()) {
|
|
4548
|
+
const cfg = await loadConfig(p);
|
|
4549
|
+
const cp = cfg.controlPlane;
|
|
4550
|
+
if (!cp) throw new KvboxError("this host has not joined a control plane");
|
|
4551
|
+
const told = await request2(`${cp.url}/hosts/self`, {
|
|
4552
|
+
method: "DELETE",
|
|
4553
|
+
headers: { authorization: `Bearer ${cp.secret}` },
|
|
4554
|
+
headersTimeout: 3e3,
|
|
4555
|
+
bodyTimeout: 3e3
|
|
4556
|
+
}).then(async (res) => {
|
|
4557
|
+
await res.body.dump();
|
|
4558
|
+
return res.statusCode >= 200 && res.statusCode < 300;
|
|
4559
|
+
}).catch(() => false);
|
|
4560
|
+
const { controlPlane: _gone, ...rest } = cfg;
|
|
4561
|
+
await saveConfig(rest, p);
|
|
4562
|
+
return { controlPlane: cp.name, told };
|
|
4563
|
+
}
|
|
4564
|
+
function jsonOrNull(text) {
|
|
4569
4565
|
try {
|
|
4570
|
-
|
|
4566
|
+
return JSON.parse(text);
|
|
4571
4567
|
} catch {
|
|
4572
4568
|
return null;
|
|
4573
4569
|
}
|
|
4574
|
-
|
|
4575
|
-
|
|
4570
|
+
}
|
|
4571
|
+
function errorIn(text) {
|
|
4572
|
+
const v = jsonOrNull(text);
|
|
4573
|
+
if (v && typeof v === "object" && typeof v.error === "string") return v.error;
|
|
4574
|
+
return void 0;
|
|
4576
4575
|
}
|
|
4577
4576
|
|
|
4578
4577
|
// src/core/relay.ts
|
|
4579
4578
|
function relayConf(join3) {
|
|
4580
4579
|
return [
|
|
4581
|
-
"# kvbox relay tunnel: made by `kvbox
|
|
4580
|
+
"# kvbox relay tunnel: made by `kvbox-server relay`, installed by net-setup.sh. Do not edit.",
|
|
4582
4581
|
"[Interface]",
|
|
4583
4582
|
`PrivateKey = ${join3.privateKey}`,
|
|
4584
4583
|
`Address = ${join3.tunnelIp}/32`,
|
|
@@ -4599,11 +4598,11 @@ async function useRelay(joinString, p = paths()) {
|
|
|
4599
4598
|
if (!join3) throw new KvboxError("that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay");
|
|
4600
4599
|
const cfg = await loadConfig(p);
|
|
4601
4600
|
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
|
|
4601
|
+
throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox-server relay off first`);
|
|
4603
4602
|
}
|
|
4604
4603
|
if (cfg.relay && cfg.relay.publicIp !== join3.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {
|
|
4605
4604
|
throw new KvboxError(
|
|
4606
|
-
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join3.publicIp}; run kvbox
|
|
4605
|
+
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join3.publicIp}; run kvbox-server leave first, then join again`
|
|
4607
4606
|
);
|
|
4608
4607
|
}
|
|
4609
4608
|
await mkdir8(p.relay, { recursive: true, mode: 448 });
|
|
@@ -4626,7 +4625,7 @@ async function dropRelay(p = paths()) {
|
|
|
4626
4625
|
const relay = cfg.relay;
|
|
4627
4626
|
if (!relay) throw new KvboxError("this host does not go through a relay");
|
|
4628
4627
|
if (cfg.controlPlane?.advertise === relay.publicIp) {
|
|
4629
|
-
throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox
|
|
4628
|
+
throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
|
|
4630
4629
|
}
|
|
4631
4630
|
await netSetup(cfg, ["relay", "down"]);
|
|
4632
4631
|
await rm5(p.relayConf, { force: true });
|
|
@@ -4802,8 +4801,241 @@ function startRelayWatch(opts = {}) {
|
|
|
4802
4801
|
};
|
|
4803
4802
|
}
|
|
4804
4803
|
|
|
4804
|
+
// src/daemon.ts
|
|
4805
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
4806
|
+
import { accessSync, constants as constants2, openSync as openSync4, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
|
|
4807
|
+
import { mkdir as mkdir9, readFile as readFile9, stat as stat4 } from "node:fs/promises";
|
|
4808
|
+
import { userInfo as userInfo2 } from "node:os";
|
|
4809
|
+
import { setTimeout as sleep3 } from "node:timers/promises";
|
|
4810
|
+
|
|
4811
|
+
// ../shared/src/systemd.ts
|
|
4812
|
+
import { spawnSync } from "node:child_process";
|
|
4813
|
+
import { readFileSync as readFileSync2 } from "node:fs";
|
|
4814
|
+
import { resolve } from "node:path";
|
|
4815
|
+
var UNIT = "kvbox-server";
|
|
4816
|
+
var UNIT_FILE = `/etc/systemd/system/${UNIT}.service`;
|
|
4817
|
+
function hasUnitFor(p, file = UNIT_FILE) {
|
|
4818
|
+
let text;
|
|
4819
|
+
try {
|
|
4820
|
+
text = readFileSync2(file, "utf8");
|
|
4821
|
+
} catch {
|
|
4822
|
+
return false;
|
|
4823
|
+
}
|
|
4824
|
+
const home = /^Environment="?KVBOX_HOME=([^"\n]+)"?$/m.exec(text)?.[1];
|
|
4825
|
+
return home !== void 0 && resolve(home) === resolve(p.home);
|
|
4826
|
+
}
|
|
4827
|
+
function startUnitProcess() {
|
|
4828
|
+
const res = spawnSync("sudo", ["-n", "systemctl", "start", UNIT], { encoding: "utf8" });
|
|
4829
|
+
return { ok: res.status === 0, out: `${res.stdout ?? ""}${res.stderr ?? ""}`.trim() };
|
|
4830
|
+
}
|
|
4831
|
+
function unitActive() {
|
|
4832
|
+
const res = spawnSync("systemctl", ["is-active", UNIT], { encoding: "utf8" });
|
|
4833
|
+
return (res.stdout ?? "").trim() === "active";
|
|
4834
|
+
}
|
|
4835
|
+
function startsAtBoot(p) {
|
|
4836
|
+
return hasUnitFor(p) && spawnSync("systemctl", ["is-enabled", "--quiet", UNIT]).status === 0;
|
|
4837
|
+
}
|
|
4838
|
+
|
|
4839
|
+
// src/socketClient.ts
|
|
4840
|
+
import { Agent as Agent2, request as request3 } from "undici";
|
|
4841
|
+
var SocketClient = class {
|
|
4842
|
+
agent;
|
|
4843
|
+
constructor(socketPath) {
|
|
4844
|
+
this.agent = new Agent2({ connect: { socketPath } });
|
|
4845
|
+
}
|
|
4846
|
+
health() {
|
|
4847
|
+
return this.call("GET", "/health", HealthSchema);
|
|
4848
|
+
}
|
|
4849
|
+
cloudCa() {
|
|
4850
|
+
return this.call("GET", "/ssh/cloud-ca", CloudCaSchema);
|
|
4851
|
+
}
|
|
4852
|
+
trustCa(req) {
|
|
4853
|
+
return this.call("POST", "/ssh/trust-ca", TrustCaReportSchema, req);
|
|
4854
|
+
}
|
|
4855
|
+
async close() {
|
|
4856
|
+
await this.agent.close();
|
|
4857
|
+
}
|
|
4858
|
+
async call(method, path, schema, body) {
|
|
4859
|
+
let res;
|
|
4860
|
+
try {
|
|
4861
|
+
res = await request3(`http://kvbox-server${path}`, {
|
|
4862
|
+
method,
|
|
4863
|
+
dispatcher: this.agent,
|
|
4864
|
+
...body === void 0 ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }
|
|
4865
|
+
});
|
|
4866
|
+
} catch (err) {
|
|
4867
|
+
const code = err.code ?? "";
|
|
4868
|
+
if (code === "ENOENT" || code === "ECONNREFUSED") throw new KvboxError("kvbox-server is not running; start it with: kvbox-server start -d");
|
|
4869
|
+
throw new KvboxError(`cannot reach kvbox-server: ${err.message}`);
|
|
4870
|
+
}
|
|
4871
|
+
const text = await res.body.text();
|
|
4872
|
+
if (res.statusCode >= 300) {
|
|
4873
|
+
const parsed = ApiErrorSchema.safeParse(safeJson(text) ?? {});
|
|
4874
|
+
if (!parsed.success) throw new KvboxError(`kvbox-server answered ${res.statusCode}`);
|
|
4875
|
+
throw new KvboxError(parsed.data.error, res.statusCode === 501 ? 2 : 1);
|
|
4876
|
+
}
|
|
4877
|
+
const json = safeJson(text);
|
|
4878
|
+
if (json === void 0) throw new KvboxError(`kvbox-server answered ${res.statusCode} with something that is not JSON`);
|
|
4879
|
+
return schema.parse(json);
|
|
4880
|
+
}
|
|
4881
|
+
};
|
|
4882
|
+
function safeJson(text) {
|
|
4883
|
+
try {
|
|
4884
|
+
return JSON.parse(text);
|
|
4885
|
+
} catch {
|
|
4886
|
+
return void 0;
|
|
4887
|
+
}
|
|
4888
|
+
}
|
|
4889
|
+
|
|
4890
|
+
// src/daemon.ts
|
|
4891
|
+
async function runningPid(p = paths()) {
|
|
4892
|
+
let pid;
|
|
4893
|
+
try {
|
|
4894
|
+
pid = Number.parseInt(await readFile9(p.serverPid, "utf8"), 10);
|
|
4895
|
+
} catch {
|
|
4896
|
+
return null;
|
|
4897
|
+
}
|
|
4898
|
+
return Number.isInteger(pid) && alive(pid) ? pid : null;
|
|
4899
|
+
}
|
|
4900
|
+
function alive(pid) {
|
|
4901
|
+
try {
|
|
4902
|
+
process.kill(pid, 0);
|
|
4903
|
+
return true;
|
|
4904
|
+
} catch {
|
|
4905
|
+
return false;
|
|
4906
|
+
}
|
|
4907
|
+
}
|
|
4908
|
+
async function stopDaemon(pid, timeoutMs = 1e4) {
|
|
4909
|
+
process.kill(pid, "SIGTERM");
|
|
4910
|
+
const deadline = Date.now() + timeoutMs;
|
|
4911
|
+
while (alive(pid)) {
|
|
4912
|
+
if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1e3}s`);
|
|
4913
|
+
await sleep3(100);
|
|
4914
|
+
}
|
|
4915
|
+
}
|
|
4916
|
+
async function answering(p = paths()) {
|
|
4917
|
+
if (!await stat4(p.serverSock).then(() => true, () => false)) return null;
|
|
4918
|
+
const probe = new SocketClient(p.serverSock);
|
|
4919
|
+
try {
|
|
4920
|
+
const health = await probe.health();
|
|
4921
|
+
return { pid: health.pid, version: health.version };
|
|
4922
|
+
} catch {
|
|
4923
|
+
return null;
|
|
4924
|
+
} finally {
|
|
4925
|
+
await probe.close();
|
|
4926
|
+
}
|
|
4927
|
+
}
|
|
4928
|
+
async function startDetached(p = paths(), timeoutMs = 5e3) {
|
|
4929
|
+
await mkdir9(p.home, { recursive: true });
|
|
4930
|
+
const running = await answering(p);
|
|
4931
|
+
if (running) return { pid: running.pid, socketPath: p.serverSock, viaGroup: void 0, viaUnit: false, alreadyRunning: running.version };
|
|
4932
|
+
if (hasUnitFor(p)) return startUnit(p, timeoutMs);
|
|
4933
|
+
const log2 = openSync4(p.serverLog, "a");
|
|
4934
|
+
const launcher = selfLauncher();
|
|
4935
|
+
const child = spawn2(launcher.cmd, launcher.args, { detached: true, stdio: ["ignore", log2, log2], env: { ...process.env, KVBOX_HOME: p.home } });
|
|
4936
|
+
const failed = new Promise((_, reject) => {
|
|
4937
|
+
child.once("error", (err) => reject(new KvboxError(`could not start kvbox-server: ${err.message}`)));
|
|
4938
|
+
child.once("exit", (code) => {
|
|
4939
|
+
void lastErrorLine(p.serverLog).then((why) => {
|
|
4940
|
+
reject(new KvboxError(why === void 0 ? `kvbox-server exited with code ${String(code)} before listening; see ${p.serverLog}` : `kvbox-server could not start: ${why}`));
|
|
4941
|
+
});
|
|
4942
|
+
});
|
|
4943
|
+
});
|
|
4944
|
+
await Promise.race([serving(p, timeoutMs), failed]);
|
|
4945
|
+
child.removeAllListeners("exit");
|
|
4946
|
+
child.unref();
|
|
4947
|
+
return { pid: await pidFile(p, child.pid ?? -1), socketPath: p.serverSock, viaGroup: launcher.viaGroup, viaUnit: false };
|
|
4948
|
+
}
|
|
4949
|
+
async function restartDaemon(p = paths()) {
|
|
4950
|
+
const pid = await runningPid(p);
|
|
4951
|
+
if (pid !== null) await stopDaemon(pid);
|
|
4952
|
+
return startDetached(p);
|
|
4953
|
+
}
|
|
4954
|
+
async function startUnit(p, timeoutMs) {
|
|
4955
|
+
const logFrom = await stat4(p.serverLog).then((s) => s.size, () => 0);
|
|
4956
|
+
const res = startUnitProcess();
|
|
4957
|
+
if (!res.ok) {
|
|
4958
|
+
const why = res.out || await lastErrorLine(p.serverLog, logFrom) || "systemctl start failed";
|
|
4959
|
+
throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT}; rerun install-server.sh if sudo asked for a password)`);
|
|
4960
|
+
}
|
|
4961
|
+
await serving(p, timeoutMs, async () => {
|
|
4962
|
+
if (unitActive()) return;
|
|
4963
|
+
const why = await lastErrorLine(p.serverLog, logFrom) ?? "it exited right after starting";
|
|
4964
|
+
throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT})`);
|
|
4965
|
+
});
|
|
4966
|
+
return { pid: await pidFile(p, -1), socketPath: p.serverSock, viaGroup: void 0, viaUnit: true };
|
|
4967
|
+
}
|
|
4968
|
+
async function pidFile(p, fallback) {
|
|
4969
|
+
const pid = Number.parseInt(await readFile9(p.serverPid, "utf8").catch(() => ""), 10);
|
|
4970
|
+
return Number.isNaN(pid) ? fallback : pid;
|
|
4971
|
+
}
|
|
4972
|
+
async function serving(p, timeoutMs, check) {
|
|
4973
|
+
const deadline = Date.now() + timeoutMs;
|
|
4974
|
+
while (Date.now() < deadline) {
|
|
4975
|
+
await check?.();
|
|
4976
|
+
if (await stat4(p.serverSock).then(() => true, () => false)) {
|
|
4977
|
+
const probe = new SocketClient(p.serverSock);
|
|
4978
|
+
try {
|
|
4979
|
+
await probe.health();
|
|
4980
|
+
return;
|
|
4981
|
+
} catch {
|
|
4982
|
+
} finally {
|
|
4983
|
+
await probe.close();
|
|
4984
|
+
}
|
|
4985
|
+
}
|
|
4986
|
+
await sleep3(100);
|
|
4987
|
+
}
|
|
4988
|
+
throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
|
|
4989
|
+
}
|
|
4990
|
+
async function lastErrorLine(logPath, from = 0) {
|
|
4991
|
+
const text = (await readFile9(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
|
|
4992
|
+
for (const line of text.trimEnd().split("\n").slice(-20).reverse()) {
|
|
4993
|
+
const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
|
|
4994
|
+
if (m?.[1] !== void 0) return m[1];
|
|
4995
|
+
}
|
|
4996
|
+
return void 0;
|
|
4997
|
+
}
|
|
4998
|
+
function selfLauncher(opts = {}) {
|
|
4999
|
+
const device = opts.device ?? KVM_DEVICE;
|
|
5000
|
+
const argv = [process.execPath, ...process.execArgv, process.argv[1] ?? "kvbox-server", "start"];
|
|
5001
|
+
const plain = { cmd: argv[0], args: argv.slice(1) };
|
|
5002
|
+
try {
|
|
5003
|
+
accessSync(device, constants2.R_OK | constants2.W_OK);
|
|
5004
|
+
return plain;
|
|
5005
|
+
} catch (err) {
|
|
5006
|
+
const code = err.code;
|
|
5007
|
+
if (code !== "EACCES" && code !== "EPERM") return plain;
|
|
5008
|
+
}
|
|
5009
|
+
let gid;
|
|
5010
|
+
try {
|
|
5011
|
+
gid = statSync3(device).gid;
|
|
5012
|
+
} catch {
|
|
5013
|
+
return plain;
|
|
5014
|
+
}
|
|
5015
|
+
const group = groupWithMember(gid, opts.user ?? userInfo2().username, opts.groupFile ?? "/etc/group");
|
|
5016
|
+
if (group === void 0) return plain;
|
|
5017
|
+
return { cmd: "sg", args: [group, "-c", argv.map(shellQuote).join(" ")], viaGroup: group };
|
|
5018
|
+
}
|
|
5019
|
+
function shellQuote(word) {
|
|
5020
|
+
return `'${word.replaceAll("'", `'\\''`)}'`;
|
|
5021
|
+
}
|
|
5022
|
+
function groupWithMember(gid, user, groupFile) {
|
|
5023
|
+
let text;
|
|
5024
|
+
try {
|
|
5025
|
+
text = readFileSync3(groupFile, "utf8");
|
|
5026
|
+
} catch {
|
|
5027
|
+
return void 0;
|
|
5028
|
+
}
|
|
5029
|
+
for (const line of text.split("\n")) {
|
|
5030
|
+
const [name, , id, members = ""] = line.split(":");
|
|
5031
|
+
if (name === void 0 || id === void 0 || Number.parseInt(id, 10) !== gid) continue;
|
|
5032
|
+
return members.split(",").includes(user) ? name : void 0;
|
|
5033
|
+
}
|
|
5034
|
+
return void 0;
|
|
5035
|
+
}
|
|
5036
|
+
|
|
4805
5037
|
// src/listen.ts
|
|
4806
|
-
import { readFile as
|
|
5038
|
+
import { readFile as readFile10, rm as rm6, writeFile as writeFile8 } from "node:fs/promises";
|
|
4807
5039
|
import { createServer as createHttpsServer } from "node:https";
|
|
4808
5040
|
import { createAdaptorServer } from "@hono/node-server";
|
|
4809
5041
|
|
|
@@ -4823,7 +5055,7 @@ function versionOf(srcFileUrl, injected) {
|
|
|
4823
5055
|
}
|
|
4824
5056
|
|
|
4825
5057
|
// src/version.ts
|
|
4826
|
-
var VERSION = versionOf(import.meta.url, true ? "0.5.
|
|
5058
|
+
var VERSION = versionOf(import.meta.url, true ? "0.5.44" : void 0);
|
|
4827
5059
|
|
|
4828
5060
|
// src/caller.ts
|
|
4829
5061
|
import { createHash as createHash2, timingSafeEqual } from "node:crypto";
|
|
@@ -4930,14 +5162,14 @@ function backupRoutes() {
|
|
|
4930
5162
|
import { connect as connect2 } from "node:net";
|
|
4931
5163
|
import { Readable } from "node:stream";
|
|
4932
5164
|
import { Hono as Hono2 } from "hono";
|
|
4933
|
-
import { request as
|
|
5165
|
+
import { request as request4 } from "undici";
|
|
4934
5166
|
|
|
4935
5167
|
// ../shared/src/httpHead.ts
|
|
4936
5168
|
var END = "\r\n\r\n";
|
|
4937
5169
|
var HeadTimeoutError = class extends Error {
|
|
4938
5170
|
};
|
|
4939
5171
|
function readHead(socket, opts) {
|
|
4940
|
-
return new Promise((
|
|
5172
|
+
return new Promise((resolve2, reject) => {
|
|
4941
5173
|
let bytes = Buffer.alloc(0);
|
|
4942
5174
|
const done = (err) => {
|
|
4943
5175
|
clearTimeout(timer);
|
|
@@ -4946,7 +5178,7 @@ function readHead(socket, opts) {
|
|
|
4946
5178
|
socket.pause();
|
|
4947
5179
|
if (err) return reject(err);
|
|
4948
5180
|
const end = bytes.indexOf(END);
|
|
4949
|
-
|
|
5181
|
+
resolve2({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
|
|
4950
5182
|
};
|
|
4951
5183
|
const onData = (chunk) => {
|
|
4952
5184
|
bytes = Buffer.concat([bytes, chunk]);
|
|
@@ -5072,7 +5304,7 @@ async function forward(c, wake) {
|
|
|
5072
5304
|
raw.headers.forEach((value, name) => pairs.push([name, value]));
|
|
5073
5305
|
let res;
|
|
5074
5306
|
try {
|
|
5075
|
-
res = await
|
|
5307
|
+
res = await request4(`http://${target.ip}:${target.port}${target.path}`, {
|
|
5076
5308
|
method: raw.method,
|
|
5077
5309
|
headers: boxHeaders(pairs, target).flat(),
|
|
5078
5310
|
body: raw.body === null ? null : Readable.fromWeb(raw.body),
|
|
@@ -5347,7 +5579,7 @@ import { Hono as Hono7 } from "hono";
|
|
|
5347
5579
|
function sshRoutes(opts = {}) {
|
|
5348
5580
|
const r = new Hono7();
|
|
5349
5581
|
if (opts.controlPlane) {
|
|
5350
|
-
r.all("/*", (c) => c.json({ error: "trusting a CA is done on the host itself (kvbox
|
|
5582
|
+
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
5583
|
return r;
|
|
5352
5584
|
}
|
|
5353
5585
|
r.get("/cloud-ca", async (c) => c.json(await fetchCloudCa()));
|
|
@@ -5474,9 +5706,9 @@ async function listen(opts = {}) {
|
|
|
5474
5706
|
}
|
|
5475
5707
|
await rm6(socketPath, { force: true });
|
|
5476
5708
|
const server = createAdaptorServer({ fetch: createApp().fetch });
|
|
5477
|
-
await new Promise((
|
|
5709
|
+
await new Promise((resolve2, reject) => {
|
|
5478
5710
|
server.once("error", reject);
|
|
5479
|
-
server.listen(socketPath, () =>
|
|
5711
|
+
server.listen(socketPath, () => resolve2());
|
|
5480
5712
|
});
|
|
5481
5713
|
await writeFile8(p.serverPid, `${process.pid}
|
|
5482
5714
|
`);
|
|
@@ -5484,7 +5716,7 @@ async function listen(opts = {}) {
|
|
|
5484
5716
|
let httpsServer;
|
|
5485
5717
|
const cp = cfg.controlPlane;
|
|
5486
5718
|
if (cp) {
|
|
5487
|
-
const [key, cert] = await Promise.all([
|
|
5719
|
+
const [key, cert] = await Promise.all([readFile10(p.tlsKey), readFile10(p.tlsCert)]).catch((err) => {
|
|
5488
5720
|
throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
|
|
5489
5721
|
});
|
|
5490
5722
|
httpsServer = createAdaptorServer({
|
|
@@ -5494,9 +5726,9 @@ async function listen(opts = {}) {
|
|
|
5494
5726
|
});
|
|
5495
5727
|
httpsServer.on("upgrade", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));
|
|
5496
5728
|
const port = opts.httpsPort ?? cp.port;
|
|
5497
|
-
await new Promise((
|
|
5729
|
+
await new Promise((resolve2, reject) => {
|
|
5498
5730
|
httpsServer.once("error", reject);
|
|
5499
|
-
httpsServer.listen(port, "0.0.0.0", () =>
|
|
5731
|
+
httpsServer.listen(port, "0.0.0.0", () => resolve2());
|
|
5500
5732
|
}).catch(async (err) => {
|
|
5501
5733
|
server.close();
|
|
5502
5734
|
await rm6(socketPath, { force: true });
|
|
@@ -5508,8 +5740,8 @@ async function listen(opts = {}) {
|
|
|
5508
5740
|
}
|
|
5509
5741
|
const close = async () => {
|
|
5510
5742
|
await Promise.all([
|
|
5511
|
-
new Promise((
|
|
5512
|
-
httpsServer ? new Promise((
|
|
5743
|
+
new Promise((resolve2) => server.close(() => resolve2())),
|
|
5744
|
+
httpsServer ? new Promise((resolve2) => httpsServer.close(() => resolve2())) : void 0
|
|
5513
5745
|
]);
|
|
5514
5746
|
await rm6(socketPath, { force: true });
|
|
5515
5747
|
await rm6(p.serverPid, { force: true });
|
|
@@ -5527,10 +5759,20 @@ async function listen(opts = {}) {
|
|
|
5527
5759
|
return https ? { socketPath, server, https, close } : { socketPath, server, close };
|
|
5528
5760
|
}
|
|
5529
5761
|
|
|
5530
|
-
// src/
|
|
5762
|
+
// src/commands/start.ts
|
|
5531
5763
|
var daemon = false;
|
|
5532
|
-
var
|
|
5533
|
-
|
|
5764
|
+
var isDaemon = () => daemon;
|
|
5765
|
+
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) => {
|
|
5766
|
+
if (opts.detach) {
|
|
5767
|
+
const started = await startDetached(paths());
|
|
5768
|
+
if (started.alreadyRunning !== void 0) {
|
|
5769
|
+
console.log(`kvbox-server ${started.alreadyRunning} is already running (pid ${started.pid})`);
|
|
5770
|
+
return;
|
|
5771
|
+
}
|
|
5772
|
+
console.log(`kvbox-server started (pid ${started.pid}), listening on ${started.socketPath}${started.viaUnit ? " (through systemd)" : ""}`);
|
|
5773
|
+
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)`);
|
|
5774
|
+
return;
|
|
5775
|
+
}
|
|
5534
5776
|
daemon = true;
|
|
5535
5777
|
await requireKvm();
|
|
5536
5778
|
const settled = await settleDeadBoxes(paths());
|
|
@@ -5553,7 +5795,7 @@ program.command("start", { isDefault: true }).description("serve the API on the
|
|
|
5553
5795
|
const relay = await restoreRelay(paths());
|
|
5554
5796
|
if (relay) log.info(`relay ${relay.name}: the control plane may reach this host through the tunnel again`);
|
|
5555
5797
|
} catch (err) {
|
|
5556
|
-
log.warn(`the control plane may not reach this host through its relay (${err.message}); run: kvbox
|
|
5798
|
+
log.warn(`the control plane may not reach this host through its relay (${err.message}); run: kvbox-server relay <join string>`);
|
|
5557
5799
|
}
|
|
5558
5800
|
let dnsWarned = false;
|
|
5559
5801
|
const bindDns = () => {
|
|
@@ -5576,45 +5818,236 @@ program.command("start", { isDefault: true }).description("serve the API on the
|
|
|
5576
5818
|
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
5819
|
}
|
|
5578
5820
|
});
|
|
5579
|
-
|
|
5580
|
-
|
|
5821
|
+
|
|
5822
|
+
// src/program.ts
|
|
5823
|
+
import { Command as Command10 } from "commander";
|
|
5824
|
+
|
|
5825
|
+
// src/commands/join.ts
|
|
5826
|
+
import { Command as Command2 } from "commander";
|
|
5827
|
+
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) => {
|
|
5828
|
+
const p = paths();
|
|
5829
|
+
const joined = await joinControlPlane({ url, ...opts }, p);
|
|
5581
5830
|
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
5831
|
console.log(`make sure port ${new URL(joined.hostUrl).port} is reachable from the control plane`);
|
|
5832
|
+
if (await runningPid(p) === null) {
|
|
5833
|
+
console.log(`it answers the control plane on ${joined.hostUrl} once the daemon starts (kvbox-server start -d)`);
|
|
5834
|
+
return;
|
|
5835
|
+
}
|
|
5836
|
+
const started = await restartDaemon(p);
|
|
5837
|
+
console.log(`kvbox-server restarted (pid ${started.pid}); it answers the control plane on ${joined.hostUrl} now`);
|
|
5584
5838
|
});
|
|
5585
|
-
|
|
5586
|
-
|
|
5587
|
-
|
|
5839
|
+
|
|
5840
|
+
// src/commands/leave.ts
|
|
5841
|
+
import { Command as Command3 } from "commander";
|
|
5842
|
+
var leaveCommand = new Command3("leave").description("take this host out from behind its control plane and restart the daemon").action(async () => {
|
|
5843
|
+
const p = paths();
|
|
5844
|
+
const left = await leaveControlPlane(p);
|
|
5845
|
+
console.log(`left ${left.controlPlane}`);
|
|
5588
5846
|
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}`);
|
|
5847
|
+
if (await runningPid(p) === null) {
|
|
5848
|
+
console.log("the HTTPS port stays closed from the daemon's next start");
|
|
5594
5849
|
return;
|
|
5595
5850
|
}
|
|
5596
|
-
const
|
|
5597
|
-
console.log(`
|
|
5598
|
-
|
|
5851
|
+
const started = await restartDaemon(p);
|
|
5852
|
+
console.log(`kvbox-server restarted (pid ${started.pid}); only this machine talks to it now`);
|
|
5853
|
+
});
|
|
5854
|
+
|
|
5855
|
+
// src/commands/logs.ts
|
|
5856
|
+
import { open as open2, readFile as readFile11, stat as stat5 } from "node:fs/promises";
|
|
5857
|
+
import { setTimeout as sleep4 } from "node:timers/promises";
|
|
5858
|
+
import { Command as Command4 } from "commander";
|
|
5859
|
+
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) => {
|
|
5860
|
+
const n = Number.parseInt(opts.lines, 10);
|
|
5861
|
+
if (!Number.isInteger(n) || n < 0) throw new KvboxError(`--lines: expected a number, got ${opts.lines}`);
|
|
5862
|
+
const p = paths();
|
|
5863
|
+
const text = await readFile11(p.serverLog, "utf8").catch((err) => {
|
|
5864
|
+
if (err.code === "ENOENT") throw new KvboxError(`no log yet at ${p.serverLog} (the daemon writes it once it has run)`);
|
|
5865
|
+
throw err;
|
|
5866
|
+
});
|
|
5867
|
+
const tail = tailLines(text, n);
|
|
5868
|
+
if (tail !== "") process.stdout.write(`${tail}
|
|
5869
|
+
`);
|
|
5870
|
+
if (!opts.follow) return;
|
|
5871
|
+
const ac = new AbortController();
|
|
5872
|
+
process.once("SIGINT", () => ac.abort());
|
|
5873
|
+
process.once("SIGTERM", () => ac.abort());
|
|
5874
|
+
await follow(p.serverLog, (chunk) => process.stdout.write(chunk), { from: Buffer.byteLength(text), signal: ac.signal });
|
|
5599
5875
|
});
|
|
5600
|
-
|
|
5876
|
+
function tailLines(text, n) {
|
|
5877
|
+
if (n === 0) return "";
|
|
5878
|
+
const lines = text.endsWith("\n") ? text.slice(0, -1).split("\n") : text.split("\n");
|
|
5879
|
+
return lines.slice(-n).join("\n");
|
|
5880
|
+
}
|
|
5881
|
+
async function follow(path, write, opts = {}) {
|
|
5882
|
+
const intervalMs = opts.intervalMs ?? 250;
|
|
5883
|
+
let offset = opts.from ?? await stat5(path).then((s) => s.size, () => 0);
|
|
5884
|
+
while (!opts.signal?.aborted) {
|
|
5885
|
+
const size = await stat5(path).then((s) => s.size, () => 0);
|
|
5886
|
+
if (size < offset) offset = 0;
|
|
5887
|
+
if (size > offset) {
|
|
5888
|
+
const fh = await open2(path, "r");
|
|
5889
|
+
try {
|
|
5890
|
+
const buf = Buffer.alloc(size - offset);
|
|
5891
|
+
const { bytesRead } = await fh.read(buf, 0, buf.length, offset);
|
|
5892
|
+
write(buf.subarray(0, bytesRead).toString("utf8"));
|
|
5893
|
+
offset += bytesRead;
|
|
5894
|
+
} finally {
|
|
5895
|
+
await fh.close();
|
|
5896
|
+
}
|
|
5897
|
+
}
|
|
5898
|
+
await sleep4(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
|
|
5899
|
+
}
|
|
5900
|
+
}
|
|
5901
|
+
|
|
5902
|
+
// src/commands/net.ts
|
|
5903
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
5904
|
+
import { Command as Command5 } from "commander";
|
|
5905
|
+
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
5906
|
if (!["up", "down", "status"].includes(action)) throw new KvboxError("net: expected up, down or status");
|
|
5602
5907
|
const cfg = await loadConfig(paths());
|
|
5603
|
-
const res =
|
|
5908
|
+
const res = spawnSync2(netSetupScript(), [action], {
|
|
5604
5909
|
stdio: "inherit",
|
|
5605
5910
|
env: { ...process.env, KVBOX_BRIDGE: cfg.bridge, KVBOX_SUBNET: cfg.subnet, KVBOX_GATEWAY: cfg.gateway }
|
|
5606
5911
|
});
|
|
5607
5912
|
process.exit(res.status ?? 1);
|
|
5608
5913
|
});
|
|
5914
|
+
|
|
5915
|
+
// src/commands/relay.ts
|
|
5916
|
+
import { Command as Command6 } from "commander";
|
|
5917
|
+
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) => {
|
|
5918
|
+
if (joinString === "off") {
|
|
5919
|
+
const relay2 = await dropRelay(paths());
|
|
5920
|
+
console.log(`tunnel to relay ${relay2.name} is down; this host no longer answers at ${relay2.publicIp}`);
|
|
5921
|
+
return;
|
|
5922
|
+
}
|
|
5923
|
+
const relay = await useRelay(joinString, paths());
|
|
5924
|
+
console.log(`tunnel to relay ${relay.name} (${relay.endpoint}) is up`);
|
|
5925
|
+
console.log(`this host is reachable at ${relay.publicIp}; kvbox-server join advertises it by default`);
|
|
5926
|
+
});
|
|
5927
|
+
|
|
5928
|
+
// src/commands/status.ts
|
|
5929
|
+
import { Command as Command7 } from "commander";
|
|
5930
|
+
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) => {
|
|
5931
|
+
const p = paths();
|
|
5932
|
+
const atBoot = startsAtBoot(p);
|
|
5933
|
+
const pid = await runningPid(p);
|
|
5934
|
+
if (pid === null) {
|
|
5935
|
+
if (opts.json) {
|
|
5936
|
+
console.log(JSON.stringify({ running: false, startsAtBoot: atBoot }, null, 2));
|
|
5937
|
+
process.exitCode = 1;
|
|
5938
|
+
return;
|
|
5939
|
+
}
|
|
5940
|
+
throw new KvboxError(`kvbox-server is not running (start it with: kvbox-server start -d)${atBoot ? "; it starts at boot" : ""}`);
|
|
5941
|
+
}
|
|
5942
|
+
const client = new SocketClient(p.serverSock);
|
|
5943
|
+
try {
|
|
5944
|
+
const health = await client.health();
|
|
5945
|
+
if (opts.json) {
|
|
5946
|
+
console.log(JSON.stringify({ running: true, ...health, startsAtBoot: atBoot }, null, 2));
|
|
5947
|
+
return;
|
|
5948
|
+
}
|
|
5949
|
+
console.log(`kvbox-server ${health.version} running, pid ${health.pid}`);
|
|
5950
|
+
console.log(atBoot ? "starts at boot: yes, and brings back the boxes that were running" : "starts at boot: no (install-server.sh sets that up)");
|
|
5951
|
+
const r = health.recovery;
|
|
5952
|
+
if (r) {
|
|
5953
|
+
if (r.booted.length > 0) console.log(`after the last restart it booted again: ${r.booted.join(", ")}`);
|
|
5954
|
+
if (r.leftStopped.length > 0) console.log(`left stopped (were in standby, their memory was lost): ${r.leftStopped.join(", ")}`);
|
|
5955
|
+
for (const f of r.failed) console.log(`did not come back: ${f.box} (${f.error})`);
|
|
5956
|
+
}
|
|
5957
|
+
if (health.controlPlane) console.log(`control plane: ${health.controlPlane.name} at ${health.controlPlane.url}, this host answers it on ${health.controlPlane.hostUrl}`);
|
|
5958
|
+
else console.log("control plane: none (kvbox-server join <url> --token <token> puts this host behind one)");
|
|
5959
|
+
if (health.relay) {
|
|
5960
|
+
console.log(`relay: ${health.relay.name} lends this host ${health.relay.publicIp} (tunnel to ${health.relay.endpoint})`);
|
|
5961
|
+
if (health.relay.restarts && health.relay.lastRestartAt) {
|
|
5962
|
+
console.log(`the tunnel stopped carrying traffic and was redialed ${health.relay.restarts} time(s) since the server started, last at ${health.relay.lastRestartAt}`);
|
|
5963
|
+
}
|
|
5964
|
+
}
|
|
5965
|
+
if (health.base === null) console.log("base image: none usable yet (run install-server.sh)");
|
|
5966
|
+
else console.log(`base image: ${health.base} (what kvbox new uses; kvbox vm update <box> moves an older box onto it)`);
|
|
5967
|
+
console.log(`log: ${p.serverLog} (kvbox-server logs -f)`);
|
|
5968
|
+
} finally {
|
|
5969
|
+
await client.close();
|
|
5970
|
+
}
|
|
5971
|
+
});
|
|
5972
|
+
|
|
5973
|
+
// src/commands/stop.ts
|
|
5974
|
+
import { Command as Command8 } from "commander";
|
|
5975
|
+
var stopCommand = new Command8("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
|
|
5976
|
+
const pid = await runningPid(paths());
|
|
5977
|
+
if (pid === null) throw new KvboxError("kvbox-server is not running");
|
|
5978
|
+
await stopDaemon(pid);
|
|
5979
|
+
console.log(`kvbox-server stopped (pid ${pid}); boxes keep running`);
|
|
5980
|
+
});
|
|
5981
|
+
|
|
5982
|
+
// src/commands/trust-ca.ts
|
|
5983
|
+
import { Command as Command9 } from "commander";
|
|
5984
|
+
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) => {
|
|
5985
|
+
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");
|
|
5986
|
+
if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
|
|
5987
|
+
const client = new SocketClient(paths().serverSock);
|
|
5988
|
+
try {
|
|
5989
|
+
let key = publicKey;
|
|
5990
|
+
if (key === void 0) {
|
|
5991
|
+
const ca = await client.cloudCa();
|
|
5992
|
+
console.log(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);
|
|
5993
|
+
if (!await confirm("make every cloud box on this host trust it (in place of the CA it trusts now)?", opts.yes ?? false)) {
|
|
5994
|
+
throw new KvboxError("cancelled", 130);
|
|
5995
|
+
}
|
|
5996
|
+
key = ca.publicKey;
|
|
5997
|
+
}
|
|
5998
|
+
const report2 = await client.trustCa({ publicKey: key });
|
|
5999
|
+
if (opts.json) console.log(JSON.stringify(report2, null, 2));
|
|
6000
|
+
else describeReport(report2);
|
|
6001
|
+
} finally {
|
|
6002
|
+
await client.close();
|
|
6003
|
+
}
|
|
6004
|
+
});
|
|
6005
|
+
async function confirm(question, yes) {
|
|
6006
|
+
if (yes) return true;
|
|
6007
|
+
if (!process.stdin.isTTY) {
|
|
6008
|
+
console.error("refusing without -y when stdin is not a terminal");
|
|
6009
|
+
return false;
|
|
6010
|
+
}
|
|
6011
|
+
const { createInterface } = await import("node:readline/promises");
|
|
6012
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
6013
|
+
try {
|
|
6014
|
+
const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
|
|
6015
|
+
return answer === "y" || answer === "yes";
|
|
6016
|
+
} finally {
|
|
6017
|
+
rl.close();
|
|
6018
|
+
}
|
|
6019
|
+
}
|
|
6020
|
+
var WHEN = {
|
|
6021
|
+
start: "is stopped: it trusts the CA from its next start",
|
|
6022
|
+
wake: "is hibernated: it trusts the CA from its next wake",
|
|
6023
|
+
resume: "is in standby: it trusts the CA from its next resume",
|
|
6024
|
+
later: "is running but could not take it now; it trusts the CA from its next stop and start"
|
|
6025
|
+
};
|
|
6026
|
+
function describeReport(report2) {
|
|
6027
|
+
console.log(`CA ${report2.fingerprint}`);
|
|
6028
|
+
for (const box of report2.updated) console.log(`box ${box} now trusts the CA`);
|
|
6029
|
+
for (const p of report2.pending) console.log(`box ${p.box} ${WHEN[p.when]}${p.why ? ` (${p.why})` : ""}`);
|
|
6030
|
+
for (const f of report2.failed) console.error(`box ${f.box}: ${f.error}`);
|
|
6031
|
+
const parts = [`${report2.updated.length} box(es) updated now`, `${report2.pending.length} pending`, `${report2.failed.length} failed`];
|
|
6032
|
+
if (report2.local > 0) parts.push(`${report2.local} local box(es) untouched (they trust this host's key only)`);
|
|
6033
|
+
console.log(parts.join(", "));
|
|
6034
|
+
}
|
|
6035
|
+
|
|
6036
|
+
// src/program.ts
|
|
6037
|
+
function buildProgram() {
|
|
6038
|
+
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, { isDefault: true }).addCommand(stopCommand).addCommand(statusCommand).addCommand(logsCommand).addCommand(joinCommand).addCommand(leaveCommand).addCommand(relayCommand).addCommand(trustCaCommand).addCommand(netCommand);
|
|
6039
|
+
}
|
|
6040
|
+
|
|
6041
|
+
// src/index.ts
|
|
5609
6042
|
try {
|
|
5610
|
-
await
|
|
6043
|
+
await buildProgram().parseAsync(process.argv);
|
|
5611
6044
|
} catch (err) {
|
|
5612
6045
|
if (err instanceof KvboxError) {
|
|
5613
|
-
if (
|
|
6046
|
+
if (isDaemon()) log.error(err.message);
|
|
5614
6047
|
else console.error(`error: ${err.message}`);
|
|
5615
6048
|
process.exit(err.exitCode);
|
|
5616
6049
|
}
|
|
5617
|
-
if (
|
|
6050
|
+
if (isDaemon()) {
|
|
5618
6051
|
log.error(err.stack ?? String(err));
|
|
5619
6052
|
process.exit(1);
|
|
5620
6053
|
}
|