@kvbox/cli 0.6.3 → 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 CHANGED
@@ -149,7 +149,7 @@ async function spin(message, work, opts = {}) {
149
149
  }
150
150
 
151
151
  // src/program.ts
152
- import { Command as Command112 } from "commander";
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.3" : void 0);
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 spawnSync2 } from "child_process";
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 { readFile as readFile2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
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 as z2 } from "zod";
343
+ import { z } from "zod";
444
344
 
445
345
  // ../shared/src/sizes.ts
446
346
  var SIZES = {
@@ -460,923 +360,1151 @@ function parseMib(text2) {
460
360
  }
461
361
 
462
362
  // ../shared/src/api.ts
463
- var SizeSchema = z2.enum(SIZE_NAMES);
363
+ var SizeSchema = z.enum(SIZE_NAMES);
464
364
  var BOX_SSH_USER = "kvbox";
465
- var BoxStatusSchema = z2.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
466
- var PortProtoSchema = z2.enum(["tcp", "udp"]);
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 = z2.object({
469
- guestPort: z2.number().int().min(1).max(65535),
470
- hostPort: z2.number().int(),
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: z2.string().optional(),
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: z2.literal(true).optional()
378
+ closed: z.literal(true).optional()
479
379
  });
480
- var PortsRequest = z2.object({
481
- ports: z2.array(z2.object({ guestPort: z2.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_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: z2.boolean().optional()
484
- });
485
- var BoxPortSchema = z2.number().int().min(1).max(65535);
486
- var BoxLinkSchema = z2.object({ from: z2.string(), port: BoxPortSchema });
487
- var LinkRequest = z2.object({ from: z2.string().min(1), fromOwner: z2.string().optional(), port: BoxPortSchema });
488
- var ClaimSubdomainRequest = z2.object({ name: z2.string(), port: BoxPortSchema });
489
- var SubdomainPortRequest = z2.object({ port: BoxPortSchema });
490
- var SubdomainRouteRequest = z2.object({ name: z2.string(), port: BoxPortSchema });
491
- var SubdomainSchema = z2.object({
492
- owner: z2.string(),
493
- box: z2.string(),
494
- subdomain: z2.string(),
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: z2.string(),
497
- routes: z2.array(z2.object({ name: z2.string(), port: BoxPortSchema, url: z2.string() }))
396
+ url: z.string(),
397
+ routes: z.array(z.object({ name: z.string(), port: BoxPortSchema, url: z.string() }))
498
398
  });
499
- var AddDomainRequest = z2.object({ domain: z2.string(), port: BoxPortSchema.optional() });
500
- var DomainSchema = z2.object({
501
- owner: z2.string(),
502
- box: z2.string(),
503
- domain: z2.string(),
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: z2.enum(["pending", "live"]),
506
- www: z2.boolean(),
507
- url: z2.string(),
508
- error: z2.string().nullable(),
509
- records: z2.array(z2.object({ type: z2.enum(["A", "TXT", "CNAME"]), name: z2.string(), value: z2.string() })),
510
- createdAt: z2.string()
511
- });
512
- var WakeHookSchema = z2.object({
513
- id: z2.string(),
514
- owner: z2.string(),
515
- box: z2.string(),
516
- url: z2.string(),
517
- createdBy: z2.string().nullable(),
518
- createdAt: z2.string(),
519
- lastCalledAt: z2.string().nullable()
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: z2.string() });
522
- var WakeHookCallSchema = z2.object({
523
- box: z2.string(),
524
- action: z2.enum(["wake", "resume", "none"]),
525
- reason: z2.string().optional()
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 = z2.object({
530
- id: z2.string(),
531
- owner: z2.string(),
532
- box: z2.string(),
533
- status: z2.enum(BACKUP_STATUSES),
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: z2.string().nullable(),
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: z2.string().nullable(),
538
- image: z2.string().optional(),
539
- vcpu: z2.number().int().nullable(),
540
- memMib: z2.number().int().nullable(),
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: z2.number().int().nullable(),
442
+ diskBytes: z.number().int().nullable(),
543
443
  /** What it holds: the slots that are not all zeros. */
544
- dataBytes: z2.number().int().nullable(),
444
+ dataBytes: z.number().int().nullable(),
545
445
  /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
546
- uploadedBytes: z2.number().int().nullable(),
547
- createdBy: z2.string().nullable(),
548
- createdAt: z2.string(),
549
- finishedAt: z2.string().nullable()
550
- });
551
- var HostBackupRequest = z2.object({ id: z2.string(), key: z2.string() });
552
- var HostBackupManifestSchema = z2.object({
553
- id: z2.string(),
554
- sizeBytes: z2.number().int(),
555
- chunks: z2.array(z2.string().nullable()),
556
- env: z2.string().nullable(),
557
- base: z2.string(),
558
- image: z2.string().optional(),
559
- vcpu: z2.number().int(),
560
- memMib: z2.number().int()
561
- });
562
- var HostUploadRequest = z2.object({ key: z2.string(), urls: z2.record(z2.string(), z2.string()), pin: z2.string().optional() });
563
- var HostUploadResultSchema = z2.object({ chunks: z2.number().int(), bytes: z2.number().int(), sizes: z2.record(z2.string(), z2.number().int()) });
564
- var HostRestoreRequest = z2.object({
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: z2.string(),
567
- key: z2.string(),
568
- sizeBytes: z2.number().int().positive(),
569
- base: z2.string(),
570
- image: z2.string().optional(),
571
- env: z2.string().nullable(),
572
- chunks: z2.array(z2.object({ index: z2.number().int().nonnegative(), hash: z2.string(), url: z2.string() })),
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: z2.string().optional()
474
+ pin: z.string().optional()
575
475
  });
576
- var VolumeBackupSchema = z2.object({
577
- id: z2.string(),
578
- owner: z2.string(),
579
- volume: z2.string(),
580
- status: z2.enum(BACKUP_STATUSES),
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: z2.string().nullable(),
482
+ error: z.string().nullable(),
583
483
  /** The volume's size when taken. */
584
- diskBytes: z2.number().int().nullable(),
484
+ diskBytes: z.number().int().nullable(),
585
485
  /** What it holds: the slots that are not all zeros. */
586
- dataBytes: z2.number().int().nullable(),
486
+ dataBytes: z.number().int().nullable(),
587
487
  /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
588
- uploadedBytes: z2.number().int().nullable(),
589
- createdBy: z2.string().nullable(),
590
- createdAt: z2.string(),
591
- finishedAt: z2.string().nullable()
592
- });
593
- var HostVolumeBackupManifestSchema = z2.object({ id: z2.string(), sizeBytes: z2.number().int(), chunks: z2.array(z2.string().nullable()) });
594
- var HostVolumeRestoreRequest = z2.object({
595
- id: z2.string(),
596
- key: z2.string(),
597
- sizeBytes: z2.number().int().positive(),
598
- chunks: z2.array(z2.object({ index: z2.number().int().nonnegative(), hash: z2.string(), url: z2.string() })),
599
- pin: z2.string().optional()
600
- });
601
- var BackupStoreSetupRequest = z2.object({ path: z2.string().min(1), force: z2.boolean().optional(), newStore: z2.boolean().optional() });
602
- var BackupStoreStatusSchema = z2.object({
603
- path: z2.string(),
604
- bucket: z2.string(),
605
- accessKey: z2.string(),
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: z2.boolean(),
507
+ running: z.boolean(),
608
508
  /** The filesystem the path is on. */
609
- totalBytes: z2.number().int(),
610
- freeBytes: z2.number().int(),
509
+ totalBytes: z.number().int(),
510
+ freeBytes: z.number().int(),
611
511
  /** What the bucket holds, when Garage answers. */
612
- objects: z2.number().int().optional(),
613
- storedBytes: z2.number().int().optional(),
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: z2.boolean().optional()
515
+ registered: z.boolean().optional()
616
516
  });
617
- var BackupStoreRegistration = z2.object({ bucket: z2.string().min(1), region: z2.string().min(1), accessKey: z2.string().min(1), secretKey: z2.string().min(1) });
618
- var CloudBackupStoreSchema = z2.object({
619
- id: z2.string(),
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: z2.string().nullable(),
622
- endpoint: z2.string().nullable(),
623
- bucket: z2.string(),
624
- accessKey: z2.string(),
625
- createdAt: z2.string(),
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: z2.boolean(),
527
+ live: z.boolean(),
628
528
  /** From the host's last poll; null when it never reported a store. */
629
- totalBytes: z2.number().int().nullable(),
630
- freeBytes: z2.number().int().nullable(),
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: z2.number().int(),
633
- storedBytes: z2.number().int(),
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: z2.number().int(),
636
- volumes: z2.number().int(),
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: z2.string().nullable()
538
+ lastBackupAt: z.string().nullable()
639
539
  });
640
- var StoredItemSchema = z2.object({
641
- kind: z2.enum(BACKUP_KINDS),
642
- owner: z2.string(),
643
- name: z2.string(),
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: z2.string().nullable(),
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: z2.boolean(),
547
+ sameHost: z.boolean(),
648
548
  /** Ready backups kept here, and what they added to the store together (encrypted, compressed). */
649
- backups: z2.number().int(),
650
- uploadedBytes: z2.number().int(),
549
+ backups: z.number().int(),
550
+ uploadedBytes: z.number().int(),
651
551
  /** The newest backup sent here, whatever became of it. */
652
- latest: z2.object({ id: z2.string(), status: z2.enum(BACKUP_STATUSES), error: z2.string().nullable(), createdAt: z2.string() })
552
+ latest: z.object({ id: z.string(), status: z.enum(BACKUP_STATUSES), error: z.string().nullable(), createdAt: z.string() })
653
553
  });
654
- var FailedBackupSchema = z2.object({
655
- id: z2.string(),
656
- owner: z2.string(),
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: z2.enum(BACKUP_KINDS),
659
- name: z2.string(),
660
- error: z2.string().nullable(),
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: z2.string().nullable(),
663
- store: z2.string().nullable(),
664
- createdAt: z2.string()
562
+ host: z.string().nullable(),
563
+ store: z.string().nullable(),
564
+ createdAt: z.string()
665
565
  });
666
- var MachineSchema = z2.object({
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: z2.string(),
669
- name: z2.string(),
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: z2.string(),
672
- ip: z2.string(),
673
- mac: z2.string(),
674
- pid: z2.number().int().nullable(),
675
- vcpu: z2.number().int(),
676
- memMib: z2.number().int(),
677
- diskBytes: z2.number().int(),
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: z2.number().int(),
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: z2.number().int().optional(),
683
- base: z2.string(),
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: z2.string().optional(),
687
- createdAt: z2.string(),
688
- source: z2.string(),
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: z2.number().int().optional(),
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: z2.object({ host: z2.string(), port: z2.number().int(), user: z2.string() }).optional(),
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: z2.array(PortForwardSchema).optional(),
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: z2.enum(["user", "org"]).optional(),
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: z2.string().optional(),
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: z2.string().optional(),
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: z2.string().optional(),
617
+ managed: z.string().optional(),
718
618
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
719
- autoHibernateSec: z2.number().int().positive().optional(),
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: z2.string().optional(),
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: z2.array(z2.object({ name: z2.string(), sizeGib: z2.number().int(), mountPath: z2.string() })).optional(),
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: z2.array(BoxLinkSchema).optional(),
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: z2.string().optional(),
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: z2.string().optional()
632
+ connect: z.string().optional()
733
633
  });
734
- var VolumeSchema = z2.object({
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: z2.string(),
737
- name: z2.string(),
738
- owner: z2.string(),
739
- sizeGib: z2.number().int(),
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: z2.number().int(),
742
- attachedTo: z2.string().nullable(),
743
- createdAt: z2.string(),
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: z2.enum(["user", "org"]).optional(),
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: z2.string().optional()
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 = z2.object({
753
- name: z2.string(),
754
- sizeGib: z2.number().int().min(1).max(MAX_VOLUME_GIB),
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: z2.string().optional()
660
+ box: z.string().optional()
761
661
  });
762
- var AttachVolumeRequest = z2.object({
763
- box: z2.string()
662
+ var AttachVolumeRequest = z.object({
663
+ box: z.string()
764
664
  });
765
- var ResizeVolumeRequest = z2.object({
766
- sizeGib: z2.number().int().min(1).max(MAX_VOLUME_GIB)
665
+ var ResizeVolumeRequest = z.object({
666
+ sizeGib: z.number().int().min(1).max(MAX_VOLUME_GIB)
767
667
  });
768
- var RunScriptRequest = z2.object({ input: z2.unknown().optional() });
769
- var ScriptOutputSchema = z2.object({ output: z2.unknown() });
668
+ var RunScriptRequest = z.object({ input: z.unknown().optional() });
669
+ var ScriptOutputSchema = z.object({ output: z.unknown() });
770
670
  var BOX_RUN_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
771
- var StartRunRequest = z2.object({
772
- id: z2.string().regex(BOX_RUN_ID_RE),
773
- command: z2.string().min(1).max(8192),
671
+ var StartRunRequest = z.object({
672
+ id: z.string().regex(BOX_RUN_ID_RE),
673
+ command: z.string().min(1).max(8192),
774
674
  /** The command and everything it started are killed after this long. */
775
- timeoutSec: z2.number().int().min(1).max(86400)
675
+ timeoutSec: z.number().int().min(1).max(86400)
776
676
  });
777
- var StartRunAnswerSchema = z2.object({
778
- id: z2.string(),
677
+ var StartRunAnswerSchema = z.object({
678
+ id: z.string(),
779
679
  /** False: a run of this id was already there. */
780
- started: z2.boolean(),
680
+ started: z.boolean(),
781
681
  /** The box was asleep and this request woke it. */
782
- woke: z2.boolean()
682
+ woke: z.boolean()
783
683
  });
784
684
  var BOX_RUN_STATES = ["running", "exited", "timeout", "unknown"];
785
- var BoxRunSchema = z2.object({
786
- id: z2.string(),
787
- state: z2.enum(BOX_RUN_STATES),
685
+ var BoxRunSchema = z.object({
686
+ id: z.string(),
687
+ state: z.enum(BOX_RUN_STATES),
788
688
  /** With `exited`; 128 + the signal for a command a signal ended. */
789
- exitCode: z2.number().int().optional()
790
- });
791
- var RunRefusalSchema = z2.object({ error: z2.string(), code: z2.string().optional() });
792
- var EnvVarSchema = z2.object({
793
- name: z2.string(),
794
- value: z2.string().optional(),
795
- secret: z2.boolean(),
796
- updatedAt: z2.string()
797
- });
798
- var BoxEnvSchema = z2.object({
799
- box: z2.string(),
800
- vars: z2.array(EnvVarSchema)
801
- });
802
- var BoxEnvChangeSchema = z2.object({
803
- box: z2.string(),
804
- name: z2.string(),
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(),
805
705
  /** Whether the box is running now: the change waits for its next start. */
806
- running: z2.boolean()
706
+ running: z.boolean()
807
707
  });
808
- var SetEnvRequest = z2.object({
809
- value: z2.string(),
810
- secret: z2.boolean().optional()
708
+ var SetEnvRequest = z.object({
709
+ value: z.string(),
710
+ secret: z.boolean().optional()
811
711
  });
812
- var EnvChangeSchema = z2.object({
813
- owner: z2.string(),
814
- name: z2.string(),
815
- boxes: z2.number().int()
712
+ var EnvChangeSchema = z.object({
713
+ owner: z.string(),
714
+ name: z.string(),
715
+ boxes: z.number().int()
816
716
  });
817
- var HostEnvRequest = z2.object({
818
- version: z2.number().int().min(0),
819
- vars: z2.array(z2.object({ name: z2.string(), value: z2.string() }))
717
+ var HostEnvRequest = z.object({
718
+ version: z.number().int().min(0),
719
+ vars: z.array(z.object({ name: z.string(), value: z.string() }))
820
720
  });
821
- var HostEnvVersionsSchema = z2.array(z2.object({ owner: z2.string(), version: z2.number().int() }));
822
- var CreateMachineRequest = z2.object({
823
- name: z2.string().optional(),
721
+ var HostEnvVersionsSchema = z.array(z.object({ owner: z.string(), version: z.number().int() }));
722
+ var CreateMachineRequest = z.object({
723
+ name: z.string().optional(),
824
724
  /** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
825
- owner: z2.string().optional(),
725
+ owner: z.string().optional(),
826
726
  size: SizeSchema.optional(),
827
- from: z2.string().optional(),
828
- force: z2.boolean().optional(),
727
+ from: z.string().optional(),
728
+ force: z.boolean().optional(),
829
729
  /**
830
730
  * Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends
831
731
  * its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every
832
732
  * boot (#49); a host older than that ignores them.
833
733
  */
834
- sshKeys: z2.array(z2.string()).optional(),
734
+ sshKeys: z.array(z.string()).optional(),
835
735
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
836
- autoHibernateSec: z2.number().int().min(0).optional(),
736
+ autoHibernateSec: z.number().int().min(0).optional(),
837
737
  /**
838
738
  * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
839
739
  * control plane reads it; a host has one place to put a box.
840
740
  */
841
- near: z2.string().optional(),
741
+ near: z.string().optional(),
842
742
  /**
843
743
  * Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
844
744
  * `@kvbox/shared/country`. Only the control plane reads it.
845
745
  */
846
- country: z2.string().optional(),
746
+ country: z.string().optional(),
847
747
  /**
848
748
  * Place the box on the host of this name and nowhere else (`kvbox new --host kvbox2`, a hidden flag):
849
749
  * an admin's, to try a host out. Only the control plane reads it, and refuses it from anyone else.
850
750
  */
851
- host: z2.string().optional(),
751
+ host: z.string().optional(),
852
752
  /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
853
- image: z2.string().optional(),
753
+ image: z.string().optional(),
854
754
  /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
855
- env: z2.array(z2.object({ name: z2.string(), value: z2.string() })).optional()
755
+ env: z.array(z.object({ name: z.string(), value: z.string() })).optional()
856
756
  });
857
- var ForkMachineRequest = z2.object({
858
- name: z2.string().optional(),
757
+ var ForkMachineRequest = z.object({
758
+ name: z.string().optional(),
859
759
  /**
860
760
  * The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host
861
761
  * qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.
862
762
  */
863
- owner: z2.string().optional(),
763
+ owner: z.string().optional(),
864
764
  /** A cold fork only: a warm one keeps the source's vCPU and memory. */
865
765
  size: SizeSchema.optional(),
866
- force: z2.boolean().optional(),
766
+ force: z.boolean().optional(),
867
767
  /** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */
868
- sshKeys: z2.array(z2.string()).optional(),
869
- autoHibernateSec: z2.number().int().min(0).optional()
768
+ sshKeys: z.array(z.string()).optional(),
769
+ autoHibernateSec: z.number().int().min(0).optional()
870
770
  });
871
- var SetSshKeysRequest = z2.object({
872
- sshKeys: z2.array(z2.string())
771
+ var SetSshKeysRequest = z.object({
772
+ sshKeys: z.array(z.string())
873
773
  });
874
- var RescaleMachineRequest = z2.object({
774
+ var RescaleMachineRequest = z.object({
875
775
  size: SizeSchema.optional(),
876
- vcpu: z2.number().int().min(1).max(64).optional(),
877
- memMib: z2.number().int().min(256).optional(),
878
- diskGib: z2.number().int().min(1).optional(),
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(),
879
779
  /** Skip the capacity guard when a running box grows (#37). */
880
- force: z2.boolean().optional()
780
+ force: z.boolean().optional()
881
781
  });
882
- var StartMachineRequest = z2.object({
883
- force: z2.boolean().optional()
782
+ var StartMachineRequest = z.object({
783
+ force: z.boolean().optional()
884
784
  });
885
- var SetMachineRequest = z2.object({
785
+ var SetMachineRequest = z.object({
886
786
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. */
887
- autoHibernateSec: z2.number().int().min(0).optional(),
787
+ autoHibernateSec: z.number().int().min(0).optional(),
888
788
  /** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
889
- idleCheck: z2.union([z2.literal(""), z2.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
789
+ idleCheck: z.union([z.literal(""), z.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
890
790
  });
891
- var SnapshotSchema = z2.object({
892
- name: z2.string(),
893
- owner: z2.string(),
894
- source: z2.string(),
791
+ var SnapshotSchema = z.object({
792
+ name: z.string(),
793
+ owner: z.string(),
794
+ source: z.string(),
895
795
  // the box it was taken from, as owner/name
896
- base: z2.string(),
796
+ base: z.string(),
897
797
  // version of the image the overlay stacks on; a restore needs the same one
898
798
  /** As in MachineSchema: the image when it is not the base one (#87). */
899
- image: z2.string().optional(),
900
- vcpu: z2.number().int(),
901
- memMib: z2.number().int(),
902
- sizeBytes: z2.number().int(),
799
+ image: z.string().optional(),
800
+ vcpu: z.number().int(),
801
+ memMib: z.number().int(),
802
+ sizeBytes: z.number().int(),
903
803
  // what vmstate + mem + overlay really occupy on the host
904
- createdAt: z2.string()
804
+ createdAt: z.string()
905
805
  });
906
- var CreateSnapshotRequest = z2.object({
907
- box: z2.string(),
908
- name: z2.string(),
806
+ var CreateSnapshotRequest = z.object({
807
+ box: z.string(),
808
+ name: z.string(),
909
809
  /** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
910
- replace: z2.boolean().optional()
911
- });
912
- var DiskCapacitySchema = z2.object({
913
- totalGib: z2.number().int(),
914
- freeGib: z2.number().int(),
915
- volumesGib: z2.number().int(),
916
- volumesUsedGib: z2.number().int(),
917
- headroomGib: z2.number().int()
918
- });
919
- var CapacitySchema = z2.object({
920
- hostMemMib: z2.number().int(),
921
- hostCores: z2.number().int(),
922
- reservedMemMib: z2.number().int(),
923
- reservedVcpu: z2.number().int(),
924
- running: z2.number().int(),
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(),
925
825
  /** Absent on a host from before volumes (#91): it cannot take one. */
926
826
  disk: DiskCapacitySchema.optional(),
927
827
  /**
928
828
  * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
929
829
  * Absent on a host from before images: it has only the base.
930
830
  */
931
- images: z2.array(z2.object({ name: z2.string(), version: z2.string() })).optional(),
831
+ images: z.array(z.object({ name: z.string(), version: z.string() })).optional(),
932
832
  /** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */
933
- version: z2.string().optional(),
833
+ version: z.string().optional(),
934
834
  /** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */
935
- backupStore: z2.object({ totalBytes: z2.number().int(), freeBytes: z2.number().int(), running: z2.boolean() }).optional(),
835
+ backupStore: z.object({ totalBytes: z.number().int(), freeBytes: z.number().int(), running: z.boolean() }).optional(),
936
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. */
937
- storeClient: z2.boolean().optional()
837
+ storeClient: z.boolean().optional()
938
838
  });
939
- var ImageSchema = z2.object({ name: z2.string(), version: z2.string().nullable() });
940
- var ImageIndexSchema = z2.object({
941
- updatedAt: z2.string(),
942
- images: z2.record(z2.string(), z2.object({ version: z2.string().min(1), minServer: z2.string().min(1).optional() }))
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() }))
943
843
  });
944
- var LatestImagesSchema = z2.object({
945
- updatedAt: z2.string().nullable(),
844
+ var LatestImagesSchema = z.object({
845
+ updatedAt: z.string().nullable(),
946
846
  images: ImageIndexSchema.shape.images,
947
- checkedAt: z2.string().nullable()
948
- });
949
- var RecoveryReportSchema = z2.object({
950
- at: z2.string(),
951
- booted: z2.array(z2.string()),
952
- leftStopped: z2.array(z2.string()),
953
- failed: z2.array(z2.object({ box: z2.string(), error: z2.string() }))
954
- });
955
- var HostUpdateSchema = z2.object({
956
- state: z2.enum(["running", "done", "failed"]),
957
- startedAt: z2.string(),
958
- finishedAt: z2.string().nullable(),
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(),
959
859
  /** kvbox-server's version when the update started, and when it ended (null while running or when it failed before). */
960
- from: z2.string(),
961
- to: z2.string().nullable(),
962
- error: z2.string().nullable(),
963
- needsManual: z2.array(z2.string())
964
- });
965
- var HealthSchema = z2.object({
966
- ok: z2.literal(true),
967
- version: z2.string(),
968
- pid: z2.number().int(),
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(),
969
869
  /** Base image version new boxes get (null when the host has no usable base image yet). */
970
- base: z2.string().nullable(),
870
+ base: z.string().nullable(),
971
871
  /** Owner that boxes made over the local socket get (the Unix user running the server). */
972
- owner: z2.string(),
872
+ owner: z.string(),
973
873
  /** The control plane this host joined (null when none). */
974
- controlPlane: z2.object({
874
+ controlPlane: z.object({
975
875
  /** Realm name, e.g. kvbox.sh. */
976
- name: z2.string(),
977
- url: z2.string(),
876
+ name: z.string(),
877
+ url: z.string(),
978
878
  /** Where this host answers the control plane. */
979
- hostUrl: z2.string()
879
+ hostUrl: z.string()
980
880
  }).nullable(),
981
881
  /** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */
982
- relay: z2.object({
983
- name: z2.string(),
882
+ relay: z.object({
883
+ name: z.string(),
984
884
  /** The public IP the relay owns for this host. */
985
- publicIp: z2.string(),
885
+ publicIp: z.string(),
986
886
  /** The relay's WireGuard endpoint the tunnel dials. */
987
- endpoint: z2.string(),
887
+ endpoint: z.string(),
988
888
  /** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */
989
- restarts: z2.number().int().optional(),
990
- lastRestartAt: z2.string().nullable().optional()
889
+ restarts: z.number().int().optional(),
890
+ lastRestartAt: z.string().nullable().optional()
991
891
  }).nullable().optional(),
992
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. */
993
893
  recovery: RecoveryReportSchema.nullable().optional(),
994
894
  /** The last self-update; null when none ran. Older servers omit it. */
995
895
  update: HostUpdateSchema.nullable().optional()
996
896
  });
997
- var MachineUsageSchema = z2.object({
998
- name: z2.string(),
999
- owner: z2.string(),
897
+ var MachineUsageSchema = z.object({
898
+ name: z.string(),
899
+ owner: z.string(),
1000
900
  status: BoxStatusSchema,
1001
- window: z2.object({ from: z2.string(), to: z2.string() }),
1002
- seconds: z2.object({
1003
- running: z2.number().int(),
1004
- standby: z2.number().int(),
1005
- hibernated: z2.number().int(),
1006
- stopped: z2.number().int()
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()
1007
907
  }),
1008
- vcpuHours: z2.number(),
1009
- ramGibHours: z2.number(),
1010
- diskGibHours: z2.number(),
1011
- cost: z2.object({ amount: z2.number(), currency: z2.string() }).optional(),
908
+ vcpuHours: z.number(),
909
+ ramGibHours: z.number(),
910
+ diskGibHours: z.number(),
911
+ cost: z.object({ amount: z.number(), currency: z.string() }).optional(),
1012
912
  /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */
1013
- estimatedStops: z2.number().int(),
1014
- historyFrom: z2.string().nullable()
913
+ estimatedStops: z.number().int(),
914
+ historyFrom: z.string().nullable()
1015
915
  });
1016
- var GuestStatsSchema = z2.object({
916
+ var GuestStatsSchema = z.object({
1017
917
  /** Load average over 1, 5 and 15 minutes. */
1018
- load: z2.tuple([z2.number(), z2.number(), z2.number()]),
1019
- cpus: z2.number().int(),
1020
- memTotalMib: z2.number().int(),
918
+ load: z.tuple([z.number(), z.number(), z.number()]),
919
+ cpus: z.number().int(),
920
+ memTotalMib: z.number().int(),
1021
921
  /** Total minus available: page cache counts as free. */
1022
- memUsedMib: z2.number().int(),
922
+ memUsedMib: z.number().int(),
1023
923
  /** The box's root, which is its overlay disk: the box's own writes, not the shared base. */
1024
- diskTotalBytes: z2.number().int(),
1025
- diskUsedBytes: z2.number().int(),
1026
- uptimeSec: z2.number().int()
924
+ diskTotalBytes: z.number().int(),
925
+ diskUsedBytes: z.number().int(),
926
+ uptimeSec: z.number().int()
1027
927
  });
1028
- var MachineStatsSchema = z2.object({
1029
- name: z2.string(),
1030
- owner: z2.string(),
928
+ var MachineStatsSchema = z.object({
929
+ name: z.string(),
930
+ owner: z.string(),
1031
931
  stats: GuestStatsSchema.nullable()
1032
932
  });
1033
- var UsageStatusSchema = z2.enum([...BoxStatusSchema.options, "removed"]);
933
+ var UsageStatusSchema = z.enum([...BoxStatusSchema.options, "removed"]);
1034
934
  var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({
1035
935
  /** The host's box id; a name removed and recreated appears twice, with two ids. */
1036
- id: z2.string(),
936
+ id: z.string(),
1037
937
  status: UsageStatusSchema,
1038
938
  /** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */
1039
- ownerKind: z2.enum(["user", "org"]).optional(),
939
+ ownerKind: z.enum(["user", "org"]).optional(),
1040
940
  /**
1041
941
  * Through a control plane: the username that made the box (#60), absent when the box is gone from
1042
942
  * the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.
1043
943
  */
1044
- createdBy: z2.string().optional()
944
+ createdBy: z.string().optional()
1045
945
  });
1046
- var VolumeUsageSchema = z2.object({
946
+ var VolumeUsageSchema = z.object({
1047
947
  /** The host's volume id; a name removed and made again appears twice, with two ids. */
1048
- id: z2.string(),
1049
- name: z2.string(),
1050
- owner: z2.string(),
1051
- ownerKind: z2.enum(["user", "org"]).optional(),
948
+ id: z.string(),
949
+ name: z.string(),
950
+ owner: z.string(),
951
+ ownerKind: z.enum(["user", "org"]).optional(),
1052
952
  /** The size at the end of the window (or when removed). */
1053
- sizeGib: z2.number().int(),
1054
- status: z2.enum(["present", "removed"]),
1055
- volumeHours: z2.number(),
1056
- volumeGibHours: z2.number(),
1057
- cost: z2.object({ amount: z2.number(), currency: z2.string() }).optional(),
1058
- historyFrom: z2.string().nullable()
1059
- });
1060
- var CronUsageSchema = z2.object({
1061
- id: z2.string(),
1062
- name: z2.string(),
1063
- owner: z2.string(),
1064
- ownerKind: z2.enum(["user", "org"]).optional(),
1065
- status: z2.enum(["present", "removed"]),
1066
- hours: z2.number(),
1067
- cost: z2.object({ amount: z2.number(), currency: z2.string() }).optional(),
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(),
1068
968
  /** When it was made. */
1069
- historyFrom: z2.string().nullable()
969
+ historyFrom: z.string().nullable()
1070
970
  });
1071
- var UsageDayItemSchema = z2.object({
1072
- id: z2.string(),
1073
- name: z2.string(),
1074
- owner: z2.string(),
971
+ var UsageDayItemSchema = z.object({
972
+ id: z.string(),
973
+ name: z.string(),
974
+ owner: z.string(),
1075
975
  /** Removed by the end of the report's window. */
1076
- removed: z2.boolean(),
1077
- cost: z2.number()
976
+ removed: z.boolean(),
977
+ cost: z.number()
1078
978
  });
1079
- var UsageDaySchema = z2.object({
979
+ var UsageDaySchema = z.object({
1080
980
  /** `YYYY-MM-DD`, UTC. */
1081
- date: z2.string(),
1082
- from: z2.string(),
1083
- to: z2.string(),
1084
- cost: z2.number(),
1085
- currency: z2.string(),
1086
- boxes: z2.array(UsageDayItemSchema),
1087
- volumes: z2.array(UsageDayItemSchema),
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),
1088
988
  /** Object storage that existed that day (#182); absent on a day without any. */
1089
- storage: z2.array(UsageDayItemSchema).optional(),
989
+ storage: z.array(UsageDayItemSchema).optional(),
1090
990
  /** Cron services that existed that day (#190); absent on a day without any. */
1091
- cron: z2.array(UsageDayItemSchema).optional()
991
+ cron: z.array(UsageDayItemSchema).optional()
1092
992
  });
1093
- var UsageReportSchema = z2.object({
1094
- window: z2.object({ from: z2.string(), to: z2.string() }),
1095
- boxes: z2.array(BoxUsageSchema),
993
+ var UsageReportSchema = z.object({
994
+ window: z.object({ from: z.string(), to: z.string() }),
995
+ boxes: z.array(BoxUsageSchema),
1096
996
  /** Absent from a side older than #91. */
1097
- volumes: z2.array(VolumeUsageSchema).optional(),
997
+ volumes: z.array(VolumeUsageSchema).optional(),
1098
998
  /**
1099
999
  * Object storage (#182, control plane only): one row per storage a slug has or had, shaped like a
1100
1000
  * volume's. `volumeHours` are the hours it existed, `volumeGibHours` those of the GiB beyond the
1101
1001
  * included ones, `sizeGib` its whole size. Absent when there is none.
1102
1002
  */
1103
- storage: z2.array(VolumeUsageSchema).optional(),
1003
+ storage: z.array(VolumeUsageSchema).optional(),
1104
1004
  /** Cron services (#190, control plane only): one row per service a slug has or had. Absent when there is none. */
1105
- cron: z2.array(CronUsageSchema).optional(),
1005
+ cron: z.array(CronUsageSchema).optional(),
1106
1006
  /** With `?by=day` only, oldest day first. */
1107
- days: z2.array(UsageDaySchema).optional(),
1108
- totals: z2.object({
1007
+ days: z.array(UsageDaySchema).optional(),
1008
+ totals: z.object({
1109
1009
  seconds: MachineUsageSchema.shape.seconds,
1110
- vcpuHours: z2.number(),
1111
- ramGibHours: z2.number(),
1112
- diskGibHours: z2.number(),
1113
- volumeHours: z2.number().optional(),
1114
- volumeGibHours: z2.number().optional(),
1010
+ vcpuHours: z.number(),
1011
+ ramGibHours: z.number(),
1012
+ diskGibHours: z.number(),
1013
+ volumeHours: z.number().optional(),
1014
+ volumeGibHours: z.number().optional(),
1115
1015
  /** Boxes, volumes, object storage and cron services together. */
1116
- cost: z2.object({ amount: z2.number(), currency: z2.string() }).optional()
1016
+ cost: z.object({ amount: z.number(), currency: z.string() }).optional()
1117
1017
  })
1118
1018
  });
1119
- var UsageEventRowSchema = z2.object({
1120
- id: z2.number().int(),
1121
- boxId: z2.string(),
1122
- owner: z2.string(),
1123
- name: z2.string(),
1124
- at: z2.string(),
1125
- state: z2.enum(["running", "standby", "hibernated", "stopped"]),
1126
- vcpu: z2.number().int(),
1127
- memMib: z2.number().int(),
1128
- diskGib: z2.number().int(),
1129
- by: z2.string()
1130
- });
1131
- var UsageEventsResponseSchema = z2.object({
1132
- ledger: z2.string().min(1),
1133
- events: z2.array(UsageEventRowSchema),
1134
- next: z2.number().int()
1135
- });
1136
- var VolumeEventRowSchema = z2.object({
1137
- id: z2.number().int(),
1138
- volumeId: z2.string(),
1139
- owner: z2.string(),
1140
- name: z2.string(),
1141
- at: z2.string(),
1142
- sizeGib: z2.number().int(),
1143
- by: z2.enum(["create", "resize", "rm"])
1144
- });
1145
- var VolumeEventsResponseSchema = z2.object({
1146
- ledger: z2.string().min(1),
1147
- events: z2.array(VolumeEventRowSchema),
1148
- next: z2.number().int()
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()
1149
1049
  });
1150
1050
  var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
1151
- var ApiErrorCodeSchema = z2.enum(API_ERROR_CODES);
1152
- var ApiErrorSchema = z2.object({
1153
- error: z2.string(),
1051
+ var ApiErrorCodeSchema = z.enum(API_ERROR_CODES);
1052
+ var ApiErrorSchema = z.object({
1053
+ error: z.string(),
1154
1054
  code: ApiErrorCodeSchema.optional()
1155
1055
  });
1156
1056
  var DEFAULT_CLOUD_URL = "https://api.kvbox.sh";
1157
1057
  var ACTIVATED_BY = ["card", "admin"];
1158
- var ActivatedBySchema = z2.enum(ACTIVATED_BY);
1159
- var CloudUserSchema = z2.object({
1058
+ var ActivatedBySchema = z.enum(ACTIVATED_BY);
1059
+ var CloudUserSchema = z.object({
1160
1060
  /** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */
1161
- username: z2.string(),
1061
+ username: z.string(),
1162
1062
  /** Display name, free text ("Alexandru Ghiura"). */
1163
- name: z2.string(),
1063
+ name: z.string(),
1164
1064
  /** Login identity, unique. */
1165
- email: z2.string(),
1166
- role: z2.enum(["admin", "user"]),
1167
- createdAt: z2.string(),
1065
+ email: z.string(),
1066
+ role: z.enum(["admin", "user"]),
1067
+ createdAt: z.string(),
1168
1068
  /**
1169
1069
  * False until a card is on file or an admin activates the account (#74): then only `/me` and
1170
1070
  * `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and
1171
1071
  * gates nobody, hence the defaults: a newer CLI must still parse its answers.
1172
1072
  */
1173
- active: z2.boolean().default(true),
1073
+ active: z.boolean().default(true),
1174
1074
  activatedBy: ActivatedBySchema.nullable().default(null),
1175
1075
  /** When too many wrong passwords locked the account (#161); null when it is not locked. Older control planes omit it. */
1176
- lockedAt: z2.string().nullable().default(null)
1076
+ lockedAt: z.string().nullable().default(null)
1177
1077
  });
1178
1078
  var ORG_ROLES = ["owner", "admin", "member"];
1179
- var OrgRoleSchema = z2.enum(ORG_ROLES);
1180
- var CloudOrgSchema = z2.object({
1181
- slug: z2.string(),
1079
+ var OrgRoleSchema = z.enum(ORG_ROLES);
1080
+ var CloudOrgSchema = z.object({
1081
+ slug: z.string(),
1182
1082
  /** Display name; the slug never changes, this may. */
1183
- name: z2.string(),
1184
- createdAt: z2.string(),
1083
+ name: z.string(),
1084
+ createdAt: z.string(),
1185
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. */
1186
- active: z2.boolean().default(true),
1086
+ active: z.boolean().default(true),
1187
1087
  activatedBy: ActivatedBySchema.nullable().default(null)
1188
1088
  });
1189
1089
  var OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });
1190
- var OrgMemberSchema = z2.object({
1191
- username: z2.string(),
1192
- name: z2.string(),
1090
+ var OrgMemberSchema = z.object({
1091
+ username: z.string(),
1092
+ name: z.string(),
1193
1093
  role: OrgRoleSchema,
1194
- addedAt: z2.string()
1094
+ addedAt: z.string()
1195
1095
  });
1196
- var OrgDetailSchema = CloudOrgSchema.extend({ members: z2.array(OrgMemberSchema) });
1197
- var CreateOrgRequestSchema = z2.object({
1198
- slug: z2.string().min(1),
1199
- name: z2.string().min(1)
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)
1200
1100
  });
1201
- var RenameOrgRequestSchema = z2.object({ name: z2.string().min(1) });
1202
- var AddMemberRequestSchema = z2.object({
1203
- username: z2.string().min(1),
1101
+ var RenameOrgRequestSchema = z.object({ name: z.string().min(1) });
1102
+ var AddMemberRequestSchema = z.object({
1103
+ username: z.string().min(1),
1204
1104
  role: OrgRoleSchema.default("member")
1205
1105
  });
1206
- var SetRoleRequestSchema = z2.object({ role: OrgRoleSchema });
1207
- var MeResponseSchema = CloudUserSchema.extend({ orgs: z2.array(OrgMembershipSchema) });
1208
- var BalanceSchema = z2.object({
1209
- slug: z2.string(),
1210
- balance: z2.number(),
1211
- currency: z2.string(),
1212
- topUps: z2.number(),
1213
- spent: z2.number(),
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(),
1214
1114
  /** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */
1215
- since: z2.string().nullable(),
1115
+ since: z.string().nullable(),
1216
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. */
1217
- suspendedAt: z2.string().nullable().default(null),
1117
+ suspendedAt: z.string().nullable().default(null),
1218
1118
  /** Promo credit left (#163), already counted in `balance`; 0 with none. Absent from a control plane older than this field. */
1219
- promo: z2.number().default(0),
1119
+ promo: z.number().default(0),
1220
1120
  /** When the next promo credit expires; null with none left. */
1221
- promoExpiresAt: z2.string().nullable().default(null)
1121
+ promoExpiresAt: z.string().nullable().default(null)
1222
1122
  });
1223
- var TopUpRequestSchema = z2.object({
1224
- slug: z2.string().min(1),
1123
+ var TopUpRequestSchema = z.object({
1124
+ slug: z.string().min(1),
1225
1125
  /** In the control plane's currency; negative corrects a mistake. */
1226
- amount: z2.number().finite(),
1227
- note: z2.string().max(200).optional()
1228
- });
1229
- var TopUpSchema = z2.object({
1230
- id: z2.string(),
1231
- slug: z2.string(),
1232
- amount: z2.number(),
1233
- currency: z2.string(),
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(),
1234
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. */
1235
- source: z2.enum(["admin", "card", "trial", "transfer"]),
1236
- note: z2.string().nullable(),
1237
- at: z2.string()
1135
+ source: z.enum(["admin", "card", "trial", "transfer"]),
1136
+ note: z.string().nullable(),
1137
+ at: z.string()
1238
1138
  });
1239
- var CreateCodeRequestSchema = z2.object({
1139
+ var CreateCodeRequestSchema = z.object({
1240
1140
  /** In the control plane's currency, cents at most. */
1241
- amount: z2.number().positive().multipleOf(0.01, "amount is in cents at most"),
1141
+ amount: z.number().positive().multipleOf(0.01, "amount is in cents at most"),
1242
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. */
1243
- expiresAt: z2.string().min(1),
1244
- note: z2.string().max(200).optional()
1245
- });
1246
- var CreditCodeSchema = z2.object({
1247
- code: z2.string(),
1248
- amount: z2.number(),
1249
- currency: z2.string(),
1250
- expiresAt: z2.string(),
1251
- note: z2.string().nullable(),
1252
- status: z2.enum(["unused", "redeemed", "expired", "revoked"]),
1253
- createdBy: z2.string(),
1254
- createdAt: z2.string(),
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(),
1255
1155
  /** Who redeemed it and the slug the credit went to (their own, or an org they own). */
1256
- redeemedBy: z2.string().nullable(),
1257
- redeemedSlug: z2.string().nullable(),
1258
- redeemedAt: z2.string().nullable(),
1259
- revokedAt: z2.string().nullable()
1260
- });
1261
- var RedeemRequestSchema = z2.object({
1262
- code: z2.string().min(1).max(64),
1263
- org: z2.string().min(1).optional()
1264
- });
1265
- var RedeemResponseSchema = z2.object({
1266
- slug: z2.string(),
1267
- amount: z2.number(),
1268
- currency: z2.string(),
1269
- expiresAt: z2.string(),
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(),
1270
1170
  balance: BalanceSchema,
1271
1171
  /** The slug was out of credit and this put it back above zero: it may start boxes again. */
1272
- reinstated: z2.boolean()
1172
+ reinstated: z.boolean()
1273
1173
  });
1274
1174
  var TOP_UP_AMOUNTS = [10, 25, 50, 100];
1275
- var BillingInfoSchema = z2.object({
1276
- card: z2.object({ brand: z2.string(), last4: z2.string() }).nullable(),
1277
- cardInUse: z2.boolean(),
1175
+ var BillingInfoSchema = z.object({
1176
+ card: z.object({ brand: z.string(), last4: z.string() }).nullable(),
1177
+ cardInUse: z.boolean(),
1278
1178
  balance: BalanceSchema
1279
1179
  });
1280
- var BillingRedirectSchema = z2.object({ url: z2.string() });
1281
- var TopUpCheckoutRequestSchema = z2.object({
1282
- amount: z2.literal(TOP_UP_AMOUNTS)
1180
+ var BillingRedirectSchema = z.object({ url: z.string() });
1181
+ var TopUpCheckoutRequestSchema = z.object({
1182
+ amount: z.literal(TOP_UP_AMOUNTS)
1283
1183
  });
1284
- var TransferRequestSchema = z2.object({
1285
- org: z2.string().min(1),
1286
- amount: z2.number().positive().multipleOf(0.01, "amount is in cents at most")
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")
1287
1187
  });
1288
- var TransferResponseSchema = z2.object({ from: BalanceSchema, to: BalanceSchema, activated: z2.boolean() });
1289
- var LoginRequestSchema = z2.object({
1290
- email: z2.string().min(1),
1291
- password: z2.string().min(1),
1292
- publicKey: z2.string().optional()
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()
1293
1193
  });
1294
- var SignupRequestSchema = z2.object({
1295
- username: z2.string().min(1),
1296
- name: z2.string().min(1),
1297
- email: z2.string().min(1),
1298
- password: z2.string().min(1)
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)
1299
1199
  });
1300
- var LoginResponseSchema = z2.object({
1301
- token: z2.string(),
1200
+ var LoginResponseSchema = z.object({
1201
+ token: z.string(),
1302
1202
  user: CloudUserSchema,
1303
- sshCert: z2.string().optional(),
1304
- sshCertExpires: z2.string().optional(),
1203
+ sshCert: z.string().optional(),
1204
+ sshCertExpires: z.string().optional(),
1305
1205
  /** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
1306
- sshCertPrincipals: z2.array(z2.string()).optional()
1307
- });
1308
- var SshCertRequestSchema = z2.object({
1309
- publicKey: z2.string().min(1)
1310
- });
1311
- var SshCertResponseSchema = z2.object({
1312
- cert: z2.string(),
1313
- expires: z2.string(),
1314
- principals: z2.array(z2.string())
1206
+ sshCertPrincipals: z.array(z.string()).optional()
1315
1207
  });
1316
- var SshCaResponseSchema = z2.object({
1317
- publicKey: z2.string(),
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(),
1318
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. */
1319
- retired: z2.array(z2.object({ publicKey: z2.string(), retiredAt: z2.string() })).optional()
1260
+ retired: z.array(z.object({ publicKey: z.string(), retiredAt: z.string() })).optional()
1320
1261
  });
1321
- var HostSshCaResponseSchema = z2.object({
1322
- publicKey: z2.string()
1262
+ var HostSshCaResponseSchema = z.object({
1263
+ publicKey: z.string()
1323
1264
  });
1324
- var CloudCaSchema = z2.object({
1325
- controlPlane: z2.string(),
1326
- publicKey: z2.string(),
1327
- fingerprint: z2.string()
1265
+ var CloudCaSchema = z.object({
1266
+ controlPlane: z.string(),
1267
+ publicKey: z.string(),
1268
+ fingerprint: z.string()
1328
1269
  });
1329
- var TrustCaRequestSchema = z2.object({
1330
- publicKey: z2.string().min(1)
1270
+ var TrustCaRequestSchema = z.object({
1271
+ publicKey: z.string().min(1)
1331
1272
  });
1332
- var SshKeysAppliedSchema = z2.enum(["now", "start", "wake", "resume", "later"]);
1333
- var TrustCaReportSchema = z2.object({
1334
- publicKey: z2.string(),
1335
- fingerprint: z2.string(),
1273
+ var SshKeysAppliedSchema = z.enum(["now", "start", "wake", "resume", "later"]);
1274
+ var TrustCaReportSchema = z.object({
1275
+ publicKey: z.string(),
1276
+ fingerprint: z.string(),
1336
1277
  /** The guest trusts the CA now. */
1337
- updated: z2.array(z2.string()),
1278
+ updated: z.array(z.string()),
1338
1279
  /** meta.json has the line; the guest gets it at `when`. */
1339
- pending: z2.array(z2.object({ box: z2.string(), when: SshKeysAppliedSchema, why: z2.string().optional() })),
1340
- failed: z2.array(z2.object({ box: z2.string(), error: z2.string() })),
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() })),
1341
1282
  /** Local boxes, untouched: they trust the host's key only. */
1342
- local: z2.number().int(),
1283
+ local: z.number().int(),
1343
1284
  /** Cloud boxes made without a CA line (a managed service's, #173), untouched: no certificate opens them. Absent from older servers. */
1344
- skipped: z2.array(z2.string()).optional()
1345
- });
1346
- var HostJoinRequestSchema = z2.object({
1347
- token: z2.string().min(1),
1348
- name: z2.string().min(1),
1349
- url: z2.string().url(),
1350
- fingerprint: z2.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
1351
- publicAddress: z2.string().min(1),
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),
1352
1293
  /** Where the host is (`kvbox-server join --country`): a code or an English name. */
1353
- country: z2.string().optional()
1294
+ country: z.string().optional()
1354
1295
  });
1355
- var HostJoinResponseSchema = z2.object({
1356
- hostSecret: z2.string(),
1357
- controlPlane: z2.object({ name: z2.string() })
1296
+ var HostJoinResponseSchema = z.object({
1297
+ hostSecret: z.string(),
1298
+ controlPlane: z.object({ name: z.string() })
1358
1299
  });
1359
- var CloudHostSchema = z2.object({
1360
- name: z2.string(),
1361
- url: z2.string(),
1362
- publicAddress: z2.string(),
1363
- joinedAt: z2.string(),
1364
- lastSeenAt: z2.string().nullable(),
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(),
1365
1306
  capacity: CapacitySchema.nullable(),
1366
1307
  /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
1367
- country: z2.string().nullable(),
1308
+ country: z.string().nullable(),
1368
1309
  /** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */
1369
- region: z2.string().nullable(),
1310
+ region: z.string().nullable(),
1370
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. */
1371
- version: z2.string().nullable()
1312
+ version: z.string().nullable()
1372
1313
  });
1373
- var HostInfoSchema = z2.object({
1314
+ var HostInfoSchema = z.object({
1374
1315
  host: CloudHostSchema,
1375
1316
  health: HealthSchema.nullable(),
1376
- error: z2.string().nullable()
1317
+ error: z.string().nullable()
1377
1318
  });
1378
- var HostPatchRequest = z2.object({ country: z2.string().nullable().optional(), region: z2.string().nullable().optional() }).refine((b) => b.country !== void 0 || b.region !== void 0, { message: "give country, region or both" });
1379
- var CountrySchema = z2.object({ code: z2.string(), name: z2.string() });
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";
1380
1508
 
1381
1509
  // ../shared/src/managed.ts
1382
1510
  import { z as z4 } from "zod";
@@ -1715,7 +1843,7 @@ function groupWithMember(gid, user, groupFile) {
1715
1843
  }
1716
1844
 
1717
1845
  // ../shared/src/systemd.ts
1718
- import { spawnSync } from "child_process";
1846
+ import { spawnSync as spawnSync2 } from "child_process";
1719
1847
  import { readFileSync as readFileSync2 } from "fs";
1720
1848
  import { resolve } from "path";
1721
1849
  var UNIT = "kvbox-server";
@@ -1731,11 +1859,11 @@ function hasUnitFor(p, file = UNIT_FILE) {
1731
1859
  return home !== void 0 && resolve(home) === resolve(p.home);
1732
1860
  }
1733
1861
  function startUnitProcess() {
1734
- const res = spawnSync("sudo", ["-n", "systemctl", "start", UNIT], { encoding: "utf8" });
1862
+ const res = spawnSync2("sudo", ["-n", "systemctl", "start", UNIT], { encoding: "utf8" });
1735
1863
  return { ok: res.status === 0, out: `${res.stdout ?? ""}${res.stderr ?? ""}`.trim() };
1736
1864
  }
1737
1865
  function unitActive() {
1738
- const res = spawnSync("systemctl", ["is-active", UNIT], { encoding: "utf8" });
1866
+ const res = spawnSync2("systemctl", ["is-active", UNIT], { encoding: "utf8" });
1739
1867
  return (res.stdout ?? "").trim() === "active";
1740
1868
  }
1741
1869
 
@@ -1748,11 +1876,15 @@ function orgOption(opts) {
1748
1876
  }
1749
1877
  async function resolveTarget(opts, p = paths()) {
1750
1878
  if (!opts.local) {
1751
- const session = await readSession(p);
1752
- if (session) {
1753
- const org = orgOption(opts);
1754
- return { kind: "cloud", url: session.url, token: session.token, user: session.user, ...org === void 0 ? {} : { org } };
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 } };
1755
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 } };
1756
1888
  }
1757
1889
  return { kind: "local", socketPath: p.serverSock };
1758
1890
  }
@@ -1798,20 +1930,22 @@ var ServerClient = class {
1798
1930
  }
1799
1931
  throw new KvboxError(`kvbox-server is not running (${String(code)}); start it with: kvbox-server start -d`);
1800
1932
  }
1801
- throw new KvboxError(cloudDown(this.target.url, String(code)));
1933
+ throw new CallError(cloudDown(this.target.url, String(code)), 0);
1802
1934
  }
1803
1935
  const text2 = await res.body.text();
1804
1936
  const where = this.target.kind === "cloud" ? hostOf(this.target.url) : "kvbox-server";
1805
1937
  if (res.statusCode >= 300) {
1806
1938
  const parsed = ApiErrorSchema.safeParse(safeJson(text2) ?? {});
1807
- if (!parsed.success) throw new KvboxError(`${where} answered ${res.statusCode}`);
1939
+ if (!parsed.success) throw new CallError(`${where} answered ${res.statusCode}`, res.statusCode);
1808
1940
  if (this.target.kind === "cloud" && this.target.token !== "") {
1809
- if (res.statusCode === 401) throw new KvboxError("session expired: kvbox login");
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
+ }
1810
1944
  if (res.statusCode === 404 && this.target.org !== void 0 && parsed.data.error === `org ${this.target.org}: not found`) {
1811
1945
  throw new KvboxError(`${parsed.data.error} (you are not in it, or it is gone)`);
1812
1946
  }
1813
1947
  }
1814
- throw new KvboxError(parsed.data.error, res.statusCode === 501 ? 2 : 1);
1948
+ throw new CallError(parsed.data.error, res.statusCode, res.statusCode === 501 ? 2 : 1);
1815
1949
  }
1816
1950
  if (text2 === "") return schema.parse(void 0);
1817
1951
  const json2 = safeJson(text2);
@@ -2152,12 +2286,29 @@ var ServerClient = class {
2152
2286
  login(req) {
2153
2287
  return this.call("POST", "/login", LoginResponseSchema, req);
2154
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
+ }
2155
2296
  logout() {
2156
2297
  return this.call("POST", "/logout", z7.unknown()).then(() => void 0);
2157
2298
  }
2158
2299
  me() {
2159
2300
  return this.call("GET", "/me", MeResponseSchema);
2160
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
+ }
2161
2312
  // ---- orgs (`kvbox org …`) ----
2162
2313
  listOrgs() {
2163
2314
  return this.call("GET", "/orgs", z7.array(OrgMembershipSchema));
@@ -2199,6 +2350,14 @@ var ServerClient = class {
2199
2350
  await this.dispatcher.close();
2200
2351
  }
2201
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);
2202
2361
  function cloudDown(url, code) {
2203
2362
  const host = hostOf(url);
2204
2363
  const hint = host.endsWith("kvbox.sh") ? "check status.kvbox.sh" : "use --local for this machine, or kvbox logout";
@@ -2286,8 +2445,8 @@ async function checkDirect(ep) {
2286
2445
  }
2287
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";
2288
2447
  async function lastErrorLine(logPath, from = 0) {
2289
- const { readFile: readFile9 } = await import("fs/promises");
2290
- const text2 = (await readFile9(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
2448
+ const { readFile: readFile8 } = await import("fs/promises");
2449
+ const text2 = (await readFile8(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
2291
2450
  for (const line of text2.trimEnd().split("\n").slice(-20).reverse()) {
2292
2451
  const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
2293
2452
  if (m?.[1] !== void 0) return m[1];
@@ -2295,7 +2454,7 @@ async function lastErrorLine(logPath, from = 0) {
2295
2454
  return void 0;
2296
2455
  }
2297
2456
  async function startLocalServer(p = paths(), timeoutMs = 5e3) {
2298
- await mkdir2(p.home, { recursive: true });
2457
+ await mkdir3(p.home, { recursive: true });
2299
2458
  if (hasUnitFor(p)) return startUnit(p, timeoutMs);
2300
2459
  const log = openSync(p.serverLog, "a");
2301
2460
  const launcher = serverLauncher();
@@ -2741,14 +2900,14 @@ var connectCommand = new Command2("connect").alias("cn").description("open a she
2741
2900
  } finally {
2742
2901
  await client.close();
2743
2902
  }
2744
- let res = spawnSync2("ssh", [...sshArgs(ep), ...cmdArgs], { stdio: "inherit" });
2903
+ let res = spawnSync3("ssh", [...sshArgs(ep), ...cmdArgs], { stdio: "inherit" });
2745
2904
  if (res.error) throw new KvboxError(`could not run ssh: ${res.error.message}`);
2746
2905
  if (res.status === SSH_FAILED) {
2747
2906
  const again = await clientFor(cmd.optsWithGlobals());
2748
2907
  const retry = await renewAfterRefusal(again, cert, owner).finally(() => again.close());
2749
2908
  if (retry) {
2750
2909
  info("renewed your SSH certificate, trying again\u2026");
2751
- res = spawnSync2("ssh", [...sshArgs(ep), ...cmdArgs], { stdio: "inherit" });
2910
+ res = spawnSync3("ssh", [...sshArgs(ep), ...cmdArgs], { stdio: "inherit" });
2752
2911
  if (res.error) throw new KvboxError(`could not run ssh: ${res.error.message}`);
2753
2912
  }
2754
2913
  }
@@ -3048,8 +3207,8 @@ var linkCommand = new Command8("link").description("let one box reach a port of
3048
3207
  return;
3049
3208
  }
3050
3209
  const fromName = from.slice(from.lastIndexOf("/") + 1);
3051
- const link = box.links?.find((l) => l.port === port && l.from.slice(l.from.lastIndexOf("/") + 1) === fromName);
3052
- const apart = link !== void 0 ? link.from.includes("/") : from.includes("/") && from.split("/")[0] !== slugOf(box.owner);
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);
3053
3212
  const host = apart ? `${box.name}.${slugOf(box.owner)}.kvbox` : `${box.name}.kvbox`;
3054
3213
  info(`${color.green("\u2713")} box ${color.bold(from)} can reach ${color.bold(`${host}:${port}`)}`);
3055
3214
  if (box.status !== "running") info(` box ${shown} is ${box.status}: the link opens when it runs`);
@@ -4007,17 +4166,53 @@ for (const cmd of vmCommand.commands) if (cmd !== proxyCommand && cmd !== hookCo
4007
4166
  var vmAliases = [newCommand, lsCommand, getCommand, connectCommand, execCommand, stopCommand, startCommand, pauseCommand, resumeCommand, hibernateCommand, wakeCommand, rmCommand3, claimCommand];
4008
4167
 
4009
4168
  // src/commands/login.ts
4010
- import { spawnSync as spawnSync3 } from "child_process";
4011
- import { mkdir as mkdir3, readFile as readFile4, writeFile as writeFile3 } from "fs/promises";
4012
- import { hostname as osHostname } from "os";
4169
+ import { hostname as osHostname2 } from "os";
4013
4170
  import { createInterface as createInterface2 } from "readline/promises";
4171
+ import { setTimeout as sleep3 } from "timers/promises";
4014
4172
  import { Writable } from "stream";
4015
4173
  import { Command as Command38 } from "commander";
4016
- 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("-e, --email <email>", "account email (prompted otherwise)").option("--password-stdin", "read the password from the first line of stdin (for scripts)").action(async (urlArg, opts) => {
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) => {
4017
4211
  const url = normalizeUrl(urlArg ?? DEFAULT_CLOUD_URL);
4018
- const creds = await readCredentials(opts);
4019
- const session = await runLogin(url, creds, paths());
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());
4020
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");
4021
4216
  });
4022
4217
  async function readCredentials(opts, io = { stdin: process.stdin, isTTY: process.stdin.isTTY === true }) {
4023
4218
  const noTerminal = () => new KvboxError("stdin is not a terminal: pass --email and --password-stdin");
@@ -4034,7 +4229,7 @@ async function readCredentials(opts, io = { stdin: process.stdin, isTTY: process
4034
4229
  if (password === "") throw new KvboxError("password is empty");
4035
4230
  return { email, password };
4036
4231
  }
4037
- async function runLogin(url, creds, p = paths(), hostname = osHostname()) {
4232
+ async function runLogin(url, creds, p = paths(), hostname = osHostname2()) {
4038
4233
  const publicKey = await ensureSshKey(p, hostname);
4039
4234
  const client = new ServerClient({ kind: "cloud", url, token: "" }, { autoStart: false });
4040
4235
  let res;
@@ -4043,6 +4238,9 @@ async function runLogin(url, creds, p = paths(), hostname = osHostname()) {
4043
4238
  } finally {
4044
4239
  await client.close();
4045
4240
  }
4241
+ return storeLogin(url, res, p);
4242
+ }
4243
+ async function storeLogin(url, res, p) {
4046
4244
  const session = { url, token: res.token, user: res.user.username };
4047
4245
  if (res.sshCert !== void 0 && res.sshCertExpires !== void 0) {
4048
4246
  await writeCert(res.sshCert, p);
@@ -4052,21 +4250,47 @@ async function runLogin(url, creds, p = paths(), hostname = osHostname()) {
4052
4250
  await writeSession(session, p);
4053
4251
  return session;
4054
4252
  }
4055
- async function ensureSshKey(p = paths(), hostname = osHostname()) {
4056
- const pubPath = `${p.sshKey}.pub`;
4057
- const pub = await readFile4(pubPath, "utf8").catch(() => null);
4058
- if (pub !== null) return pub.trim();
4059
- await mkdir3(p.ssh, { recursive: true, mode: 448 });
4060
- const havePrivate = await readFile4(p.sshKey).then(() => true, () => false);
4061
- const args = havePrivate ? ["-y", "-f", p.sshKey] : ["-q", "-t", "ed25519", "-N", "", "-C", `kvbox@${hostname}`, "-f", p.sshKey];
4062
- const res = spawnSync3("ssh-keygen", args, { stdio: ["ignore", "pipe", "pipe"], encoding: "utf8" });
4063
- if (res.error) {
4064
- if (res.error.code === "ENOENT") throw new KvboxError("ssh-keygen not found; install OpenSSH");
4065
- throw new KvboxError(`could not run ssh-keygen: ${res.error.message}`);
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();
4066
4293
  }
4067
- if (res.status !== 0) throw new KvboxError(`ssh-keygen failed: ${res.stderr.trim()}`);
4068
- if (havePrivate) await writeFile3(pubPath, res.stdout.trim() + "\n");
4069
- return (await readFile4(pubPath, "utf8")).trim();
4070
4294
  }
4071
4295
  async function prompt(question, io) {
4072
4296
  const rl = createInterface2({ input: io.input, output: io.output });
@@ -4107,6 +4331,7 @@ var logoutCommand = new Command39("logout").description("log out of the control
4107
4331
  case "cleared":
4108
4332
  info(`logged out of ${hostOf(session?.url ?? "")}`);
4109
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>");
4110
4335
  });
4111
4336
  async function runLogout(p = paths()) {
4112
4337
  let session;
@@ -4132,10 +4357,19 @@ async function runLogout(p = paths()) {
4132
4357
 
4133
4358
  // src/commands/whoami.ts
4134
4359
  import { Command as Command40 } from "commander";
4135
- 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
+ }
4136
4370
  const session = await readSession();
4137
4371
  if (opts.json) {
4138
- 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);
4139
4373
  return;
4140
4374
  }
4141
4375
  process.stdout.write(describeSession(session) + "\n");
@@ -4147,12 +4381,110 @@ function describeSession(session) {
4147
4381
  return lines.join("\n");
4148
4382
  }
4149
4383
 
4150
- // src/commands/snapshots/index.ts
4384
+ // src/commands/key/index.ts
4151
4385
  import { Command as Command44 } from "commander";
4152
4386
 
4153
- // src/commands/snapshots/ls.ts
4387
+ // src/commands/key/create.ts
4154
4388
  import { Command as Command41 } from "commander";
4155
- var lsCommand5 = new Command41("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) => {
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) => {
4156
4488
  const client = await clientFor(cmd.optsWithGlobals());
4157
4489
  try {
4158
4490
  const cloud = client.target.kind === "cloud";
@@ -4183,8 +4515,8 @@ var lsCommand5 = new Command41("ls").description("list snapshots (yours and your
4183
4515
  });
4184
4516
 
4185
4517
  // src/commands/snapshots/new.ts
4186
- import { Command as Command42 } from "commander";
4187
- var newCommand2 = new Command42("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) => {
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) => {
4188
4520
  const client = await clientFor(cmd.optsWithGlobals());
4189
4521
  try {
4190
4522
  const req = { box, name, ...opts.replace ? { replace: true } : {} };
@@ -4197,8 +4529,8 @@ var newCommand2 = new Command42("new").description("freeze a running box (memory
4197
4529
  });
4198
4530
 
4199
4531
  // src/commands/snapshots/rm.ts
4200
- import { Command as Command43 } from "commander";
4201
- var rmCommand4 = new Command43("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) => {
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) => {
4202
4534
  if (!await confirm(`Delete snapshot ${name}?`, opts.yes ?? false)) {
4203
4535
  info("cancelled");
4204
4536
  process.exitCode = 1;
@@ -4214,14 +4546,14 @@ var rmCommand4 = new Command43("rm").description("delete a snapshot (boxes made
4214
4546
  });
4215
4547
 
4216
4548
  // src/commands/snapshots/index.ts
4217
- var snapshotsCommand = new Command44("snapshots").aliases(["snapshot", "snap"]).description("freeze running boxes into snapshots and manage them").addCommand(newCommand2).addCommand(lsCommand5).addCommand(rmCommand4);
4549
+ var snapshotsCommand = new Command48("snapshots").aliases(["snapshot", "snap"]).description("freeze running boxes into snapshots and manage them").addCommand(newCommand2).addCommand(lsCommand6).addCommand(rmCommand5);
4218
4550
  for (const cmd of snapshotsCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
4219
4551
 
4220
4552
  // src/commands/org/index.ts
4221
- import { Command as Command50 } from "commander";
4553
+ import { Command as Command54 } from "commander";
4222
4554
 
4223
4555
  // src/commands/org/ls.ts
4224
- import { Command as Command45 } from "commander";
4556
+ import { Command as Command49 } from "commander";
4225
4557
 
4226
4558
  // src/commands/org/context.ts
4227
4559
  var NOT_LOGGED_IN = "orgs live on the control plane: kvbox login first";
@@ -4241,7 +4573,7 @@ function orgFor(opts, target) {
4241
4573
  }
4242
4574
 
4243
4575
  // src/commands/org/ls.ts
4244
- var lsCommand6 = new Command45("ls").description("list the orgs you belong to and your role in each").option("--json", "print as JSON").action(async (opts, cmd) => {
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) => {
4245
4577
  const client = await cloudClientFor(cmd.optsWithGlobals());
4246
4578
  try {
4247
4579
  const orgs = await client.listOrgs();
@@ -4263,8 +4595,8 @@ function orgRows(orgs) {
4263
4595
  }
4264
4596
 
4265
4597
  // src/commands/org/members.ts
4266
- import { Command as Command46, Option as Option4 } from "commander";
4267
- var lsCommand7 = new Command46("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) => {
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) => {
4268
4600
  const client = await cloudClientFor(cmd.optsWithGlobals());
4269
4601
  try {
4270
4602
  const org = await client.getOrg(orgFor(opts, client.target));
@@ -4278,7 +4610,7 @@ var lsCommand7 = new Command46("ls").description("list an org's members and thei
4278
4610
  await client.close();
4279
4611
  }
4280
4612
  });
4281
- var addCommand2 = new Command46("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) => {
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) => {
4282
4614
  const client = await cloudClientFor(cmd.optsWithGlobals());
4283
4615
  try {
4284
4616
  const slug = orgFor(opts, client.target);
@@ -4288,7 +4620,7 @@ var addCommand2 = new Command46("add").description("add a user to an org (admins
4288
4620
  await client.close();
4289
4621
  }
4290
4622
  });
4291
- var rmCommand5 = new Command46("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) => {
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) => {
4292
4624
  const client = await cloudClientFor(cmd.optsWithGlobals());
4293
4625
  try {
4294
4626
  const slug = orgFor(opts, client.target);
@@ -4304,11 +4636,11 @@ var rmCommand5 = new Command46("rm").description("remove a member (or leave: rem
4304
4636
  await client.close();
4305
4637
  }
4306
4638
  });
4307
- var membersCommand = new Command46("members").description("who is in an org and what they may do").addCommand(lsCommand7).addCommand(addCommand2).addCommand(rmCommand5);
4639
+ var membersCommand = new Command50("members").description("who is in an org and what they may do").addCommand(lsCommand8).addCommand(addCommand2).addCommand(rmCommand6);
4308
4640
 
4309
4641
  // src/commands/org/new.ts
4310
- import { Command as Command47 } from "commander";
4311
- var newCommand3 = new Command47("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) => {
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) => {
4312
4644
  const client = await cloudClientFor(cmd.optsWithGlobals());
4313
4645
  try {
4314
4646
  const org = await client.createOrg({ slug, name: opts.name ?? slug });
@@ -4324,8 +4656,8 @@ var newCommand3 = new Command47("new").description("create an org; you become it
4324
4656
  });
4325
4657
 
4326
4658
  // src/commands/org/rm.ts
4327
- import { Command as Command48 } from "commander";
4328
- var rmCommand6 = new Command48("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) => {
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) => {
4329
4661
  if (!await confirm(`Delete org ${slug}? Its members lose access; its slug stays taken.`, opts.yes ?? false)) {
4330
4662
  info("cancelled");
4331
4663
  process.exitCode = 1;
@@ -4341,8 +4673,8 @@ var rmCommand6 = new Command48("rm").description("delete an org (owners only; re
4341
4673
  });
4342
4674
 
4343
4675
  // src/commands/org/role.ts
4344
- import { Argument, Command as Command49 } from "commander";
4345
- var roleCommand = new Command49("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) => {
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) => {
4346
4678
  const client = await cloudClientFor(cmd.optsWithGlobals());
4347
4679
  try {
4348
4680
  const slug = orgFor(opts, client.target);
@@ -4354,11 +4686,11 @@ var roleCommand = new Command49("role").description("change a member's role (own
4354
4686
  });
4355
4687
 
4356
4688
  // src/commands/org/index.ts
4357
- var orgCommand = new Command50("org").description("orgs: shared slugs that own boxes, with owners, admins and members").addCommand(lsCommand6).addCommand(newCommand3).addCommand(membersCommand).addCommand(roleCommand).addCommand(rmCommand6);
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);
4358
4690
 
4359
4691
  // src/commands/usage.ts
4360
- import { Command as Command51 } from "commander";
4361
- var usageCommand2 = new Command51("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) => {
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) => {
4362
4694
  for (const [name, value] of [
4363
4695
  ["since", opts.since],
4364
4696
  ["until", opts.until]
@@ -4540,8 +4872,8 @@ function userRows(r) {
4540
4872
  }
4541
4873
 
4542
4874
  // src/commands/credit.ts
4543
- import { Command as Command52 } from "commander";
4544
- var creditCommand = new Command52("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) => {
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) => {
4545
4877
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4546
4878
  try {
4547
4879
  if (client.target.kind === "local") throw new KvboxError("credit lives on the control plane: kvbox login first");
@@ -4570,8 +4902,8 @@ function creditRow(b, me2) {
4570
4902
  }
4571
4903
 
4572
4904
  // src/commands/redeem.ts
4573
- import { Command as Command53 } from "commander";
4574
- var redeemCommand = new Command53("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) => {
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) => {
4575
4907
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4576
4908
  try {
4577
4909
  if (client.target.kind === "local") throw new KvboxError("codes are redeemed on the control plane: kvbox login first");
@@ -4589,17 +4921,17 @@ var redeemCommand = new Command53("redeem").description("redeem a promo code for
4589
4921
  });
4590
4922
 
4591
4923
  // src/commands/deploy/index.ts
4592
- import { access as access5, readFile as readFile8 } from "fs/promises";
4924
+ import { access as access5, readFile as readFile7 } from "fs/promises";
4593
4925
  import { basename as basename2, resolve as resolve3 } from "path";
4594
- import { Command as Command54, InvalidArgumentError as InvalidArgumentError2, Option as Option5 } from "commander";
4926
+ import { Command as Command58, InvalidArgumentError as InvalidArgumentError2, Option as Option5 } from "commander";
4595
4927
 
4596
4928
  // src/commands/deploy/config.ts
4597
- import { readFile as readFile6, writeFile as writeFile4 } from "fs/promises";
4929
+ import { readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
4598
4930
  import { isAbsolute, join as join6, normalize, relative as relative2 } from "path";
4599
4931
  import { z as z8 } from "zod";
4600
4932
 
4601
4933
  // src/commands/deploy/templates/docker.ts
4602
- import { readFile as readFile5 } from "fs/promises";
4934
+ import { readFile as readFile4 } from "fs/promises";
4603
4935
  import { join as join2, relative, sep } from "path";
4604
4936
 
4605
4937
  // src/commands/deploy/templates/server.ts
@@ -4725,7 +5057,7 @@ var dockerTemplate = {
4725
5057
  },
4726
5058
  /** No local build: the box does it. The Dockerfile is read for its EXPOSE port only. */
4727
5059
  async build(ctx) {
4728
- const dockerfile = await readFile5(join2(ctx.dir, "Dockerfile"), "utf8").catch(() => void 0);
5060
+ const dockerfile = await readFile4(join2(ctx.dir, "Dockerfile"), "utf8").catch(() => void 0);
4729
5061
  if (dockerfile === void 0) throw new KvboxError(`${ctx.dir}: no Dockerfile; the Docker template builds the image from it`);
4730
5062
  const containerPort = exposedPort(dockerfile);
4731
5063
  if (ctx.context !== void 0 && ctx.context !== ctx.dir) {
@@ -4901,7 +5233,7 @@ var nodeTemplate = {
4901
5233
  };
4902
5234
 
4903
5235
  // src/commands/deploy/templates/react.ts
4904
- import { spawn as spawn4 } from "child_process";
5236
+ import { spawn as spawn5 } from "child_process";
4905
5237
  import { access as access2 } from "fs/promises";
4906
5238
  import { join as join4 } from "path";
4907
5239
  var OUT_DIRS = ["dist", "build"];
@@ -4909,7 +5241,7 @@ async function runBuild(dir, pm) {
4909
5241
  const args = runScript(pm, "build");
4910
5242
  info(`${color.dim("$")} ${pm} ${args.join(" ")}`);
4911
5243
  const status2 = await new Promise((resolve4, reject) => {
4912
- const child = spawn4(pm, args, { cwd: dir, stdio: ["ignore", process.stderr, process.stderr], shell: process.platform === "win32" });
5244
+ const child = spawn5(pm, args, { cwd: dir, stdio: ["ignore", process.stderr, process.stderr], shell: process.platform === "win32" });
4913
5245
  child.once("error", (err) => reject(new KvboxError(`could not run ${pm}: ${err.message}`)));
4914
5246
  child.once("close", (code) => resolve4(code ?? 1));
4915
5247
  });
@@ -5177,7 +5509,7 @@ async function readDeployFile(dir) {
5177
5509
  const path = join6(dir, CONFIG_FILE);
5178
5510
  let raw;
5179
5511
  try {
5180
- raw = await readFile6(path, "utf8");
5512
+ raw = await readFile5(path, "utf8");
5181
5513
  } catch (err) {
5182
5514
  if (err.code === "ENOENT") return void 0;
5183
5515
  throw err;
@@ -5197,7 +5529,7 @@ async function readDeployFile(dir) {
5197
5529
  return stack ? { kind: "stack", config: parsed.data } : { kind: "single", config: parsed.data };
5198
5530
  }
5199
5531
  async function writeConfig(dir, config) {
5200
- await writeFile4(join6(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
5532
+ await writeFile3(join6(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
5201
5533
  }
5202
5534
  function nameFromDir(dirName) {
5203
5535
  const slug = dirName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 12).replace(/-+$/, "");
@@ -5208,7 +5540,7 @@ function subdomainFor(name) {
5208
5540
  }
5209
5541
 
5210
5542
  // src/commands/deploy/ship.ts
5211
- import { spawn as spawn5 } from "child_process";
5543
+ import { spawn as spawn6 } from "child_process";
5212
5544
  import { readdir, stat as stat2 } from "fs/promises";
5213
5545
  import { join as join7 } from "path";
5214
5546
  var IMAGE_TOO_OLD = 3;
@@ -5230,8 +5562,8 @@ async function measure(dir, exclude = []) {
5230
5562
  return total;
5231
5563
  }
5232
5564
  async function ship(ep, dir, remote, exclude = []) {
5233
- const tar = spawn5("tar", ["-cf", "-", ...exclude.map((e) => `--exclude=${e}`), "-C", dir, "."], { stdio: ["ignore", "pipe", "pipe"] });
5234
- const ssh = spawn5("ssh", [...sshArgs(ep), remote], { stdio: ["pipe", "pipe", "pipe"] });
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"] });
5235
5567
  tar.stdout.pipe(ssh.stdin);
5236
5568
  const chunks = [];
5237
5569
  ssh.stdout.on("data", (c2) => chunks.push(c2));
@@ -5259,7 +5591,7 @@ async function ship(ep, dir, remote, exclude = []) {
5259
5591
  return { status: status2, output: Buffer.concat(chunks).toString("utf8") };
5260
5592
  }
5261
5593
  async function run(ep, remote) {
5262
- const ssh = spawn5("ssh", [...sshArgs(ep), remote], { stdio: ["ignore", "pipe", "pipe"] });
5594
+ const ssh = spawn6("ssh", [...sshArgs(ep), remote], { stdio: ["ignore", "pipe", "pipe"] });
5263
5595
  const chunks = [];
5264
5596
  ssh.stdout.on("data", (c2) => chunks.push(c2));
5265
5597
  ssh.stderr.on("data", (c2) => chunks.push(c2));
@@ -5349,11 +5681,11 @@ the app is on box ${ref} but has no address yet: pick another with kvbox deploy
5349
5681
  }
5350
5682
 
5351
5683
  // src/commands/deploy/stack.ts
5352
- import { access as access4, readFile as readFile7 } from "fs/promises";
5684
+ import { access as access4, readFile as readFile6 } from "fs/promises";
5353
5685
  import { basename, join as join8, resolve as resolve2 } from "path";
5354
5686
 
5355
5687
  // src/commands/deploy/postgres.ts
5356
- import { randomBytes } from "crypto";
5688
+ import { randomBytes as randomBytes2 } from "crypto";
5357
5689
  var POSTGRES_USER = "kvbox";
5358
5690
  var POSTGRES_DB = "app";
5359
5691
  var ENV_MISSING = 6;
@@ -5366,7 +5698,7 @@ var DB_WAIT_SEC = 90;
5366
5698
  var AGENT = "/usr/local/sbin/kvbox-agent";
5367
5699
  var ENV_WAIT_SEC = 60;
5368
5700
  function newPassword() {
5369
- return randomBytes(24).toString("hex");
5701
+ return randomBytes2(24).toString("hex");
5370
5702
  }
5371
5703
  function postgresUrl(password, port) {
5372
5704
  return `postgres://${POSTGRES_USER}:${password}@127.0.0.1:${port}/${POSTGRES_DB}`;
@@ -5640,7 +5972,7 @@ async function exposedPorts(dir, stack) {
5640
5972
  const ports = /* @__PURE__ */ new Map();
5641
5973
  for (const [key, s] of Object.entries(stack.services)) {
5642
5974
  if (s.template !== "docker" || s.port !== void 0 || s.dir === void 0) continue;
5643
- const text2 = await readFile7(resolve2(dir, s.dir, "Dockerfile"), "utf8").catch(() => void 0);
5975
+ const text2 = await readFile6(resolve2(dir, s.dir, "Dockerfile"), "utf8").catch(() => void 0);
5644
5976
  const port = text2 !== void 0 ? exposedPort(text2) : void 0;
5645
5977
  if (port !== void 0) ports.set(key, port);
5646
5978
  }
@@ -5848,7 +6180,7 @@ function volumeNameFor(box, taken, account = /* @__PURE__ */ new Set()) {
5848
6180
  }
5849
6181
  async function readPackageJson(dir) {
5850
6182
  try {
5851
- return JSON.parse(await readFile7(join8(dir, "package.json"), "utf8"));
6183
+ return JSON.parse(await readFile6(join8(dir, "package.json"), "utf8"));
5852
6184
  } catch (err) {
5853
6185
  if (err.code === "ENOENT") return void 0;
5854
6186
  throw new KvboxError(`${join8(dir, "package.json")}: ${err.message}`);
@@ -5856,7 +6188,7 @@ async function readPackageJson(dir) {
5856
6188
  }
5857
6189
 
5858
6190
  // src/commands/deploy/index.ts
5859
- var deployCommand = new Command54("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) => {
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) => {
5860
6192
  const dir = resolve3(dirArg ?? ".");
5861
6193
  const pkg = await readPackageJson2(dir);
5862
6194
  const facts = { indexHtml: await exists2(resolve3(dir, "index.html")), dockerfile: await exists2(resolve3(dir, "Dockerfile")) };
@@ -5930,7 +6262,7 @@ function parsePort(v) {
5930
6262
  var exists2 = (path) => access5(path).then(() => true, () => false);
5931
6263
  async function readPackageJson2(dir) {
5932
6264
  try {
5933
- return JSON.parse(await readFile8(resolve3(dir, "package.json"), "utf8"));
6265
+ return JSON.parse(await readFile7(resolve3(dir, "package.json"), "utf8"));
5934
6266
  } catch (err) {
5935
6267
  if (err.code === "ENOENT") return void 0;
5936
6268
  throw new KvboxError(`${resolve3(dir, "package.json")}: ${err.message}`);
@@ -6013,15 +6345,15 @@ async function settle2(dir, pkg, facts, saved, opts, orgFlag, cloud) {
6013
6345
  }
6014
6346
 
6015
6347
  // src/commands/volume/index.ts
6016
- import { Command as Command65 } from "commander";
6348
+ import { Command as Command69 } from "commander";
6017
6349
 
6018
6350
  // src/commands/volume/attach.ts
6019
- import { Command as Command55 } from "commander";
6351
+ import { Command as Command59 } from "commander";
6020
6352
  function describeMount(machine, volume, box) {
6021
6353
  const path = machine.volumes?.find((v) => volume === v.name || volume.endsWith(`/${v.name}`))?.mountPath ?? volumeMountPath(volume.slice(volume.lastIndexOf("/") + 1));
6022
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`;
6023
6355
  }
6024
- var attachCommand = new Command55("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) => {
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) => {
6025
6357
  if (volumeArg === void 0 || boxArg === void 0) askOrUsage("give the volume and the box: kvbox volume attach <volume> <box>");
6026
6358
  const client = await clientFor(cmd.optsWithGlobals());
6027
6359
  try {
@@ -6040,11 +6372,11 @@ var attachCommand = new Command55("attach").description("attach a volume to a bo
6040
6372
  });
6041
6373
 
6042
6374
  // src/commands/volume/backup/index.ts
6043
- import { Command as Command59 } from "commander";
6375
+ import { Command as Command63 } from "commander";
6044
6376
 
6045
6377
  // src/commands/volume/backup/create.ts
6046
- import { Command as Command56 } from "commander";
6047
- var createCommand3 = new Command56("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) => {
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) => {
6048
6380
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
6049
6381
  try {
6050
6382
  requireCloud3(client);
@@ -6069,8 +6401,8 @@ var createCommand3 = new Command56("create").description("back up a volume's dis
6069
6401
  });
6070
6402
 
6071
6403
  // src/commands/volume/backup/ls.ts
6072
- import { Command as Command57 } from "commander";
6073
- var lsCommand8 = new Command57("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) => {
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) => {
6074
6406
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
6075
6407
  try {
6076
6408
  requireCloud3(client);
@@ -6103,8 +6435,8 @@ var lsCommand8 = new Command57("ls").alias("list").description("list volume back
6103
6435
  });
6104
6436
 
6105
6437
  // src/commands/volume/backup/restore.ts
6106
- import { Command as Command58 } from "commander";
6107
- var restoreCommand2 = new Command58("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) => {
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) => {
6108
6440
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
6109
6441
  try {
6110
6442
  requireCloud3(client);
@@ -6127,11 +6459,11 @@ var restoreCommand2 = new Command58("restore").description("put a backup back: t
6127
6459
  });
6128
6460
 
6129
6461
  // src/commands/volume/backup/index.ts
6130
- var backupCommand2 = new Command59("backup").description("back up a volume's disk to the kvbox cloud, list backups, restore one").addCommand(createCommand3).addCommand(lsCommand8).addCommand(restoreCommand2);
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);
6131
6463
  for (const cmd of backupCommand2.commands) cmd.option("--org <slug>", "act in this org (- for your personal volumes)");
6132
6464
 
6133
6465
  // src/commands/volume/create.ts
6134
- import { Command as Command60 } from "commander";
6466
+ import { Command as Command64 } from "commander";
6135
6467
  function parseGib2(text2, label = "--size") {
6136
6468
  const mib = parseMib(text2);
6137
6469
  if (mib === void 0 || mib % 1024 !== 0) throw new KvboxError(`${label} ${text2}: write whole GB, like 50 or 50GB`);
@@ -6147,7 +6479,7 @@ function sizeProblem(answer) {
6147
6479
  return err instanceof KvboxError ? err.message.replace(/^--size \S+: /, "") : String(err);
6148
6480
  }
6149
6481
  }
6150
- var createCommand4 = new Command60("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) => {
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) => {
6151
6483
  const ask = interactive();
6152
6484
  if (nameArg === void 0 || opts.size === void 0) askOrUsage("give the name and the size: kvbox volume create <name> --size <gb> --box <box>");
6153
6485
  const name = nameArg ?? await text("Volume name", { validate: (a) => VOLUME_NAME_RE.test(a) ? void 0 : VOLUME_NAME_RULE });
@@ -6180,8 +6512,8 @@ var createCommand4 = new Command60("create").alias("new").description("create a
6180
6512
  });
6181
6513
 
6182
6514
  // src/commands/volume/detach.ts
6183
- import { Command as Command61 } from "commander";
6184
- var detachCommand = new Command61("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) => {
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) => {
6185
6517
  if (volumeArg === void 0) askOrUsage("give the volume: kvbox volume detach <volume> [box]");
6186
6518
  const client = await clientFor(cmd.optsWithGlobals());
6187
6519
  try {
@@ -6206,8 +6538,8 @@ var detachCommand = new Command61("detach").description("detach a volume from a
6206
6538
  });
6207
6539
 
6208
6540
  // src/commands/volume/grow.ts
6209
- import { Command as Command62 } from "commander";
6210
- var growCommand = new Command62("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) => {
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) => {
6211
6543
  const sizeGib = parseGib2(size, "size");
6212
6544
  const client = await clientFor(cmd.optsWithGlobals());
6213
6545
  try {
@@ -6220,8 +6552,8 @@ var growCommand = new Command62("grow").alias("resize").description("make a volu
6220
6552
  });
6221
6553
 
6222
6554
  // src/commands/volume/ls.ts
6223
- import { Command as Command63 } from "commander";
6224
- var lsCommand9 = new Command63("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) => {
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) => {
6225
6557
  const client = await clientFor(cmd.optsWithGlobals());
6226
6558
  try {
6227
6559
  const cloud = client.target.kind === "cloud";
@@ -6252,8 +6584,8 @@ var lsCommand9 = new Command63("ls").alias("list").description("list volumes: si
6252
6584
  });
6253
6585
 
6254
6586
  // src/commands/volume/rm.ts
6255
- import { Command as Command64 } from "commander";
6256
- var rmCommand7 = new Command64("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) => {
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) => {
6257
6589
  if (!await confirm(`Delete volume ${name} and everything on it?`, opts.yes ?? false)) {
6258
6590
  info("cancelled");
6259
6591
  process.exitCode = 1;
@@ -6269,15 +6601,15 @@ var rmCommand7 = new Command64("rm").alias("remove").description("delete a volum
6269
6601
  });
6270
6602
 
6271
6603
  // src/commands/volume/index.ts
6272
- var volumeCommand = new Command65("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(createCommand4).addCommand(lsCommand9).addCommand(attachCommand).addCommand(detachCommand).addCommand(growCommand).addCommand(rmCommand7);
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);
6273
6605
  for (const cmd of volumeCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal volumes)");
6274
6606
  volumeCommand.addCommand(backupCommand2);
6275
6607
 
6276
6608
  // src/commands/bucket/index.ts
6277
- import { Command as Command75 } from "commander";
6609
+ import { Command as Command79 } from "commander";
6278
6610
 
6279
6611
  // src/commands/bucket/create.ts
6280
- import { Command as Command66 } from "commander";
6612
+ import { Command as Command70 } from "commander";
6281
6613
 
6282
6614
  // src/commands/bucket/shared.ts
6283
6615
  async function bucketClient(cmd) {
@@ -6303,7 +6635,7 @@ function printRows(rows2) {
6303
6635
  }
6304
6636
 
6305
6637
  // src/commands/bucket/create.ts
6306
- var createCommand5 = new Command66("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) => {
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) => {
6307
6639
  const sizeGib = opts.size === void 0 ? void 0 : parseGib2(opts.size);
6308
6640
  const client = await bucketClient(cmd);
6309
6641
  try {
@@ -6323,8 +6655,8 @@ var createCommand5 = new Command66("create").description("make a bucket (the fir
6323
6655
  });
6324
6656
 
6325
6657
  // src/commands/bucket/grow.ts
6326
- import { Command as Command67 } from "commander";
6327
- var growCommand2 = new Command67("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) => {
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) => {
6328
6660
  const sizeGib = parseGib2(size, "size");
6329
6661
  const client = await bucketClient(cmd);
6330
6662
  try {
@@ -6337,8 +6669,8 @@ var growCommand2 = new Command67("grow").description("make your object storage l
6337
6669
  });
6338
6670
 
6339
6671
  // src/commands/bucket/info.ts
6340
- import { Command as Command68 } from "commander";
6341
- var infoCommand = new Command68("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) => {
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) => {
6342
6674
  const client = await bucketClient(cmd);
6343
6675
  try {
6344
6676
  const b = await client.getBucket(name);
@@ -6367,11 +6699,11 @@ with the AWS CLI: aws s3 ls s3://${b.name} --endpoint-url ${b.endpoint}`));
6367
6699
  });
6368
6700
 
6369
6701
  // src/commands/bucket/key/index.ts
6370
- import { Command as Command72 } from "commander";
6702
+ import { Command as Command76 } from "commander";
6371
6703
 
6372
6704
  // src/commands/bucket/key/create.ts
6373
- import { Command as Command69 } from "commander";
6374
- var createCommand6 = new Command69("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) => {
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) => {
6375
6707
  const client = await bucketClient(cmd);
6376
6708
  try {
6377
6709
  const key = await client.createBucketKey(bucket, { ...opts.name !== void 0 ? { name: opts.name } : {}, ...opts.readOnly ? { readOnly: true } : {} });
@@ -6394,8 +6726,8 @@ var createCommand6 = new Command69("create").description("make an access key for
6394
6726
  });
6395
6727
 
6396
6728
  // src/commands/bucket/key/ls.ts
6397
- import { Command as Command70 } from "commander";
6398
- var lsCommand10 = new Command70("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) => {
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) => {
6399
6731
  const client = await bucketClient(cmd);
6400
6732
  try {
6401
6733
  const keys = await client.listBucketKeys(bucket);
@@ -6414,8 +6746,8 @@ var lsCommand10 = new Command70("ls").alias("list").description("list a bucket's
6414
6746
  });
6415
6747
 
6416
6748
  // src/commands/bucket/key/rm.ts
6417
- import { Command as Command71 } from "commander";
6418
- var rmCommand8 = new Command71("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) => {
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) => {
6419
6751
  const client = await bucketClient(cmd);
6420
6752
  try {
6421
6753
  if (!await confirm(`Delete key ${id} of bucket ${bucket}? Whatever uses it stops working.`, opts.yes ?? false)) {
@@ -6431,11 +6763,11 @@ var rmCommand8 = new Command71("rm").alias("remove").description("delete an acce
6431
6763
  });
6432
6764
 
6433
6765
  // src/commands/bucket/key/index.ts
6434
- var keyCommand = new Command72("key").aliases(["keys"]).description("access keys of a bucket: what your app signs in with").addCommand(createCommand6).addCommand(lsCommand10).addCommand(rmCommand8);
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);
6435
6767
 
6436
6768
  // src/commands/bucket/ls.ts
6437
- import { Command as Command73 } from "commander";
6438
- var lsCommand11 = new Command73("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) => {
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) => {
6439
6771
  const client = await bucketClient(cmd);
6440
6772
  try {
6441
6773
  const buckets = await client.listBuckets({ all: opts.all });
@@ -6465,8 +6797,8 @@ var lsCommand11 = new Command73("ls").alias("list").description("list buckets, a
6465
6797
  });
6466
6798
 
6467
6799
  // src/commands/bucket/rm.ts
6468
- import { Command as Command74 } from "commander";
6469
- var rmCommand9 = new Command74("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) => {
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) => {
6470
6802
  const client = await bucketClient(cmd);
6471
6803
  try {
6472
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?`;
@@ -6485,18 +6817,18 @@ var rmCommand9 = new Command74("rm").alias("remove").description("delete an empt
6485
6817
  });
6486
6818
 
6487
6819
  // src/commands/bucket/index.ts
6488
- var bucketCommand = new Command75("bucket").aliases(["buckets"]).description("object storage: S3 buckets for your files, and the access keys your apps use").addCommand(createCommand5).addCommand(lsCommand11).addCommand(infoCommand).addCommand(growCommand2).addCommand(rmCommand9).addCommand(keyCommand);
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);
6489
6821
  var withOrg = (cmd) => cmd.option("--org <slug>", "act in this org (- for your personal buckets)");
6490
6822
  for (const cmd of bucketCommand.commands) {
6491
- if (cmd === keyCommand) cmd.commands.forEach(withOrg);
6823
+ if (cmd === keyCommand2) cmd.commands.forEach(withOrg);
6492
6824
  else withOrg(cmd);
6493
6825
  }
6494
6826
 
6495
6827
  // src/commands/cron/index.ts
6496
- import { Command as Command88 } from "commander";
6828
+ import { Command as Command92 } from "commander";
6497
6829
 
6498
6830
  // src/commands/cron/create.ts
6499
- import { Command as Command76 } from "commander";
6831
+ import { Command as Command80 } from "commander";
6500
6832
 
6501
6833
  // src/commands/cron/shared.ts
6502
6834
  async function cronClient(cmd) {
@@ -6557,7 +6889,7 @@ function printRows2(rows2) {
6557
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>")`);
6558
6890
 
6559
6891
  // src/commands/cron/create.ts
6560
- var createCommand7 = new Command76("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) => {
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) => {
6561
6893
  const client = await cronClient(cmd);
6562
6894
  try {
6563
6895
  const service = await client.createCronService(name);
@@ -6574,8 +6906,8 @@ var createCommand7 = new Command76("create").description("make a cron service: a
6574
6906
  });
6575
6907
 
6576
6908
  // src/commands/cron/info.ts
6577
- import { Command as Command77 } from "commander";
6578
- var infoCommand2 = new Command77("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) => {
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) => {
6579
6911
  const client = await cronClient(cmd);
6580
6912
  try {
6581
6913
  const service = await client.getCronService(name);
@@ -6599,8 +6931,8 @@ var infoCommand2 = new Command77("info").alias("get").description("show a cron s
6599
6931
  });
6600
6932
 
6601
6933
  // src/commands/cron/ls.ts
6602
- import { Command as Command78 } from "commander";
6603
- var lsCommand12 = new Command78("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) => {
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) => {
6604
6936
  const client = await cronClient(cmd);
6605
6937
  try {
6606
6938
  const services = await client.listCronServices({ all: opts.all });
@@ -6620,8 +6952,8 @@ var lsCommand12 = new Command78("ls").alias("list").description("list cron servi
6620
6952
  });
6621
6953
 
6622
6954
  // src/commands/cron/rm.ts
6623
- import { Command as Command79 } from "commander";
6624
- var rmCommand10 = new Command79("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) => {
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) => {
6625
6957
  const client = await cronClient(cmd);
6626
6958
  try {
6627
6959
  if (!await confirm(`Delete cron service ${name}? Its triggers stop firing and their run history is deleted.`, opts.yes ?? false)) {
@@ -6637,10 +6969,10 @@ var rmCommand10 = new Command79("rm").alias("remove").description("delete a cron
6637
6969
  });
6638
6970
 
6639
6971
  // src/commands/cron/trigger/index.ts
6640
- import { Command as Command87 } from "commander";
6972
+ import { Command as Command91 } from "commander";
6641
6973
 
6642
6974
  // src/commands/cron/trigger/add.ts
6643
- import { Command as Command80 } from "commander";
6975
+ import { Command as Command84 } from "commander";
6644
6976
  function portOf(value) {
6645
6977
  const n = Number(value);
6646
6978
  if (!Number.isInteger(n) || n < 1 || n > 65535) throw new KvboxError(`--port ${value}: a port is a number from 1 to 65535`);
@@ -6660,7 +6992,7 @@ function timeoutOf(value) {
6660
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`);
6661
6993
  return sec;
6662
6994
  }
6663
- var addCommand3 = new Command80("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) => {
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) => {
6664
6996
  let action;
6665
6997
  if (opts.run !== void 0) {
6666
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");
@@ -6687,8 +7019,8 @@ var addCommand3 = new Command80("add").description("add a trigger: on a schedule
6687
7019
  });
6688
7020
 
6689
7021
  // src/commands/cron/trigger/ls.ts
6690
- import { Command as Command81 } from "commander";
6691
- var lsCommand13 = new Command81("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) => {
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) => {
6692
7024
  const client = await cronClient(cmd);
6693
7025
  try {
6694
7026
  const triggers = await client.listCronTriggers(service);
@@ -6704,8 +7036,8 @@ var lsCommand13 = new Command81("ls").alias("list").description("list a cron ser
6704
7036
  });
6705
7037
 
6706
7038
  // src/commands/cron/trigger/pause.ts
6707
- import { Command as Command82 } from "commander";
6708
- var pauseCommand2 = new Command82("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) => {
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) => {
6709
7041
  const client = await cronClient(cmd);
6710
7042
  try {
6711
7043
  const trigger = await client.setCronTriggerEnabled(service, id, false);
@@ -6720,8 +7052,8 @@ var pauseCommand2 = new Command82("pause").description("stop a trigger from firi
6720
7052
  });
6721
7053
 
6722
7054
  // src/commands/cron/trigger/resume.ts
6723
- import { Command as Command83 } from "commander";
6724
- var resumeCommand2 = new Command83("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) => {
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) => {
6725
7057
  const client = await cronClient(cmd);
6726
7058
  try {
6727
7059
  const trigger = await client.setCronTriggerEnabled(service, id, true);
@@ -6736,8 +7068,8 @@ var resumeCommand2 = new Command83("resume").description("let a paused trigger f
6736
7068
  });
6737
7069
 
6738
7070
  // src/commands/cron/trigger/rm.ts
6739
- import { Command as Command84 } from "commander";
6740
- var rmCommand11 = new Command84("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) => {
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) => {
6741
7073
  const client = await cronClient(cmd);
6742
7074
  try {
6743
7075
  if (!await confirm(`Delete trigger ${id} of cron service ${service}? Its run history is deleted too.`, opts.yes ?? false)) {
@@ -6753,8 +7085,8 @@ var rmCommand11 = new Command84("rm").alias("remove").description("delete a trig
6753
7085
  });
6754
7086
 
6755
7087
  // src/commands/cron/trigger/run.ts
6756
- import { Command as Command85 } from "commander";
6757
- var runCommand = new Command85("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) => {
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) => {
6758
7090
  const client = await cronClient(cmd);
6759
7091
  try {
6760
7092
  const trigger = await client.runCronTrigger(service, id);
@@ -6770,13 +7102,13 @@ var runCommand = new Command85("run").description("fire a trigger now, once, bes
6770
7102
  });
6771
7103
 
6772
7104
  // src/commands/cron/trigger/runs.ts
6773
- import { Command as Command86 } from "commander";
7105
+ import { Command as Command90 } from "commander";
6774
7106
  function limitOf(value) {
6775
7107
  const n = Number(value);
6776
7108
  if (!Number.isInteger(n) || n < 1) throw new KvboxError(`-n ${value}: a number of runs, 1 or more`);
6777
7109
  return n;
6778
7110
  }
6779
- var runsCommand = new Command86("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) => {
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) => {
6780
7112
  const limit = limitOf(opts.limit);
6781
7113
  const client = await cronClient(cmd);
6782
7114
  try {
@@ -6806,10 +7138,10 @@ var runsCommand = new Command86("runs").aliases(["logs"]).description("show how
6806
7138
  });
6807
7139
 
6808
7140
  // src/commands/cron/trigger/index.ts
6809
- var triggerCommand = new Command87("trigger").aliases(["triggers"]).description("a cron service's triggers: a schedule and the request it sends to a box").addCommand(addCommand3).addCommand(lsCommand13).addCommand(runsCommand).addCommand(runCommand).addCommand(pauseCommand2).addCommand(resumeCommand2).addCommand(rmCommand11);
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);
6810
7142
 
6811
7143
  // src/commands/cron/index.ts
6812
- var cronCommand = new Command88("cron").description("cron: call a box on a schedule, waking it first if it sleeps").addCommand(createCommand7).addCommand(lsCommand12).addCommand(infoCommand2).addCommand(rmCommand10).addCommand(triggerCommand);
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);
6813
7145
  var withOrg2 = (cmd) => cmd.option("--org <slug>", "act in this org (- for your personal cron services)");
6814
7146
  for (const cmd of cronCommand.commands) {
6815
7147
  if (cmd === triggerCommand) cmd.commands.forEach(withOrg2);
@@ -6817,11 +7149,11 @@ for (const cmd of cronCommand.commands) {
6817
7149
  }
6818
7150
 
6819
7151
  // src/commands/managed/kind.ts
6820
- import { Command as Command101 } from "commander";
7152
+ import { Command as Command105 } from "commander";
6821
7153
 
6822
7154
  // src/commands/managed/create.ts
6823
- import { Command as Command90 } from "commander";
6824
- import { setTimeout as sleep3 } from "timers/promises";
7155
+ import { Command as Command94 } from "commander";
7156
+ import { setTimeout as sleep4 } from "timers/promises";
6825
7157
 
6826
7158
  // src/commands/managed/shared.ts
6827
7159
  import "commander";
@@ -6906,8 +7238,8 @@ function parseStorage(text2, flag) {
6906
7238
  // src/commands/managed/create.ts
6907
7239
  var READY_WAIT_MS = 9e4;
6908
7240
  var READY_STEP_MS = 2e3;
6909
- var createCommand8 = (spec) => {
6910
- const command = new Command90("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");
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");
6911
7243
  for (const o of spec.options) command.option(`--${o.name} <${o.arg}>`, o.help);
6912
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) => {
6913
7245
  const options = Object.fromEntries(spec.options.flatMap((o) => typeof opts[o.name] === "string" ? [[o.name, opts[o.name]]] : []));
@@ -6923,7 +7255,7 @@ var createCommand8 = (spec) => {
6923
7255
  const made = await spin(`creating ${spec.title} database ${name}\u2026`, client.createManaged(spec.kind, req));
6924
7256
  const shown = shownName3(made, me(client));
6925
7257
  const ready = await spin(`starting ${spec.title}\u2026`, async () => {
6926
- for (const until2 = Date.now() + READY_WAIT_MS; Date.now() < until2; await sleep3(READY_STEP_MS)) {
7258
+ for (const until2 = Date.now() + READY_WAIT_MS; Date.now() < until2; await sleep4(READY_STEP_MS)) {
6927
7259
  const now = await client.getManaged(spec.kind, shown).catch(() => void 0);
6928
7260
  if (now?.health?.ready && now.health.accepting) return true;
6929
7261
  }
@@ -6948,8 +7280,8 @@ var createCommand8 = (spec) => {
6948
7280
  };
6949
7281
 
6950
7282
  // src/commands/managed/grow.ts
6951
- import { Command as Command91 } from "commander";
6952
- var growCommand3 = (spec) => new Command91("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) => {
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) => {
6953
7285
  const storageGib = parseStorage(size, "size");
6954
7286
  const client = await managedClient(cmd);
6955
7287
  try {
@@ -6962,8 +7294,8 @@ var growCommand3 = (spec) => new Command91("grow").description("give a database
6962
7294
  });
6963
7295
 
6964
7296
  // src/commands/managed/info.ts
6965
- import { Command as Command92 } from "commander";
6966
- var infoCommand3 = (spec) => new Command92("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) => {
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) => {
6967
7299
  const client = await managedClient(cmd);
6968
7300
  try {
6969
7301
  const m = await client.getManaged(spec.kind, name);
@@ -6975,8 +7307,8 @@ var infoCommand3 = (spec) => new Command92("info").alias("get").description("sho
6975
7307
  });
6976
7308
 
6977
7309
  // src/commands/managed/link.ts
6978
- import { Command as Command93 } from "commander";
6979
- var linkCommand2 = (spec) => new Command93("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) => {
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) => {
6980
7312
  const client = await managedClient(cmd);
6981
7313
  try {
6982
7314
  const m = await spin(`linking ${box} to ${name}\u2026`, client.linkManaged(spec.kind, name, box));
@@ -6992,7 +7324,7 @@ var linkCommand2 = (spec) => new Command93("link").description("let a box reach
6992
7324
  });
6993
7325
 
6994
7326
  // src/commands/managed/ls.ts
6995
- import { Command as Command94 } from "commander";
7327
+ import { Command as Command98 } from "commander";
6996
7328
  function listRows(items, user, kindColumn) {
6997
7329
  return items.map((m) => ({
6998
7330
  owner: m.owner === user ? "private" : m.owner,
@@ -7006,7 +7338,7 @@ function listRows(items, user, kindColumn) {
7006
7338
  created: age(m.createdAt)
7007
7339
  }));
7008
7340
  }
7009
- var lsCommand14 = (spec) => new Command94("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) => {
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) => {
7010
7342
  const client = await managedClient(cmd);
7011
7343
  try {
7012
7344
  const items = await client.listManaged(spec?.kind, { all: opts.all });
@@ -7026,8 +7358,8 @@ var lsCommand14 = (spec) => new Command94("ls").alias("list").description(spec ?
7026
7358
  });
7027
7359
 
7028
7360
  // src/commands/managed/password.ts
7029
- import { Command as Command95 } from "commander";
7030
- var passwordCommand = (spec) => new Command95("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) => {
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) => {
7031
7363
  const client = await managedClient(cmd);
7032
7364
  try {
7033
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);
@@ -7043,8 +7375,8 @@ var passwordCommand = (spec) => new Command95("password").description("show a da
7043
7375
  });
7044
7376
 
7045
7377
  // src/commands/managed/public.ts
7046
- import { Command as Command96 } from "commander";
7047
- var publicCommand = (spec) => new Command96("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) => {
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) => {
7048
7380
  if (state !== "on" && state !== "off") throw new KvboxError(`write on or off: kvbox ${spec.command} public ${name} on`);
7049
7381
  const client = await managedClient(cmd);
7050
7382
  try {
@@ -7065,8 +7397,8 @@ var publicCommand = (spec) => new Command96("public").description("open a databa
7065
7397
  });
7066
7398
 
7067
7399
  // src/commands/managed/rm.ts
7068
- import { Command as Command97 } from "commander";
7069
- var rmCommand12 = (spec) => new Command97("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) => {
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) => {
7070
7402
  const client = await managedClient(cmd);
7071
7403
  try {
7072
7404
  if (!await confirm(`Delete database ${name} and all its data? There is no backup.`, opts.yes ?? false)) {
@@ -7082,8 +7414,8 @@ var rmCommand12 = (spec) => new Command97("rm").alias("remove").description("del
7082
7414
  });
7083
7415
 
7084
7416
  // src/commands/managed/start.ts
7085
- import { Command as Command98 } from "commander";
7086
- var startCommand2 = (spec) => new Command98("start").description("run a stopped database again").argument("<db>", "its name").option("--json", "print as JSON").action(async (name, opts, cmd) => {
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) => {
7087
7419
  const client = await managedClient(cmd);
7088
7420
  try {
7089
7421
  const m = await spin(`starting ${name}\u2026`, client.startManaged(spec.kind, name));
@@ -7095,8 +7427,8 @@ var startCommand2 = (spec) => new Command98("start").description("run a stopped
7095
7427
  });
7096
7428
 
7097
7429
  // src/commands/managed/stop.ts
7098
- import { Command as Command99 } from "commander";
7099
- var stopCommand2 = (spec) => new Command99("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) => {
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) => {
7100
7432
  const client = await managedClient(cmd);
7101
7433
  try {
7102
7434
  const m = await spin(`stopping ${name}\u2026`, client.stopManaged(spec.kind, name));
@@ -7108,8 +7440,8 @@ var stopCommand2 = (spec) => new Command99("stop").description("shut a database
7108
7440
  });
7109
7441
 
7110
7442
  // src/commands/managed/unlink.ts
7111
- import { Command as Command100 } from "commander";
7112
- var unlinkCommand2 = (spec) => new Command100("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) => {
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) => {
7113
7445
  const client = await managedClient(cmd);
7114
7446
  try {
7115
7447
  const m = await spin(`unlinking ${box} from ${name}\u2026`, client.unlinkManaged(spec.kind, name, box));
@@ -7122,8 +7454,8 @@ var unlinkCommand2 = (spec) => new Command100("unlink").description("stop a box
7122
7454
 
7123
7455
  // src/commands/managed/kind.ts
7124
7456
  function kindCommand(spec, description) {
7125
- const command = new Command101(spec.command).aliases(spec.aliases).description(description);
7126
- for (const make of [createCommand8, lsCommand14, infoCommand3, passwordCommand, publicCommand, linkCommand2, unlinkCommand2, growCommand3, stopCommand2, startCommand2, rmCommand12]) {
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]) {
7127
7459
  command.addCommand(make(spec).option("--org <slug>", "act in this org (- for your personal databases)"));
7128
7460
  }
7129
7461
  return command;
@@ -7136,14 +7468,14 @@ var pgCommand = kindCommand(POSTGRES2, "managed PostgreSQL: a database kvbox run
7136
7468
  var redisCommand = kindCommand(REDIS, "managed Redis (Valkey): a Redis kvbox runs for you, private until you link a box or make it public");
7137
7469
 
7138
7470
  // src/commands/managed/index.ts
7139
- import { Command as Command102 } from "commander";
7140
- var managedCommand = new Command102("managed").description(`databases kvbox runs for you, every kind together (${KINDS.map((k) => `${k.title}: kvbox ${k.command}`).join(", ")})`).addCommand(lsCommand14().option("--org <slug>", "act in this org (- for your personal databases)"));
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)"));
7141
7473
 
7142
7474
  // src/commands/env/index.ts
7143
- import { Command as Command106 } from "commander";
7475
+ import { Command as Command110 } from "commander";
7144
7476
 
7145
7477
  // src/commands/env/ls.ts
7146
- import { Command as Command103 } from "commander";
7478
+ import { Command as Command107 } from "commander";
7147
7479
 
7148
7480
  // src/commands/env/shared.ts
7149
7481
  function requireCloud4(client) {
@@ -7170,7 +7502,7 @@ function firstBootHint(box, name) {
7170
7502
  }
7171
7503
 
7172
7504
  // src/commands/env/ls.ts
7173
- var lsCommand15 = new Command103("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) => {
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) => {
7174
7506
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
7175
7507
  try {
7176
7508
  if (opts.box !== void 0) {
@@ -7209,8 +7541,8 @@ var lsCommand15 = new Command103("ls").alias("list").description("list the varia
7209
7541
  });
7210
7542
 
7211
7543
  // src/commands/env/rm.ts
7212
- import { Command as Command104 } from "commander";
7213
- var rmCommand13 = new Command104("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) => {
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) => {
7214
7546
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
7215
7547
  try {
7216
7548
  const target = opts.box === void 0 ? void 0 : await findBox2(client, opts.box);
@@ -7247,8 +7579,8 @@ var rmCommand13 = new Command104("rm").alias("remove").description("remove varia
7247
7579
  });
7248
7580
 
7249
7581
  // src/commands/env/set.ts
7250
- import { Command as Command105 } from "commander";
7251
- var setCommand2 = new Command105("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) => {
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) => {
7252
7584
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
7253
7585
  try {
7254
7586
  const owner = opts.box === void 0 ? requireCloud4(client) : void 0;
@@ -7285,14 +7617,14 @@ var setCommand2 = new Command105("set").description("add or change a variable; b
7285
7617
  });
7286
7618
 
7287
7619
  // src/commands/env/index.ts
7288
- var envCommand = new Command106("env").description("environment variables every box of yours gets when it starts (secrets too)").addCommand(lsCommand15, { isDefault: true }).addCommand(setCommand2).addCommand(rmCommand13);
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);
7289
7621
  for (const cmd of envCommand.commands) cmd.option("--org <slug>", "the org's variables instead of yours");
7290
7622
 
7291
7623
  // src/commands/domain/index.ts
7292
- import { Command as Command110 } from "commander";
7624
+ import { Command as Command114 } from "commander";
7293
7625
 
7294
7626
  // src/commands/domain/add.ts
7295
- import { Command as Command107 } from "commander";
7627
+ import { Command as Command111 } from "commander";
7296
7628
 
7297
7629
  // src/commands/domain/shared.ts
7298
7630
  function requireCloud5(client) {
@@ -7312,7 +7644,7 @@ function hostIn(name, zone) {
7312
7644
  }
7313
7645
 
7314
7646
  // src/commands/domain/add.ts
7315
- var addCommand4 = new Command107("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) => {
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) => {
7316
7648
  const domain = assertDomain(domainArg.trim().toLowerCase());
7317
7649
  const port = opts.port === void 0 ? void 0 : parsePorts([opts.port])[0];
7318
7650
  const client = await clientFor(cmd.optsWithGlobals());
@@ -7348,8 +7680,8 @@ kvbox checks every minute; ${domain} is served at ${d.url} once its records are
7348
7680
  });
7349
7681
 
7350
7682
  // src/commands/domain/ls.ts
7351
- import { Command as Command108 } from "commander";
7352
- var lsCommand16 = new Command108("ls").alias("list").description("list your custom domains and whether they are live").option("--json", "print as JSON").action(async (opts, cmd) => {
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) => {
7353
7685
  const client = await clientFor(cmd.optsWithGlobals());
7354
7686
  try {
7355
7687
  requireCloud5(client);
@@ -7378,8 +7710,8 @@ var lsCommand16 = new Command108("ls").alias("list").description("list your cust
7378
7710
  });
7379
7711
 
7380
7712
  // src/commands/domain/rm.ts
7381
- import { Command as Command109 } from "commander";
7382
- var rmCommand14 = new Command109("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) => {
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) => {
7383
7715
  const domain = domainArg.trim().toLowerCase();
7384
7716
  const client = await clientFor(cmd.optsWithGlobals());
7385
7717
  try {
@@ -7400,15 +7732,15 @@ var rmCommand14 = new Command109("rm").alias("remove").description("stop serving
7400
7732
  });
7401
7733
 
7402
7734
  // src/commands/domain/index.ts
7403
- var domainCommand = new Command110("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand4).addCommand(lsCommand16).addCommand(rmCommand14);
7735
+ var domainCommand = new Command114("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand4).addCommand(lsCommand17).addCommand(rmCommand15);
7404
7736
  for (const cmd of domainCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
7405
7737
 
7406
7738
  // src/commands/update.ts
7407
- import { spawn as spawn6 } from "child_process";
7739
+ import { spawn as spawn7 } from "child_process";
7408
7740
  import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
7409
7741
  import { tmpdir } from "os";
7410
7742
  import { join as join9 } from "path";
7411
- import { Command as Command111 } from "commander";
7743
+ import { Command as Command115 } from "commander";
7412
7744
 
7413
7745
  // src/update.ts
7414
7746
  import { mkdirSync, readFileSync as readFileSync3, writeFileSync } from "fs";
@@ -7522,12 +7854,12 @@ async function download(url) {
7522
7854
  }
7523
7855
  function run2(cmd, args) {
7524
7856
  return new Promise((resolve4, reject) => {
7525
- const child = spawn6(cmd, args, { stdio: "inherit" });
7857
+ const child = spawn7(cmd, args, { stdio: "inherit" });
7526
7858
  child.on("error", (err) => reject(new KvboxError(`could not run ${cmd}: ${err.message}`)));
7527
7859
  child.on("exit", (code, signal) => resolve4(code ?? (signal ? 1 : 0)));
7528
7860
  });
7529
7861
  }
7530
- var selfUpdateCommand = new Command111("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
7862
+ var selfUpdateCommand = new Command115("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
7531
7863
  suppressUpdateNotice();
7532
7864
  const inst = installerFor(process.platform, process.env["KVBOX_INSTALL_URL"] || INSTALL_BASE);
7533
7865
  let code;
@@ -7606,6 +7938,7 @@ var HELP_GROUPS = [
7606
7938
  ["login", "log in to the kvbox cloud or your own control plane"],
7607
7939
  ["logout", "log out; commands target this machine again"],
7608
7940
  ["whoami", "show the account and control plane in use"],
7941
+ ["key", "API keys for programs: CI, agents, the SDK"],
7609
7942
  ["org", "shared slugs that own boxes, with owners, admins and members"],
7610
7943
  ["usage", "what your boxes and volumes used, and what it cost"],
7611
7944
  ["credit", "the prepaid credit left on your account and orgs"],
@@ -7653,7 +7986,7 @@ function installRootHelp(program) {
7653
7986
 
7654
7987
  // src/program.ts
7655
7988
  function buildProgram() {
7656
- const program = new Command112("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").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();
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();
7657
7990
  program.addCommand(vmCommand);
7658
7991
  program.addCommand(snapshotsCommand);
7659
7992
  program.addCommand(volumeCommand);
@@ -7667,6 +8000,7 @@ function buildProgram() {
7667
8000
  program.addCommand(loginCommand);
7668
8001
  program.addCommand(logoutCommand);
7669
8002
  program.addCommand(whoamiCommand);
8003
+ program.addCommand(keyCommand);
7670
8004
  program.addCommand(orgCommand);
7671
8005
  program.addCommand(usageCommand2);
7672
8006
  program.addCommand(creditCommand);