@kvbox/cli 0.6.2 → 0.6.4
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.js +1344 -940
- package/dist/kvbox.js.map +1 -1
- package/package.json +1 -1
package/dist/kvbox.js
CHANGED
|
@@ -149,7 +149,7 @@ async function spin(message, work, opts = {}) {
|
|
|
149
149
|
}
|
|
150
150
|
|
|
151
151
|
// src/program.ts
|
|
152
|
-
import { Command as
|
|
152
|
+
import { Command as Command116 } from "commander";
|
|
153
153
|
|
|
154
154
|
// ../shared/src/version.ts
|
|
155
155
|
import { createRequire } from "module";
|
|
@@ -164,17 +164,20 @@ function versionOf(srcFileUrl, injected) {
|
|
|
164
164
|
}
|
|
165
165
|
|
|
166
166
|
// src/version.ts
|
|
167
|
-
var VERSION = versionOf(import.meta.url, true ? "0.6.
|
|
167
|
+
var VERSION = versionOf(import.meta.url, true ? "0.6.4" : void 0);
|
|
168
168
|
|
|
169
169
|
// src/commands/vm/index.ts
|
|
170
170
|
import { Command as Command37 } from "commander";
|
|
171
171
|
|
|
172
172
|
// src/commands/vm/connect.ts
|
|
173
|
-
import { spawnSync as
|
|
173
|
+
import { spawnSync as spawnSync3 } from "child_process";
|
|
174
174
|
import { Command as Command2 } from "commander";
|
|
175
175
|
|
|
176
176
|
// src/cert.ts
|
|
177
|
-
import {
|
|
177
|
+
import { spawnSync } from "child_process";
|
|
178
|
+
import { randomBytes } from "crypto";
|
|
179
|
+
import { link, mkdir as mkdir2, readFile as readFile2, rename, rm as rm2, writeFile as writeFile2 } from "fs/promises";
|
|
180
|
+
import { hostname as osHostname } from "os";
|
|
178
181
|
|
|
179
182
|
// ../shared/src/paths.ts
|
|
180
183
|
import { homedir } from "os";
|
|
@@ -334,113 +337,10 @@ function volumeMountPath(volume) {
|
|
|
334
337
|
|
|
335
338
|
// src/session.ts
|
|
336
339
|
import { chmod, mkdir, readFile, rm, writeFile } from "fs/promises";
|
|
337
|
-
import { z } from "zod";
|
|
338
|
-
var SessionSchema = z.object({
|
|
339
|
-
url: z.string(),
|
|
340
|
-
token: z.string(),
|
|
341
|
-
user: z.string(),
|
|
342
|
-
/** When the SSH certificate at paths().sshCert stops being accepted (ISO); absent before the first login with a key. */
|
|
343
|
-
sshCertExpires: z.string().optional(),
|
|
344
|
-
/** Whose boxes that certificate opens (`<slug>@<realm>`, the user and their orgs); absent with `sshCertExpires`. */
|
|
345
|
-
sshCertPrincipals: z.array(z.string()).optional()
|
|
346
|
-
});
|
|
347
|
-
async function readSession(p = paths()) {
|
|
348
|
-
let text2;
|
|
349
|
-
try {
|
|
350
|
-
text2 = await readFile(p.cli, "utf8");
|
|
351
|
-
} catch (err) {
|
|
352
|
-
if (err.code === "ENOENT") return null;
|
|
353
|
-
throw err;
|
|
354
|
-
}
|
|
355
|
-
try {
|
|
356
|
-
return SessionSchema.parse(JSON.parse(text2));
|
|
357
|
-
} catch {
|
|
358
|
-
throw new KvboxError(`${p.cli} is unreadable; run: kvbox logout (then log in again)`);
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
async function writeSession(session, p = paths()) {
|
|
362
|
-
await mkdir(p.home, { recursive: true });
|
|
363
|
-
await writeFile(p.cli, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
|
|
364
|
-
await chmod(p.cli, 384);
|
|
365
|
-
}
|
|
366
|
-
async function clearSession(p = paths()) {
|
|
367
|
-
await rm(p.cli, { force: true });
|
|
368
|
-
}
|
|
369
|
-
function hostOf(url) {
|
|
370
|
-
try {
|
|
371
|
-
return new URL(url).host;
|
|
372
|
-
} catch {
|
|
373
|
-
return url;
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
function isLoopback(hostname) {
|
|
377
|
-
return hostname === "localhost" || hostname.startsWith("127.") || hostname === "[::1]";
|
|
378
|
-
}
|
|
379
|
-
function normalizeUrl(input) {
|
|
380
|
-
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `https://${input}`;
|
|
381
|
-
let url;
|
|
382
|
-
try {
|
|
383
|
-
url = new URL(withScheme);
|
|
384
|
-
} catch {
|
|
385
|
-
throw new KvboxError(`not a URL: ${input}`);
|
|
386
|
-
}
|
|
387
|
-
if (!/^https?:$/.test(url.protocol) || url.hostname === "" || /\s/.test(input)) throw new KvboxError(`not a URL: ${input}`);
|
|
388
|
-
if (url.protocol === "http:" && !isLoopback(url.hostname)) {
|
|
389
|
-
throw new KvboxError(`${input}: use https (plain http is only allowed for localhost)`);
|
|
390
|
-
}
|
|
391
|
-
return url.origin + url.pathname.replace(/\/+$/, "");
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
// src/cert.ts
|
|
395
|
-
var RENEW_BEFORE_MS = 60 * 60 * 1e3;
|
|
396
|
-
async function writeCert(cert, p = paths()) {
|
|
397
|
-
await writeFile2(p.sshCert, cert.trim() + "\n", { mode: 420 });
|
|
398
|
-
}
|
|
399
|
-
async function renewAfterRefusal(client, kept, owner, p = paths()) {
|
|
400
|
-
if (kept !== "kept") return false;
|
|
401
|
-
await ensureCert(client, p, Date.now(), { owner, force: true });
|
|
402
|
-
return true;
|
|
403
|
-
}
|
|
404
|
-
async function removeCert(p = paths()) {
|
|
405
|
-
await rm2(p.sshCert, { force: true });
|
|
406
|
-
}
|
|
407
|
-
async function ensureCert(client, p = paths(), now = Date.now(), opts = {}) {
|
|
408
|
-
if (client.target.kind !== "cloud") return "local";
|
|
409
|
-
const session = await readSession(p);
|
|
410
|
-
if (!session) return "local";
|
|
411
|
-
const expires = session.sshCertExpires ? new Date(session.sshCertExpires).getTime() : 0;
|
|
412
|
-
const onDisk = await readFile2(p.sshCert, "utf8").then(() => true, () => false);
|
|
413
|
-
const names2 = opts.owner === void 0 || (session.sshCertPrincipals ?? []).includes(opts.owner);
|
|
414
|
-
if (onDisk && expires - now > RENEW_BEFORE_MS && names2 && !opts.force) return "kept";
|
|
415
|
-
const publicKey = await readFile2(`${p.sshKey}.pub`, "utf8").catch(() => null);
|
|
416
|
-
if (publicKey === null) throw new KvboxError(`could not renew your SSH certificate: no key at ${p.sshKey}.pub; run: kvbox login`);
|
|
417
|
-
let signed;
|
|
418
|
-
try {
|
|
419
|
-
signed = await client.sshCert({ publicKey: publicKey.trim() });
|
|
420
|
-
} catch (err) {
|
|
421
|
-
throw new KvboxError(`could not renew your SSH certificate: ${err.message}`);
|
|
422
|
-
}
|
|
423
|
-
await writeCert(signed.cert, p);
|
|
424
|
-
await writeSession({ ...session, sshCertExpires: signed.expires, sshCertPrincipals: signed.principals }, p);
|
|
425
|
-
if (opts.owner !== void 0 && !signed.principals.includes(opts.owner)) {
|
|
426
|
-
const slug = opts.owner.split("@")[0];
|
|
427
|
-
const sameSlugElsewhere = signed.principals.find((pr) => pr.split("@")[0] === slug && pr !== opts.owner);
|
|
428
|
-
const why = sameSlugElsewhere ? `the control plane signs for ${sameSlugElsewhere} but the box's host qualifies its owner as ${opts.owner}: the control plane's name (KVBOX_CLOUD_NAME) changed after the host joined` : `you are not a member of ${slug} (a platform admin reaches org boxes over the API, not over SSH)`;
|
|
429
|
-
throw new KvboxError(`your SSH certificate does not name ${opts.owner}: ${why}`);
|
|
430
|
-
}
|
|
431
|
-
return "renewed";
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
// src/client.ts
|
|
435
|
-
import { spawn } from "child_process";
|
|
436
|
-
import { openSync } from "fs";
|
|
437
|
-
import { mkdir as mkdir2, readFile as readFile3, stat } from "fs/promises";
|
|
438
|
-
import { setTimeout as sleep } from "timers/promises";
|
|
439
|
-
import { Agent, request } from "undici";
|
|
440
|
-
import { z as z7 } from "zod";
|
|
340
|
+
import { z as z2 } from "zod";
|
|
441
341
|
|
|
442
342
|
// ../shared/src/api.ts
|
|
443
|
-
import { z
|
|
343
|
+
import { z } from "zod";
|
|
444
344
|
|
|
445
345
|
// ../shared/src/sizes.ts
|
|
446
346
|
var SIZES = {
|
|
@@ -460,901 +360,1151 @@ function parseMib(text2) {
|
|
|
460
360
|
}
|
|
461
361
|
|
|
462
362
|
// ../shared/src/api.ts
|
|
463
|
-
var SizeSchema =
|
|
363
|
+
var SizeSchema = z.enum(SIZE_NAMES);
|
|
464
364
|
var BOX_SSH_USER = "kvbox";
|
|
465
|
-
var BoxStatusSchema =
|
|
466
|
-
var PortProtoSchema =
|
|
365
|
+
var BoxStatusSchema = z.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
|
|
366
|
+
var PortProtoSchema = z.enum(["tcp", "udp"]);
|
|
467
367
|
var MAX_BOX_PORTS = 16;
|
|
468
|
-
var PortForwardSchema =
|
|
469
|
-
guestPort:
|
|
470
|
-
hostPort:
|
|
368
|
+
var PortForwardSchema = z.object({
|
|
369
|
+
guestPort: z.number().int().min(1).max(65535),
|
|
370
|
+
hostPort: z.number().int(),
|
|
471
371
|
proto: PortProtoSchema,
|
|
472
372
|
/** The host's public address; only the control plane fills it in, as for `ssh`. */
|
|
473
|
-
address:
|
|
373
|
+
address: z.string().optional(),
|
|
474
374
|
/**
|
|
475
375
|
* Closed but kept (#173): nothing reaches the box through it, and the host port stays the box's, so
|
|
476
376
|
* publishing the same box port again opens the same number. Absent: open while the box runs.
|
|
477
377
|
*/
|
|
478
|
-
closed:
|
|
378
|
+
closed: z.literal(true).optional()
|
|
479
379
|
});
|
|
480
|
-
var PortsRequest =
|
|
481
|
-
ports:
|
|
380
|
+
var PortsRequest = z.object({
|
|
381
|
+
ports: z.array(z.object({ guestPort: z.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),
|
|
482
382
|
/** `DELETE` only (#173): close the ports but keep their host ports for the box (`closed`). */
|
|
483
|
-
keep:
|
|
484
|
-
});
|
|
485
|
-
var BoxPortSchema =
|
|
486
|
-
var BoxLinkSchema =
|
|
487
|
-
var LinkRequest =
|
|
488
|
-
var ClaimSubdomainRequest =
|
|
489
|
-
var SubdomainPortRequest =
|
|
490
|
-
var SubdomainRouteRequest =
|
|
491
|
-
var SubdomainSchema =
|
|
492
|
-
owner:
|
|
493
|
-
box:
|
|
494
|
-
subdomain:
|
|
383
|
+
keep: z.boolean().optional()
|
|
384
|
+
});
|
|
385
|
+
var BoxPortSchema = z.number().int().min(1).max(65535);
|
|
386
|
+
var BoxLinkSchema = z.object({ from: z.string(), port: BoxPortSchema });
|
|
387
|
+
var LinkRequest = z.object({ from: z.string().min(1), fromOwner: z.string().optional(), port: BoxPortSchema });
|
|
388
|
+
var ClaimSubdomainRequest = z.object({ name: z.string(), port: BoxPortSchema });
|
|
389
|
+
var SubdomainPortRequest = z.object({ port: BoxPortSchema });
|
|
390
|
+
var SubdomainRouteRequest = z.object({ name: z.string(), port: BoxPortSchema });
|
|
391
|
+
var SubdomainSchema = z.object({
|
|
392
|
+
owner: z.string(),
|
|
393
|
+
box: z.string(),
|
|
394
|
+
subdomain: z.string(),
|
|
495
395
|
port: BoxPortSchema,
|
|
496
|
-
url:
|
|
497
|
-
routes:
|
|
396
|
+
url: z.string(),
|
|
397
|
+
routes: z.array(z.object({ name: z.string(), port: BoxPortSchema, url: z.string() }))
|
|
498
398
|
});
|
|
499
|
-
var AddDomainRequest =
|
|
500
|
-
var DomainSchema =
|
|
501
|
-
owner:
|
|
502
|
-
box:
|
|
503
|
-
domain:
|
|
399
|
+
var AddDomainRequest = z.object({ domain: z.string(), port: BoxPortSchema.optional() });
|
|
400
|
+
var DomainSchema = z.object({
|
|
401
|
+
owner: z.string(),
|
|
402
|
+
box: z.string(),
|
|
403
|
+
domain: z.string(),
|
|
504
404
|
port: BoxPortSchema,
|
|
505
|
-
status:
|
|
506
|
-
www:
|
|
507
|
-
url:
|
|
508
|
-
error:
|
|
509
|
-
records:
|
|
510
|
-
createdAt:
|
|
511
|
-
});
|
|
512
|
-
var WakeHookSchema =
|
|
513
|
-
id:
|
|
514
|
-
owner:
|
|
515
|
-
box:
|
|
516
|
-
url:
|
|
517
|
-
createdBy:
|
|
518
|
-
createdAt:
|
|
519
|
-
lastCalledAt:
|
|
405
|
+
status: z.enum(["pending", "live"]),
|
|
406
|
+
www: z.boolean(),
|
|
407
|
+
url: z.string(),
|
|
408
|
+
error: z.string().nullable(),
|
|
409
|
+
records: z.array(z.object({ type: z.enum(["A", "TXT", "CNAME"]), name: z.string(), value: z.string() })),
|
|
410
|
+
createdAt: z.string()
|
|
411
|
+
});
|
|
412
|
+
var WakeHookSchema = z.object({
|
|
413
|
+
id: z.string(),
|
|
414
|
+
owner: z.string(),
|
|
415
|
+
box: z.string(),
|
|
416
|
+
url: z.string(),
|
|
417
|
+
createdBy: z.string().nullable(),
|
|
418
|
+
createdAt: z.string(),
|
|
419
|
+
lastCalledAt: z.string().nullable()
|
|
520
420
|
});
|
|
521
|
-
var CreatedWakeHookSchema = WakeHookSchema.extend({ secret:
|
|
522
|
-
var WakeHookCallSchema =
|
|
523
|
-
box:
|
|
524
|
-
action:
|
|
525
|
-
reason:
|
|
421
|
+
var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z.string() });
|
|
422
|
+
var WakeHookCallSchema = z.object({
|
|
423
|
+
box: z.string(),
|
|
424
|
+
action: z.enum(["wake", "resume", "none"]),
|
|
425
|
+
reason: z.string().optional()
|
|
526
426
|
});
|
|
527
427
|
var BACKUP_STATUSES = ["running", "ready", "failed"];
|
|
528
428
|
var BACKUP_KINDS = ["box", "volume"];
|
|
529
|
-
var BackupSchema =
|
|
530
|
-
id:
|
|
531
|
-
owner:
|
|
532
|
-
box:
|
|
533
|
-
status:
|
|
429
|
+
var BackupSchema = z.object({
|
|
430
|
+
id: z.string(),
|
|
431
|
+
owner: z.string(),
|
|
432
|
+
box: z.string(),
|
|
433
|
+
status: z.enum(BACKUP_STATUSES),
|
|
534
434
|
/** Why it failed; null otherwise. */
|
|
535
|
-
error:
|
|
435
|
+
error: z.string().nullable(),
|
|
536
436
|
/** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
|
|
537
|
-
base:
|
|
538
|
-
image:
|
|
539
|
-
vcpu:
|
|
540
|
-
memMib:
|
|
437
|
+
base: z.string().nullable(),
|
|
438
|
+
image: z.string().optional(),
|
|
439
|
+
vcpu: z.number().int().nullable(),
|
|
440
|
+
memMib: z.number().int().nullable(),
|
|
541
441
|
/** The disk's size. */
|
|
542
|
-
diskBytes:
|
|
442
|
+
diskBytes: z.number().int().nullable(),
|
|
543
443
|
/** What it holds: the slots that are not all zeros. */
|
|
544
|
-
dataBytes:
|
|
444
|
+
dataBytes: z.number().int().nullable(),
|
|
545
445
|
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
546
|
-
uploadedBytes:
|
|
547
|
-
createdBy:
|
|
548
|
-
createdAt:
|
|
549
|
-
finishedAt:
|
|
550
|
-
});
|
|
551
|
-
var HostBackupRequest =
|
|
552
|
-
var HostBackupManifestSchema =
|
|
553
|
-
id:
|
|
554
|
-
sizeBytes:
|
|
555
|
-
chunks:
|
|
556
|
-
env:
|
|
557
|
-
base:
|
|
558
|
-
image:
|
|
559
|
-
vcpu:
|
|
560
|
-
memMib:
|
|
561
|
-
});
|
|
562
|
-
var HostUploadRequest =
|
|
563
|
-
var HostUploadResultSchema =
|
|
564
|
-
var HostRestoreRequest =
|
|
446
|
+
uploadedBytes: z.number().int().nullable(),
|
|
447
|
+
createdBy: z.string().nullable(),
|
|
448
|
+
createdAt: z.string(),
|
|
449
|
+
finishedAt: z.string().nullable()
|
|
450
|
+
});
|
|
451
|
+
var HostBackupRequest = z.object({ id: z.string(), key: z.string() });
|
|
452
|
+
var HostBackupManifestSchema = z.object({
|
|
453
|
+
id: z.string(),
|
|
454
|
+
sizeBytes: z.number().int(),
|
|
455
|
+
chunks: z.array(z.string().nullable()),
|
|
456
|
+
env: z.string().nullable(),
|
|
457
|
+
base: z.string(),
|
|
458
|
+
image: z.string().optional(),
|
|
459
|
+
vcpu: z.number().int(),
|
|
460
|
+
memMib: z.number().int()
|
|
461
|
+
});
|
|
462
|
+
var HostUploadRequest = z.object({ key: z.string(), urls: z.record(z.string(), z.string()), pin: z.string().optional() });
|
|
463
|
+
var HostUploadResultSchema = z.object({ chunks: z.number().int(), bytes: z.number().int(), sizes: z.record(z.string(), z.number().int()) });
|
|
464
|
+
var HostRestoreRequest = z.object({
|
|
565
465
|
/** The backup's id: its variables were sealed under it. */
|
|
566
|
-
id:
|
|
567
|
-
key:
|
|
568
|
-
sizeBytes:
|
|
569
|
-
base:
|
|
570
|
-
image:
|
|
571
|
-
env:
|
|
572
|
-
chunks:
|
|
466
|
+
id: z.string(),
|
|
467
|
+
key: z.string(),
|
|
468
|
+
sizeBytes: z.number().int().positive(),
|
|
469
|
+
base: z.string(),
|
|
470
|
+
image: z.string().optional(),
|
|
471
|
+
env: z.string().nullable(),
|
|
472
|
+
chunks: z.array(z.object({ index: z.number().int().nonnegative(), hash: z.string(), url: z.string() })),
|
|
573
473
|
/** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */
|
|
574
|
-
pin:
|
|
474
|
+
pin: z.string().optional()
|
|
575
475
|
});
|
|
576
|
-
var VolumeBackupSchema =
|
|
577
|
-
id:
|
|
578
|
-
owner:
|
|
579
|
-
volume:
|
|
580
|
-
status:
|
|
476
|
+
var VolumeBackupSchema = z.object({
|
|
477
|
+
id: z.string(),
|
|
478
|
+
owner: z.string(),
|
|
479
|
+
volume: z.string(),
|
|
480
|
+
status: z.enum(BACKUP_STATUSES),
|
|
581
481
|
/** Why it failed; null otherwise. */
|
|
582
|
-
error:
|
|
482
|
+
error: z.string().nullable(),
|
|
583
483
|
/** The volume's size when taken. */
|
|
584
|
-
diskBytes:
|
|
484
|
+
diskBytes: z.number().int().nullable(),
|
|
585
485
|
/** What it holds: the slots that are not all zeros. */
|
|
586
|
-
dataBytes:
|
|
486
|
+
dataBytes: z.number().int().nullable(),
|
|
587
487
|
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
588
|
-
uploadedBytes:
|
|
589
|
-
createdBy:
|
|
590
|
-
createdAt:
|
|
591
|
-
finishedAt:
|
|
592
|
-
});
|
|
593
|
-
var HostVolumeBackupManifestSchema =
|
|
594
|
-
var HostVolumeRestoreRequest =
|
|
595
|
-
id:
|
|
596
|
-
key:
|
|
597
|
-
sizeBytes:
|
|
598
|
-
chunks:
|
|
599
|
-
pin:
|
|
600
|
-
});
|
|
601
|
-
var BackupStoreSetupRequest =
|
|
602
|
-
var BackupStoreStatusSchema =
|
|
603
|
-
path:
|
|
604
|
-
bucket:
|
|
605
|
-
accessKey:
|
|
488
|
+
uploadedBytes: z.number().int().nullable(),
|
|
489
|
+
createdBy: z.string().nullable(),
|
|
490
|
+
createdAt: z.string(),
|
|
491
|
+
finishedAt: z.string().nullable()
|
|
492
|
+
});
|
|
493
|
+
var HostVolumeBackupManifestSchema = z.object({ id: z.string(), sizeBytes: z.number().int(), chunks: z.array(z.string().nullable()) });
|
|
494
|
+
var HostVolumeRestoreRequest = z.object({
|
|
495
|
+
id: z.string(),
|
|
496
|
+
key: z.string(),
|
|
497
|
+
sizeBytes: z.number().int().positive(),
|
|
498
|
+
chunks: z.array(z.object({ index: z.number().int().nonnegative(), hash: z.string(), url: z.string() })),
|
|
499
|
+
pin: z.string().optional()
|
|
500
|
+
});
|
|
501
|
+
var BackupStoreSetupRequest = z.object({ path: z.string().min(1), force: z.boolean().optional(), newStore: z.boolean().optional() });
|
|
502
|
+
var BackupStoreStatusSchema = z.object({
|
|
503
|
+
path: z.string(),
|
|
504
|
+
bucket: z.string(),
|
|
505
|
+
accessKey: z.string(),
|
|
606
506
|
/** Whether Garage is running and can store. */
|
|
607
|
-
running:
|
|
507
|
+
running: z.boolean(),
|
|
608
508
|
/** The filesystem the path is on. */
|
|
609
|
-
totalBytes:
|
|
610
|
-
freeBytes:
|
|
509
|
+
totalBytes: z.number().int(),
|
|
510
|
+
freeBytes: z.number().int(),
|
|
611
511
|
/** What the bucket holds, when Garage answers. */
|
|
612
|
-
objects:
|
|
613
|
-
storedBytes:
|
|
512
|
+
objects: z.number().int().optional(),
|
|
513
|
+
storedBytes: z.number().int().optional(),
|
|
614
514
|
/** Whether the control plane took the store's registration at setup. */
|
|
615
|
-
registered:
|
|
515
|
+
registered: z.boolean().optional()
|
|
616
516
|
});
|
|
617
|
-
var BackupStoreRegistration =
|
|
618
|
-
var CloudBackupStoreSchema =
|
|
619
|
-
id:
|
|
517
|
+
var BackupStoreRegistration = z.object({ bucket: z.string().min(1), region: z.string().min(1), accessKey: z.string().min(1), secretKey: z.string().min(1) });
|
|
518
|
+
var CloudBackupStoreSchema = z.object({
|
|
519
|
+
id: z.string(),
|
|
620
520
|
/** Null while no host serves it (its host left; it comes back when a host registers its key and secret again). */
|
|
621
|
-
host:
|
|
622
|
-
endpoint:
|
|
623
|
-
bucket:
|
|
624
|
-
accessKey:
|
|
625
|
-
createdAt:
|
|
521
|
+
host: z.string().nullable(),
|
|
522
|
+
endpoint: z.string().nullable(),
|
|
523
|
+
bucket: z.string(),
|
|
524
|
+
accessKey: z.string(),
|
|
525
|
+
createdAt: z.string(),
|
|
626
526
|
/** The host answered a poll in the last minute and its Garage runs. */
|
|
627
|
-
live:
|
|
527
|
+
live: z.boolean(),
|
|
628
528
|
/** From the host's last poll; null when it never reported a store. */
|
|
629
|
-
totalBytes:
|
|
630
|
-
freeBytes:
|
|
529
|
+
totalBytes: z.number().int().nullable(),
|
|
530
|
+
freeBytes: z.number().int().nullable(),
|
|
631
531
|
/** Ready backups kept here, and what their chunks take (encrypted, compressed). */
|
|
632
|
-
backups:
|
|
633
|
-
storedBytes:
|
|
532
|
+
backups: z.number().int(),
|
|
533
|
+
storedBytes: z.number().int(),
|
|
634
534
|
/** How many boxes have a ready backup here (a box and an earlier one of the same name count once), and how many volumes (#168). */
|
|
635
|
-
boxes:
|
|
636
|
-
volumes:
|
|
535
|
+
boxes: z.number().int(),
|
|
536
|
+
volumes: z.number().int(),
|
|
637
537
|
/** When the newest ready backup kept here finished; null when it keeps none. */
|
|
638
|
-
lastBackupAt:
|
|
538
|
+
lastBackupAt: z.string().nullable()
|
|
639
539
|
});
|
|
640
|
-
var StoredItemSchema =
|
|
641
|
-
kind:
|
|
642
|
-
owner:
|
|
643
|
-
name:
|
|
540
|
+
var StoredItemSchema = z.object({
|
|
541
|
+
kind: z.enum(BACKUP_KINDS),
|
|
542
|
+
owner: z.string(),
|
|
543
|
+
name: z.string(),
|
|
644
544
|
/** The host the box (or volume) is on now; null when it is gone (its backups stay). */
|
|
645
|
-
host:
|
|
545
|
+
host: z.string().nullable(),
|
|
646
546
|
/** It is on the store's own host: losing that host loses it and its backups together. */
|
|
647
|
-
sameHost:
|
|
547
|
+
sameHost: z.boolean(),
|
|
648
548
|
/** Ready backups kept here, and what they added to the store together (encrypted, compressed). */
|
|
649
|
-
backups:
|
|
650
|
-
uploadedBytes:
|
|
549
|
+
backups: z.number().int(),
|
|
550
|
+
uploadedBytes: z.number().int(),
|
|
651
551
|
/** The newest backup sent here, whatever became of it. */
|
|
652
|
-
latest:
|
|
552
|
+
latest: z.object({ id: z.string(), status: z.enum(BACKUP_STATUSES), error: z.string().nullable(), createdAt: z.string() })
|
|
653
553
|
});
|
|
654
|
-
var FailedBackupSchema =
|
|
655
|
-
id:
|
|
656
|
-
owner:
|
|
554
|
+
var FailedBackupSchema = z.object({
|
|
555
|
+
id: z.string(),
|
|
556
|
+
owner: z.string(),
|
|
657
557
|
/** What it was a backup of: a box or a volume (#168), and its name. */
|
|
658
|
-
kind:
|
|
659
|
-
name:
|
|
660
|
-
error:
|
|
558
|
+
kind: z.enum(BACKUP_KINDS),
|
|
559
|
+
name: z.string(),
|
|
560
|
+
error: z.string().nullable(),
|
|
661
561
|
/** The host that took it, and the host of the store it was going to; null when gone, or when it failed before a store was picked. */
|
|
662
|
-
host:
|
|
663
|
-
store:
|
|
664
|
-
createdAt:
|
|
562
|
+
host: z.string().nullable(),
|
|
563
|
+
store: z.string().nullable(),
|
|
564
|
+
createdAt: z.string()
|
|
665
565
|
});
|
|
666
|
-
var MachineSchema =
|
|
566
|
+
var MachineSchema = z.object({
|
|
667
567
|
/** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
|
|
668
|
-
id:
|
|
669
|
-
name:
|
|
568
|
+
id: z.string(),
|
|
569
|
+
name: z.string(),
|
|
670
570
|
/** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */
|
|
671
|
-
owner:
|
|
672
|
-
ip:
|
|
673
|
-
mac:
|
|
674
|
-
pid:
|
|
675
|
-
vcpu:
|
|
676
|
-
memMib:
|
|
677
|
-
diskBytes:
|
|
571
|
+
owner: z.string(),
|
|
572
|
+
ip: z.string(),
|
|
573
|
+
mac: z.string(),
|
|
574
|
+
pid: z.number().int().nullable(),
|
|
575
|
+
vcpu: z.number().int(),
|
|
576
|
+
memMib: z.number().int(),
|
|
577
|
+
diskBytes: z.number().int(),
|
|
678
578
|
// the box's own writable disk, as the guest sees it
|
|
679
|
-
diskUsedBytes:
|
|
579
|
+
diskUsedBytes: z.number().int(),
|
|
680
580
|
// what the box uses of it: the filesystem's own count, like the guest's `df` (#115)
|
|
681
581
|
/** 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. */
|
|
682
|
-
diskHostBytes:
|
|
683
|
-
base:
|
|
582
|
+
diskHostBytes: z.number().int().optional(),
|
|
583
|
+
base: z.string(),
|
|
684
584
|
// version of the image the box's overlay stacks on
|
|
685
585
|
/** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
|
|
686
|
-
image:
|
|
687
|
-
createdAt:
|
|
688
|
-
source:
|
|
586
|
+
image: z.string().optional(),
|
|
587
|
+
createdAt: z.string(),
|
|
588
|
+
source: z.string(),
|
|
689
589
|
// "base", "snapshot:<owner/name>" or "fork:<owner/name>" (#79)
|
|
690
590
|
status: BoxStatusSchema,
|
|
691
591
|
/**
|
|
692
592
|
* Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made
|
|
693
593
|
* through a control plane have one; the control plane adds the host's address for `connect` (#21).
|
|
694
594
|
*/
|
|
695
|
-
sshPort:
|
|
595
|
+
sshPort: z.number().int().optional(),
|
|
696
596
|
/**
|
|
697
597
|
* Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only
|
|
698
598
|
* the control plane fills it in (a host does not know its own public address); absent for a box
|
|
699
599
|
* whose host reported no port or did not answer.
|
|
700
600
|
*/
|
|
701
|
-
ssh:
|
|
601
|
+
ssh: z.object({ host: z.string(), port: z.number().int(), user: z.string() }).optional(),
|
|
702
602
|
/** Box ports published on the host (#30). Absent: none. */
|
|
703
|
-
ports:
|
|
603
|
+
ports: z.array(PortForwardSchema).optional(),
|
|
704
604
|
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
|
|
705
|
-
ownerKind:
|
|
605
|
+
ownerKind: z.enum(["user", "org"]).optional(),
|
|
706
606
|
/**
|
|
707
607
|
* The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
|
|
708
608
|
* links to, and a volume attaches to, only a box on the same host.
|
|
709
609
|
*/
|
|
710
|
-
host:
|
|
610
|
+
host: z.string().optional(),
|
|
711
611
|
/** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
|
|
712
|
-
country:
|
|
612
|
+
country: z.string().optional(),
|
|
713
613
|
/**
|
|
714
614
|
* The kind of managed service the box runs (`postgres`, `redis`, `storage`). Only an admin's
|
|
715
615
|
* `GET /machines?all=1` lists such boxes, so a host's boxes add up; every other listing hides them.
|
|
716
616
|
*/
|
|
717
|
-
managed:
|
|
617
|
+
managed: z.string().optional(),
|
|
718
618
|
/** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
|
|
719
|
-
autoHibernateSec:
|
|
619
|
+
autoHibernateSec: z.number().int().positive().optional(),
|
|
720
620
|
/** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
|
|
721
|
-
idleCheck:
|
|
621
|
+
idleCheck: z.string().optional(),
|
|
722
622
|
/** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
|
|
723
|
-
volumes:
|
|
623
|
+
volumes: z.array(z.object({ name: z.string(), sizeGib: z.number().int(), mountPath: z.string() })).optional(),
|
|
724
624
|
/** Boxes that may reach this one, each on one port (#98). Absent: none. */
|
|
725
|
-
links:
|
|
625
|
+
links: z.array(BoxLinkSchema).optional(),
|
|
726
626
|
/** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */
|
|
727
|
-
url:
|
|
627
|
+
url: z.string().optional(),
|
|
728
628
|
/**
|
|
729
629
|
* Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
|
|
730
630
|
* serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
|
|
731
631
|
*/
|
|
732
|
-
connect:
|
|
632
|
+
connect: z.string().optional()
|
|
733
633
|
});
|
|
734
|
-
var VolumeSchema =
|
|
634
|
+
var VolumeSchema = z.object({
|
|
735
635
|
/** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
736
|
-
id:
|
|
737
|
-
name:
|
|
738
|
-
owner:
|
|
739
|
-
sizeGib:
|
|
636
|
+
id: z.string(),
|
|
637
|
+
name: z.string(),
|
|
638
|
+
owner: z.string(),
|
|
639
|
+
sizeGib: z.number().int(),
|
|
740
640
|
/** What the sparse file really occupies on the host. */
|
|
741
|
-
usedBytes:
|
|
742
|
-
attachedTo:
|
|
743
|
-
createdAt:
|
|
641
|
+
usedBytes: z.number().int(),
|
|
642
|
+
attachedTo: z.string().nullable(),
|
|
643
|
+
createdAt: z.string(),
|
|
744
644
|
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
|
|
745
|
-
ownerKind:
|
|
645
|
+
ownerKind: z.enum(["user", "org"]).optional(),
|
|
746
646
|
/** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
|
|
747
|
-
host:
|
|
647
|
+
host: z.string().optional()
|
|
748
648
|
});
|
|
749
649
|
var MAX_VOLUME_GIB = 4096;
|
|
750
650
|
var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
751
651
|
var VOLUME_NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
|
|
752
|
-
var CreateVolumeRequest =
|
|
753
|
-
name:
|
|
754
|
-
sizeGib:
|
|
652
|
+
var CreateVolumeRequest = z.object({
|
|
653
|
+
name: z.string(),
|
|
654
|
+
sizeGib: z.number().int().min(1).max(MAX_VOLUME_GIB),
|
|
755
655
|
/**
|
|
756
656
|
* Through a control plane (#91): the box this volume is for, so it is made on that box's host; the
|
|
757
657
|
* control plane requires it (a volume attaches only to a box on its own host, so one made for no box
|
|
758
658
|
* could never attach) and the CLI attaches right after. A host ignores it.
|
|
759
659
|
*/
|
|
760
|
-
box:
|
|
761
|
-
});
|
|
762
|
-
var AttachVolumeRequest =
|
|
763
|
-
box:
|
|
764
|
-
});
|
|
765
|
-
var ResizeVolumeRequest =
|
|
766
|
-
sizeGib:
|
|
767
|
-
});
|
|
768
|
-
var RunScriptRequest =
|
|
769
|
-
var ScriptOutputSchema =
|
|
770
|
-
var
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
box
|
|
782
|
-
|
|
660
|
+
box: z.string().optional()
|
|
661
|
+
});
|
|
662
|
+
var AttachVolumeRequest = z.object({
|
|
663
|
+
box: z.string()
|
|
664
|
+
});
|
|
665
|
+
var ResizeVolumeRequest = z.object({
|
|
666
|
+
sizeGib: z.number().int().min(1).max(MAX_VOLUME_GIB)
|
|
667
|
+
});
|
|
668
|
+
var RunScriptRequest = z.object({ input: z.unknown().optional() });
|
|
669
|
+
var ScriptOutputSchema = z.object({ output: z.unknown() });
|
|
670
|
+
var BOX_RUN_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
671
|
+
var StartRunRequest = z.object({
|
|
672
|
+
id: z.string().regex(BOX_RUN_ID_RE),
|
|
673
|
+
command: z.string().min(1).max(8192),
|
|
674
|
+
/** The command and everything it started are killed after this long. */
|
|
675
|
+
timeoutSec: z.number().int().min(1).max(86400)
|
|
676
|
+
});
|
|
677
|
+
var StartRunAnswerSchema = z.object({
|
|
678
|
+
id: z.string(),
|
|
679
|
+
/** False: a run of this id was already there. */
|
|
680
|
+
started: z.boolean(),
|
|
681
|
+
/** The box was asleep and this request woke it. */
|
|
682
|
+
woke: z.boolean()
|
|
683
|
+
});
|
|
684
|
+
var BOX_RUN_STATES = ["running", "exited", "timeout", "unknown"];
|
|
685
|
+
var BoxRunSchema = z.object({
|
|
686
|
+
id: z.string(),
|
|
687
|
+
state: z.enum(BOX_RUN_STATES),
|
|
688
|
+
/** With `exited`; 128 + the signal for a command a signal ended. */
|
|
689
|
+
exitCode: z.number().int().optional()
|
|
690
|
+
});
|
|
691
|
+
var RunRefusalSchema = z.object({ error: z.string(), code: z.string().optional() });
|
|
692
|
+
var EnvVarSchema = z.object({
|
|
693
|
+
name: z.string(),
|
|
694
|
+
value: z.string().optional(),
|
|
695
|
+
secret: z.boolean(),
|
|
696
|
+
updatedAt: z.string()
|
|
697
|
+
});
|
|
698
|
+
var BoxEnvSchema = z.object({
|
|
699
|
+
box: z.string(),
|
|
700
|
+
vars: z.array(EnvVarSchema)
|
|
701
|
+
});
|
|
702
|
+
var BoxEnvChangeSchema = z.object({
|
|
703
|
+
box: z.string(),
|
|
704
|
+
name: z.string(),
|
|
783
705
|
/** Whether the box is running now: the change waits for its next start. */
|
|
784
|
-
running:
|
|
706
|
+
running: z.boolean()
|
|
785
707
|
});
|
|
786
|
-
var SetEnvRequest =
|
|
787
|
-
value:
|
|
788
|
-
secret:
|
|
708
|
+
var SetEnvRequest = z.object({
|
|
709
|
+
value: z.string(),
|
|
710
|
+
secret: z.boolean().optional()
|
|
789
711
|
});
|
|
790
|
-
var EnvChangeSchema =
|
|
791
|
-
owner:
|
|
792
|
-
name:
|
|
793
|
-
boxes:
|
|
712
|
+
var EnvChangeSchema = z.object({
|
|
713
|
+
owner: z.string(),
|
|
714
|
+
name: z.string(),
|
|
715
|
+
boxes: z.number().int()
|
|
794
716
|
});
|
|
795
|
-
var HostEnvRequest =
|
|
796
|
-
version:
|
|
797
|
-
vars:
|
|
717
|
+
var HostEnvRequest = z.object({
|
|
718
|
+
version: z.number().int().min(0),
|
|
719
|
+
vars: z.array(z.object({ name: z.string(), value: z.string() }))
|
|
798
720
|
});
|
|
799
|
-
var HostEnvVersionsSchema =
|
|
800
|
-
var CreateMachineRequest =
|
|
801
|
-
name:
|
|
721
|
+
var HostEnvVersionsSchema = z.array(z.object({ owner: z.string(), version: z.number().int() }));
|
|
722
|
+
var CreateMachineRequest = z.object({
|
|
723
|
+
name: z.string().optional(),
|
|
802
724
|
/** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
|
|
803
|
-
owner:
|
|
725
|
+
owner: z.string().optional(),
|
|
804
726
|
size: SizeSchema.optional(),
|
|
805
|
-
from:
|
|
806
|
-
force:
|
|
727
|
+
from: z.string().optional(),
|
|
728
|
+
force: z.boolean().optional(),
|
|
807
729
|
/**
|
|
808
730
|
* Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends
|
|
809
731
|
* its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every
|
|
810
732
|
* boot (#49); a host older than that ignores them.
|
|
811
733
|
*/
|
|
812
|
-
sshKeys:
|
|
734
|
+
sshKeys: z.array(z.string()).optional(),
|
|
813
735
|
/** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
|
|
814
|
-
autoHibernateSec:
|
|
736
|
+
autoHibernateSec: z.number().int().min(0).optional(),
|
|
815
737
|
/**
|
|
816
738
|
* Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
|
|
817
739
|
* control plane reads it; a host has one place to put a box.
|
|
818
740
|
*/
|
|
819
|
-
near:
|
|
741
|
+
near: z.string().optional(),
|
|
820
742
|
/**
|
|
821
743
|
* Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
|
|
822
744
|
* `@kvbox/shared/country`. Only the control plane reads it.
|
|
823
745
|
*/
|
|
824
|
-
country:
|
|
746
|
+
country: z.string().optional(),
|
|
825
747
|
/**
|
|
826
748
|
* Place the box on the host of this name and nowhere else (`kvbox new --host kvbox2`, a hidden flag):
|
|
827
749
|
* an admin's, to try a host out. Only the control plane reads it, and refuses it from anyone else.
|
|
828
750
|
*/
|
|
829
|
-
host:
|
|
751
|
+
host: z.string().optional(),
|
|
830
752
|
/** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
|
|
831
|
-
image:
|
|
753
|
+
image: z.string().optional(),
|
|
832
754
|
/** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
|
|
833
|
-
env:
|
|
755
|
+
env: z.array(z.object({ name: z.string(), value: z.string() })).optional()
|
|
834
756
|
});
|
|
835
|
-
var ForkMachineRequest =
|
|
836
|
-
name:
|
|
757
|
+
var ForkMachineRequest = z.object({
|
|
758
|
+
name: z.string().optional(),
|
|
837
759
|
/**
|
|
838
760
|
* The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host
|
|
839
761
|
* qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.
|
|
840
762
|
*/
|
|
841
|
-
owner:
|
|
763
|
+
owner: z.string().optional(),
|
|
842
764
|
/** A cold fork only: a warm one keeps the source's vCPU and memory. */
|
|
843
765
|
size: SizeSchema.optional(),
|
|
844
|
-
force:
|
|
766
|
+
force: z.boolean().optional(),
|
|
845
767
|
/** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */
|
|
846
|
-
sshKeys:
|
|
847
|
-
autoHibernateSec:
|
|
768
|
+
sshKeys: z.array(z.string()).optional(),
|
|
769
|
+
autoHibernateSec: z.number().int().min(0).optional()
|
|
848
770
|
});
|
|
849
|
-
var SetSshKeysRequest =
|
|
850
|
-
sshKeys:
|
|
771
|
+
var SetSshKeysRequest = z.object({
|
|
772
|
+
sshKeys: z.array(z.string())
|
|
851
773
|
});
|
|
852
|
-
var RescaleMachineRequest =
|
|
774
|
+
var RescaleMachineRequest = z.object({
|
|
853
775
|
size: SizeSchema.optional(),
|
|
854
|
-
vcpu:
|
|
855
|
-
memMib:
|
|
856
|
-
diskGib:
|
|
776
|
+
vcpu: z.number().int().min(1).max(64).optional(),
|
|
777
|
+
memMib: z.number().int().min(256).optional(),
|
|
778
|
+
diskGib: z.number().int().min(1).optional(),
|
|
857
779
|
/** Skip the capacity guard when a running box grows (#37). */
|
|
858
|
-
force:
|
|
780
|
+
force: z.boolean().optional()
|
|
859
781
|
});
|
|
860
|
-
var StartMachineRequest =
|
|
861
|
-
force:
|
|
782
|
+
var StartMachineRequest = z.object({
|
|
783
|
+
force: z.boolean().optional()
|
|
862
784
|
});
|
|
863
|
-
var SetMachineRequest =
|
|
785
|
+
var SetMachineRequest = z.object({
|
|
864
786
|
/** Seconds without network traffic before the box is hibernated (#47); 0: never. */
|
|
865
|
-
autoHibernateSec:
|
|
787
|
+
autoHibernateSec: z.number().int().min(0).optional(),
|
|
866
788
|
/** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
|
|
867
|
-
idleCheck:
|
|
789
|
+
idleCheck: z.union([z.literal(""), z.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
|
|
868
790
|
});
|
|
869
|
-
var SnapshotSchema =
|
|
870
|
-
name:
|
|
871
|
-
owner:
|
|
872
|
-
source:
|
|
791
|
+
var SnapshotSchema = z.object({
|
|
792
|
+
name: z.string(),
|
|
793
|
+
owner: z.string(),
|
|
794
|
+
source: z.string(),
|
|
873
795
|
// the box it was taken from, as owner/name
|
|
874
|
-
base:
|
|
796
|
+
base: z.string(),
|
|
875
797
|
// version of the image the overlay stacks on; a restore needs the same one
|
|
876
798
|
/** As in MachineSchema: the image when it is not the base one (#87). */
|
|
877
|
-
image:
|
|
878
|
-
vcpu:
|
|
879
|
-
memMib:
|
|
880
|
-
sizeBytes:
|
|
799
|
+
image: z.string().optional(),
|
|
800
|
+
vcpu: z.number().int(),
|
|
801
|
+
memMib: z.number().int(),
|
|
802
|
+
sizeBytes: z.number().int(),
|
|
881
803
|
// what vmstate + mem + overlay really occupy on the host
|
|
882
|
-
createdAt:
|
|
804
|
+
createdAt: z.string()
|
|
883
805
|
});
|
|
884
|
-
var CreateSnapshotRequest =
|
|
885
|
-
box:
|
|
886
|
-
name:
|
|
806
|
+
var CreateSnapshotRequest = z.object({
|
|
807
|
+
box: z.string(),
|
|
808
|
+
name: z.string(),
|
|
887
809
|
/** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
|
|
888
|
-
replace:
|
|
889
|
-
});
|
|
890
|
-
var DiskCapacitySchema =
|
|
891
|
-
totalGib:
|
|
892
|
-
freeGib:
|
|
893
|
-
volumesGib:
|
|
894
|
-
volumesUsedGib:
|
|
895
|
-
headroomGib:
|
|
896
|
-
});
|
|
897
|
-
var CapacitySchema =
|
|
898
|
-
hostMemMib:
|
|
899
|
-
hostCores:
|
|
900
|
-
reservedMemMib:
|
|
901
|
-
reservedVcpu:
|
|
902
|
-
running:
|
|
810
|
+
replace: z.boolean().optional()
|
|
811
|
+
});
|
|
812
|
+
var DiskCapacitySchema = z.object({
|
|
813
|
+
totalGib: z.number().int(),
|
|
814
|
+
freeGib: z.number().int(),
|
|
815
|
+
volumesGib: z.number().int(),
|
|
816
|
+
volumesUsedGib: z.number().int(),
|
|
817
|
+
headroomGib: z.number().int()
|
|
818
|
+
});
|
|
819
|
+
var CapacitySchema = z.object({
|
|
820
|
+
hostMemMib: z.number().int(),
|
|
821
|
+
hostCores: z.number().int(),
|
|
822
|
+
reservedMemMib: z.number().int(),
|
|
823
|
+
reservedVcpu: z.number().int(),
|
|
824
|
+
running: z.number().int(),
|
|
903
825
|
/** Absent on a host from before volumes (#91): it cannot take one. */
|
|
904
826
|
disk: DiskCapacitySchema.optional(),
|
|
905
827
|
/**
|
|
906
828
|
* The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
|
|
907
829
|
* Absent on a host from before images: it has only the base.
|
|
908
830
|
*/
|
|
909
|
-
images:
|
|
831
|
+
images: z.array(z.object({ name: z.string(), version: z.string() })).optional(),
|
|
910
832
|
/** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */
|
|
911
|
-
version:
|
|
833
|
+
version: z.string().optional(),
|
|
912
834
|
/** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */
|
|
913
|
-
backupStore:
|
|
835
|
+
backupStore: z.object({ totalBytes: z.number().int(), freeBytes: z.number().int(), running: z.boolean() }).optional(),
|
|
914
836
|
/** True on a kvbox-server that reaches a backup store by its certificate's `pin`; older ones omit it and cannot back up to a store. */
|
|
915
|
-
storeClient:
|
|
837
|
+
storeClient: z.boolean().optional()
|
|
916
838
|
});
|
|
917
|
-
var ImageSchema =
|
|
918
|
-
var ImageIndexSchema =
|
|
919
|
-
updatedAt:
|
|
920
|
-
images:
|
|
839
|
+
var ImageSchema = z.object({ name: z.string(), version: z.string().nullable() });
|
|
840
|
+
var ImageIndexSchema = z.object({
|
|
841
|
+
updatedAt: z.string(),
|
|
842
|
+
images: z.record(z.string(), z.object({ version: z.string().min(1), minServer: z.string().min(1).optional() }))
|
|
921
843
|
});
|
|
922
|
-
var LatestImagesSchema =
|
|
923
|
-
updatedAt:
|
|
844
|
+
var LatestImagesSchema = z.object({
|
|
845
|
+
updatedAt: z.string().nullable(),
|
|
924
846
|
images: ImageIndexSchema.shape.images,
|
|
925
|
-
checkedAt:
|
|
926
|
-
});
|
|
927
|
-
var RecoveryReportSchema =
|
|
928
|
-
at:
|
|
929
|
-
booted:
|
|
930
|
-
leftStopped:
|
|
931
|
-
failed:
|
|
932
|
-
});
|
|
933
|
-
var HostUpdateSchema =
|
|
934
|
-
state:
|
|
935
|
-
startedAt:
|
|
936
|
-
finishedAt:
|
|
847
|
+
checkedAt: z.string().nullable()
|
|
848
|
+
});
|
|
849
|
+
var RecoveryReportSchema = z.object({
|
|
850
|
+
at: z.string(),
|
|
851
|
+
booted: z.array(z.string()),
|
|
852
|
+
leftStopped: z.array(z.string()),
|
|
853
|
+
failed: z.array(z.object({ box: z.string(), error: z.string() }))
|
|
854
|
+
});
|
|
855
|
+
var HostUpdateSchema = z.object({
|
|
856
|
+
state: z.enum(["running", "done", "failed"]),
|
|
857
|
+
startedAt: z.string(),
|
|
858
|
+
finishedAt: z.string().nullable(),
|
|
937
859
|
/** kvbox-server's version when the update started, and when it ended (null while running or when it failed before). */
|
|
938
|
-
from:
|
|
939
|
-
to:
|
|
940
|
-
error:
|
|
941
|
-
needsManual:
|
|
942
|
-
});
|
|
943
|
-
var HealthSchema =
|
|
944
|
-
ok:
|
|
945
|
-
version:
|
|
946
|
-
pid:
|
|
860
|
+
from: z.string(),
|
|
861
|
+
to: z.string().nullable(),
|
|
862
|
+
error: z.string().nullable(),
|
|
863
|
+
needsManual: z.array(z.string())
|
|
864
|
+
});
|
|
865
|
+
var HealthSchema = z.object({
|
|
866
|
+
ok: z.literal(true),
|
|
867
|
+
version: z.string(),
|
|
868
|
+
pid: z.number().int(),
|
|
947
869
|
/** Base image version new boxes get (null when the host has no usable base image yet). */
|
|
948
|
-
base:
|
|
870
|
+
base: z.string().nullable(),
|
|
949
871
|
/** Owner that boxes made over the local socket get (the Unix user running the server). */
|
|
950
|
-
owner:
|
|
872
|
+
owner: z.string(),
|
|
951
873
|
/** The control plane this host joined (null when none). */
|
|
952
|
-
controlPlane:
|
|
874
|
+
controlPlane: z.object({
|
|
953
875
|
/** Realm name, e.g. kvbox.sh. */
|
|
954
|
-
name:
|
|
955
|
-
url:
|
|
876
|
+
name: z.string(),
|
|
877
|
+
url: z.string(),
|
|
956
878
|
/** Where this host answers the control plane. */
|
|
957
|
-
hostUrl:
|
|
879
|
+
hostUrl: z.string()
|
|
958
880
|
}).nullable(),
|
|
959
881
|
/** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */
|
|
960
|
-
relay:
|
|
961
|
-
name:
|
|
882
|
+
relay: z.object({
|
|
883
|
+
name: z.string(),
|
|
962
884
|
/** The public IP the relay owns for this host. */
|
|
963
|
-
publicIp:
|
|
885
|
+
publicIp: z.string(),
|
|
964
886
|
/** The relay's WireGuard endpoint the tunnel dials. */
|
|
965
|
-
endpoint:
|
|
887
|
+
endpoint: z.string(),
|
|
966
888
|
/** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */
|
|
967
|
-
restarts:
|
|
968
|
-
lastRestartAt:
|
|
889
|
+
restarts: z.number().int().optional(),
|
|
890
|
+
lastRestartAt: z.string().nullable().optional()
|
|
969
891
|
}).nullable().optional(),
|
|
970
892
|
/** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */
|
|
971
893
|
recovery: RecoveryReportSchema.nullable().optional(),
|
|
972
894
|
/** The last self-update; null when none ran. Older servers omit it. */
|
|
973
895
|
update: HostUpdateSchema.nullable().optional()
|
|
974
896
|
});
|
|
975
|
-
var MachineUsageSchema =
|
|
976
|
-
name:
|
|
977
|
-
owner:
|
|
897
|
+
var MachineUsageSchema = z.object({
|
|
898
|
+
name: z.string(),
|
|
899
|
+
owner: z.string(),
|
|
978
900
|
status: BoxStatusSchema,
|
|
979
|
-
window:
|
|
980
|
-
seconds:
|
|
981
|
-
running:
|
|
982
|
-
standby:
|
|
983
|
-
hibernated:
|
|
984
|
-
stopped:
|
|
901
|
+
window: z.object({ from: z.string(), to: z.string() }),
|
|
902
|
+
seconds: z.object({
|
|
903
|
+
running: z.number().int(),
|
|
904
|
+
standby: z.number().int(),
|
|
905
|
+
hibernated: z.number().int(),
|
|
906
|
+
stopped: z.number().int()
|
|
985
907
|
}),
|
|
986
|
-
vcpuHours:
|
|
987
|
-
ramGibHours:
|
|
988
|
-
diskGibHours:
|
|
989
|
-
cost:
|
|
908
|
+
vcpuHours: z.number(),
|
|
909
|
+
ramGibHours: z.number(),
|
|
910
|
+
diskGibHours: z.number(),
|
|
911
|
+
cost: z.object({ amount: z.number(), currency: z.string() }).optional(),
|
|
990
912
|
/** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */
|
|
991
|
-
estimatedStops:
|
|
992
|
-
historyFrom:
|
|
913
|
+
estimatedStops: z.number().int(),
|
|
914
|
+
historyFrom: z.string().nullable()
|
|
993
915
|
});
|
|
994
|
-
var GuestStatsSchema =
|
|
916
|
+
var GuestStatsSchema = z.object({
|
|
995
917
|
/** Load average over 1, 5 and 15 minutes. */
|
|
996
|
-
load:
|
|
997
|
-
cpus:
|
|
998
|
-
memTotalMib:
|
|
918
|
+
load: z.tuple([z.number(), z.number(), z.number()]),
|
|
919
|
+
cpus: z.number().int(),
|
|
920
|
+
memTotalMib: z.number().int(),
|
|
999
921
|
/** Total minus available: page cache counts as free. */
|
|
1000
|
-
memUsedMib:
|
|
922
|
+
memUsedMib: z.number().int(),
|
|
1001
923
|
/** The box's root, which is its overlay disk: the box's own writes, not the shared base. */
|
|
1002
|
-
diskTotalBytes:
|
|
1003
|
-
diskUsedBytes:
|
|
1004
|
-
uptimeSec:
|
|
924
|
+
diskTotalBytes: z.number().int(),
|
|
925
|
+
diskUsedBytes: z.number().int(),
|
|
926
|
+
uptimeSec: z.number().int()
|
|
1005
927
|
});
|
|
1006
|
-
var MachineStatsSchema =
|
|
1007
|
-
name:
|
|
1008
|
-
owner:
|
|
928
|
+
var MachineStatsSchema = z.object({
|
|
929
|
+
name: z.string(),
|
|
930
|
+
owner: z.string(),
|
|
1009
931
|
stats: GuestStatsSchema.nullable()
|
|
1010
932
|
});
|
|
1011
|
-
var UsageStatusSchema =
|
|
933
|
+
var UsageStatusSchema = z.enum([...BoxStatusSchema.options, "removed"]);
|
|
1012
934
|
var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({
|
|
1013
935
|
/** The host's box id; a name removed and recreated appears twice, with two ids. */
|
|
1014
|
-
id:
|
|
936
|
+
id: z.string(),
|
|
1015
937
|
status: UsageStatusSchema,
|
|
1016
938
|
/** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */
|
|
1017
|
-
ownerKind:
|
|
939
|
+
ownerKind: z.enum(["user", "org"]).optional(),
|
|
1018
940
|
/**
|
|
1019
941
|
* Through a control plane: the username that made the box (#60), absent when the box is gone from
|
|
1020
942
|
* the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.
|
|
1021
943
|
*/
|
|
1022
|
-
createdBy:
|
|
944
|
+
createdBy: z.string().optional()
|
|
1023
945
|
});
|
|
1024
|
-
var VolumeUsageSchema =
|
|
946
|
+
var VolumeUsageSchema = z.object({
|
|
1025
947
|
/** The host's volume id; a name removed and made again appears twice, with two ids. */
|
|
1026
|
-
id:
|
|
1027
|
-
name:
|
|
1028
|
-
owner:
|
|
1029
|
-
ownerKind:
|
|
948
|
+
id: z.string(),
|
|
949
|
+
name: z.string(),
|
|
950
|
+
owner: z.string(),
|
|
951
|
+
ownerKind: z.enum(["user", "org"]).optional(),
|
|
1030
952
|
/** The size at the end of the window (or when removed). */
|
|
1031
|
-
sizeGib:
|
|
1032
|
-
status:
|
|
1033
|
-
volumeHours:
|
|
1034
|
-
volumeGibHours:
|
|
1035
|
-
cost:
|
|
1036
|
-
historyFrom:
|
|
1037
|
-
});
|
|
1038
|
-
var CronUsageSchema =
|
|
1039
|
-
id:
|
|
1040
|
-
name:
|
|
1041
|
-
owner:
|
|
1042
|
-
ownerKind:
|
|
1043
|
-
status:
|
|
1044
|
-
hours:
|
|
1045
|
-
cost:
|
|
953
|
+
sizeGib: z.number().int(),
|
|
954
|
+
status: z.enum(["present", "removed"]),
|
|
955
|
+
volumeHours: z.number(),
|
|
956
|
+
volumeGibHours: z.number(),
|
|
957
|
+
cost: z.object({ amount: z.number(), currency: z.string() }).optional(),
|
|
958
|
+
historyFrom: z.string().nullable()
|
|
959
|
+
});
|
|
960
|
+
var CronUsageSchema = z.object({
|
|
961
|
+
id: z.string(),
|
|
962
|
+
name: z.string(),
|
|
963
|
+
owner: z.string(),
|
|
964
|
+
ownerKind: z.enum(["user", "org"]).optional(),
|
|
965
|
+
status: z.enum(["present", "removed"]),
|
|
966
|
+
hours: z.number(),
|
|
967
|
+
cost: z.object({ amount: z.number(), currency: z.string() }).optional(),
|
|
1046
968
|
/** When it was made. */
|
|
1047
|
-
historyFrom:
|
|
969
|
+
historyFrom: z.string().nullable()
|
|
1048
970
|
});
|
|
1049
|
-
var UsageDayItemSchema =
|
|
1050
|
-
id:
|
|
1051
|
-
name:
|
|
1052
|
-
owner:
|
|
971
|
+
var UsageDayItemSchema = z.object({
|
|
972
|
+
id: z.string(),
|
|
973
|
+
name: z.string(),
|
|
974
|
+
owner: z.string(),
|
|
1053
975
|
/** Removed by the end of the report's window. */
|
|
1054
|
-
removed:
|
|
1055
|
-
cost:
|
|
976
|
+
removed: z.boolean(),
|
|
977
|
+
cost: z.number()
|
|
1056
978
|
});
|
|
1057
|
-
var UsageDaySchema =
|
|
979
|
+
var UsageDaySchema = z.object({
|
|
1058
980
|
/** `YYYY-MM-DD`, UTC. */
|
|
1059
|
-
date:
|
|
1060
|
-
from:
|
|
1061
|
-
to:
|
|
1062
|
-
cost:
|
|
1063
|
-
currency:
|
|
1064
|
-
boxes:
|
|
1065
|
-
volumes:
|
|
981
|
+
date: z.string(),
|
|
982
|
+
from: z.string(),
|
|
983
|
+
to: z.string(),
|
|
984
|
+
cost: z.number(),
|
|
985
|
+
currency: z.string(),
|
|
986
|
+
boxes: z.array(UsageDayItemSchema),
|
|
987
|
+
volumes: z.array(UsageDayItemSchema),
|
|
1066
988
|
/** Object storage that existed that day (#182); absent on a day without any. */
|
|
1067
|
-
storage:
|
|
989
|
+
storage: z.array(UsageDayItemSchema).optional(),
|
|
1068
990
|
/** Cron services that existed that day (#190); absent on a day without any. */
|
|
1069
|
-
cron:
|
|
991
|
+
cron: z.array(UsageDayItemSchema).optional()
|
|
1070
992
|
});
|
|
1071
|
-
var UsageReportSchema =
|
|
1072
|
-
window:
|
|
1073
|
-
boxes:
|
|
993
|
+
var UsageReportSchema = z.object({
|
|
994
|
+
window: z.object({ from: z.string(), to: z.string() }),
|
|
995
|
+
boxes: z.array(BoxUsageSchema),
|
|
1074
996
|
/** Absent from a side older than #91. */
|
|
1075
|
-
volumes:
|
|
997
|
+
volumes: z.array(VolumeUsageSchema).optional(),
|
|
1076
998
|
/**
|
|
1077
999
|
* Object storage (#182, control plane only): one row per storage a slug has or had, shaped like a
|
|
1078
1000
|
* volume's. `volumeHours` are the hours it existed, `volumeGibHours` those of the GiB beyond the
|
|
1079
1001
|
* included ones, `sizeGib` its whole size. Absent when there is none.
|
|
1080
1002
|
*/
|
|
1081
|
-
storage:
|
|
1003
|
+
storage: z.array(VolumeUsageSchema).optional(),
|
|
1082
1004
|
/** Cron services (#190, control plane only): one row per service a slug has or had. Absent when there is none. */
|
|
1083
|
-
cron:
|
|
1005
|
+
cron: z.array(CronUsageSchema).optional(),
|
|
1084
1006
|
/** With `?by=day` only, oldest day first. */
|
|
1085
|
-
days:
|
|
1086
|
-
totals:
|
|
1007
|
+
days: z.array(UsageDaySchema).optional(),
|
|
1008
|
+
totals: z.object({
|
|
1087
1009
|
seconds: MachineUsageSchema.shape.seconds,
|
|
1088
|
-
vcpuHours:
|
|
1089
|
-
ramGibHours:
|
|
1090
|
-
diskGibHours:
|
|
1091
|
-
volumeHours:
|
|
1092
|
-
volumeGibHours:
|
|
1010
|
+
vcpuHours: z.number(),
|
|
1011
|
+
ramGibHours: z.number(),
|
|
1012
|
+
diskGibHours: z.number(),
|
|
1013
|
+
volumeHours: z.number().optional(),
|
|
1014
|
+
volumeGibHours: z.number().optional(),
|
|
1093
1015
|
/** Boxes, volumes, object storage and cron services together. */
|
|
1094
|
-
cost:
|
|
1016
|
+
cost: z.object({ amount: z.number(), currency: z.string() }).optional()
|
|
1095
1017
|
})
|
|
1096
1018
|
});
|
|
1097
|
-
var UsageEventRowSchema =
|
|
1098
|
-
id:
|
|
1099
|
-
boxId:
|
|
1100
|
-
owner:
|
|
1101
|
-
name:
|
|
1102
|
-
at:
|
|
1103
|
-
state:
|
|
1104
|
-
vcpu:
|
|
1105
|
-
memMib:
|
|
1106
|
-
diskGib:
|
|
1107
|
-
by:
|
|
1108
|
-
});
|
|
1109
|
-
var UsageEventsResponseSchema =
|
|
1110
|
-
ledger:
|
|
1111
|
-
events:
|
|
1112
|
-
next:
|
|
1113
|
-
});
|
|
1114
|
-
var VolumeEventRowSchema =
|
|
1115
|
-
id:
|
|
1116
|
-
volumeId:
|
|
1117
|
-
owner:
|
|
1118
|
-
name:
|
|
1119
|
-
at:
|
|
1120
|
-
sizeGib:
|
|
1121
|
-
by:
|
|
1122
|
-
});
|
|
1123
|
-
var VolumeEventsResponseSchema =
|
|
1124
|
-
ledger:
|
|
1125
|
-
events:
|
|
1126
|
-
next:
|
|
1019
|
+
var UsageEventRowSchema = z.object({
|
|
1020
|
+
id: z.number().int(),
|
|
1021
|
+
boxId: z.string(),
|
|
1022
|
+
owner: z.string(),
|
|
1023
|
+
name: z.string(),
|
|
1024
|
+
at: z.string(),
|
|
1025
|
+
state: z.enum(["running", "standby", "hibernated", "stopped"]),
|
|
1026
|
+
vcpu: z.number().int(),
|
|
1027
|
+
memMib: z.number().int(),
|
|
1028
|
+
diskGib: z.number().int(),
|
|
1029
|
+
by: z.string()
|
|
1030
|
+
});
|
|
1031
|
+
var UsageEventsResponseSchema = z.object({
|
|
1032
|
+
ledger: z.string().min(1),
|
|
1033
|
+
events: z.array(UsageEventRowSchema),
|
|
1034
|
+
next: z.number().int()
|
|
1035
|
+
});
|
|
1036
|
+
var VolumeEventRowSchema = z.object({
|
|
1037
|
+
id: z.number().int(),
|
|
1038
|
+
volumeId: z.string(),
|
|
1039
|
+
owner: z.string(),
|
|
1040
|
+
name: z.string(),
|
|
1041
|
+
at: z.string(),
|
|
1042
|
+
sizeGib: z.number().int(),
|
|
1043
|
+
by: z.enum(["create", "resize", "rm"])
|
|
1044
|
+
});
|
|
1045
|
+
var VolumeEventsResponseSchema = z.object({
|
|
1046
|
+
ledger: z.string().min(1),
|
|
1047
|
+
events: z.array(VolumeEventRowSchema),
|
|
1048
|
+
next: z.number().int()
|
|
1127
1049
|
});
|
|
1128
1050
|
var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
|
|
1129
|
-
var ApiErrorCodeSchema =
|
|
1130
|
-
var ApiErrorSchema =
|
|
1131
|
-
error:
|
|
1051
|
+
var ApiErrorCodeSchema = z.enum(API_ERROR_CODES);
|
|
1052
|
+
var ApiErrorSchema = z.object({
|
|
1053
|
+
error: z.string(),
|
|
1132
1054
|
code: ApiErrorCodeSchema.optional()
|
|
1133
1055
|
});
|
|
1134
1056
|
var DEFAULT_CLOUD_URL = "https://api.kvbox.sh";
|
|
1135
1057
|
var ACTIVATED_BY = ["card", "admin"];
|
|
1136
|
-
var ActivatedBySchema =
|
|
1137
|
-
var CloudUserSchema =
|
|
1058
|
+
var ActivatedBySchema = z.enum(ACTIVATED_BY);
|
|
1059
|
+
var CloudUserSchema = z.object({
|
|
1138
1060
|
/** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */
|
|
1139
|
-
username:
|
|
1061
|
+
username: z.string(),
|
|
1140
1062
|
/** Display name, free text ("Alexandru Ghiura"). */
|
|
1141
|
-
name:
|
|
1063
|
+
name: z.string(),
|
|
1142
1064
|
/** Login identity, unique. */
|
|
1143
|
-
email:
|
|
1144
|
-
role:
|
|
1145
|
-
createdAt:
|
|
1065
|
+
email: z.string(),
|
|
1066
|
+
role: z.enum(["admin", "user"]),
|
|
1067
|
+
createdAt: z.string(),
|
|
1146
1068
|
/**
|
|
1147
1069
|
* False until a card is on file or an admin activates the account (#74): then only `/me` and
|
|
1148
1070
|
* `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and
|
|
1149
1071
|
* gates nobody, hence the defaults: a newer CLI must still parse its answers.
|
|
1150
1072
|
*/
|
|
1151
|
-
active:
|
|
1073
|
+
active: z.boolean().default(true),
|
|
1152
1074
|
activatedBy: ActivatedBySchema.nullable().default(null),
|
|
1153
1075
|
/** When too many wrong passwords locked the account (#161); null when it is not locked. Older control planes omit it. */
|
|
1154
|
-
lockedAt:
|
|
1076
|
+
lockedAt: z.string().nullable().default(null)
|
|
1155
1077
|
});
|
|
1156
1078
|
var ORG_ROLES = ["owner", "admin", "member"];
|
|
1157
|
-
var OrgRoleSchema =
|
|
1158
|
-
var CloudOrgSchema =
|
|
1159
|
-
slug:
|
|
1079
|
+
var OrgRoleSchema = z.enum(ORG_ROLES);
|
|
1080
|
+
var CloudOrgSchema = z.object({
|
|
1081
|
+
slug: z.string(),
|
|
1160
1082
|
/** Display name; the slug never changes, this may. */
|
|
1161
|
-
name:
|
|
1162
|
-
createdAt:
|
|
1083
|
+
name: z.string(),
|
|
1084
|
+
createdAt: z.string(),
|
|
1163
1085
|
/** 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. */
|
|
1164
|
-
active:
|
|
1086
|
+
active: z.boolean().default(true),
|
|
1165
1087
|
activatedBy: ActivatedBySchema.nullable().default(null)
|
|
1166
1088
|
});
|
|
1167
1089
|
var OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });
|
|
1168
|
-
var OrgMemberSchema =
|
|
1169
|
-
username:
|
|
1170
|
-
name:
|
|
1090
|
+
var OrgMemberSchema = z.object({
|
|
1091
|
+
username: z.string(),
|
|
1092
|
+
name: z.string(),
|
|
1171
1093
|
role: OrgRoleSchema,
|
|
1172
|
-
addedAt:
|
|
1094
|
+
addedAt: z.string()
|
|
1173
1095
|
});
|
|
1174
|
-
var OrgDetailSchema = CloudOrgSchema.extend({ members:
|
|
1175
|
-
var CreateOrgRequestSchema =
|
|
1176
|
-
slug:
|
|
1177
|
-
name:
|
|
1096
|
+
var OrgDetailSchema = CloudOrgSchema.extend({ members: z.array(OrgMemberSchema) });
|
|
1097
|
+
var CreateOrgRequestSchema = z.object({
|
|
1098
|
+
slug: z.string().min(1),
|
|
1099
|
+
name: z.string().min(1)
|
|
1178
1100
|
});
|
|
1179
|
-
var RenameOrgRequestSchema =
|
|
1180
|
-
var AddMemberRequestSchema =
|
|
1181
|
-
username:
|
|
1101
|
+
var RenameOrgRequestSchema = z.object({ name: z.string().min(1) });
|
|
1102
|
+
var AddMemberRequestSchema = z.object({
|
|
1103
|
+
username: z.string().min(1),
|
|
1182
1104
|
role: OrgRoleSchema.default("member")
|
|
1183
1105
|
});
|
|
1184
|
-
var SetRoleRequestSchema =
|
|
1185
|
-
var MeResponseSchema = CloudUserSchema.extend({ orgs:
|
|
1186
|
-
var BalanceSchema =
|
|
1187
|
-
slug:
|
|
1188
|
-
balance:
|
|
1189
|
-
currency:
|
|
1190
|
-
topUps:
|
|
1191
|
-
spent:
|
|
1106
|
+
var SetRoleRequestSchema = z.object({ role: OrgRoleSchema });
|
|
1107
|
+
var MeResponseSchema = CloudUserSchema.extend({ orgs: z.array(OrgMembershipSchema) });
|
|
1108
|
+
var BalanceSchema = z.object({
|
|
1109
|
+
slug: z.string(),
|
|
1110
|
+
balance: z.number(),
|
|
1111
|
+
currency: z.string(),
|
|
1112
|
+
topUps: z.number(),
|
|
1113
|
+
spent: z.number(),
|
|
1192
1114
|
/** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */
|
|
1193
|
-
since:
|
|
1115
|
+
since: z.string().nullable(),
|
|
1194
1116
|
/** 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. */
|
|
1195
|
-
suspendedAt:
|
|
1117
|
+
suspendedAt: z.string().nullable().default(null),
|
|
1196
1118
|
/** Promo credit left (#163), already counted in `balance`; 0 with none. Absent from a control plane older than this field. */
|
|
1197
|
-
promo:
|
|
1119
|
+
promo: z.number().default(0),
|
|
1198
1120
|
/** When the next promo credit expires; null with none left. */
|
|
1199
|
-
promoExpiresAt:
|
|
1121
|
+
promoExpiresAt: z.string().nullable().default(null)
|
|
1200
1122
|
});
|
|
1201
|
-
var TopUpRequestSchema =
|
|
1202
|
-
slug:
|
|
1123
|
+
var TopUpRequestSchema = z.object({
|
|
1124
|
+
slug: z.string().min(1),
|
|
1203
1125
|
/** In the control plane's currency; negative corrects a mistake. */
|
|
1204
|
-
amount:
|
|
1205
|
-
note:
|
|
1206
|
-
});
|
|
1207
|
-
var TopUpSchema =
|
|
1208
|
-
id:
|
|
1209
|
-
slug:
|
|
1210
|
-
amount:
|
|
1211
|
-
currency:
|
|
1126
|
+
amount: z.number().finite(),
|
|
1127
|
+
note: z.string().max(200).optional()
|
|
1128
|
+
});
|
|
1129
|
+
var TopUpSchema = z.object({
|
|
1130
|
+
id: z.string(),
|
|
1131
|
+
slug: z.string(),
|
|
1132
|
+
amount: z.number(),
|
|
1133
|
+
currency: z.string(),
|
|
1212
1134
|
/** `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. */
|
|
1213
|
-
source:
|
|
1214
|
-
note:
|
|
1215
|
-
at:
|
|
1135
|
+
source: z.enum(["admin", "card", "trial", "transfer"]),
|
|
1136
|
+
note: z.string().nullable(),
|
|
1137
|
+
at: z.string()
|
|
1216
1138
|
});
|
|
1217
|
-
var CreateCodeRequestSchema =
|
|
1139
|
+
var CreateCodeRequestSchema = z.object({
|
|
1218
1140
|
/** In the control plane's currency, cents at most. */
|
|
1219
|
-
amount:
|
|
1141
|
+
amount: z.number().positive().multipleOf(0.01, "amount is in cents at most"),
|
|
1220
1142
|
/** A day (`2026-12-11`, through the end of it, UTC) or an ISO time. The credit is gone then, and so is the code. */
|
|
1221
|
-
expiresAt:
|
|
1222
|
-
note:
|
|
1223
|
-
});
|
|
1224
|
-
var CreditCodeSchema =
|
|
1225
|
-
code:
|
|
1226
|
-
amount:
|
|
1227
|
-
currency:
|
|
1228
|
-
expiresAt:
|
|
1229
|
-
note:
|
|
1230
|
-
status:
|
|
1231
|
-
createdBy:
|
|
1232
|
-
createdAt:
|
|
1143
|
+
expiresAt: z.string().min(1),
|
|
1144
|
+
note: z.string().max(200).optional()
|
|
1145
|
+
});
|
|
1146
|
+
var CreditCodeSchema = z.object({
|
|
1147
|
+
code: z.string(),
|
|
1148
|
+
amount: z.number(),
|
|
1149
|
+
currency: z.string(),
|
|
1150
|
+
expiresAt: z.string(),
|
|
1151
|
+
note: z.string().nullable(),
|
|
1152
|
+
status: z.enum(["unused", "redeemed", "expired", "revoked"]),
|
|
1153
|
+
createdBy: z.string(),
|
|
1154
|
+
createdAt: z.string(),
|
|
1233
1155
|
/** Who redeemed it and the slug the credit went to (their own, or an org they own). */
|
|
1234
|
-
redeemedBy:
|
|
1235
|
-
redeemedSlug:
|
|
1236
|
-
redeemedAt:
|
|
1237
|
-
revokedAt:
|
|
1238
|
-
});
|
|
1239
|
-
var RedeemRequestSchema =
|
|
1240
|
-
code:
|
|
1241
|
-
org:
|
|
1242
|
-
});
|
|
1243
|
-
var RedeemResponseSchema =
|
|
1244
|
-
slug:
|
|
1245
|
-
amount:
|
|
1246
|
-
currency:
|
|
1247
|
-
expiresAt:
|
|
1156
|
+
redeemedBy: z.string().nullable(),
|
|
1157
|
+
redeemedSlug: z.string().nullable(),
|
|
1158
|
+
redeemedAt: z.string().nullable(),
|
|
1159
|
+
revokedAt: z.string().nullable()
|
|
1160
|
+
});
|
|
1161
|
+
var RedeemRequestSchema = z.object({
|
|
1162
|
+
code: z.string().min(1).max(64),
|
|
1163
|
+
org: z.string().min(1).optional()
|
|
1164
|
+
});
|
|
1165
|
+
var RedeemResponseSchema = z.object({
|
|
1166
|
+
slug: z.string(),
|
|
1167
|
+
amount: z.number(),
|
|
1168
|
+
currency: z.string(),
|
|
1169
|
+
expiresAt: z.string(),
|
|
1248
1170
|
balance: BalanceSchema,
|
|
1249
1171
|
/** The slug was out of credit and this put it back above zero: it may start boxes again. */
|
|
1250
|
-
reinstated:
|
|
1172
|
+
reinstated: z.boolean()
|
|
1251
1173
|
});
|
|
1252
1174
|
var TOP_UP_AMOUNTS = [10, 25, 50, 100];
|
|
1253
|
-
var BillingInfoSchema =
|
|
1254
|
-
card:
|
|
1255
|
-
cardInUse:
|
|
1175
|
+
var BillingInfoSchema = z.object({
|
|
1176
|
+
card: z.object({ brand: z.string(), last4: z.string() }).nullable(),
|
|
1177
|
+
cardInUse: z.boolean(),
|
|
1256
1178
|
balance: BalanceSchema
|
|
1257
1179
|
});
|
|
1258
|
-
var BillingRedirectSchema =
|
|
1259
|
-
var TopUpCheckoutRequestSchema =
|
|
1260
|
-
amount:
|
|
1180
|
+
var BillingRedirectSchema = z.object({ url: z.string() });
|
|
1181
|
+
var TopUpCheckoutRequestSchema = z.object({
|
|
1182
|
+
amount: z.literal(TOP_UP_AMOUNTS)
|
|
1261
1183
|
});
|
|
1262
|
-
var TransferRequestSchema =
|
|
1263
|
-
org:
|
|
1264
|
-
amount:
|
|
1184
|
+
var TransferRequestSchema = z.object({
|
|
1185
|
+
org: z.string().min(1),
|
|
1186
|
+
amount: z.number().positive().multipleOf(0.01, "amount is in cents at most")
|
|
1265
1187
|
});
|
|
1266
|
-
var TransferResponseSchema =
|
|
1267
|
-
var LoginRequestSchema =
|
|
1268
|
-
email:
|
|
1269
|
-
password:
|
|
1270
|
-
publicKey:
|
|
1188
|
+
var TransferResponseSchema = z.object({ from: BalanceSchema, to: BalanceSchema, activated: z.boolean() });
|
|
1189
|
+
var LoginRequestSchema = z.object({
|
|
1190
|
+
email: z.string().min(1),
|
|
1191
|
+
password: z.string().min(1),
|
|
1192
|
+
publicKey: z.string().optional()
|
|
1271
1193
|
});
|
|
1272
|
-
var SignupRequestSchema =
|
|
1273
|
-
username:
|
|
1274
|
-
name:
|
|
1275
|
-
email:
|
|
1276
|
-
password:
|
|
1194
|
+
var SignupRequestSchema = z.object({
|
|
1195
|
+
username: z.string().min(1),
|
|
1196
|
+
name: z.string().min(1),
|
|
1197
|
+
email: z.string().min(1),
|
|
1198
|
+
password: z.string().min(1)
|
|
1277
1199
|
});
|
|
1278
|
-
var LoginResponseSchema =
|
|
1279
|
-
token:
|
|
1200
|
+
var LoginResponseSchema = z.object({
|
|
1201
|
+
token: z.string(),
|
|
1280
1202
|
user: CloudUserSchema,
|
|
1281
|
-
sshCert:
|
|
1282
|
-
sshCertExpires:
|
|
1203
|
+
sshCert: z.string().optional(),
|
|
1204
|
+
sshCertExpires: z.string().optional(),
|
|
1283
1205
|
/** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
|
|
1284
|
-
sshCertPrincipals:
|
|
1285
|
-
});
|
|
1286
|
-
var SshCertRequestSchema = z2.object({
|
|
1287
|
-
publicKey: z2.string().min(1)
|
|
1288
|
-
});
|
|
1289
|
-
var SshCertResponseSchema = z2.object({
|
|
1290
|
-
cert: z2.string(),
|
|
1291
|
-
expires: z2.string(),
|
|
1292
|
-
principals: z2.array(z2.string())
|
|
1206
|
+
sshCertPrincipals: z.array(z.string()).optional()
|
|
1293
1207
|
});
|
|
1294
|
-
var
|
|
1295
|
-
|
|
1208
|
+
var DEVICE_LOGIN_PICKUP_SEC = 60;
|
|
1209
|
+
var DeviceLoginRequestSchema = z.object({
|
|
1210
|
+
// Capped: anyone may open a login, and the key is stored until it expires (an RSA-16384 key is ~2.8 KB).
|
|
1211
|
+
publicKey: z.string().max(16384).optional(),
|
|
1212
|
+
hostname: z.string().max(255).optional()
|
|
1213
|
+
});
|
|
1214
|
+
var DeviceLoginStartSchema = z.object({
|
|
1215
|
+
deviceCode: z.string(),
|
|
1216
|
+
userCode: z.string(),
|
|
1217
|
+
verifyUrl: z.string(),
|
|
1218
|
+
expiresIn: z.number(),
|
|
1219
|
+
interval: z.number()
|
|
1220
|
+
});
|
|
1221
|
+
var DeviceLoginPollRequestSchema = z.object({ deviceCode: z.string().min(1) });
|
|
1222
|
+
var DeviceLoginPollSchema = z.union([
|
|
1223
|
+
z.object({ status: z.enum(["pending", "slow_down", "refused", "expired"]) }),
|
|
1224
|
+
LoginResponseSchema.extend({ status: z.literal("approved") })
|
|
1225
|
+
]);
|
|
1226
|
+
var DeviceLoginInfoSchema = z.object({
|
|
1227
|
+
userCode: z.string(),
|
|
1228
|
+
hostname: z.string(),
|
|
1229
|
+
/** The address the request came from; null when the control plane could not tell. */
|
|
1230
|
+
ip: z.string().nullable(),
|
|
1231
|
+
createdAt: z.string(),
|
|
1232
|
+
expiresAt: z.string()
|
|
1233
|
+
});
|
|
1234
|
+
var DEFAULT_API_KEY_DAYS = 90;
|
|
1235
|
+
var API_KEY_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
|
|
1236
|
+
var ApiKeySchema = z.object({
|
|
1237
|
+
name: z.string(),
|
|
1238
|
+
createdAt: z.string(),
|
|
1239
|
+
/** Last request made with it (ISO); null: never used. */
|
|
1240
|
+
lastUsedAt: z.string().nullable(),
|
|
1241
|
+
/** When it stops working (ISO); null: never. */
|
|
1242
|
+
expiresAt: z.string().nullable()
|
|
1243
|
+
});
|
|
1244
|
+
var CreateApiKeyRequestSchema = z.object({
|
|
1245
|
+
name: z.string().regex(API_KEY_NAME_RE, "a key's name is lowercase letters, digits, '.', '_' or '-' (up to 32 characters)"),
|
|
1246
|
+
expiresAt: z.iso.datetime({ offset: true }).nullable().optional()
|
|
1247
|
+
});
|
|
1248
|
+
var CreatedApiKeySchema = ApiKeySchema.extend({ key: z.string() });
|
|
1249
|
+
var SshCertRequestSchema = z.object({
|
|
1250
|
+
publicKey: z.string().min(1)
|
|
1251
|
+
});
|
|
1252
|
+
var SshCertResponseSchema = z.object({
|
|
1253
|
+
cert: z.string(),
|
|
1254
|
+
expires: z.string(),
|
|
1255
|
+
principals: z.array(z.string())
|
|
1256
|
+
});
|
|
1257
|
+
var SshCaResponseSchema = z.object({
|
|
1258
|
+
publicKey: z.string(),
|
|
1296
1259
|
/** 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. */
|
|
1297
|
-
retired:
|
|
1260
|
+
retired: z.array(z.object({ publicKey: z.string(), retiredAt: z.string() })).optional()
|
|
1298
1261
|
});
|
|
1299
|
-
var HostSshCaResponseSchema =
|
|
1300
|
-
publicKey:
|
|
1262
|
+
var HostSshCaResponseSchema = z.object({
|
|
1263
|
+
publicKey: z.string()
|
|
1301
1264
|
});
|
|
1302
|
-
var CloudCaSchema =
|
|
1303
|
-
controlPlane:
|
|
1304
|
-
publicKey:
|
|
1305
|
-
fingerprint:
|
|
1265
|
+
var CloudCaSchema = z.object({
|
|
1266
|
+
controlPlane: z.string(),
|
|
1267
|
+
publicKey: z.string(),
|
|
1268
|
+
fingerprint: z.string()
|
|
1306
1269
|
});
|
|
1307
|
-
var TrustCaRequestSchema =
|
|
1308
|
-
publicKey:
|
|
1270
|
+
var TrustCaRequestSchema = z.object({
|
|
1271
|
+
publicKey: z.string().min(1)
|
|
1309
1272
|
});
|
|
1310
|
-
var SshKeysAppliedSchema =
|
|
1311
|
-
var TrustCaReportSchema =
|
|
1312
|
-
publicKey:
|
|
1313
|
-
fingerprint:
|
|
1273
|
+
var SshKeysAppliedSchema = z.enum(["now", "start", "wake", "resume", "later"]);
|
|
1274
|
+
var TrustCaReportSchema = z.object({
|
|
1275
|
+
publicKey: z.string(),
|
|
1276
|
+
fingerprint: z.string(),
|
|
1314
1277
|
/** The guest trusts the CA now. */
|
|
1315
|
-
updated:
|
|
1278
|
+
updated: z.array(z.string()),
|
|
1316
1279
|
/** meta.json has the line; the guest gets it at `when`. */
|
|
1317
|
-
pending:
|
|
1318
|
-
failed:
|
|
1280
|
+
pending: z.array(z.object({ box: z.string(), when: SshKeysAppliedSchema, why: z.string().optional() })),
|
|
1281
|
+
failed: z.array(z.object({ box: z.string(), error: z.string() })),
|
|
1319
1282
|
/** Local boxes, untouched: they trust the host's key only. */
|
|
1320
|
-
local:
|
|
1283
|
+
local: z.number().int(),
|
|
1321
1284
|
/** Cloud boxes made without a CA line (a managed service's, #173), untouched: no certificate opens them. Absent from older servers. */
|
|
1322
|
-
skipped:
|
|
1323
|
-
});
|
|
1324
|
-
var HostJoinRequestSchema =
|
|
1325
|
-
token:
|
|
1326
|
-
name:
|
|
1327
|
-
url:
|
|
1328
|
-
fingerprint:
|
|
1329
|
-
publicAddress:
|
|
1285
|
+
skipped: z.array(z.string()).optional()
|
|
1286
|
+
});
|
|
1287
|
+
var HostJoinRequestSchema = z.object({
|
|
1288
|
+
token: z.string().min(1),
|
|
1289
|
+
name: z.string().min(1),
|
|
1290
|
+
url: z.string().url(),
|
|
1291
|
+
fingerprint: z.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
|
|
1292
|
+
publicAddress: z.string().min(1),
|
|
1330
1293
|
/** Where the host is (`kvbox-server join --country`): a code or an English name. */
|
|
1331
|
-
country:
|
|
1294
|
+
country: z.string().optional()
|
|
1332
1295
|
});
|
|
1333
|
-
var HostJoinResponseSchema =
|
|
1334
|
-
hostSecret:
|
|
1335
|
-
controlPlane:
|
|
1296
|
+
var HostJoinResponseSchema = z.object({
|
|
1297
|
+
hostSecret: z.string(),
|
|
1298
|
+
controlPlane: z.object({ name: z.string() })
|
|
1336
1299
|
});
|
|
1337
|
-
var CloudHostSchema =
|
|
1338
|
-
name:
|
|
1339
|
-
url:
|
|
1340
|
-
publicAddress:
|
|
1341
|
-
joinedAt:
|
|
1342
|
-
lastSeenAt:
|
|
1300
|
+
var CloudHostSchema = z.object({
|
|
1301
|
+
name: z.string(),
|
|
1302
|
+
url: z.string(),
|
|
1303
|
+
publicAddress: z.string(),
|
|
1304
|
+
joinedAt: z.string(),
|
|
1305
|
+
lastSeenAt: z.string().nullable(),
|
|
1343
1306
|
capacity: CapacitySchema.nullable(),
|
|
1344
1307
|
/** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
|
|
1345
|
-
country:
|
|
1308
|
+
country: z.string().nullable(),
|
|
1346
1309
|
/** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */
|
|
1347
|
-
region:
|
|
1310
|
+
region: z.string().nullable(),
|
|
1348
1311
|
/** kvbox-server's version as of the poller's last look (`capacity.version`); null before one, or for a server older than 0.5.45. */
|
|
1349
|
-
version:
|
|
1312
|
+
version: z.string().nullable()
|
|
1350
1313
|
});
|
|
1351
|
-
var HostInfoSchema =
|
|
1314
|
+
var HostInfoSchema = z.object({
|
|
1352
1315
|
host: CloudHostSchema,
|
|
1353
1316
|
health: HealthSchema.nullable(),
|
|
1354
|
-
error:
|
|
1317
|
+
error: z.string().nullable()
|
|
1355
1318
|
});
|
|
1356
|
-
var HostPatchRequest =
|
|
1357
|
-
var CountrySchema =
|
|
1319
|
+
var HostPatchRequest = z.object({ country: z.string().nullable().optional(), region: z.string().nullable().optional() }).refine((b) => b.country !== void 0 || b.region !== void 0, { message: "give country, region or both" });
|
|
1320
|
+
var CountrySchema = z.object({ code: z.string(), name: z.string() });
|
|
1321
|
+
|
|
1322
|
+
// src/session.ts
|
|
1323
|
+
var SessionSchema = z2.object({
|
|
1324
|
+
url: z2.string(),
|
|
1325
|
+
token: z2.string(),
|
|
1326
|
+
user: z2.string(),
|
|
1327
|
+
/** When the SSH certificate at paths().sshCert stops being accepted (ISO); absent before the first login with a key. */
|
|
1328
|
+
sshCertExpires: z2.string().optional(),
|
|
1329
|
+
/** Whose boxes that certificate opens (`<slug>@<realm>`, the user and their orgs); absent with `sshCertExpires`. */
|
|
1330
|
+
sshCertPrincipals: z2.array(z2.string()).optional()
|
|
1331
|
+
});
|
|
1332
|
+
async function readSession(p = paths()) {
|
|
1333
|
+
let text2;
|
|
1334
|
+
try {
|
|
1335
|
+
text2 = await readFile(p.cli, "utf8");
|
|
1336
|
+
} catch (err) {
|
|
1337
|
+
if (err.code === "ENOENT") return null;
|
|
1338
|
+
throw err;
|
|
1339
|
+
}
|
|
1340
|
+
try {
|
|
1341
|
+
return SessionSchema.parse(JSON.parse(text2));
|
|
1342
|
+
} catch {
|
|
1343
|
+
throw new KvboxError(`${p.cli} is unreadable; run: kvbox logout (then log in again)`);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
async function writeSession(session, p = paths()) {
|
|
1347
|
+
await mkdir(p.home, { recursive: true });
|
|
1348
|
+
await writeFile(p.cli, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
|
|
1349
|
+
await chmod(p.cli, 384);
|
|
1350
|
+
}
|
|
1351
|
+
async function clearSession(p = paths()) {
|
|
1352
|
+
await rm(p.cli, { force: true });
|
|
1353
|
+
}
|
|
1354
|
+
function envLogin(env = process.env) {
|
|
1355
|
+
const token = env["KVBOX_TOKEN"]?.trim();
|
|
1356
|
+
if (token === void 0 || token === "") return null;
|
|
1357
|
+
const url = env["KVBOX_URL"]?.trim();
|
|
1358
|
+
return { url: normalizeUrl(url === void 0 || url === "" ? DEFAULT_CLOUD_URL : url), token };
|
|
1359
|
+
}
|
|
1360
|
+
function hostOf(url) {
|
|
1361
|
+
try {
|
|
1362
|
+
return new URL(url).host;
|
|
1363
|
+
} catch {
|
|
1364
|
+
return url;
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
function isLoopback(hostname) {
|
|
1368
|
+
return hostname === "localhost" || hostname.startsWith("127.") || hostname === "[::1]";
|
|
1369
|
+
}
|
|
1370
|
+
function normalizeUrl(input) {
|
|
1371
|
+
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `https://${input}`;
|
|
1372
|
+
let url;
|
|
1373
|
+
try {
|
|
1374
|
+
url = new URL(withScheme);
|
|
1375
|
+
} catch {
|
|
1376
|
+
throw new KvboxError(`not a URL: ${input}`);
|
|
1377
|
+
}
|
|
1378
|
+
if (!/^https?:$/.test(url.protocol) || url.hostname === "" || /\s/.test(input)) throw new KvboxError(`not a URL: ${input}`);
|
|
1379
|
+
if (url.protocol === "http:" && !isLoopback(url.hostname)) {
|
|
1380
|
+
throw new KvboxError(`${input}: use https (plain http is only allowed for localhost)`);
|
|
1381
|
+
}
|
|
1382
|
+
return url.origin + url.pathname.replace(/\/+$/, "");
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
// src/cert.ts
|
|
1386
|
+
var RENEW_BEFORE_MS = 60 * 60 * 1e3;
|
|
1387
|
+
async function writeCert(cert, p = paths()) {
|
|
1388
|
+
const tmp = `${p.sshCert}.${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
1389
|
+
try {
|
|
1390
|
+
await writeFile2(tmp, cert.trim() + "\n", { mode: 420 });
|
|
1391
|
+
for (let attempt = 1; ; attempt++) {
|
|
1392
|
+
try {
|
|
1393
|
+
await rename(tmp, p.sshCert);
|
|
1394
|
+
break;
|
|
1395
|
+
} catch (err) {
|
|
1396
|
+
if (attempt >= 10 || !["EPERM", "EBUSY", "EACCES"].includes(err.code ?? "")) throw err;
|
|
1397
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
} finally {
|
|
1401
|
+
await rm2(tmp, { force: true });
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
async function renewAfterRefusal(client, kept, owner, p = paths()) {
|
|
1405
|
+
if (kept !== "kept") return false;
|
|
1406
|
+
await ensureCert(client, p, Date.now(), { owner, force: true });
|
|
1407
|
+
return true;
|
|
1408
|
+
}
|
|
1409
|
+
async function removeCert(p = paths()) {
|
|
1410
|
+
await rm2(p.sshCert, { force: true });
|
|
1411
|
+
}
|
|
1412
|
+
function sshKeygen(args) {
|
|
1413
|
+
const res = spawnSync("ssh-keygen", args, { stdio: ["ignore", "pipe", "pipe"], encoding: "utf8" });
|
|
1414
|
+
if (res.error) {
|
|
1415
|
+
if (res.error.code === "ENOENT") throw new KvboxError("ssh-keygen not found; install OpenSSH");
|
|
1416
|
+
throw new KvboxError(`could not run ssh-keygen: ${res.error.message}`);
|
|
1417
|
+
}
|
|
1418
|
+
if (res.status !== 0) throw new KvboxError(`ssh-keygen failed: ${res.stderr.trim()}`);
|
|
1419
|
+
return res.stdout;
|
|
1420
|
+
}
|
|
1421
|
+
async function placeKey(tmp, dest) {
|
|
1422
|
+
try {
|
|
1423
|
+
await link(tmp, dest);
|
|
1424
|
+
} catch (err) {
|
|
1425
|
+
if (!["EPERM", "ENOTSUP", "ENOSYS", "EXDEV", "EOPNOTSUPP"].includes(err.code ?? "")) throw err;
|
|
1426
|
+
await writeFile2(dest, await readFile2(tmp), { flag: "wx", mode: 384 });
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
async function ensureSshKey(p = paths(), hostname = osHostname()) {
|
|
1430
|
+
const pubPath = `${p.sshKey}.pub`;
|
|
1431
|
+
const pub = await readFile2(pubPath, "utf8").catch(() => null);
|
|
1432
|
+
if (pub !== null) return pub.trim();
|
|
1433
|
+
await mkdir2(p.ssh, { recursive: true, mode: 448 });
|
|
1434
|
+
const tmp = `${p.sshKey}.${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
1435
|
+
try {
|
|
1436
|
+
const havePrivate = await readFile2(p.sshKey).then(() => true, () => false);
|
|
1437
|
+
if (!havePrivate) {
|
|
1438
|
+
sshKeygen(["-q", "-t", "ed25519", "-N", "", "-C", `kvbox@${hostname}`, "-f", tmp]);
|
|
1439
|
+
try {
|
|
1440
|
+
await placeKey(tmp, p.sshKey);
|
|
1441
|
+
await rename(`${tmp}.pub`, pubPath);
|
|
1442
|
+
return (await readFile2(pubPath, "utf8")).trim();
|
|
1443
|
+
} catch (err) {
|
|
1444
|
+
if (err.code !== "EEXIST") throw err;
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
let derived;
|
|
1448
|
+
for (let attempt = 1; derived === void 0; attempt++) {
|
|
1449
|
+
try {
|
|
1450
|
+
derived = sshKeygen(["-y", "-f", p.sshKey]);
|
|
1451
|
+
} catch (err) {
|
|
1452
|
+
if (attempt >= 10) throw err;
|
|
1453
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
await writeFile2(`${tmp}.pub`, derived.trim() + "\n");
|
|
1457
|
+
await rename(`${tmp}.pub`, pubPath);
|
|
1458
|
+
} finally {
|
|
1459
|
+
await rm2(tmp, { force: true });
|
|
1460
|
+
await rm2(`${tmp}.pub`, { force: true });
|
|
1461
|
+
}
|
|
1462
|
+
return (await readFile2(pubPath, "utf8")).trim();
|
|
1463
|
+
}
|
|
1464
|
+
async function forgetCertOf(p) {
|
|
1465
|
+
const session = await readSession(p).catch(() => null);
|
|
1466
|
+
if (!session || session.sshCertExpires === void 0) return;
|
|
1467
|
+
const { sshCertExpires: _expires, sshCertPrincipals: _principals, ...rest } = session;
|
|
1468
|
+
await writeSession(rest, p);
|
|
1469
|
+
}
|
|
1470
|
+
async function ensureCert(client, p = paths(), now = Date.now(), opts = {}) {
|
|
1471
|
+
if (client.target.kind !== "cloud") return "local";
|
|
1472
|
+
const fromEnv = client.target.env === true;
|
|
1473
|
+
const session = fromEnv ? null : await readSession(p);
|
|
1474
|
+
if (!fromEnv && !session) return "local";
|
|
1475
|
+
if (session) {
|
|
1476
|
+
const expires = session.sshCertExpires ? new Date(session.sshCertExpires).getTime() : 0;
|
|
1477
|
+
const onDisk = await readFile2(p.sshCert, "utf8").then(() => true, () => false);
|
|
1478
|
+
const names2 = opts.owner === void 0 || (session.sshCertPrincipals ?? []).includes(opts.owner);
|
|
1479
|
+
if (onDisk && expires - now > RENEW_BEFORE_MS && names2 && !opts.force) return "kept";
|
|
1480
|
+
}
|
|
1481
|
+
const publicKey = fromEnv ? await ensureSshKey(p) : await readFile2(`${p.sshKey}.pub`, "utf8").catch(() => null);
|
|
1482
|
+
if (publicKey === null) throw new KvboxError(`could not renew your SSH certificate: no key at ${p.sshKey}.pub; run: kvbox login`);
|
|
1483
|
+
let signed;
|
|
1484
|
+
try {
|
|
1485
|
+
signed = await client.sshCert({ publicKey: publicKey.trim() });
|
|
1486
|
+
} catch (err) {
|
|
1487
|
+
throw new KvboxError(`could not renew your SSH certificate: ${err.message}`);
|
|
1488
|
+
}
|
|
1489
|
+
await writeCert(signed.cert, p);
|
|
1490
|
+
if (session) await writeSession({ ...session, sshCertExpires: signed.expires, sshCertPrincipals: signed.principals }, p);
|
|
1491
|
+
else await forgetCertOf(p);
|
|
1492
|
+
if (opts.owner !== void 0 && !signed.principals.includes(opts.owner)) {
|
|
1493
|
+
const slug = opts.owner.split("@")[0];
|
|
1494
|
+
const sameSlugElsewhere = signed.principals.find((pr) => pr.split("@")[0] === slug && pr !== opts.owner);
|
|
1495
|
+
const why = sameSlugElsewhere ? `the control plane signs for ${sameSlugElsewhere} but the box's host qualifies its owner as ${opts.owner}: the control plane's name (KVBOX_CLOUD_NAME) changed after the host joined` : `you are not a member of ${slug} (a platform admin reaches org boxes over the API, not over SSH)`;
|
|
1496
|
+
throw new KvboxError(`your SSH certificate does not name ${opts.owner}: ${why}`);
|
|
1497
|
+
}
|
|
1498
|
+
return "renewed";
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
// src/client.ts
|
|
1502
|
+
import { spawn } from "child_process";
|
|
1503
|
+
import { openSync } from "fs";
|
|
1504
|
+
import { mkdir as mkdir3, readFile as readFile3, stat } from "fs/promises";
|
|
1505
|
+
import { setTimeout as sleep } from "timers/promises";
|
|
1506
|
+
import { Agent, request } from "undici";
|
|
1507
|
+
import { z as z7 } from "zod";
|
|
1358
1508
|
|
|
1359
1509
|
// ../shared/src/managed.ts
|
|
1360
1510
|
import { z as z4 } from "zod";
|
|
@@ -1496,8 +1646,11 @@ var GrowManagedRequest = z4.object({ storageGib: z4.number().int() });
|
|
|
1496
1646
|
|
|
1497
1647
|
// ../shared/src/cron.ts
|
|
1498
1648
|
import { z as z5 } from "zod";
|
|
1649
|
+
var DEFAULT_CRON_COMMAND_TIMEOUT_SEC = 600;
|
|
1650
|
+
var MAX_CRON_COMMAND_TIMEOUT_SEC = 3600;
|
|
1651
|
+
var CRON_RUN_LOG_DIR = "/var/log/kvbox/runs";
|
|
1499
1652
|
var CRON_METHODS = ["GET", "POST"];
|
|
1500
|
-
var CRON_OUTCOMES = ["running", "ok", "failed", "timeout", "no-credit", "box-stopped", "host-down", "host-outdated", "lost"];
|
|
1653
|
+
var CRON_OUTCOMES = ["running", "ok", "failed", "timeout", "no-credit", "box-stopped", "host-down", "host-outdated", "lost", "still-running", "box-outdated"];
|
|
1501
1654
|
var CronServiceSchema = z5.object({
|
|
1502
1655
|
owner: z5.string(),
|
|
1503
1656
|
ownerKind: z5.enum(["user", "org"]),
|
|
@@ -1510,20 +1663,16 @@ var CronServiceSchema = z5.object({
|
|
|
1510
1663
|
/** What it costs while it exists; on the answer to `POST /cron` only. */
|
|
1511
1664
|
price: z5.object({ perMonth: z5.number(), currency: z5.string() }).optional()
|
|
1512
1665
|
});
|
|
1513
|
-
var
|
|
1666
|
+
var triggerCommon = {
|
|
1514
1667
|
id: z5.string(),
|
|
1515
1668
|
service: z5.string(),
|
|
1516
1669
|
owner: z5.string(),
|
|
1517
|
-
/** The box
|
|
1670
|
+
/** The box it acts on; a trigger is removed with its box. */
|
|
1518
1671
|
box: z5.string(),
|
|
1519
1672
|
/** Five fields, `minute hour day-of-month month day-of-week`. */
|
|
1520
1673
|
expr: z5.string(),
|
|
1521
1674
|
/** An IANA zone (`Europe/Bucharest`) the expression is read in; `UTC` unless said. */
|
|
1522
1675
|
timezone: z5.string(),
|
|
1523
|
-
method: z5.enum(CRON_METHODS),
|
|
1524
|
-
port: z5.number().int(),
|
|
1525
|
-
/** Path and query, starting with `/`. */
|
|
1526
|
-
path: z5.string(),
|
|
1527
1676
|
/** False: paused, it fires again when resumed. */
|
|
1528
1677
|
enabled: z5.boolean(),
|
|
1529
1678
|
/** When it fires next (ISO); null while paused. */
|
|
@@ -1532,15 +1681,36 @@ var CronTriggerSchema = z5.object({
|
|
|
1532
1681
|
lastOutcome: z5.enum(CRON_OUTCOMES).nullable(),
|
|
1533
1682
|
createdBy: z5.string().nullable(),
|
|
1534
1683
|
createdAt: z5.string()
|
|
1684
|
+
};
|
|
1685
|
+
var CronHttpTriggerSchema = z5.object({
|
|
1686
|
+
...triggerCommon,
|
|
1687
|
+
kind: z5.literal("http"),
|
|
1688
|
+
method: z5.enum(CRON_METHODS),
|
|
1689
|
+
port: z5.number().int(),
|
|
1690
|
+
/** Path and query, starting with `/`. */
|
|
1691
|
+
path: z5.string()
|
|
1535
1692
|
});
|
|
1693
|
+
var CronCommandTriggerSchema = z5.object({
|
|
1694
|
+
...triggerCommon,
|
|
1695
|
+
kind: z5.literal("command"),
|
|
1696
|
+
/** Run by a login shell as the box's user, in its home. */
|
|
1697
|
+
command: z5.string(),
|
|
1698
|
+
/** The command is stopped after this long. */
|
|
1699
|
+
timeoutSec: z5.number().int()
|
|
1700
|
+
});
|
|
1701
|
+
var CronTriggerSchema = z5.discriminatedUnion("kind", [CronHttpTriggerSchema, CronCommandTriggerSchema]);
|
|
1536
1702
|
var CronRunSchema = z5.object({
|
|
1537
1703
|
/** The slot this run was for (ISO); a run asked for by hand has the moment it was asked. */
|
|
1538
1704
|
scheduledFor: z5.string(),
|
|
1539
1705
|
startedAt: z5.string(),
|
|
1540
1706
|
/** Null while `running`, and for a run that was never sent. */
|
|
1541
1707
|
durationMs: z5.number().int().nullable(),
|
|
1542
|
-
/** The box's HTTP status; null when it never answered. */
|
|
1708
|
+
/** The box's HTTP status; null when it never answered, and for a command. */
|
|
1543
1709
|
status: z5.number().int().nullable(),
|
|
1710
|
+
/** A command's exit code (128 + the signal when one ended it); null until it ends, and for a request. */
|
|
1711
|
+
exitCode: z5.number().int().nullable(),
|
|
1712
|
+
/** The file in the box that holds what a command printed; null for a request and for a command that never started. */
|
|
1713
|
+
output: z5.string().nullable(),
|
|
1544
1714
|
outcome: z5.enum(CRON_OUTCOMES),
|
|
1545
1715
|
/** Why it did not end `ok`, in a line. */
|
|
1546
1716
|
error: z5.string().nullable(),
|
|
@@ -1556,6 +1726,9 @@ var CronCatalogSchema = z5.object({
|
|
|
1556
1726
|
minIntervalSeconds: z5.number().int(),
|
|
1557
1727
|
/** How long a box has to answer, in seconds. */
|
|
1558
1728
|
timeoutSeconds: z5.number().int(),
|
|
1729
|
+
/** How long a command may run: unless the trigger says, and at most. */
|
|
1730
|
+
commandTimeoutSeconds: z5.number().int(),
|
|
1731
|
+
maxCommandTimeoutSeconds: z5.number().int(),
|
|
1559
1732
|
docs: z5.string().optional()
|
|
1560
1733
|
});
|
|
1561
1734
|
var CreateCronServiceRequest = z5.object({ name: z5.string() });
|
|
@@ -1563,12 +1736,16 @@ var CreateCronTriggerRequest = z5.object({
|
|
|
1563
1736
|
box: z5.string().min(1),
|
|
1564
1737
|
expr: z5.string().min(1),
|
|
1565
1738
|
timezone: z5.string().optional(),
|
|
1739
|
+
/** A request: `port`, with `method` and `path`. */
|
|
1566
1740
|
method: z5.enum(CRON_METHODS).optional(),
|
|
1567
|
-
port: z5.number().int().min(1).max(65535),
|
|
1568
|
-
path: z5.string().optional()
|
|
1741
|
+
port: z5.number().int().min(1).max(65535).optional(),
|
|
1742
|
+
path: z5.string().optional(),
|
|
1743
|
+
/** Or a command, with `timeoutSec`; exactly one of `port` and `command`. */
|
|
1744
|
+
command: z5.string().optional(),
|
|
1745
|
+
timeoutSec: z5.number().int().optional()
|
|
1569
1746
|
});
|
|
1570
1747
|
var UpdateCronTriggerRequest = z5.object({ enabled: z5.boolean() });
|
|
1571
|
-
var cronTarget = (t) => `${t.method} ${t.box}:${t.port}${t.path}`;
|
|
1748
|
+
var cronTarget = (t) => t.kind === "command" ? `${t.box}$ ${t.command}` : `${t.method} ${t.box}:${t.port}${t.path}`;
|
|
1572
1749
|
|
|
1573
1750
|
// ../shared/src/storage.ts
|
|
1574
1751
|
import { z as z6 } from "zod";
|
|
@@ -1666,7 +1843,7 @@ function groupWithMember(gid, user, groupFile) {
|
|
|
1666
1843
|
}
|
|
1667
1844
|
|
|
1668
1845
|
// ../shared/src/systemd.ts
|
|
1669
|
-
import { spawnSync } from "child_process";
|
|
1846
|
+
import { spawnSync as spawnSync2 } from "child_process";
|
|
1670
1847
|
import { readFileSync as readFileSync2 } from "fs";
|
|
1671
1848
|
import { resolve } from "path";
|
|
1672
1849
|
var UNIT = "kvbox-server";
|
|
@@ -1682,11 +1859,11 @@ function hasUnitFor(p, file = UNIT_FILE) {
|
|
|
1682
1859
|
return home !== void 0 && resolve(home) === resolve(p.home);
|
|
1683
1860
|
}
|
|
1684
1861
|
function startUnitProcess() {
|
|
1685
|
-
const res =
|
|
1862
|
+
const res = spawnSync2("sudo", ["-n", "systemctl", "start", UNIT], { encoding: "utf8" });
|
|
1686
1863
|
return { ok: res.status === 0, out: `${res.stdout ?? ""}${res.stderr ?? ""}`.trim() };
|
|
1687
1864
|
}
|
|
1688
1865
|
function unitActive() {
|
|
1689
|
-
const res =
|
|
1866
|
+
const res = spawnSync2("systemctl", ["is-active", UNIT], { encoding: "utf8" });
|
|
1690
1867
|
return (res.stdout ?? "").trim() === "active";
|
|
1691
1868
|
}
|
|
1692
1869
|
|
|
@@ -1699,11 +1876,15 @@ function orgOption(opts) {
|
|
|
1699
1876
|
}
|
|
1700
1877
|
async function resolveTarget(opts, p = paths()) {
|
|
1701
1878
|
if (!opts.local) {
|
|
1702
|
-
const
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1879
|
+
const org = orgOption(opts);
|
|
1880
|
+
const fromEnv = envLogin();
|
|
1881
|
+
if (fromEnv) {
|
|
1882
|
+
const asking = new ServerClient({ kind: "cloud", ...fromEnv, env: true }, { autoStart: false });
|
|
1883
|
+
const user = await asking.me().finally(() => asking.close());
|
|
1884
|
+
return { kind: "cloud", ...fromEnv, env: true, user: user.username, ...org === void 0 ? {} : { org } };
|
|
1706
1885
|
}
|
|
1886
|
+
const session = await readSession(p);
|
|
1887
|
+
if (session) return { kind: "cloud", url: session.url, token: session.token, user: session.user, ...org === void 0 ? {} : { org } };
|
|
1707
1888
|
}
|
|
1708
1889
|
return { kind: "local", socketPath: p.serverSock };
|
|
1709
1890
|
}
|
|
@@ -1749,20 +1930,22 @@ var ServerClient = class {
|
|
|
1749
1930
|
}
|
|
1750
1931
|
throw new KvboxError(`kvbox-server is not running (${String(code)}); start it with: kvbox-server start -d`);
|
|
1751
1932
|
}
|
|
1752
|
-
throw new
|
|
1933
|
+
throw new CallError(cloudDown(this.target.url, String(code)), 0);
|
|
1753
1934
|
}
|
|
1754
1935
|
const text2 = await res.body.text();
|
|
1755
1936
|
const where = this.target.kind === "cloud" ? hostOf(this.target.url) : "kvbox-server";
|
|
1756
1937
|
if (res.statusCode >= 300) {
|
|
1757
1938
|
const parsed = ApiErrorSchema.safeParse(safeJson(text2) ?? {});
|
|
1758
|
-
if (!parsed.success) throw new
|
|
1939
|
+
if (!parsed.success) throw new CallError(`${where} answered ${res.statusCode}`, res.statusCode);
|
|
1759
1940
|
if (this.target.kind === "cloud" && this.target.token !== "") {
|
|
1760
|
-
if (res.statusCode === 401)
|
|
1941
|
+
if (res.statusCode === 401) {
|
|
1942
|
+
throw new KvboxError(this.target.env ? `${where} refused the API key in KVBOX_TOKEN: it was removed or has expired` : "session expired: kvbox login");
|
|
1943
|
+
}
|
|
1761
1944
|
if (res.statusCode === 404 && this.target.org !== void 0 && parsed.data.error === `org ${this.target.org}: not found`) {
|
|
1762
1945
|
throw new KvboxError(`${parsed.data.error} (you are not in it, or it is gone)`);
|
|
1763
1946
|
}
|
|
1764
1947
|
}
|
|
1765
|
-
throw new
|
|
1948
|
+
throw new CallError(parsed.data.error, res.statusCode, res.statusCode === 501 ? 2 : 1);
|
|
1766
1949
|
}
|
|
1767
1950
|
if (text2 === "") return schema.parse(void 0);
|
|
1768
1951
|
const json2 = safeJson(text2);
|
|
@@ -2103,12 +2286,29 @@ var ServerClient = class {
|
|
|
2103
2286
|
login(req) {
|
|
2104
2287
|
return this.call("POST", "/login", LoginResponseSchema, req);
|
|
2105
2288
|
}
|
|
2289
|
+
/** Device login (#189): open one, then poll with the answer's `deviceCode` until it is approved, refused or expired. */
|
|
2290
|
+
startDeviceLogin(req) {
|
|
2291
|
+
return this.call("POST", "/login/device", DeviceLoginStartSchema, req);
|
|
2292
|
+
}
|
|
2293
|
+
pollDeviceLogin(deviceCode) {
|
|
2294
|
+
return this.call("POST", "/login/device/token", DeviceLoginPollSchema, { deviceCode });
|
|
2295
|
+
}
|
|
2106
2296
|
logout() {
|
|
2107
2297
|
return this.call("POST", "/logout", z7.unknown()).then(() => void 0);
|
|
2108
2298
|
}
|
|
2109
2299
|
me() {
|
|
2110
2300
|
return this.call("GET", "/me", MeResponseSchema);
|
|
2111
2301
|
}
|
|
2302
|
+
// ---- API keys (`kvbox key …`, #189) ----
|
|
2303
|
+
listApiKeys() {
|
|
2304
|
+
return this.call("GET", "/keys", z7.array(ApiKeySchema));
|
|
2305
|
+
}
|
|
2306
|
+
createApiKey(req) {
|
|
2307
|
+
return this.call("POST", "/keys", CreatedApiKeySchema, req);
|
|
2308
|
+
}
|
|
2309
|
+
deleteApiKey(name) {
|
|
2310
|
+
return this.call("DELETE", `/keys/${encodeURIComponent(name)}`, z7.unknown()).then(() => void 0);
|
|
2311
|
+
}
|
|
2112
2312
|
// ---- orgs (`kvbox org …`) ----
|
|
2113
2313
|
listOrgs() {
|
|
2114
2314
|
return this.call("GET", "/orgs", z7.array(OrgMembershipSchema));
|
|
@@ -2150,6 +2350,14 @@ var ServerClient = class {
|
|
|
2150
2350
|
await this.dispatcher.close();
|
|
2151
2351
|
}
|
|
2152
2352
|
};
|
|
2353
|
+
var CallError = class extends KvboxError {
|
|
2354
|
+
constructor(message, status2, exitCode = 1) {
|
|
2355
|
+
super(message, exitCode);
|
|
2356
|
+
this.status = status2;
|
|
2357
|
+
}
|
|
2358
|
+
status;
|
|
2359
|
+
};
|
|
2360
|
+
var isUnreachable = (err) => err instanceof CallError && [0, 502, 503, 504].includes(err.status);
|
|
2153
2361
|
function cloudDown(url, code) {
|
|
2154
2362
|
const host = hostOf(url);
|
|
2155
2363
|
const hint = host.endsWith("kvbox.sh") ? "check status.kvbox.sh" : "use --local for this machine, or kvbox logout";
|
|
@@ -2237,8 +2445,8 @@ async function checkDirect(ep) {
|
|
|
2237
2445
|
}
|
|
2238
2446
|
var NOT_A_HOST_HINT = "kvbox-server is not installed, so this machine is not a kvbox host. Set it up with install-server.sh, or log in to the cloud with: kvbox login";
|
|
2239
2447
|
async function lastErrorLine(logPath, from = 0) {
|
|
2240
|
-
const { readFile:
|
|
2241
|
-
const text2 = (await
|
|
2448
|
+
const { readFile: readFile8 } = await import("fs/promises");
|
|
2449
|
+
const text2 = (await readFile8(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
|
|
2242
2450
|
for (const line of text2.trimEnd().split("\n").slice(-20).reverse()) {
|
|
2243
2451
|
const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
|
|
2244
2452
|
if (m?.[1] !== void 0) return m[1];
|
|
@@ -2246,7 +2454,7 @@ async function lastErrorLine(logPath, from = 0) {
|
|
|
2246
2454
|
return void 0;
|
|
2247
2455
|
}
|
|
2248
2456
|
async function startLocalServer(p = paths(), timeoutMs = 5e3) {
|
|
2249
|
-
await
|
|
2457
|
+
await mkdir3(p.home, { recursive: true });
|
|
2250
2458
|
if (hasUnitFor(p)) return startUnit(p, timeoutMs);
|
|
2251
2459
|
const log = openSync(p.serverLog, "a");
|
|
2252
2460
|
const launcher = serverLauncher();
|
|
@@ -2692,14 +2900,14 @@ var connectCommand = new Command2("connect").alias("cn").description("open a she
|
|
|
2692
2900
|
} finally {
|
|
2693
2901
|
await client.close();
|
|
2694
2902
|
}
|
|
2695
|
-
let res =
|
|
2903
|
+
let res = spawnSync3("ssh", [...sshArgs(ep), ...cmdArgs], { stdio: "inherit" });
|
|
2696
2904
|
if (res.error) throw new KvboxError(`could not run ssh: ${res.error.message}`);
|
|
2697
2905
|
if (res.status === SSH_FAILED) {
|
|
2698
2906
|
const again = await clientFor(cmd.optsWithGlobals());
|
|
2699
2907
|
const retry = await renewAfterRefusal(again, cert, owner).finally(() => again.close());
|
|
2700
2908
|
if (retry) {
|
|
2701
2909
|
info("renewed your SSH certificate, trying again\u2026");
|
|
2702
|
-
res =
|
|
2910
|
+
res = spawnSync3("ssh", [...sshArgs(ep), ...cmdArgs], { stdio: "inherit" });
|
|
2703
2911
|
if (res.error) throw new KvboxError(`could not run ssh: ${res.error.message}`);
|
|
2704
2912
|
}
|
|
2705
2913
|
}
|
|
@@ -2999,8 +3207,8 @@ var linkCommand = new Command8("link").description("let one box reach a port of
|
|
|
2999
3207
|
return;
|
|
3000
3208
|
}
|
|
3001
3209
|
const fromName = from.slice(from.lastIndexOf("/") + 1);
|
|
3002
|
-
const
|
|
3003
|
-
const apart =
|
|
3210
|
+
const link2 = box.links?.find((l) => l.port === port && l.from.slice(l.from.lastIndexOf("/") + 1) === fromName);
|
|
3211
|
+
const apart = link2 !== void 0 ? link2.from.includes("/") : from.includes("/") && from.split("/")[0] !== slugOf(box.owner);
|
|
3004
3212
|
const host = apart ? `${box.name}.${slugOf(box.owner)}.kvbox` : `${box.name}.kvbox`;
|
|
3005
3213
|
info(`${color.green("\u2713")} box ${color.bold(from)} can reach ${color.bold(`${host}:${port}`)}`);
|
|
3006
3214
|
if (box.status !== "running") info(` box ${shown} is ${box.status}: the link opens when it runs`);
|
|
@@ -3958,17 +4166,53 @@ for (const cmd of vmCommand.commands) if (cmd !== proxyCommand && cmd !== hookCo
|
|
|
3958
4166
|
var vmAliases = [newCommand, lsCommand, getCommand, connectCommand, execCommand, stopCommand, startCommand, pauseCommand, resumeCommand, hibernateCommand, wakeCommand, rmCommand3, claimCommand];
|
|
3959
4167
|
|
|
3960
4168
|
// src/commands/login.ts
|
|
3961
|
-
import {
|
|
3962
|
-
import { mkdir as mkdir3, readFile as readFile4, writeFile as writeFile3 } from "fs/promises";
|
|
3963
|
-
import { hostname as osHostname } from "os";
|
|
4169
|
+
import { hostname as osHostname2 } from "os";
|
|
3964
4170
|
import { createInterface as createInterface2 } from "readline/promises";
|
|
4171
|
+
import { setTimeout as sleep3 } from "timers/promises";
|
|
3965
4172
|
import { Writable } from "stream";
|
|
3966
4173
|
import { Command as Command38 } from "commander";
|
|
3967
|
-
|
|
4174
|
+
|
|
4175
|
+
// src/browser.ts
|
|
4176
|
+
import { spawn as spawn4 } from "child_process";
|
|
4177
|
+
function isWebLink(url) {
|
|
4178
|
+
if (/[^\x21-\x7e]/.test(url)) return false;
|
|
4179
|
+
let parsed;
|
|
4180
|
+
try {
|
|
4181
|
+
parsed = new URL(url);
|
|
4182
|
+
} catch {
|
|
4183
|
+
return false;
|
|
4184
|
+
}
|
|
4185
|
+
if (parsed.protocol === "https:") return parsed.hostname !== "";
|
|
4186
|
+
const host = parsed.hostname;
|
|
4187
|
+
return parsed.protocol === "http:" && (host === "localhost" || host.startsWith("127.") || host === "[::1]");
|
|
4188
|
+
}
|
|
4189
|
+
function browserCommand(url, platform = process.platform, env = process.env, isTTY = process.stderr.isTTY === true) {
|
|
4190
|
+
if (!isWebLink(url)) return null;
|
|
4191
|
+
if (!isTTY || env["SSH_CONNECTION"] || env["SSH_TTY"] || env["CI"]) return null;
|
|
4192
|
+
if (platform === "darwin") return ["open", url];
|
|
4193
|
+
if (platform === "win32") return ["rundll32", "url.dll,FileProtocolHandler", url];
|
|
4194
|
+
if (!env["DISPLAY"] && !env["WAYLAND_DISPLAY"]) return null;
|
|
4195
|
+
return ["xdg-open", url];
|
|
4196
|
+
}
|
|
4197
|
+
function openBrowser(url) {
|
|
4198
|
+
const argv = browserCommand(url);
|
|
4199
|
+
if (argv === null) return;
|
|
4200
|
+
try {
|
|
4201
|
+
const child = spawn4(argv[0], argv.slice(1), { stdio: "ignore", detached: true });
|
|
4202
|
+
child.on("error", () => {
|
|
4203
|
+
});
|
|
4204
|
+
child.unref();
|
|
4205
|
+
} catch {
|
|
4206
|
+
}
|
|
4207
|
+
}
|
|
4208
|
+
|
|
4209
|
+
// src/commands/login.ts
|
|
4210
|
+
var loginCommand = new Command38("login").description("log in to the kvbox cloud (or your own control plane) and target it from now on").argument("[url]", `control plane URL (default: ${DEFAULT_CLOUD_URL})`).option("--password", "log in with email and password instead of approving a code in the web app").option("-e, --email <email>", "account email, for a password login (prompted otherwise)").option("--password-stdin", "read the password from the first line of stdin (for scripts)").action(async (urlArg, opts) => {
|
|
3968
4211
|
const url = normalizeUrl(urlArg ?? DEFAULT_CLOUD_URL);
|
|
3969
|
-
const
|
|
3970
|
-
const session = await runLogin(url,
|
|
4212
|
+
const byPassword = opts.password === true || opts.passwordStdin === true || opts.email !== void 0;
|
|
4213
|
+
const session = byPassword ? await runLogin(url, await readCredentials(opts), paths()) : await runDeviceLogin(url, paths());
|
|
3971
4214
|
info(`logged in to ${hostOf(url)} as ${session.user}`);
|
|
4215
|
+
if (envLogin()) info("KVBOX_TOKEN is set: commands keep using that API key until it is unset");
|
|
3972
4216
|
});
|
|
3973
4217
|
async function readCredentials(opts, io = { stdin: process.stdin, isTTY: process.stdin.isTTY === true }) {
|
|
3974
4218
|
const noTerminal = () => new KvboxError("stdin is not a terminal: pass --email and --password-stdin");
|
|
@@ -3985,7 +4229,7 @@ async function readCredentials(opts, io = { stdin: process.stdin, isTTY: process
|
|
|
3985
4229
|
if (password === "") throw new KvboxError("password is empty");
|
|
3986
4230
|
return { email, password };
|
|
3987
4231
|
}
|
|
3988
|
-
async function runLogin(url, creds, p = paths(), hostname =
|
|
4232
|
+
async function runLogin(url, creds, p = paths(), hostname = osHostname2()) {
|
|
3989
4233
|
const publicKey = await ensureSshKey(p, hostname);
|
|
3990
4234
|
const client = new ServerClient({ kind: "cloud", url, token: "" }, { autoStart: false });
|
|
3991
4235
|
let res;
|
|
@@ -3994,6 +4238,9 @@ async function runLogin(url, creds, p = paths(), hostname = osHostname()) {
|
|
|
3994
4238
|
} finally {
|
|
3995
4239
|
await client.close();
|
|
3996
4240
|
}
|
|
4241
|
+
return storeLogin(url, res, p);
|
|
4242
|
+
}
|
|
4243
|
+
async function storeLogin(url, res, p) {
|
|
3997
4244
|
const session = { url, token: res.token, user: res.user.username };
|
|
3998
4245
|
if (res.sshCert !== void 0 && res.sshCertExpires !== void 0) {
|
|
3999
4246
|
await writeCert(res.sshCert, p);
|
|
@@ -4003,21 +4250,47 @@ async function runLogin(url, creds, p = paths(), hostname = osHostname()) {
|
|
|
4003
4250
|
await writeSession(session, p);
|
|
4004
4251
|
return session;
|
|
4005
4252
|
}
|
|
4006
|
-
|
|
4007
|
-
|
|
4008
|
-
const
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
|
|
4012
|
-
|
|
4013
|
-
|
|
4014
|
-
|
|
4015
|
-
|
|
4016
|
-
|
|
4253
|
+
var terminalIo = { say: info, sleep: sleep3, open: openBrowser, wait: (message, work) => spin(message, work) };
|
|
4254
|
+
async function runDeviceLogin(url, p = paths(), hostname = osHostname2(), io = terminalIo) {
|
|
4255
|
+
const publicKey = await ensureSshKey(p, hostname);
|
|
4256
|
+
const client = new ServerClient({ kind: "cloud", url, token: "" }, { autoStart: false });
|
|
4257
|
+
try {
|
|
4258
|
+
let start;
|
|
4259
|
+
try {
|
|
4260
|
+
start = await client.startDeviceLogin({ publicKey, hostname });
|
|
4261
|
+
} catch (err) {
|
|
4262
|
+
if (err instanceof KvboxError && err.message.startsWith("no route")) throw new KvboxError(`${hostOf(url)} has no login by code yet: use kvbox login --password`);
|
|
4263
|
+
throw err;
|
|
4264
|
+
}
|
|
4265
|
+
if (!isWebLink(start.verifyUrl)) throw new KvboxError(`${hostOf(url)} answered a link to approve the login that is not https; nothing was opened`);
|
|
4266
|
+
const minutes = Math.round(start.expiresIn / 60);
|
|
4267
|
+
io.say(`To log in, open this link and approve the code ${start.userCode} (good for ${minutes} min):`);
|
|
4268
|
+
io.say(` ${start.verifyUrl}`);
|
|
4269
|
+
io.open(start.verifyUrl);
|
|
4270
|
+
const { deviceCode } = start;
|
|
4271
|
+
let interval = start.interval;
|
|
4272
|
+
let waited = 0;
|
|
4273
|
+
const res = await io.wait("waiting for you to approve it in the browser\u2026", async () => {
|
|
4274
|
+
for (; ; ) {
|
|
4275
|
+
await io.sleep(interval * 1e3);
|
|
4276
|
+
waited += interval;
|
|
4277
|
+
let poll;
|
|
4278
|
+
try {
|
|
4279
|
+
poll = await client.pollDeviceLogin(deviceCode);
|
|
4280
|
+
} catch (err) {
|
|
4281
|
+
if (isUnreachable(err) && waited < start.expiresIn + DEVICE_LOGIN_PICKUP_SEC) continue;
|
|
4282
|
+
throw err;
|
|
4283
|
+
}
|
|
4284
|
+
if (poll.status === "approved") return poll;
|
|
4285
|
+
if (poll.status === "refused") throw new KvboxError("the login was refused in the web app; nothing was stored");
|
|
4286
|
+
if (poll.status === "expired") throw new KvboxError("nobody approved the code in time: run kvbox login again");
|
|
4287
|
+
if (poll.status === "slow_down") interval += 5;
|
|
4288
|
+
}
|
|
4289
|
+
});
|
|
4290
|
+
return await storeLogin(url, res, p);
|
|
4291
|
+
} finally {
|
|
4292
|
+
await client.close();
|
|
4017
4293
|
}
|
|
4018
|
-
if (res.status !== 0) throw new KvboxError(`ssh-keygen failed: ${res.stderr.trim()}`);
|
|
4019
|
-
if (havePrivate) await writeFile3(pubPath, res.stdout.trim() + "\n");
|
|
4020
|
-
return (await readFile4(pubPath, "utf8")).trim();
|
|
4021
4294
|
}
|
|
4022
4295
|
async function prompt(question, io) {
|
|
4023
4296
|
const rl = createInterface2({ input: io.input, output: io.output });
|
|
@@ -4058,6 +4331,7 @@ var logoutCommand = new Command39("logout").description("log out of the control
|
|
|
4058
4331
|
case "cleared":
|
|
4059
4332
|
info(`logged out of ${hostOf(session?.url ?? "")}`);
|
|
4060
4333
|
}
|
|
4334
|
+
if (envLogin()) info("KVBOX_TOKEN is still set: commands keep using that API key. Unset it, or remove the key with: kvbox key rm <name>");
|
|
4061
4335
|
});
|
|
4062
4336
|
async function runLogout(p = paths()) {
|
|
4063
4337
|
let session;
|
|
@@ -4083,10 +4357,19 @@ async function runLogout(p = paths()) {
|
|
|
4083
4357
|
|
|
4084
4358
|
// src/commands/whoami.ts
|
|
4085
4359
|
import { Command as Command40 } from "commander";
|
|
4086
|
-
var whoamiCommand = new Command40("whoami").description("show which account and control plane commands target (or local mode)").option("--json", "print as JSON").action(async (opts) => {
|
|
4360
|
+
var whoamiCommand = new Command40("whoami").description("show which account and control plane commands target (or local mode)").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
4361
|
+
if (!cmd.optsWithGlobals().local && envLogin()) {
|
|
4362
|
+
const target = await resolveTarget({});
|
|
4363
|
+
if (target.kind !== "cloud") return;
|
|
4364
|
+
if (opts.json) json({ user: target.user ?? null, url: target.url, sshCertExpires: null, apiKey: true });
|
|
4365
|
+
else process.stdout.write(`${target.user} on ${hostOf(target.url)}
|
|
4366
|
+
using the API key in KVBOX_TOKEN
|
|
4367
|
+
`);
|
|
4368
|
+
return;
|
|
4369
|
+
}
|
|
4087
4370
|
const session = await readSession();
|
|
4088
4371
|
if (opts.json) {
|
|
4089
|
-
json(session ? { user: session.user, url: session.url, sshCertExpires: session.sshCertExpires ?? null } : null);
|
|
4372
|
+
json(session ? { user: session.user, url: session.url, sshCertExpires: session.sshCertExpires ?? null, apiKey: false } : null);
|
|
4090
4373
|
return;
|
|
4091
4374
|
}
|
|
4092
4375
|
process.stdout.write(describeSession(session) + "\n");
|
|
@@ -4098,12 +4381,110 @@ function describeSession(session) {
|
|
|
4098
4381
|
return lines.join("\n");
|
|
4099
4382
|
}
|
|
4100
4383
|
|
|
4101
|
-
// src/commands/
|
|
4384
|
+
// src/commands/key/index.ts
|
|
4102
4385
|
import { Command as Command44 } from "commander";
|
|
4103
4386
|
|
|
4104
|
-
// src/commands/
|
|
4387
|
+
// src/commands/key/create.ts
|
|
4105
4388
|
import { Command as Command41 } from "commander";
|
|
4106
|
-
|
|
4389
|
+
|
|
4390
|
+
// src/commands/key/shared.ts
|
|
4391
|
+
async function keyClient(cmd) {
|
|
4392
|
+
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
4393
|
+
if (client.target.kind !== "cloud") {
|
|
4394
|
+
await client.close();
|
|
4395
|
+
throw new KvboxError("API keys belong to an account on the kvbox cloud: kvbox login first");
|
|
4396
|
+
}
|
|
4397
|
+
if (client.target.env) {
|
|
4398
|
+
await client.close();
|
|
4399
|
+
throw new KvboxError("KVBOX_TOKEN is set, and an API key cannot manage keys: unset it and use your login (kvbox login)");
|
|
4400
|
+
}
|
|
4401
|
+
return client;
|
|
4402
|
+
}
|
|
4403
|
+
function parseExpires(text2, now = Date.now()) {
|
|
4404
|
+
if (text2.trim().toLowerCase() === "never") return null;
|
|
4405
|
+
const sec = parseDuration(text2);
|
|
4406
|
+
if (sec !== void 0 && sec > 0) {
|
|
4407
|
+
const at = new Date(now + sec * 1e3);
|
|
4408
|
+
if (Number.isNaN(at.getTime()) || at.getUTCFullYear() > 9999) throw new KvboxError(`--expires ${text2} is too far ahead: use never for a key without an end`);
|
|
4409
|
+
return at;
|
|
4410
|
+
}
|
|
4411
|
+
const day3 = /^\d{4}-\d{2}-\d{2}$/.test(text2.trim()) ? /* @__PURE__ */ new Date(`${text2.trim()}T23:59:59.999Z`) : null;
|
|
4412
|
+
if (day3 === null || Number.isNaN(day3.getTime()) || day3.toISOString().slice(0, 10) !== text2.trim()) throw new KvboxError(`--expires takes a duration like 90d, a day like 2027-01-31, or never, not: ${text2}`);
|
|
4413
|
+
if (day3.getTime() <= now) throw new KvboxError(`--expires ${text2} is in the past`);
|
|
4414
|
+
return day3;
|
|
4415
|
+
}
|
|
4416
|
+
function expiryText(expiresAt, now = Date.now()) {
|
|
4417
|
+
if (expiresAt === null) return "never";
|
|
4418
|
+
const left = Date.parse(expiresAt) - now;
|
|
4419
|
+
if (left <= 0) return "expired";
|
|
4420
|
+
const days = Math.floor(left / 864e5);
|
|
4421
|
+
return days === 0 ? "today" : `in ${days} day${days === 1 ? "" : "s"}`;
|
|
4422
|
+
}
|
|
4423
|
+
|
|
4424
|
+
// src/commands/key/create.ts
|
|
4425
|
+
var createCommand3 = new Command41("create").description("make an API key for a program: CI, an agent, the SDK (the key is shown once)").argument("<name>", "what to call the key: lowercase letters, digits, '.', '_' or '-'").option("--expires <when>", `when it stops working: a duration (30d, 12h; m is minutes), a day (2027-01-31), or never; ${DEFAULT_API_KEY_DAYS}d by default`).option("--json", "print as JSON").action(async (name, opts, cmd) => {
|
|
4426
|
+
const expiresAt = opts.expires === void 0 ? void 0 : parseExpires(opts.expires);
|
|
4427
|
+
const client = await keyClient(cmd);
|
|
4428
|
+
try {
|
|
4429
|
+
const made = await client.createApiKey({ name, ...expiresAt === void 0 ? {} : { expiresAt: expiresAt?.toISOString() ?? null } });
|
|
4430
|
+
if (opts.json) {
|
|
4431
|
+
json(made);
|
|
4432
|
+
return;
|
|
4433
|
+
}
|
|
4434
|
+
info(`${color.green("\u2713")} API key ${color.bold(made.name)} made; it ${made.expiresAt === null ? "never expires" : `expires ${expiryText(made.expiresAt)}`}`);
|
|
4435
|
+
process.stdout.write(made.key + "\n");
|
|
4436
|
+
info(color.dim("\nThe key is shown only now. A program uses it as KVBOX_TOKEN; it can do everything you can, except manage keys."));
|
|
4437
|
+
} finally {
|
|
4438
|
+
await client.close();
|
|
4439
|
+
}
|
|
4440
|
+
});
|
|
4441
|
+
|
|
4442
|
+
// src/commands/key/ls.ts
|
|
4443
|
+
import { Command as Command42 } from "commander";
|
|
4444
|
+
var lsCommand5 = new Command42("ls").alias("list").description("list your API keys (never the keys themselves)").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
4445
|
+
const client = await keyClient(cmd);
|
|
4446
|
+
try {
|
|
4447
|
+
const keys = await client.listApiKeys();
|
|
4448
|
+
if (opts.json) {
|
|
4449
|
+
json(keys);
|
|
4450
|
+
return;
|
|
4451
|
+
}
|
|
4452
|
+
if (keys.length === 0) {
|
|
4453
|
+
info("no API keys yet; make one with: kvbox key create <name>");
|
|
4454
|
+
return;
|
|
4455
|
+
}
|
|
4456
|
+
table(keys.map((k) => ({ name: k.name, created: age(k.createdAt), "last used": k.lastUsedAt === null ? "never" : age(k.lastUsedAt), expires: expiryText(k.expiresAt) })));
|
|
4457
|
+
} finally {
|
|
4458
|
+
await client.close();
|
|
4459
|
+
}
|
|
4460
|
+
});
|
|
4461
|
+
|
|
4462
|
+
// src/commands/key/rm.ts
|
|
4463
|
+
import { Command as Command43 } from "commander";
|
|
4464
|
+
var rmCommand4 = new Command43("rm").alias("remove").description("remove an API key: whatever uses it stops working").argument("<name>", "the key's name (kvbox key ls)").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
|
|
4465
|
+
const client = await keyClient(cmd);
|
|
4466
|
+
try {
|
|
4467
|
+
if (!await confirm(`Remove API key ${name}? Whatever uses it stops working.`, opts.yes ?? false)) {
|
|
4468
|
+
info("cancelled");
|
|
4469
|
+
process.exitCode = 1;
|
|
4470
|
+
return;
|
|
4471
|
+
}
|
|
4472
|
+
await client.deleteApiKey(name);
|
|
4473
|
+
info(`${color.green("\u2713")} API key ${name} removed`);
|
|
4474
|
+
} finally {
|
|
4475
|
+
await client.close();
|
|
4476
|
+
}
|
|
4477
|
+
});
|
|
4478
|
+
|
|
4479
|
+
// src/commands/key/index.ts
|
|
4480
|
+
var keyCommand = new Command44("key").aliases(["keys"]).description("API keys: named tokens a program (CI, an agent, the SDK) uses as KVBOX_TOKEN in place of a login").addCommand(createCommand3).addCommand(lsCommand5).addCommand(rmCommand4);
|
|
4481
|
+
|
|
4482
|
+
// src/commands/snapshots/index.ts
|
|
4483
|
+
import { Command as Command48 } from "commander";
|
|
4484
|
+
|
|
4485
|
+
// src/commands/snapshots/ls.ts
|
|
4486
|
+
import { Command as Command45 } from "commander";
|
|
4487
|
+
var lsCommand6 = new Command45("ls").description("list snapshots (yours and your orgs'; --org <slug> for one org)").option("-a, --all", "every snapshot on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
4107
4488
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
4108
4489
|
try {
|
|
4109
4490
|
const cloud = client.target.kind === "cloud";
|
|
@@ -4134,8 +4515,8 @@ var lsCommand5 = new Command41("ls").description("list snapshots (yours and your
|
|
|
4134
4515
|
});
|
|
4135
4516
|
|
|
4136
4517
|
// src/commands/snapshots/new.ts
|
|
4137
|
-
import { Command as
|
|
4138
|
-
var newCommand2 = new
|
|
4518
|
+
import { Command as Command46 } from "commander";
|
|
4519
|
+
var newCommand2 = new Command46("new").description("freeze a running box (memory + disk) into a snapshot; the box keeps running").argument("<box>", "box name").argument("<name>", "snapshot name").option("--replace", "retake a snapshot that exists under this name; the old one stays until the new one is complete").option("--json", "print the snapshot as JSON").action(async (box, name, opts, cmd) => {
|
|
4139
4520
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
4140
4521
|
try {
|
|
4141
4522
|
const req = { box, name, ...opts.replace ? { replace: true } : {} };
|
|
@@ -4148,8 +4529,8 @@ var newCommand2 = new Command42("new").description("freeze a running box (memory
|
|
|
4148
4529
|
});
|
|
4149
4530
|
|
|
4150
4531
|
// src/commands/snapshots/rm.ts
|
|
4151
|
-
import { Command as
|
|
4152
|
-
var
|
|
4532
|
+
import { Command as Command47 } from "commander";
|
|
4533
|
+
var rmCommand5 = new Command47("rm").description("delete a snapshot (boxes made from it are not affected)").argument("<name>", "snapshot name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
|
|
4153
4534
|
if (!await confirm(`Delete snapshot ${name}?`, opts.yes ?? false)) {
|
|
4154
4535
|
info("cancelled");
|
|
4155
4536
|
process.exitCode = 1;
|
|
@@ -4165,14 +4546,14 @@ var rmCommand4 = new Command43("rm").description("delete a snapshot (boxes made
|
|
|
4165
4546
|
});
|
|
4166
4547
|
|
|
4167
4548
|
// src/commands/snapshots/index.ts
|
|
4168
|
-
var snapshotsCommand = new
|
|
4549
|
+
var snapshotsCommand = new Command48("snapshots").aliases(["snapshot", "snap"]).description("freeze running boxes into snapshots and manage them").addCommand(newCommand2).addCommand(lsCommand6).addCommand(rmCommand5);
|
|
4169
4550
|
for (const cmd of snapshotsCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
|
|
4170
4551
|
|
|
4171
4552
|
// src/commands/org/index.ts
|
|
4172
|
-
import { Command as
|
|
4553
|
+
import { Command as Command54 } from "commander";
|
|
4173
4554
|
|
|
4174
4555
|
// src/commands/org/ls.ts
|
|
4175
|
-
import { Command as
|
|
4556
|
+
import { Command as Command49 } from "commander";
|
|
4176
4557
|
|
|
4177
4558
|
// src/commands/org/context.ts
|
|
4178
4559
|
var NOT_LOGGED_IN = "orgs live on the control plane: kvbox login first";
|
|
@@ -4192,7 +4573,7 @@ function orgFor(opts, target) {
|
|
|
4192
4573
|
}
|
|
4193
4574
|
|
|
4194
4575
|
// src/commands/org/ls.ts
|
|
4195
|
-
var
|
|
4576
|
+
var lsCommand7 = new Command49("ls").description("list the orgs you belong to and your role in each").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
4196
4577
|
const client = await cloudClientFor(cmd.optsWithGlobals());
|
|
4197
4578
|
try {
|
|
4198
4579
|
const orgs = await client.listOrgs();
|
|
@@ -4214,8 +4595,8 @@ function orgRows(orgs) {
|
|
|
4214
4595
|
}
|
|
4215
4596
|
|
|
4216
4597
|
// src/commands/org/members.ts
|
|
4217
|
-
import { Command as
|
|
4218
|
-
var
|
|
4598
|
+
import { Command as Command50, Option as Option4 } from "commander";
|
|
4599
|
+
var lsCommand8 = new Command50("ls").description("list an org's members and their roles").option("-o, --org <slug>", "the org (or --org before the command)").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
4219
4600
|
const client = await cloudClientFor(cmd.optsWithGlobals());
|
|
4220
4601
|
try {
|
|
4221
4602
|
const org = await client.getOrg(orgFor(opts, client.target));
|
|
@@ -4229,7 +4610,7 @@ var lsCommand7 = new Command46("ls").description("list an org's members and thei
|
|
|
4229
4610
|
await client.close();
|
|
4230
4611
|
}
|
|
4231
4612
|
});
|
|
4232
|
-
var addCommand2 = new
|
|
4613
|
+
var addCommand2 = new Command50("add").description("add a user to an org (admins and owners; only an owner can add an owner)").argument("<user>", "their username").addOption(new Option4("-r, --role <role>", "their role").choices(ORG_ROLES).default("member")).option("-o, --org <slug>", "the org (or --org before the command)").action(async (user, opts, cmd) => {
|
|
4233
4614
|
const client = await cloudClientFor(cmd.optsWithGlobals());
|
|
4234
4615
|
try {
|
|
4235
4616
|
const slug = orgFor(opts, client.target);
|
|
@@ -4239,7 +4620,7 @@ var addCommand2 = new Command46("add").description("add a user to an org (admins
|
|
|
4239
4620
|
await client.close();
|
|
4240
4621
|
}
|
|
4241
4622
|
});
|
|
4242
|
-
var
|
|
4623
|
+
var rmCommand6 = new Command50("rm").description("remove a member (or leave: remove yourself)").argument("<user>", "their username").option("-o, --org <slug>", "the org (or --org before the command)").option("-y, --yes", "do not ask for confirmation").action(async (user, opts, cmd) => {
|
|
4243
4624
|
const client = await cloudClientFor(cmd.optsWithGlobals());
|
|
4244
4625
|
try {
|
|
4245
4626
|
const slug = orgFor(opts, client.target);
|
|
@@ -4255,11 +4636,11 @@ var rmCommand5 = new Command46("rm").description("remove a member (or leave: rem
|
|
|
4255
4636
|
await client.close();
|
|
4256
4637
|
}
|
|
4257
4638
|
});
|
|
4258
|
-
var membersCommand = new
|
|
4639
|
+
var membersCommand = new Command50("members").description("who is in an org and what they may do").addCommand(lsCommand8).addCommand(addCommand2).addCommand(rmCommand6);
|
|
4259
4640
|
|
|
4260
4641
|
// src/commands/org/new.ts
|
|
4261
|
-
import { Command as
|
|
4262
|
-
var newCommand3 = new
|
|
4642
|
+
import { Command as Command51 } from "commander";
|
|
4643
|
+
var newCommand3 = new Command51("new").description("create an org; you become its owner (the slug is permanent, the name is not)").argument("<slug>", "the org's slug: lowercase, like a username (acme)").option("-n, --name <name>", "display name (default: the slug)").option("--json", "print the org as JSON").action(async (slug, opts, cmd) => {
|
|
4263
4644
|
const client = await cloudClientFor(cmd.optsWithGlobals());
|
|
4264
4645
|
try {
|
|
4265
4646
|
const org = await client.createOrg({ slug, name: opts.name ?? slug });
|
|
@@ -4275,8 +4656,8 @@ var newCommand3 = new Command47("new").description("create an org; you become it
|
|
|
4275
4656
|
});
|
|
4276
4657
|
|
|
4277
4658
|
// src/commands/org/rm.ts
|
|
4278
|
-
import { Command as
|
|
4279
|
-
var
|
|
4659
|
+
import { Command as Command52 } from "commander";
|
|
4660
|
+
var rmCommand7 = new Command52("rm").description("delete an org (owners only; remove its boxes and snapshots first)").argument("<slug>", "the org").option("-y, --yes", "do not ask for confirmation").action(async (slug, opts, cmd) => {
|
|
4280
4661
|
if (!await confirm(`Delete org ${slug}? Its members lose access; its slug stays taken.`, opts.yes ?? false)) {
|
|
4281
4662
|
info("cancelled");
|
|
4282
4663
|
process.exitCode = 1;
|
|
@@ -4292,8 +4673,8 @@ var rmCommand6 = new Command48("rm").description("delete an org (owners only; re
|
|
|
4292
4673
|
});
|
|
4293
4674
|
|
|
4294
4675
|
// src/commands/org/role.ts
|
|
4295
|
-
import { Argument, Command as
|
|
4296
|
-
var roleCommand = new
|
|
4676
|
+
import { Argument, Command as Command53 } from "commander";
|
|
4677
|
+
var roleCommand = new Command53("role").description("change a member's role (owners only)").argument("<user>", "their username").addArgument(new Argument("<role>", "owner, admin or member").choices(ORG_ROLES)).option("-o, --org <slug>", "the org (default: the current context)").action(async (user, role, opts, cmd) => {
|
|
4297
4678
|
const client = await cloudClientFor(cmd.optsWithGlobals());
|
|
4298
4679
|
try {
|
|
4299
4680
|
const slug = orgFor(opts, client.target);
|
|
@@ -4305,11 +4686,11 @@ var roleCommand = new Command49("role").description("change a member's role (own
|
|
|
4305
4686
|
});
|
|
4306
4687
|
|
|
4307
4688
|
// src/commands/org/index.ts
|
|
4308
|
-
var orgCommand = new
|
|
4689
|
+
var orgCommand = new Command54("org").description("orgs: shared slugs that own boxes, with owners, admins and members").addCommand(lsCommand7).addCommand(newCommand3).addCommand(membersCommand).addCommand(roleCommand).addCommand(rmCommand7);
|
|
4309
4690
|
|
|
4310
4691
|
// src/commands/usage.ts
|
|
4311
|
-
import { Command as
|
|
4312
|
-
var usageCommand2 = new
|
|
4692
|
+
import { Command as Command55 } from "commander";
|
|
4693
|
+
var usageCommand2 = new Command55("usage").description("what your boxes and volumes used this month (or --since/--until): running time, vCPU-h, RAM and disk GiB-h, cost").option("--since <date>", "count from this date, e.g. 2026-10-01 (default: the 1st of this month)").option("--until <date>", "count up to this date (default: now)").option("--org <slug>", "one org's boxes only").option("-a, --all", "every box on the platform (platform admins only)").option("--by-user", "one line per user who made the boxes (e.g. who spent what in --org)").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
4313
4694
|
for (const [name, value] of [
|
|
4314
4695
|
["since", opts.since],
|
|
4315
4696
|
["until", opts.until]
|
|
@@ -4491,8 +4872,8 @@ function userRows(r) {
|
|
|
4491
4872
|
}
|
|
4492
4873
|
|
|
4493
4874
|
// src/commands/credit.ts
|
|
4494
|
-
import { Command as
|
|
4495
|
-
var creditCommand = new
|
|
4875
|
+
import { Command as Command56 } from "commander";
|
|
4876
|
+
var creditCommand = new Command56("credit").description("the prepaid credit left on your account and on each of your orgs").option("--org <slug>", "one org only").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
4496
4877
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
4497
4878
|
try {
|
|
4498
4879
|
if (client.target.kind === "local") throw new KvboxError("credit lives on the control plane: kvbox login first");
|
|
@@ -4521,8 +4902,8 @@ function creditRow(b, me2) {
|
|
|
4521
4902
|
}
|
|
4522
4903
|
|
|
4523
4904
|
// src/commands/redeem.ts
|
|
4524
|
-
import { Command as
|
|
4525
|
-
var redeemCommand = new
|
|
4905
|
+
import { Command as Command57 } from "commander";
|
|
4906
|
+
var redeemCommand = new Command57("redeem").description("redeem a promo code for credit, on your account or (--org) an org you own").argument("<code>", "the code, like KV-7F3K-9QXM-2HBD").option("--org <slug>", "give the credit to this org, which you own; it cannot be moved later").option("--json", "print as JSON").action(async (code, opts, cmd) => {
|
|
4526
4907
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
4527
4908
|
try {
|
|
4528
4909
|
if (client.target.kind === "local") throw new KvboxError("codes are redeemed on the control plane: kvbox login first");
|
|
@@ -4540,17 +4921,17 @@ var redeemCommand = new Command53("redeem").description("redeem a promo code for
|
|
|
4540
4921
|
});
|
|
4541
4922
|
|
|
4542
4923
|
// src/commands/deploy/index.ts
|
|
4543
|
-
import { access as access5, readFile as
|
|
4924
|
+
import { access as access5, readFile as readFile7 } from "fs/promises";
|
|
4544
4925
|
import { basename as basename2, resolve as resolve3 } from "path";
|
|
4545
|
-
import { Command as
|
|
4926
|
+
import { Command as Command58, InvalidArgumentError as InvalidArgumentError2, Option as Option5 } from "commander";
|
|
4546
4927
|
|
|
4547
4928
|
// src/commands/deploy/config.ts
|
|
4548
|
-
import { readFile as
|
|
4929
|
+
import { readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
|
|
4549
4930
|
import { isAbsolute, join as join6, normalize, relative as relative2 } from "path";
|
|
4550
4931
|
import { z as z8 } from "zod";
|
|
4551
4932
|
|
|
4552
4933
|
// src/commands/deploy/templates/docker.ts
|
|
4553
|
-
import { readFile as
|
|
4934
|
+
import { readFile as readFile4 } from "fs/promises";
|
|
4554
4935
|
import { join as join2, relative, sep } from "path";
|
|
4555
4936
|
|
|
4556
4937
|
// src/commands/deploy/templates/server.ts
|
|
@@ -4676,7 +5057,7 @@ var dockerTemplate = {
|
|
|
4676
5057
|
},
|
|
4677
5058
|
/** No local build: the box does it. The Dockerfile is read for its EXPOSE port only. */
|
|
4678
5059
|
async build(ctx) {
|
|
4679
|
-
const dockerfile = await
|
|
5060
|
+
const dockerfile = await readFile4(join2(ctx.dir, "Dockerfile"), "utf8").catch(() => void 0);
|
|
4680
5061
|
if (dockerfile === void 0) throw new KvboxError(`${ctx.dir}: no Dockerfile; the Docker template builds the image from it`);
|
|
4681
5062
|
const containerPort = exposedPort(dockerfile);
|
|
4682
5063
|
if (ctx.context !== void 0 && ctx.context !== ctx.dir) {
|
|
@@ -4852,7 +5233,7 @@ var nodeTemplate = {
|
|
|
4852
5233
|
};
|
|
4853
5234
|
|
|
4854
5235
|
// src/commands/deploy/templates/react.ts
|
|
4855
|
-
import { spawn as
|
|
5236
|
+
import { spawn as spawn5 } from "child_process";
|
|
4856
5237
|
import { access as access2 } from "fs/promises";
|
|
4857
5238
|
import { join as join4 } from "path";
|
|
4858
5239
|
var OUT_DIRS = ["dist", "build"];
|
|
@@ -4860,7 +5241,7 @@ async function runBuild(dir, pm) {
|
|
|
4860
5241
|
const args = runScript(pm, "build");
|
|
4861
5242
|
info(`${color.dim("$")} ${pm} ${args.join(" ")}`);
|
|
4862
5243
|
const status2 = await new Promise((resolve4, reject) => {
|
|
4863
|
-
const child =
|
|
5244
|
+
const child = spawn5(pm, args, { cwd: dir, stdio: ["ignore", process.stderr, process.stderr], shell: process.platform === "win32" });
|
|
4864
5245
|
child.once("error", (err) => reject(new KvboxError(`could not run ${pm}: ${err.message}`)));
|
|
4865
5246
|
child.once("close", (code) => resolve4(code ?? 1));
|
|
4866
5247
|
});
|
|
@@ -5128,7 +5509,7 @@ async function readDeployFile(dir) {
|
|
|
5128
5509
|
const path = join6(dir, CONFIG_FILE);
|
|
5129
5510
|
let raw;
|
|
5130
5511
|
try {
|
|
5131
|
-
raw = await
|
|
5512
|
+
raw = await readFile5(path, "utf8");
|
|
5132
5513
|
} catch (err) {
|
|
5133
5514
|
if (err.code === "ENOENT") return void 0;
|
|
5134
5515
|
throw err;
|
|
@@ -5148,7 +5529,7 @@ async function readDeployFile(dir) {
|
|
|
5148
5529
|
return stack ? { kind: "stack", config: parsed.data } : { kind: "single", config: parsed.data };
|
|
5149
5530
|
}
|
|
5150
5531
|
async function writeConfig(dir, config) {
|
|
5151
|
-
await
|
|
5532
|
+
await writeFile3(join6(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
|
|
5152
5533
|
}
|
|
5153
5534
|
function nameFromDir(dirName) {
|
|
5154
5535
|
const slug = dirName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 12).replace(/-+$/, "");
|
|
@@ -5159,7 +5540,7 @@ function subdomainFor(name) {
|
|
|
5159
5540
|
}
|
|
5160
5541
|
|
|
5161
5542
|
// src/commands/deploy/ship.ts
|
|
5162
|
-
import { spawn as
|
|
5543
|
+
import { spawn as spawn6 } from "child_process";
|
|
5163
5544
|
import { readdir, stat as stat2 } from "fs/promises";
|
|
5164
5545
|
import { join as join7 } from "path";
|
|
5165
5546
|
var IMAGE_TOO_OLD = 3;
|
|
@@ -5181,8 +5562,8 @@ async function measure(dir, exclude = []) {
|
|
|
5181
5562
|
return total;
|
|
5182
5563
|
}
|
|
5183
5564
|
async function ship(ep, dir, remote, exclude = []) {
|
|
5184
|
-
const tar =
|
|
5185
|
-
const ssh =
|
|
5565
|
+
const tar = spawn6("tar", ["-cf", "-", ...exclude.map((e) => `--exclude=${e}`), "-C", dir, "."], { stdio: ["ignore", "pipe", "pipe"] });
|
|
5566
|
+
const ssh = spawn6("ssh", [...sshArgs(ep), remote], { stdio: ["pipe", "pipe", "pipe"] });
|
|
5186
5567
|
tar.stdout.pipe(ssh.stdin);
|
|
5187
5568
|
const chunks = [];
|
|
5188
5569
|
ssh.stdout.on("data", (c2) => chunks.push(c2));
|
|
@@ -5210,7 +5591,7 @@ async function ship(ep, dir, remote, exclude = []) {
|
|
|
5210
5591
|
return { status: status2, output: Buffer.concat(chunks).toString("utf8") };
|
|
5211
5592
|
}
|
|
5212
5593
|
async function run(ep, remote) {
|
|
5213
|
-
const ssh =
|
|
5594
|
+
const ssh = spawn6("ssh", [...sshArgs(ep), remote], { stdio: ["ignore", "pipe", "pipe"] });
|
|
5214
5595
|
const chunks = [];
|
|
5215
5596
|
ssh.stdout.on("data", (c2) => chunks.push(c2));
|
|
5216
5597
|
ssh.stderr.on("data", (c2) => chunks.push(c2));
|
|
@@ -5300,11 +5681,11 @@ the app is on box ${ref} but has no address yet: pick another with kvbox deploy
|
|
|
5300
5681
|
}
|
|
5301
5682
|
|
|
5302
5683
|
// src/commands/deploy/stack.ts
|
|
5303
|
-
import { access as access4, readFile as
|
|
5684
|
+
import { access as access4, readFile as readFile6 } from "fs/promises";
|
|
5304
5685
|
import { basename, join as join8, resolve as resolve2 } from "path";
|
|
5305
5686
|
|
|
5306
5687
|
// src/commands/deploy/postgres.ts
|
|
5307
|
-
import { randomBytes } from "crypto";
|
|
5688
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
5308
5689
|
var POSTGRES_USER = "kvbox";
|
|
5309
5690
|
var POSTGRES_DB = "app";
|
|
5310
5691
|
var ENV_MISSING = 6;
|
|
@@ -5317,7 +5698,7 @@ var DB_WAIT_SEC = 90;
|
|
|
5317
5698
|
var AGENT = "/usr/local/sbin/kvbox-agent";
|
|
5318
5699
|
var ENV_WAIT_SEC = 60;
|
|
5319
5700
|
function newPassword() {
|
|
5320
|
-
return
|
|
5701
|
+
return randomBytes2(24).toString("hex");
|
|
5321
5702
|
}
|
|
5322
5703
|
function postgresUrl(password, port) {
|
|
5323
5704
|
return `postgres://${POSTGRES_USER}:${password}@127.0.0.1:${port}/${POSTGRES_DB}`;
|
|
@@ -5591,7 +5972,7 @@ async function exposedPorts(dir, stack) {
|
|
|
5591
5972
|
const ports = /* @__PURE__ */ new Map();
|
|
5592
5973
|
for (const [key, s] of Object.entries(stack.services)) {
|
|
5593
5974
|
if (s.template !== "docker" || s.port !== void 0 || s.dir === void 0) continue;
|
|
5594
|
-
const text2 = await
|
|
5975
|
+
const text2 = await readFile6(resolve2(dir, s.dir, "Dockerfile"), "utf8").catch(() => void 0);
|
|
5595
5976
|
const port = text2 !== void 0 ? exposedPort(text2) : void 0;
|
|
5596
5977
|
if (port !== void 0) ports.set(key, port);
|
|
5597
5978
|
}
|
|
@@ -5799,7 +6180,7 @@ function volumeNameFor(box, taken, account = /* @__PURE__ */ new Set()) {
|
|
|
5799
6180
|
}
|
|
5800
6181
|
async function readPackageJson(dir) {
|
|
5801
6182
|
try {
|
|
5802
|
-
return JSON.parse(await
|
|
6183
|
+
return JSON.parse(await readFile6(join8(dir, "package.json"), "utf8"));
|
|
5803
6184
|
} catch (err) {
|
|
5804
6185
|
if (err.code === "ENOENT") return void 0;
|
|
5805
6186
|
throw new KvboxError(`${join8(dir, "package.json")}: ${err.message}`);
|
|
@@ -5807,7 +6188,7 @@ async function readPackageJson(dir) {
|
|
|
5807
6188
|
}
|
|
5808
6189
|
|
|
5809
6190
|
// src/commands/deploy/index.ts
|
|
5810
|
-
var deployCommand = new
|
|
6191
|
+
var deployCommand = new Command58("deploy").description("put the app in this directory (React, Next.js, a Node server, a Dockerfile or a static site) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json and the directory when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the box port of a Next.js app, Node server or container (default 3000; saved to kvbox.json)", parsePort).option("--only <service>", "with several services in kvbox.json: deploy this one only (repeatable)", (v, all) => [...all ?? [], v]).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
|
|
5811
6192
|
const dir = resolve3(dirArg ?? ".");
|
|
5812
6193
|
const pkg = await readPackageJson2(dir);
|
|
5813
6194
|
const facts = { indexHtml: await exists2(resolve3(dir, "index.html")), dockerfile: await exists2(resolve3(dir, "Dockerfile")) };
|
|
@@ -5881,7 +6262,7 @@ function parsePort(v) {
|
|
|
5881
6262
|
var exists2 = (path) => access5(path).then(() => true, () => false);
|
|
5882
6263
|
async function readPackageJson2(dir) {
|
|
5883
6264
|
try {
|
|
5884
|
-
return JSON.parse(await
|
|
6265
|
+
return JSON.parse(await readFile7(resolve3(dir, "package.json"), "utf8"));
|
|
5885
6266
|
} catch (err) {
|
|
5886
6267
|
if (err.code === "ENOENT") return void 0;
|
|
5887
6268
|
throw new KvboxError(`${resolve3(dir, "package.json")}: ${err.message}`);
|
|
@@ -5964,15 +6345,15 @@ async function settle2(dir, pkg, facts, saved, opts, orgFlag, cloud) {
|
|
|
5964
6345
|
}
|
|
5965
6346
|
|
|
5966
6347
|
// src/commands/volume/index.ts
|
|
5967
|
-
import { Command as
|
|
6348
|
+
import { Command as Command69 } from "commander";
|
|
5968
6349
|
|
|
5969
6350
|
// src/commands/volume/attach.ts
|
|
5970
|
-
import { Command as
|
|
6351
|
+
import { Command as Command59 } from "commander";
|
|
5971
6352
|
function describeMount(machine, volume, box) {
|
|
5972
6353
|
const path = machine.volumes?.find((v) => volume === v.name || volume.endsWith(`/${v.name}`))?.mountPath ?? volumeMountPath(volume.slice(volume.lastIndexOf("/") + 1));
|
|
5973
6354
|
return machine.status === "running" ? ` the box was restarted; the volume is at ${path} inside it` : ` box ${box} is ${machine.status}; the volume is at ${path} once it runs`;
|
|
5974
6355
|
}
|
|
5975
|
-
var attachCommand = new
|
|
6356
|
+
var attachCommand = new Command59("attach").description("attach a volume to a box at /mnt/<volume> (a running box is restarted to take it)").argument("[volume]", "volume name (picked from a list when left out)").argument("[box]", "box name (picked from a list when left out)").option("--json", "print the box as JSON").action(async (volumeArg, boxArg, opts, cmd) => {
|
|
5976
6357
|
if (volumeArg === void 0 || boxArg === void 0) askOrUsage("give the volume and the box: kvbox volume attach <volume> <box>");
|
|
5977
6358
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
5978
6359
|
try {
|
|
@@ -5991,11 +6372,11 @@ var attachCommand = new Command55("attach").description("attach a volume to a bo
|
|
|
5991
6372
|
});
|
|
5992
6373
|
|
|
5993
6374
|
// src/commands/volume/backup/index.ts
|
|
5994
|
-
import { Command as
|
|
6375
|
+
import { Command as Command63 } from "commander";
|
|
5995
6376
|
|
|
5996
6377
|
// src/commands/volume/backup/create.ts
|
|
5997
|
-
import { Command as
|
|
5998
|
-
var
|
|
6378
|
+
import { Command as Command60 } from "commander";
|
|
6379
|
+
var createCommand4 = new Command60("create").description("back up a volume's disk to the kvbox cloud (encrypted)").argument("<volume>", "volume name").option("--wait", "stay until the backup is ready (by default it runs in the background)").option("--json", "print the backup as JSON").action(async (volume, opts, cmd) => {
|
|
5999
6380
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
6000
6381
|
try {
|
|
6001
6382
|
requireCloud3(client);
|
|
@@ -6020,8 +6401,8 @@ var createCommand3 = new Command56("create").description("back up a volume's dis
|
|
|
6020
6401
|
});
|
|
6021
6402
|
|
|
6022
6403
|
// src/commands/volume/backup/ls.ts
|
|
6023
|
-
import { Command as
|
|
6024
|
-
var
|
|
6404
|
+
import { Command as Command61 } from "commander";
|
|
6405
|
+
var lsCommand9 = new Command61("ls").alias("list").description("list volume backups: every volume's, or one volume's").argument("[volume]", "volume name (default: every volume)").option("--json", "print as JSON").action(async (volume, opts, cmd) => {
|
|
6025
6406
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
6026
6407
|
try {
|
|
6027
6408
|
requireCloud3(client);
|
|
@@ -6054,8 +6435,8 @@ var lsCommand8 = new Command57("ls").alias("list").description("list volume back
|
|
|
6054
6435
|
});
|
|
6055
6436
|
|
|
6056
6437
|
// src/commands/volume/backup/restore.ts
|
|
6057
|
-
import { Command as
|
|
6058
|
-
var restoreCommand2 = new
|
|
6438
|
+
import { Command as Command62 } from "commander";
|
|
6439
|
+
var restoreCommand2 = new Command62("restore").description("put a backup back: the volume's data becomes the backup's (a running box holding it restarts)").argument("<volume>", "volume name").argument("<id>", "the backup's id (kvbox volume backup ls <volume>)").option("-y, --yes", "do not ask for confirmation").option("--json", "print the volume as JSON").action(async (volume, id, opts, cmd) => {
|
|
6059
6440
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
6060
6441
|
try {
|
|
6061
6442
|
requireCloud3(client);
|
|
@@ -6078,11 +6459,11 @@ var restoreCommand2 = new Command58("restore").description("put a backup back: t
|
|
|
6078
6459
|
});
|
|
6079
6460
|
|
|
6080
6461
|
// src/commands/volume/backup/index.ts
|
|
6081
|
-
var backupCommand2 = new
|
|
6462
|
+
var backupCommand2 = new Command63("backup").description("back up a volume's disk to the kvbox cloud, list backups, restore one").addCommand(createCommand4).addCommand(lsCommand9).addCommand(restoreCommand2);
|
|
6082
6463
|
for (const cmd of backupCommand2.commands) cmd.option("--org <slug>", "act in this org (- for your personal volumes)");
|
|
6083
6464
|
|
|
6084
6465
|
// src/commands/volume/create.ts
|
|
6085
|
-
import { Command as
|
|
6466
|
+
import { Command as Command64 } from "commander";
|
|
6086
6467
|
function parseGib2(text2, label = "--size") {
|
|
6087
6468
|
const mib = parseMib(text2);
|
|
6088
6469
|
if (mib === void 0 || mib % 1024 !== 0) throw new KvboxError(`${label} ${text2}: write whole GB, like 50 or 50GB`);
|
|
@@ -6098,7 +6479,7 @@ function sizeProblem(answer) {
|
|
|
6098
6479
|
return err instanceof KvboxError ? err.message.replace(/^--size \S+: /, "") : String(err);
|
|
6099
6480
|
}
|
|
6100
6481
|
}
|
|
6101
|
-
var
|
|
6482
|
+
var createCommand5 = new Command64("create").alias("new").description("create a volume for a box: an empty disk of its own at /mnt/<name> inside it (a running box is restarted)").argument("[name]", "volume name (1-12 chars; the box mounts it at /mnt/<name>; asked for when left out)").option("--size <gb>", "size in GB, like 50 or 50GB (whole GB; it only occupies what is written)").option("--box <box>", "the box it is for: made on that box's host and attached to it (required on kvbox.sh; optional with --local)").option("--json", "print the volume as JSON").action(async (nameArg, opts, cmd) => {
|
|
6102
6483
|
const ask = interactive();
|
|
6103
6484
|
if (nameArg === void 0 || opts.size === void 0) askOrUsage("give the name and the size: kvbox volume create <name> --size <gb> --box <box>");
|
|
6104
6485
|
const name = nameArg ?? await text("Volume name", { validate: (a) => VOLUME_NAME_RE.test(a) ? void 0 : VOLUME_NAME_RULE });
|
|
@@ -6131,8 +6512,8 @@ var createCommand4 = new Command60("create").alias("new").description("create a
|
|
|
6131
6512
|
});
|
|
6132
6513
|
|
|
6133
6514
|
// src/commands/volume/detach.ts
|
|
6134
|
-
import { Command as
|
|
6135
|
-
var detachCommand = new
|
|
6515
|
+
import { Command as Command65 } from "commander";
|
|
6516
|
+
var detachCommand = new Command65("detach").description("detach a volume from a box; its data is kept (a running box is restarted)").argument("[volume]", "volume name (picked from a list when left out)").argument("[box]", "box name (the one the volume is on when left out)").option("--json", "print the box as JSON").action(async (volumeArg, boxArg, opts, cmd) => {
|
|
6136
6517
|
if (volumeArg === void 0) askOrUsage("give the volume: kvbox volume detach <volume> [box]");
|
|
6137
6518
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
6138
6519
|
try {
|
|
@@ -6157,8 +6538,8 @@ var detachCommand = new Command61("detach").description("detach a volume from a
|
|
|
6157
6538
|
});
|
|
6158
6539
|
|
|
6159
6540
|
// src/commands/volume/grow.ts
|
|
6160
|
-
import { Command as
|
|
6161
|
-
var growCommand = new
|
|
6541
|
+
import { Command as Command66 } from "commander";
|
|
6542
|
+
var growCommand = new Command66("grow").alias("resize").description("make a volume larger (a running box holding it is restarted once)").argument("<volume>", "volume name").argument("<GB>", "the new size in GB, larger than what it has").option("--json", "print the volume as JSON").action(async (name, size, opts, cmd) => {
|
|
6162
6543
|
const sizeGib = parseGib2(size, "size");
|
|
6163
6544
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
6164
6545
|
try {
|
|
@@ -6171,8 +6552,8 @@ var growCommand = new Command62("grow").alias("resize").description("make a volu
|
|
|
6171
6552
|
});
|
|
6172
6553
|
|
|
6173
6554
|
// src/commands/volume/ls.ts
|
|
6174
|
-
import { Command as
|
|
6175
|
-
var
|
|
6555
|
+
import { Command as Command67 } from "commander";
|
|
6556
|
+
var lsCommand10 = new Command67("ls").alias("list").description("list volumes: size, what they occupy, which box has them").option("-a, --all", "every volume on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
6176
6557
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
6177
6558
|
try {
|
|
6178
6559
|
const cloud = client.target.kind === "cloud";
|
|
@@ -6203,8 +6584,8 @@ var lsCommand9 = new Command63("ls").alias("list").description("list volumes: si
|
|
|
6203
6584
|
});
|
|
6204
6585
|
|
|
6205
6586
|
// src/commands/volume/rm.ts
|
|
6206
|
-
import { Command as
|
|
6207
|
-
var
|
|
6587
|
+
import { Command as Command68 } from "commander";
|
|
6588
|
+
var rmCommand8 = new Command68("rm").alias("remove").description("delete a volume and everything on it (detach it first)").argument("<name>", "volume name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
|
|
6208
6589
|
if (!await confirm(`Delete volume ${name} and everything on it?`, opts.yes ?? false)) {
|
|
6209
6590
|
info("cancelled");
|
|
6210
6591
|
process.exitCode = 1;
|
|
@@ -6220,15 +6601,15 @@ var rmCommand7 = new Command64("rm").alias("remove").description("delete a volum
|
|
|
6220
6601
|
});
|
|
6221
6602
|
|
|
6222
6603
|
// src/commands/volume/index.ts
|
|
6223
|
-
var volumeCommand = new
|
|
6604
|
+
var volumeCommand = new Command69("volume").aliases(["volumes", "vol"]).description("disks of their own: create one, attach it to a box at /mnt/<name>, move it to another box later").addCommand(createCommand5).addCommand(lsCommand10).addCommand(attachCommand).addCommand(detachCommand).addCommand(growCommand).addCommand(rmCommand8);
|
|
6224
6605
|
for (const cmd of volumeCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal volumes)");
|
|
6225
6606
|
volumeCommand.addCommand(backupCommand2);
|
|
6226
6607
|
|
|
6227
6608
|
// src/commands/bucket/index.ts
|
|
6228
|
-
import { Command as
|
|
6609
|
+
import { Command as Command79 } from "commander";
|
|
6229
6610
|
|
|
6230
6611
|
// src/commands/bucket/create.ts
|
|
6231
|
-
import { Command as
|
|
6612
|
+
import { Command as Command70 } from "commander";
|
|
6232
6613
|
|
|
6233
6614
|
// src/commands/bucket/shared.ts
|
|
6234
6615
|
async function bucketClient(cmd) {
|
|
@@ -6254,7 +6635,7 @@ function printRows(rows2) {
|
|
|
6254
6635
|
}
|
|
6255
6636
|
|
|
6256
6637
|
// src/commands/bucket/create.ts
|
|
6257
|
-
var
|
|
6638
|
+
var createCommand6 = new Command70("create").description("make a bucket (the first one also makes your object storage)").argument("<name>", "bucket name: 3-63 lowercase letters, digits and '-'").option("--size <GB>", "how much your object storage may hold, when this is your first bucket (default 10)").option("--region <region>", "the S3 region of your object storage (ro-west-1, de-center-1), when this is your first bucket").option("--near <box>", "put the object storage on the host of this box, when this is your first bucket").option("--json", "print as JSON").action(async (name, opts, cmd) => {
|
|
6258
6639
|
const sizeGib = opts.size === void 0 ? void 0 : parseGib2(opts.size);
|
|
6259
6640
|
const client = await bucketClient(cmd);
|
|
6260
6641
|
try {
|
|
@@ -6274,8 +6655,8 @@ var createCommand5 = new Command66("create").description("make a bucket (the fir
|
|
|
6274
6655
|
});
|
|
6275
6656
|
|
|
6276
6657
|
// src/commands/bucket/grow.ts
|
|
6277
|
-
import { Command as
|
|
6278
|
-
var growCommand2 = new
|
|
6658
|
+
import { Command as Command71 } from "commander";
|
|
6659
|
+
var growCommand2 = new Command71("grow").description("make your object storage larger (all your buckets share it; it restarts once)").argument("<GB>", "the new size in GB, larger than what it has").option("--json", "print the object storage as JSON").action(async (size, opts, cmd) => {
|
|
6279
6660
|
const sizeGib = parseGib2(size, "size");
|
|
6280
6661
|
const client = await bucketClient(cmd);
|
|
6281
6662
|
try {
|
|
@@ -6288,8 +6669,8 @@ var growCommand2 = new Command67("grow").description("make your object storage l
|
|
|
6288
6669
|
});
|
|
6289
6670
|
|
|
6290
6671
|
// src/commands/bucket/info.ts
|
|
6291
|
-
import { Command as
|
|
6292
|
-
var infoCommand = new
|
|
6672
|
+
import { Command as Command72 } from "commander";
|
|
6673
|
+
var infoCommand = new Command72("info").description("one bucket: its address, what it holds, how full your object storage is").argument("<name>", "bucket name").option("--json", "print as JSON").action(async (name, opts, cmd) => {
|
|
6293
6674
|
const client = await bucketClient(cmd);
|
|
6294
6675
|
try {
|
|
6295
6676
|
const b = await client.getBucket(name);
|
|
@@ -6318,11 +6699,11 @@ with the AWS CLI: aws s3 ls s3://${b.name} --endpoint-url ${b.endpoint}`));
|
|
|
6318
6699
|
});
|
|
6319
6700
|
|
|
6320
6701
|
// src/commands/bucket/key/index.ts
|
|
6321
|
-
import { Command as
|
|
6702
|
+
import { Command as Command76 } from "commander";
|
|
6322
6703
|
|
|
6323
6704
|
// src/commands/bucket/key/create.ts
|
|
6324
|
-
import { Command as
|
|
6325
|
-
var
|
|
6705
|
+
import { Command as Command73 } from "commander";
|
|
6706
|
+
var createCommand7 = new Command73("create").description("make an access key for a bucket (the secret is shown once)").argument("<bucket>", "bucket name").option("--name <label>", "what to call the key, to tell it from the others").option("--read-only", "the key reads the bucket but cannot write to it").option("--json", "print as JSON").action(async (bucket, opts, cmd) => {
|
|
6326
6707
|
const client = await bucketClient(cmd);
|
|
6327
6708
|
try {
|
|
6328
6709
|
const key = await client.createBucketKey(bucket, { ...opts.name !== void 0 ? { name: opts.name } : {}, ...opts.readOnly ? { readOnly: true } : {} });
|
|
@@ -6345,8 +6726,8 @@ var createCommand6 = new Command69("create").description("make an access key for
|
|
|
6345
6726
|
});
|
|
6346
6727
|
|
|
6347
6728
|
// src/commands/bucket/key/ls.ts
|
|
6348
|
-
import { Command as
|
|
6349
|
-
var
|
|
6729
|
+
import { Command as Command74 } from "commander";
|
|
6730
|
+
var lsCommand11 = new Command74("ls").alias("list").description("list a bucket's access keys (never their secrets)").argument("<bucket>", "bucket name").option("--json", "print as JSON").action(async (bucket, opts, cmd) => {
|
|
6350
6731
|
const client = await bucketClient(cmd);
|
|
6351
6732
|
try {
|
|
6352
6733
|
const keys = await client.listBucketKeys(bucket);
|
|
@@ -6365,8 +6746,8 @@ var lsCommand10 = new Command70("ls").alias("list").description("list a bucket's
|
|
|
6365
6746
|
});
|
|
6366
6747
|
|
|
6367
6748
|
// src/commands/bucket/key/rm.ts
|
|
6368
|
-
import { Command as
|
|
6369
|
-
var
|
|
6749
|
+
import { Command as Command75 } from "commander";
|
|
6750
|
+
var rmCommand9 = new Command75("rm").alias("remove").description("delete an access key: whatever uses it stops reaching the bucket").argument("<bucket>", "bucket name").argument("<access-key>", "the access key id (kvbox bucket key ls)").option("-y, --yes", "do not ask for confirmation").action(async (bucket, id, opts, cmd) => {
|
|
6370
6751
|
const client = await bucketClient(cmd);
|
|
6371
6752
|
try {
|
|
6372
6753
|
if (!await confirm(`Delete key ${id} of bucket ${bucket}? Whatever uses it stops working.`, opts.yes ?? false)) {
|
|
@@ -6382,11 +6763,11 @@ var rmCommand8 = new Command71("rm").alias("remove").description("delete an acce
|
|
|
6382
6763
|
});
|
|
6383
6764
|
|
|
6384
6765
|
// src/commands/bucket/key/index.ts
|
|
6385
|
-
var
|
|
6766
|
+
var keyCommand2 = new Command76("key").aliases(["keys"]).description("access keys of a bucket: what your app signs in with").addCommand(createCommand7).addCommand(lsCommand11).addCommand(rmCommand9);
|
|
6386
6767
|
|
|
6387
6768
|
// src/commands/bucket/ls.ts
|
|
6388
|
-
import { Command as
|
|
6389
|
-
var
|
|
6769
|
+
import { Command as Command77 } from "commander";
|
|
6770
|
+
var lsCommand12 = new Command77("ls").alias("list").description("list buckets, and the object storage they are in").option("-a, --all", "every bucket on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
6390
6771
|
const client = await bucketClient(cmd);
|
|
6391
6772
|
try {
|
|
6392
6773
|
const buckets = await client.listBuckets({ all: opts.all });
|
|
@@ -6416,8 +6797,8 @@ var lsCommand11 = new Command73("ls").alias("list").description("list buckets, a
|
|
|
6416
6797
|
});
|
|
6417
6798
|
|
|
6418
6799
|
// src/commands/bucket/rm.ts
|
|
6419
|
-
import { Command as
|
|
6420
|
-
var
|
|
6800
|
+
import { Command as Command78 } from "commander";
|
|
6801
|
+
var rmCommand10 = new Command78("rm").alias("remove").description("delete an empty bucket and its keys (the last one takes your object storage with it)").argument("<name>", "bucket name").option("--force", "your last bucket only: delete it with everything in it").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
|
|
6421
6802
|
const client = await bucketClient(cmd);
|
|
6422
6803
|
try {
|
|
6423
6804
|
const question = opts.force ? `Delete bucket ${name} with everything in it, and the object storage it is in?` : `Delete bucket ${name} and its keys?`;
|
|
@@ -6436,18 +6817,18 @@ var rmCommand9 = new Command74("rm").alias("remove").description("delete an empt
|
|
|
6436
6817
|
});
|
|
6437
6818
|
|
|
6438
6819
|
// src/commands/bucket/index.ts
|
|
6439
|
-
var bucketCommand = new
|
|
6820
|
+
var bucketCommand = new Command79("bucket").aliases(["buckets"]).description("object storage: S3 buckets for your files, and the access keys your apps use").addCommand(createCommand6).addCommand(lsCommand12).addCommand(infoCommand).addCommand(growCommand2).addCommand(rmCommand10).addCommand(keyCommand2);
|
|
6440
6821
|
var withOrg = (cmd) => cmd.option("--org <slug>", "act in this org (- for your personal buckets)");
|
|
6441
6822
|
for (const cmd of bucketCommand.commands) {
|
|
6442
|
-
if (cmd ===
|
|
6823
|
+
if (cmd === keyCommand2) cmd.commands.forEach(withOrg);
|
|
6443
6824
|
else withOrg(cmd);
|
|
6444
6825
|
}
|
|
6445
6826
|
|
|
6446
6827
|
// src/commands/cron/index.ts
|
|
6447
|
-
import { Command as
|
|
6828
|
+
import { Command as Command92 } from "commander";
|
|
6448
6829
|
|
|
6449
6830
|
// src/commands/cron/create.ts
|
|
6450
|
-
import { Command as
|
|
6831
|
+
import { Command as Command80 } from "commander";
|
|
6451
6832
|
|
|
6452
6833
|
// src/commands/cron/shared.ts
|
|
6453
6834
|
async function cronClient(cmd) {
|
|
@@ -6482,7 +6863,9 @@ function outcomeText(outcome) {
|
|
|
6482
6863
|
"box-stopped": "skipped: box stopped",
|
|
6483
6864
|
"host-down": "host unreachable",
|
|
6484
6865
|
"host-outdated": "host needs an update",
|
|
6485
|
-
lost: "lost"
|
|
6866
|
+
lost: "lost",
|
|
6867
|
+
"still-running": "skipped: still running",
|
|
6868
|
+
"box-outdated": "box image too old"
|
|
6486
6869
|
};
|
|
6487
6870
|
const text2 = words[outcome];
|
|
6488
6871
|
return outcome === "ok" ? color.green(text2) : outcome === "running" ? color.dim(text2) : color.red(text2);
|
|
@@ -6492,7 +6875,7 @@ function printTriggers(triggers) {
|
|
|
6492
6875
|
triggers.map((t) => ({
|
|
6493
6876
|
id: t.id,
|
|
6494
6877
|
schedule: scheduleText(t),
|
|
6495
|
-
|
|
6878
|
+
action: cronTarget(t),
|
|
6496
6879
|
next: t.enabled ? t.nextRunAt ? until(t.nextRunAt) : "never" : color.yellow("paused"),
|
|
6497
6880
|
"last run": t.lastRunAt && t.lastOutcome ? `${outcomeText(t.lastOutcome)} ${color.dim(age(t.lastRunAt))}` : "-"
|
|
6498
6881
|
}))
|
|
@@ -6503,10 +6886,10 @@ function printRows2(rows2) {
|
|
|
6503
6886
|
for (const [label, value] of rows2) process.stdout.write(`${color.dim(label.padEnd(width2))} ${value}
|
|
6504
6887
|
`);
|
|
6505
6888
|
}
|
|
6506
|
-
var noTriggers = (service) => info(`cron service ${service} has no triggers yet; add one with: kvbox cron trigger add ${service} <box> "0 6 * * *" --port 3000`);
|
|
6889
|
+
var noTriggers = (service) => info(`cron service ${service} has no triggers yet; add one with: kvbox cron trigger add ${service} <box> "0 6 * * *" --port 3000 (or --run "<command>")`);
|
|
6507
6890
|
|
|
6508
6891
|
// src/commands/cron/create.ts
|
|
6509
|
-
var
|
|
6892
|
+
var createCommand8 = new Command80("create").description("make a cron service: a named set of triggers").argument("<name>", "what to call it (lowercase letters, digits and '-')").option("--json", "print as JSON").action(async (name, opts, cmd) => {
|
|
6510
6893
|
const client = await cronClient(cmd);
|
|
6511
6894
|
try {
|
|
6512
6895
|
const service = await client.createCronService(name);
|
|
@@ -6523,8 +6906,8 @@ var createCommand7 = new Command76("create").description("make a cron service: a
|
|
|
6523
6906
|
});
|
|
6524
6907
|
|
|
6525
6908
|
// src/commands/cron/info.ts
|
|
6526
|
-
import { Command as
|
|
6527
|
-
var infoCommand2 = new
|
|
6909
|
+
import { Command as Command81 } from "commander";
|
|
6910
|
+
var infoCommand2 = new Command81("info").alias("get").description("show a cron service and its triggers").argument("<name>", "cron service name").option("--json", "print as JSON").action(async (name, opts, cmd) => {
|
|
6528
6911
|
const client = await cronClient(cmd);
|
|
6529
6912
|
try {
|
|
6530
6913
|
const service = await client.getCronService(name);
|
|
@@ -6548,8 +6931,8 @@ var infoCommand2 = new Command77("info").alias("get").description("show a cron s
|
|
|
6548
6931
|
});
|
|
6549
6932
|
|
|
6550
6933
|
// src/commands/cron/ls.ts
|
|
6551
|
-
import { Command as
|
|
6552
|
-
var
|
|
6934
|
+
import { Command as Command82 } from "commander";
|
|
6935
|
+
var lsCommand13 = new Command82("ls").alias("list").description("list cron services").option("-a, --all", "every cron service on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
6553
6936
|
const client = await cronClient(cmd);
|
|
6554
6937
|
try {
|
|
6555
6938
|
const services = await client.listCronServices({ all: opts.all });
|
|
@@ -6569,8 +6952,8 @@ var lsCommand12 = new Command78("ls").alias("list").description("list cron servi
|
|
|
6569
6952
|
});
|
|
6570
6953
|
|
|
6571
6954
|
// src/commands/cron/rm.ts
|
|
6572
|
-
import { Command as
|
|
6573
|
-
var
|
|
6955
|
+
import { Command as Command83 } from "commander";
|
|
6956
|
+
var rmCommand11 = new Command83("rm").alias("remove").description("delete a cron service, its triggers and their run history").argument("<name>", "cron service name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
|
|
6574
6957
|
const client = await cronClient(cmd);
|
|
6575
6958
|
try {
|
|
6576
6959
|
if (!await confirm(`Delete cron service ${name}? Its triggers stop firing and their run history is deleted.`, opts.yes ?? false)) {
|
|
@@ -6586,12 +6969,11 @@ var rmCommand10 = new Command79("rm").alias("remove").description("delete a cron
|
|
|
6586
6969
|
});
|
|
6587
6970
|
|
|
6588
6971
|
// src/commands/cron/trigger/index.ts
|
|
6589
|
-
import { Command as
|
|
6972
|
+
import { Command as Command91 } from "commander";
|
|
6590
6973
|
|
|
6591
6974
|
// src/commands/cron/trigger/add.ts
|
|
6592
|
-
import { Command as
|
|
6975
|
+
import { Command as Command84 } from "commander";
|
|
6593
6976
|
function portOf(value) {
|
|
6594
|
-
if (value === void 0) throw new KvboxError("say which port your app listens on in the box: --port 3000");
|
|
6595
6977
|
const n = Number(value);
|
|
6596
6978
|
if (!Number.isInteger(n) || n < 1 || n > 65535) throw new KvboxError(`--port ${value}: a port is a number from 1 to 65535`);
|
|
6597
6979
|
return n;
|
|
@@ -6601,17 +6983,35 @@ function methodOf(value) {
|
|
|
6601
6983
|
if (!CRON_METHODS.includes(method)) throw new KvboxError(`--method ${value}: a trigger sends ${CRON_METHODS.join(" or ")}`);
|
|
6602
6984
|
return method;
|
|
6603
6985
|
}
|
|
6604
|
-
|
|
6605
|
-
const
|
|
6606
|
-
const
|
|
6986
|
+
function timeoutOf(value) {
|
|
6987
|
+
const t = value.trim().toLowerCase();
|
|
6988
|
+
const units = { s: 1, m: 60, h: 3600 };
|
|
6989
|
+
let sec = 0;
|
|
6990
|
+
for (const [, n, unit] of t.matchAll(/(\d+)([smh])/g)) sec += Number(n) * units[unit];
|
|
6991
|
+
if (!/^(\d+[smh])+$/.test(t) || sec < 1) throw new KvboxError(`--timeout ${value}: give a duration like 90s, 10m or 1h`);
|
|
6992
|
+
if (sec > MAX_CRON_COMMAND_TIMEOUT_SEC) throw new KvboxError(`--timeout ${value}: a command may run for ${MAX_CRON_COMMAND_TIMEOUT_SEC / 60} minutes at most`);
|
|
6993
|
+
return sec;
|
|
6994
|
+
}
|
|
6995
|
+
var addCommand3 = new Command84("add").description("add a trigger: on a schedule, call a port of a box or run a command in it").argument("<service>", "cron service name").argument("<box>", "the box it acts on").argument("<expr>", 'cron expression in quotes, five fields: "0 6 * * *" is every day at 06:00').option("--port <n>", "call this port, the one your app listens on in the box").option("--path <path>", "with --port: path and query to request (default: /)").option("--method <method>", `with --port: HTTP method, ${CRON_METHODS.join(" or ")} (default: POST)`).option("--run <command>", 'or run this command in the box, in quotes: "node ~/app/embed.js"').option("--timeout <duration>", `with --run: stop the command after this long (90s, 10m, 1h; default: ${DEFAULT_CRON_COMMAND_TIMEOUT_SEC / 60}m)`).option("--tz <zone>", "time zone the schedule is read in, like Europe/Bucharest", "UTC").option("--json", "print as JSON").action(async (service, box, expr, opts, cmd) => {
|
|
6996
|
+
let action;
|
|
6997
|
+
if (opts.run !== void 0) {
|
|
6998
|
+
if (opts.port !== void 0 || opts.path !== void 0 || opts.method !== void 0) throw new KvboxError("a trigger runs a command or calls a port: use --run, or --port with --path and --method, not both");
|
|
6999
|
+
if (opts.run.trim() === "") throw new KvboxError('--run needs the command, in quotes: --run "node ~/app/embed.js"');
|
|
7000
|
+
action = { command: opts.run, ...opts.timeout === void 0 ? {} : { timeoutSec: timeoutOf(opts.timeout) } };
|
|
7001
|
+
} else {
|
|
7002
|
+
if (opts.timeout !== void 0) throw new KvboxError("--timeout is for --run; a request to a port has a fixed time to answer");
|
|
7003
|
+
if (opts.port === void 0) throw new KvboxError('say what the trigger does: --port 3000 to call your app in the box, or --run "<command>" to run a command in it');
|
|
7004
|
+
action = { port: portOf(opts.port), method: methodOf(opts.method ?? "POST"), path: opts.path ?? "/" };
|
|
7005
|
+
}
|
|
6607
7006
|
const client = await cronClient(cmd);
|
|
6608
7007
|
try {
|
|
6609
|
-
const trigger = await client.addCronTrigger(service, { box, expr, timezone: opts.tz,
|
|
7008
|
+
const trigger = await client.addCronTrigger(service, { box, expr, timezone: opts.tz, ...action });
|
|
6610
7009
|
if (opts.json) {
|
|
6611
7010
|
json(trigger);
|
|
6612
7011
|
return;
|
|
6613
7012
|
}
|
|
6614
7013
|
info(`${color.green("\u2713")} trigger ${color.bold(trigger.id)} added: ${cronTarget(trigger)} on ${scheduleText(trigger)}`);
|
|
7014
|
+
if (trigger.kind === "command") info(color.dim(`Stopped after ${trigger.timeoutSec % 60 === 0 ? `${trigger.timeoutSec / 60} min` : `${trigger.timeoutSec} s`} if still going. What it prints stays in the box: ${CRON_RUN_LOG_DIR}/`));
|
|
6615
7015
|
if (trigger.nextRunAt) info(color.dim(`First run ${until(trigger.nextRunAt)}. Try it now: kvbox cron trigger run ${refFor(service, client)} ${trigger.id}`));
|
|
6616
7016
|
} finally {
|
|
6617
7017
|
await client.close();
|
|
@@ -6619,8 +7019,8 @@ var addCommand3 = new Command80("add").description("add a trigger: on a schedule
|
|
|
6619
7019
|
});
|
|
6620
7020
|
|
|
6621
7021
|
// src/commands/cron/trigger/ls.ts
|
|
6622
|
-
import { Command as
|
|
6623
|
-
var
|
|
7022
|
+
import { Command as Command85 } from "commander";
|
|
7023
|
+
var lsCommand14 = new Command85("ls").alias("list").description("list a cron service's triggers").argument("<service>", "cron service name").option("--json", "print as JSON").action(async (service, opts, cmd) => {
|
|
6624
7024
|
const client = await cronClient(cmd);
|
|
6625
7025
|
try {
|
|
6626
7026
|
const triggers = await client.listCronTriggers(service);
|
|
@@ -6636,8 +7036,8 @@ var lsCommand13 = new Command81("ls").alias("list").description("list a cron ser
|
|
|
6636
7036
|
});
|
|
6637
7037
|
|
|
6638
7038
|
// src/commands/cron/trigger/pause.ts
|
|
6639
|
-
import { Command as
|
|
6640
|
-
var pauseCommand2 = new
|
|
7039
|
+
import { Command as Command86 } from "commander";
|
|
7040
|
+
var pauseCommand2 = new Command86("pause").description("stop a trigger from firing until it is resumed").argument("<service>", "cron service name").argument("<id>", "trigger id (kvbox cron trigger ls)").option("--json", "print as JSON").action(async (service, id, opts, cmd) => {
|
|
6641
7041
|
const client = await cronClient(cmd);
|
|
6642
7042
|
try {
|
|
6643
7043
|
const trigger = await client.setCronTriggerEnabled(service, id, false);
|
|
@@ -6652,8 +7052,8 @@ var pauseCommand2 = new Command82("pause").description("stop a trigger from firi
|
|
|
6652
7052
|
});
|
|
6653
7053
|
|
|
6654
7054
|
// src/commands/cron/trigger/resume.ts
|
|
6655
|
-
import { Command as
|
|
6656
|
-
var resumeCommand2 = new
|
|
7055
|
+
import { Command as Command87 } from "commander";
|
|
7056
|
+
var resumeCommand2 = new Command87("resume").description("let a paused trigger fire again").argument("<service>", "cron service name").argument("<id>", "trigger id (kvbox cron trigger ls)").option("--json", "print as JSON").action(async (service, id, opts, cmd) => {
|
|
6657
7057
|
const client = await cronClient(cmd);
|
|
6658
7058
|
try {
|
|
6659
7059
|
const trigger = await client.setCronTriggerEnabled(service, id, true);
|
|
@@ -6668,8 +7068,8 @@ var resumeCommand2 = new Command83("resume").description("let a paused trigger f
|
|
|
6668
7068
|
});
|
|
6669
7069
|
|
|
6670
7070
|
// src/commands/cron/trigger/rm.ts
|
|
6671
|
-
import { Command as
|
|
6672
|
-
var
|
|
7071
|
+
import { Command as Command88 } from "commander";
|
|
7072
|
+
var rmCommand12 = new Command88("rm").alias("remove").description("delete a trigger and its run history").argument("<service>", "cron service name").argument("<id>", "trigger id (kvbox cron trigger ls)").option("-y, --yes", "do not ask for confirmation").action(async (service, id, opts, cmd) => {
|
|
6673
7073
|
const client = await cronClient(cmd);
|
|
6674
7074
|
try {
|
|
6675
7075
|
if (!await confirm(`Delete trigger ${id} of cron service ${service}? Its run history is deleted too.`, opts.yes ?? false)) {
|
|
@@ -6685,8 +7085,8 @@ var rmCommand11 = new Command84("rm").alias("remove").description("delete a trig
|
|
|
6685
7085
|
});
|
|
6686
7086
|
|
|
6687
7087
|
// src/commands/cron/trigger/run.ts
|
|
6688
|
-
import { Command as
|
|
6689
|
-
var runCommand = new
|
|
7088
|
+
import { Command as Command89 } from "commander";
|
|
7089
|
+
var runCommand = new Command89("run").description("fire a trigger now, once, besides its schedule").argument("<service>", "cron service name").argument("<id>", "trigger id (kvbox cron trigger ls)").option("--json", "print as JSON").action(async (service, id, opts, cmd) => {
|
|
6690
7090
|
const client = await cronClient(cmd);
|
|
6691
7091
|
try {
|
|
6692
7092
|
const trigger = await client.runCronTrigger(service, id);
|
|
@@ -6702,13 +7102,13 @@ var runCommand = new Command85("run").description("fire a trigger now, once, bes
|
|
|
6702
7102
|
});
|
|
6703
7103
|
|
|
6704
7104
|
// src/commands/cron/trigger/runs.ts
|
|
6705
|
-
import { Command as
|
|
7105
|
+
import { Command as Command90 } from "commander";
|
|
6706
7106
|
function limitOf(value) {
|
|
6707
7107
|
const n = Number(value);
|
|
6708
7108
|
if (!Number.isInteger(n) || n < 1) throw new KvboxError(`-n ${value}: a number of runs, 1 or more`);
|
|
6709
7109
|
return n;
|
|
6710
7110
|
}
|
|
6711
|
-
var runsCommand = new
|
|
7111
|
+
var runsCommand = new Command90("runs").aliases(["logs"]).description("show how a trigger's last runs ended").argument("<service>", "cron service name").argument("<id>", "trigger id (kvbox cron trigger ls)").option("-n, --limit <count>", "how many runs to show", "20").option("--json", "print as JSON").action(async (service, id, opts, cmd) => {
|
|
6712
7112
|
const limit = limitOf(opts.limit);
|
|
6713
7113
|
const client = await cronClient(cmd);
|
|
6714
7114
|
try {
|
|
@@ -6725,21 +7125,23 @@ var runsCommand = new Command86("runs").aliases(["logs"]).description("show how
|
|
|
6725
7125
|
runs.map((r) => ({
|
|
6726
7126
|
when: age(r.startedAt),
|
|
6727
7127
|
result: outcomeText(r.outcome),
|
|
6728
|
-
status: r.status ?? "-",
|
|
7128
|
+
status: r.status ?? (r.exitCode === null ? "-" : `exit ${r.exitCode}`),
|
|
6729
7129
|
took: r.durationMs === null ? "-" : r.durationMs < 1e3 ? `${r.durationMs} ms` : `${(r.durationMs / 1e3).toFixed(1)} s`,
|
|
6730
7130
|
note: [r.woke ? "woke the box" : "", r.error ?? ""].filter(Boolean).join("; ") || color.dim("-")
|
|
6731
7131
|
}))
|
|
6732
7132
|
);
|
|
7133
|
+
const last = runs.find((r) => r.output !== null);
|
|
7134
|
+
if (last) info(color.dim(`A command's output stays in the box, one file per run; the newest: kvbox exec <box> -- cat ${last.output}`));
|
|
6733
7135
|
} finally {
|
|
6734
7136
|
await client.close();
|
|
6735
7137
|
}
|
|
6736
7138
|
});
|
|
6737
7139
|
|
|
6738
7140
|
// src/commands/cron/trigger/index.ts
|
|
6739
|
-
var triggerCommand = new
|
|
7141
|
+
var triggerCommand = new Command91("trigger").aliases(["triggers"]).description("a cron service's triggers: a schedule and the request it sends to a box").addCommand(addCommand3).addCommand(lsCommand14).addCommand(runsCommand).addCommand(runCommand).addCommand(pauseCommand2).addCommand(resumeCommand2).addCommand(rmCommand12);
|
|
6740
7142
|
|
|
6741
7143
|
// src/commands/cron/index.ts
|
|
6742
|
-
var cronCommand = new
|
|
7144
|
+
var cronCommand = new Command92("cron").description("cron: call a box on a schedule, waking it first if it sleeps").addCommand(createCommand8).addCommand(lsCommand13).addCommand(infoCommand2).addCommand(rmCommand11).addCommand(triggerCommand);
|
|
6743
7145
|
var withOrg2 = (cmd) => cmd.option("--org <slug>", "act in this org (- for your personal cron services)");
|
|
6744
7146
|
for (const cmd of cronCommand.commands) {
|
|
6745
7147
|
if (cmd === triggerCommand) cmd.commands.forEach(withOrg2);
|
|
@@ -6747,11 +7149,11 @@ for (const cmd of cronCommand.commands) {
|
|
|
6747
7149
|
}
|
|
6748
7150
|
|
|
6749
7151
|
// src/commands/managed/kind.ts
|
|
6750
|
-
import { Command as
|
|
7152
|
+
import { Command as Command105 } from "commander";
|
|
6751
7153
|
|
|
6752
7154
|
// src/commands/managed/create.ts
|
|
6753
|
-
import { Command as
|
|
6754
|
-
import { setTimeout as
|
|
7155
|
+
import { Command as Command94 } from "commander";
|
|
7156
|
+
import { setTimeout as sleep4 } from "timers/promises";
|
|
6755
7157
|
|
|
6756
7158
|
// src/commands/managed/shared.ts
|
|
6757
7159
|
import "commander";
|
|
@@ -6836,8 +7238,8 @@ function parseStorage(text2, flag) {
|
|
|
6836
7238
|
// src/commands/managed/create.ts
|
|
6837
7239
|
var READY_WAIT_MS = 9e4;
|
|
6838
7240
|
var READY_STEP_MS = 2e3;
|
|
6839
|
-
var
|
|
6840
|
-
const command = new
|
|
7241
|
+
var createCommand9 = (spec) => {
|
|
7242
|
+
const command = new Command94("create").alias("new").description(`create a ${spec.title} database: a name is all it needs`).argument("<name>", "its name (1-12 chars, lowercase letters, digits and '-'); a linked box reaches it at <name>.<account>.kvbox");
|
|
6841
7243
|
for (const o of spec.options) command.option(`--${o.name} <${o.arg}>`, o.help);
|
|
6842
7244
|
return command.option("--password <password>", "its password (default: generated)").option("--storage <gb>", `storage for the data in GB (default: ${spec.storageGib}; it can grow later)`).option("--near <box>", "run it on the host of this box, so the box can be linked to it").option("--json", "print it as JSON, password included").action(async (name, opts, cmd) => {
|
|
6843
7245
|
const options = Object.fromEntries(spec.options.flatMap((o) => typeof opts[o.name] === "string" ? [[o.name, opts[o.name]]] : []));
|
|
@@ -6853,7 +7255,7 @@ var createCommand8 = (spec) => {
|
|
|
6853
7255
|
const made = await spin(`creating ${spec.title} database ${name}\u2026`, client.createManaged(spec.kind, req));
|
|
6854
7256
|
const shown = shownName3(made, me(client));
|
|
6855
7257
|
const ready = await spin(`starting ${spec.title}\u2026`, async () => {
|
|
6856
|
-
for (const until2 = Date.now() + READY_WAIT_MS; Date.now() < until2; await
|
|
7258
|
+
for (const until2 = Date.now() + READY_WAIT_MS; Date.now() < until2; await sleep4(READY_STEP_MS)) {
|
|
6857
7259
|
const now = await client.getManaged(spec.kind, shown).catch(() => void 0);
|
|
6858
7260
|
if (now?.health?.ready && now.health.accepting) return true;
|
|
6859
7261
|
}
|
|
@@ -6878,8 +7280,8 @@ var createCommand8 = (spec) => {
|
|
|
6878
7280
|
};
|
|
6879
7281
|
|
|
6880
7282
|
// src/commands/managed/grow.ts
|
|
6881
|
-
import { Command as
|
|
6882
|
-
var growCommand3 = (spec) => new
|
|
7283
|
+
import { Command as Command95 } from "commander";
|
|
7284
|
+
var growCommand3 = (spec) => new Command95("grow").description("give a database more storage (it restarts once)").argument("<db>", "its name").argument("<GB>", "the new size in GB, larger than what it has").option("--json", "print as JSON").action(async (name, size, opts, cmd) => {
|
|
6883
7285
|
const storageGib = parseStorage(size, "size");
|
|
6884
7286
|
const client = await managedClient(cmd);
|
|
6885
7287
|
try {
|
|
@@ -6892,8 +7294,8 @@ var growCommand3 = (spec) => new Command91("grow").description("give a database
|
|
|
6892
7294
|
});
|
|
6893
7295
|
|
|
6894
7296
|
// src/commands/managed/info.ts
|
|
6895
|
-
import { Command as
|
|
6896
|
-
var infoCommand3 = (spec) => new
|
|
7297
|
+
import { Command as Command96 } from "commander";
|
|
7298
|
+
var infoCommand3 = (spec) => new Command96("info").alias("get").description("show one database: status, storage used, how to connect").argument("<db>", "its name").option("--json", "print as JSON").action(async (name, opts, cmd) => {
|
|
6897
7299
|
const client = await managedClient(cmd);
|
|
6898
7300
|
try {
|
|
6899
7301
|
const m = await client.getManaged(spec.kind, name);
|
|
@@ -6905,8 +7307,8 @@ var infoCommand3 = (spec) => new Command92("info").alias("get").description("sho
|
|
|
6905
7307
|
});
|
|
6906
7308
|
|
|
6907
7309
|
// src/commands/managed/link.ts
|
|
6908
|
-
import { Command as
|
|
6909
|
-
var linkCommand2 = (spec) => new
|
|
7310
|
+
import { Command as Command97 } from "commander";
|
|
7311
|
+
var linkCommand2 = (spec) => new Command97("link").description("let a box reach a database privately (same host)").argument("<db>", "the database").argument("<box>", "the box that connects to it").option("--json", "print as JSON").action(async (name, box, opts, cmd) => {
|
|
6910
7312
|
const client = await managedClient(cmd);
|
|
6911
7313
|
try {
|
|
6912
7314
|
const m = await spin(`linking ${box} to ${name}\u2026`, client.linkManaged(spec.kind, name, box));
|
|
@@ -6922,7 +7324,7 @@ var linkCommand2 = (spec) => new Command93("link").description("let a box reach
|
|
|
6922
7324
|
});
|
|
6923
7325
|
|
|
6924
7326
|
// src/commands/managed/ls.ts
|
|
6925
|
-
import { Command as
|
|
7327
|
+
import { Command as Command98 } from "commander";
|
|
6926
7328
|
function listRows(items, user, kindColumn) {
|
|
6927
7329
|
return items.map((m) => ({
|
|
6928
7330
|
owner: m.owner === user ? "private" : m.owner,
|
|
@@ -6936,7 +7338,7 @@ function listRows(items, user, kindColumn) {
|
|
|
6936
7338
|
created: age(m.createdAt)
|
|
6937
7339
|
}));
|
|
6938
7340
|
}
|
|
6939
|
-
var
|
|
7341
|
+
var lsCommand15 = (spec) => new Command98("ls").alias("list").description(spec ? `list your ${spec.title} databases` : "list every managed database, whatever its kind").option("-a, --all", "every one on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
6940
7342
|
const client = await managedClient(cmd);
|
|
6941
7343
|
try {
|
|
6942
7344
|
const items = await client.listManaged(spec?.kind, { all: opts.all });
|
|
@@ -6956,8 +7358,8 @@ var lsCommand14 = (spec) => new Command94("ls").alias("list").description(spec ?
|
|
|
6956
7358
|
});
|
|
6957
7359
|
|
|
6958
7360
|
// src/commands/managed/password.ts
|
|
6959
|
-
import { Command as
|
|
6960
|
-
var passwordCommand = (spec) => new
|
|
7361
|
+
import { Command as Command99 } from "commander";
|
|
7362
|
+
var passwordCommand = (spec) => new Command99("password").description("show a database's password, or set a new one with --reset").argument("<db>", "its name").option("--reset", "make a new password; the old one stops working").option("--json", "print as JSON").action(async (name, opts, cmd) => {
|
|
6961
7363
|
const client = await managedClient(cmd);
|
|
6962
7364
|
try {
|
|
6963
7365
|
const secret = opts.reset ? await spin(`setting a new password on ${name}\u2026`, client.resetManagedPassword(spec.kind, name)) : await client.managedPassword(spec.kind, name);
|
|
@@ -6973,8 +7375,8 @@ var passwordCommand = (spec) => new Command95("password").description("show a da
|
|
|
6973
7375
|
});
|
|
6974
7376
|
|
|
6975
7377
|
// src/commands/managed/public.ts
|
|
6976
|
-
import { Command as
|
|
6977
|
-
var publicCommand = (spec) => new
|
|
7378
|
+
import { Command as Command100 } from "commander";
|
|
7379
|
+
var publicCommand = (spec) => new Command100("public").description("open a database to the internet, or close it again").argument("<db>", "its name").argument("<state>", "on: reachable from anywhere with the password; off: only linked boxes").option("--json", "print as JSON").action(async (name, state, opts, cmd) => {
|
|
6978
7380
|
if (state !== "on" && state !== "off") throw new KvboxError(`write on or off: kvbox ${spec.command} public ${name} on`);
|
|
6979
7381
|
const client = await managedClient(cmd);
|
|
6980
7382
|
try {
|
|
@@ -6995,8 +7397,8 @@ var publicCommand = (spec) => new Command96("public").description("open a databa
|
|
|
6995
7397
|
});
|
|
6996
7398
|
|
|
6997
7399
|
// src/commands/managed/rm.ts
|
|
6998
|
-
import { Command as
|
|
6999
|
-
var
|
|
7400
|
+
import { Command as Command101 } from "commander";
|
|
7401
|
+
var rmCommand13 = (spec) => new Command101("rm").alias("remove").description("delete a database and all its data").argument("<db>", "its name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
|
|
7000
7402
|
const client = await managedClient(cmd);
|
|
7001
7403
|
try {
|
|
7002
7404
|
if (!await confirm(`Delete database ${name} and all its data? There is no backup.`, opts.yes ?? false)) {
|
|
@@ -7012,8 +7414,8 @@ var rmCommand12 = (spec) => new Command97("rm").alias("remove").description("del
|
|
|
7012
7414
|
});
|
|
7013
7415
|
|
|
7014
7416
|
// src/commands/managed/start.ts
|
|
7015
|
-
import { Command as
|
|
7016
|
-
var startCommand2 = (spec) => new
|
|
7417
|
+
import { Command as Command102 } from "commander";
|
|
7418
|
+
var startCommand2 = (spec) => new Command102("start").description("run a stopped database again").argument("<db>", "its name").option("--json", "print as JSON").action(async (name, opts, cmd) => {
|
|
7017
7419
|
const client = await managedClient(cmd);
|
|
7018
7420
|
try {
|
|
7019
7421
|
const m = await spin(`starting ${name}\u2026`, client.startManaged(spec.kind, name));
|
|
@@ -7025,8 +7427,8 @@ var startCommand2 = (spec) => new Command98("start").description("run a stopped
|
|
|
7025
7427
|
});
|
|
7026
7428
|
|
|
7027
7429
|
// src/commands/managed/stop.ts
|
|
7028
|
-
import { Command as
|
|
7029
|
-
var stopCommand2 = (spec) => new
|
|
7430
|
+
import { Command as Command103 } from "commander";
|
|
7431
|
+
var stopCommand2 = (spec) => new Command103("stop").description("shut a database down, keeping its data (only its storage is charged)").argument("<db>", "its name").option("--json", "print as JSON").action(async (name, opts, cmd) => {
|
|
7030
7432
|
const client = await managedClient(cmd);
|
|
7031
7433
|
try {
|
|
7032
7434
|
const m = await spin(`stopping ${name}\u2026`, client.stopManaged(spec.kind, name));
|
|
@@ -7038,8 +7440,8 @@ var stopCommand2 = (spec) => new Command99("stop").description("shut a database
|
|
|
7038
7440
|
});
|
|
7039
7441
|
|
|
7040
7442
|
// src/commands/managed/unlink.ts
|
|
7041
|
-
import { Command as
|
|
7042
|
-
var unlinkCommand2 = (spec) => new
|
|
7443
|
+
import { Command as Command104 } from "commander";
|
|
7444
|
+
var unlinkCommand2 = (spec) => new Command104("unlink").description("stop a box from reaching a database").argument("<db>", "the database").argument("<box>", "the box that was linked to it").option("--json", "print as JSON").action(async (name, box, opts, cmd) => {
|
|
7043
7445
|
const client = await managedClient(cmd);
|
|
7044
7446
|
try {
|
|
7045
7447
|
const m = await spin(`unlinking ${box} from ${name}\u2026`, client.unlinkManaged(spec.kind, name, box));
|
|
@@ -7052,8 +7454,8 @@ var unlinkCommand2 = (spec) => new Command100("unlink").description("stop a box
|
|
|
7052
7454
|
|
|
7053
7455
|
// src/commands/managed/kind.ts
|
|
7054
7456
|
function kindCommand(spec, description) {
|
|
7055
|
-
const command = new
|
|
7056
|
-
for (const make of [
|
|
7457
|
+
const command = new Command105(spec.command).aliases(spec.aliases).description(description);
|
|
7458
|
+
for (const make of [createCommand9, lsCommand15, infoCommand3, passwordCommand, publicCommand, linkCommand2, unlinkCommand2, growCommand3, stopCommand2, startCommand2, rmCommand13]) {
|
|
7057
7459
|
command.addCommand(make(spec).option("--org <slug>", "act in this org (- for your personal databases)"));
|
|
7058
7460
|
}
|
|
7059
7461
|
return command;
|
|
@@ -7066,14 +7468,14 @@ var pgCommand = kindCommand(POSTGRES2, "managed PostgreSQL: a database kvbox run
|
|
|
7066
7468
|
var redisCommand = kindCommand(REDIS, "managed Redis (Valkey): a Redis kvbox runs for you, private until you link a box or make it public");
|
|
7067
7469
|
|
|
7068
7470
|
// src/commands/managed/index.ts
|
|
7069
|
-
import { Command as
|
|
7070
|
-
var managedCommand = new
|
|
7471
|
+
import { Command as Command106 } from "commander";
|
|
7472
|
+
var managedCommand = new Command106("managed").description(`databases kvbox runs for you, every kind together (${KINDS.map((k) => `${k.title}: kvbox ${k.command}`).join(", ")})`).addCommand(lsCommand15().option("--org <slug>", "act in this org (- for your personal databases)"));
|
|
7071
7473
|
|
|
7072
7474
|
// src/commands/env/index.ts
|
|
7073
|
-
import { Command as
|
|
7475
|
+
import { Command as Command110 } from "commander";
|
|
7074
7476
|
|
|
7075
7477
|
// src/commands/env/ls.ts
|
|
7076
|
-
import { Command as
|
|
7478
|
+
import { Command as Command107 } from "commander";
|
|
7077
7479
|
|
|
7078
7480
|
// src/commands/env/shared.ts
|
|
7079
7481
|
function requireCloud4(client) {
|
|
@@ -7100,7 +7502,7 @@ function firstBootHint(box, name) {
|
|
|
7100
7502
|
}
|
|
7101
7503
|
|
|
7102
7504
|
// src/commands/env/ls.ts
|
|
7103
|
-
var
|
|
7505
|
+
var lsCommand16 = new Command107("ls").alias("list").description("list the variables (a secret shows as (sealed))").option("--box <box>", "what this box gets: its own variables and the ones it inherits").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
7104
7506
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
7105
7507
|
try {
|
|
7106
7508
|
if (opts.box !== void 0) {
|
|
@@ -7139,8 +7541,8 @@ var lsCommand15 = new Command103("ls").alias("list").description("list the varia
|
|
|
7139
7541
|
});
|
|
7140
7542
|
|
|
7141
7543
|
// src/commands/env/rm.ts
|
|
7142
|
-
import { Command as
|
|
7143
|
-
var
|
|
7544
|
+
import { Command as Command108 } from "commander";
|
|
7545
|
+
var rmCommand14 = new Command108("rm").alias("remove").description("remove variables; boxes lose them when they next start").argument("<names...>", "variable names").option("-y, --yes", "do not ask for confirmation").option("--box <box>", "remove this box's own variables (yours, or the org's, of the same name come back)").option("--json", "print as JSON").action(async (names2, opts, cmd) => {
|
|
7144
7546
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
7145
7547
|
try {
|
|
7146
7548
|
const target = opts.box === void 0 ? void 0 : await findBox2(client, opts.box);
|
|
@@ -7177,8 +7579,8 @@ var rmCommand13 = new Command104("rm").alias("remove").description("remove varia
|
|
|
7177
7579
|
});
|
|
7178
7580
|
|
|
7179
7581
|
// src/commands/env/set.ts
|
|
7180
|
-
import { Command as
|
|
7181
|
-
var setCommand2 = new
|
|
7582
|
+
import { Command as Command109 } from "commander";
|
|
7583
|
+
var setCommand2 = new Command109("set").description("add or change a variable; boxes get it when they next start").argument("[name]", "variable name, e.g. DATABASE_URL (asked for when left out)").argument("[value]", "its value (asked for when left out; hidden with --secret)").option("--secret", "write-only: the value is never shown again, by any command").option("--box <box>", "this box's own variable, over yours (or the org's) of the same name").option("--json", "print as JSON").action(async (nameArg, valueArg, opts, cmd) => {
|
|
7182
7584
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
7183
7585
|
try {
|
|
7184
7586
|
const owner = opts.box === void 0 ? requireCloud4(client) : void 0;
|
|
@@ -7215,14 +7617,14 @@ var setCommand2 = new Command105("set").description("add or change a variable; b
|
|
|
7215
7617
|
});
|
|
7216
7618
|
|
|
7217
7619
|
// src/commands/env/index.ts
|
|
7218
|
-
var envCommand = new
|
|
7620
|
+
var envCommand = new Command110("env").description("environment variables every box of yours gets when it starts (secrets too)").addCommand(lsCommand16, { isDefault: true }).addCommand(setCommand2).addCommand(rmCommand14);
|
|
7219
7621
|
for (const cmd of envCommand.commands) cmd.option("--org <slug>", "the org's variables instead of yours");
|
|
7220
7622
|
|
|
7221
7623
|
// src/commands/domain/index.ts
|
|
7222
|
-
import { Command as
|
|
7624
|
+
import { Command as Command114 } from "commander";
|
|
7223
7625
|
|
|
7224
7626
|
// src/commands/domain/add.ts
|
|
7225
|
-
import { Command as
|
|
7627
|
+
import { Command as Command111 } from "commander";
|
|
7226
7628
|
|
|
7227
7629
|
// src/commands/domain/shared.ts
|
|
7228
7630
|
function requireCloud5(client) {
|
|
@@ -7242,7 +7644,7 @@ function hostIn(name, zone) {
|
|
|
7242
7644
|
}
|
|
7243
7645
|
|
|
7244
7646
|
// src/commands/domain/add.ts
|
|
7245
|
-
var addCommand4 = new
|
|
7647
|
+
var addCommand4 = new Command111("add").description("serve a box at a domain of your own, https://<domain>, with its certificate made for you").argument("<domain>", "a domain you control, like example.com or app.example.com").argument("<box>", "box name").option("--port <port>", "the box port the domain serves (default: the port of its kvbox.app address)").option("--json", "print the domain as JSON").action(async (domainArg, name, opts, cmd) => {
|
|
7246
7648
|
const domain = assertDomain(domainArg.trim().toLowerCase());
|
|
7247
7649
|
const port = opts.port === void 0 ? void 0 : parsePorts([opts.port])[0];
|
|
7248
7650
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
@@ -7278,8 +7680,8 @@ kvbox checks every minute; ${domain} is served at ${d.url} once its records are
|
|
|
7278
7680
|
});
|
|
7279
7681
|
|
|
7280
7682
|
// src/commands/domain/ls.ts
|
|
7281
|
-
import { Command as
|
|
7282
|
-
var
|
|
7683
|
+
import { Command as Command112 } from "commander";
|
|
7684
|
+
var lsCommand17 = new Command112("ls").alias("list").description("list your custom domains and whether they are live").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
7283
7685
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
7284
7686
|
try {
|
|
7285
7687
|
requireCloud5(client);
|
|
@@ -7308,8 +7710,8 @@ var lsCommand16 = new Command108("ls").alias("list").description("list your cust
|
|
|
7308
7710
|
});
|
|
7309
7711
|
|
|
7310
7712
|
// src/commands/domain/rm.ts
|
|
7311
|
-
import { Command as
|
|
7312
|
-
var
|
|
7713
|
+
import { Command as Command113 } from "commander";
|
|
7714
|
+
var rmCommand15 = new Command113("rm").alias("remove").description("stop serving a box at a custom domain").argument("<domain>", "the domain").option("-y, --yes", "do not ask for confirmation").action(async (domainArg, opts, cmd) => {
|
|
7313
7715
|
const domain = domainArg.trim().toLowerCase();
|
|
7314
7716
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
7315
7717
|
try {
|
|
@@ -7330,15 +7732,15 @@ var rmCommand14 = new Command109("rm").alias("remove").description("stop serving
|
|
|
7330
7732
|
});
|
|
7331
7733
|
|
|
7332
7734
|
// src/commands/domain/index.ts
|
|
7333
|
-
var domainCommand = new
|
|
7735
|
+
var domainCommand = new Command114("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand4).addCommand(lsCommand17).addCommand(rmCommand15);
|
|
7334
7736
|
for (const cmd of domainCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
|
|
7335
7737
|
|
|
7336
7738
|
// src/commands/update.ts
|
|
7337
|
-
import { spawn as
|
|
7739
|
+
import { spawn as spawn7 } from "child_process";
|
|
7338
7740
|
import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
7339
7741
|
import { tmpdir } from "os";
|
|
7340
7742
|
import { join as join9 } from "path";
|
|
7341
|
-
import { Command as
|
|
7743
|
+
import { Command as Command115 } from "commander";
|
|
7342
7744
|
|
|
7343
7745
|
// src/update.ts
|
|
7344
7746
|
import { mkdirSync, readFileSync as readFileSync3, writeFileSync } from "fs";
|
|
@@ -7452,12 +7854,12 @@ async function download(url) {
|
|
|
7452
7854
|
}
|
|
7453
7855
|
function run2(cmd, args) {
|
|
7454
7856
|
return new Promise((resolve4, reject) => {
|
|
7455
|
-
const child =
|
|
7857
|
+
const child = spawn7(cmd, args, { stdio: "inherit" });
|
|
7456
7858
|
child.on("error", (err) => reject(new KvboxError(`could not run ${cmd}: ${err.message}`)));
|
|
7457
7859
|
child.on("exit", (code, signal) => resolve4(code ?? (signal ? 1 : 0)));
|
|
7458
7860
|
});
|
|
7459
7861
|
}
|
|
7460
|
-
var selfUpdateCommand = new
|
|
7862
|
+
var selfUpdateCommand = new Command115("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
|
|
7461
7863
|
suppressUpdateNotice();
|
|
7462
7864
|
const inst = installerFor(process.platform, process.env["KVBOX_INSTALL_URL"] || INSTALL_BASE);
|
|
7463
7865
|
let code;
|
|
@@ -7536,6 +7938,7 @@ var HELP_GROUPS = [
|
|
|
7536
7938
|
["login", "log in to the kvbox cloud or your own control plane"],
|
|
7537
7939
|
["logout", "log out; commands target this machine again"],
|
|
7538
7940
|
["whoami", "show the account and control plane in use"],
|
|
7941
|
+
["key", "API keys for programs: CI, agents, the SDK"],
|
|
7539
7942
|
["org", "shared slugs that own boxes, with owners, admins and members"],
|
|
7540
7943
|
["usage", "what your boxes and volumes used, and what it cost"],
|
|
7541
7944
|
["credit", "the prepaid credit left on your account and orgs"],
|
|
@@ -7583,7 +7986,7 @@ function installRootHelp(program) {
|
|
|
7583
7986
|
|
|
7584
7987
|
// src/program.ts
|
|
7585
7988
|
function buildProgram() {
|
|
7586
|
-
const program = new
|
|
7989
|
+
const program = new Command116("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login and KVBOX_TOKEN").option("--org <slug>", "the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it").showHelpAfterError().enablePositionalOptions();
|
|
7587
7990
|
program.addCommand(vmCommand);
|
|
7588
7991
|
program.addCommand(snapshotsCommand);
|
|
7589
7992
|
program.addCommand(volumeCommand);
|
|
@@ -7597,6 +8000,7 @@ function buildProgram() {
|
|
|
7597
8000
|
program.addCommand(loginCommand);
|
|
7598
8001
|
program.addCommand(logoutCommand);
|
|
7599
8002
|
program.addCommand(whoamiCommand);
|
|
8003
|
+
program.addCommand(keyCommand);
|
|
7600
8004
|
program.addCommand(orgCommand);
|
|
7601
8005
|
program.addCommand(usageCommand2);
|
|
7602
8006
|
program.addCommand(creditCommand);
|