@kvbox/server 0.6.1 → 0.6.3

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../shared/src/errors.ts","../src/commands/start.ts","../../shared/src/paths.ts","../src/core/config.ts","../../shared/src/sizes.ts","../../shared/src/usage.ts","../src/core/refs.ts","../src/core/kvm.ts","../src/core/dns.ts","../src/core/state.ts","../src/core/db.ts","../src/core/machines.ts","../../shared/src/duration.ts","../../shared/src/api.ts","../../shared/src/ssh.ts","../src/core/agent.ts","../src/core/env.ts","../../shared/src/env.ts","../src/core/locks.ts","../src/core/log.ts","../src/core/images.ts","../src/core/exec.ts","../src/core/volumes.ts","../../shared/src/capacity.ts","../src/core/capacity.ts","../src/core/backupStore.ts","../src/core/ext4.ts","../src/core/snapshots.ts","../src/core/firecracker.ts","../src/core/network.ts","../src/core/backups.ts","../../shared/src/backup.ts","../src/core/clone.ts","../src/core/storeFetch.ts","../src/core/relay.ts","../../shared/src/relay.ts","../src/core/controlPlane.ts","../../shared/src/country.ts","../src/core/idle.ts","../src/core/relayWatch.ts","../src/daemon.ts","../../shared/src/systemd.ts","../src/socketClient.ts","../src/listen.ts","../../shared/src/names.ts","../src/app.ts","../../shared/src/version.ts","../src/version.ts","../src/caller.ts","../src/core/update.ts","../src/routes/backups.ts","../src/routes/backupStore.ts","../src/routes/boxHttp.ts","../../shared/src/httpHead.ts","../src/routes/capacity.ts","../src/routes/env.ts","../src/routes/machines.ts","../src/core/stats.ts","../src/core/scripts.ts","../src/core/usage.ts","../src/routes/snapshots.ts","../src/routes/ssh.ts","../src/routes/usage.ts","../src/routes/volumes.ts","../src/program.ts","../src/commands/backup/index.ts","../src/commands/backup/setup.ts","../src/commands/backup/output.ts","../src/commands/backup/status.ts","../src/commands/join.ts","../src/commands/leave.ts","../src/commands/logs.ts","../src/commands/net.ts","../src/commands/relay.ts","../src/commands/rename-realm.ts","../src/core/realm.ts","../src/commands/trust-ca.ts","../src/commands/status.ts","../src/commands/stop.ts","../src/index.ts"],"sourcesContent":["/** Errors with an exit code; the entry point prints `message` and exits with `exitCode`. */\nexport class KvboxError extends Error {\n constructor(\n message: string,\n public readonly exitCode: number = 1,\n ) {\n super(message);\n this.name = \"KvboxError\";\n }\n}\n\nexport class NotImplementedError extends KvboxError {\n constructor(what: string) {\n super(`${what}: not implemented yet`, 2);\n this.name = \"NotImplementedError\";\n }\n}\n\n/** The named box/snapshot/host does not exist: HTTP 404, exit 1. */\nexport class NotFoundError extends KvboxError {\n constructor(what: string) {\n super(`${what}: not found`, 1);\n this.name = \"NotFoundError\";\n }\n}\n\n/** The caller is known but the rule says no (an org member outside their role): HTTP 403, exit 1. */\nexport class ForbiddenError extends KvboxError {\n constructor(message: string) {\n super(message, 1);\n this.name = \"ForbiddenError\";\n }\n}\n\n/** A bare name that is in more than one of the caller's orgs (#68); the CLI and the control plane say it the same way. */\nexport class AmbiguousRefError extends KvboxError {\n /** `orgFlag` false: `--org` names something else on this command (a fork's target), so only `slug/name` is offered. */\n constructor(kind: string, name: string, slugs: readonly string[], orgFlag = true) {\n const way = orgFlag ? `--org ${slugs[0]} or ${slugs[0]}/${name}` : `${slugs[0]}/${name}`;\n super(`${kind} ${name} exists in ${slugs.slice(0, -1).join(\", \")} and ${slugs.at(-1)}; say which with ${way}`, 1);\n this.name = \"AmbiguousRefError\";\n }\n}\n","/**\n * kvbox-server start [-d] [--socket <path>] — the daemon. In the foreground (what\n * the systemd unit runs) it serves the kvbox API on $KVBOX_HOME/server.sock and, once joined, answers its\n * control plane over HTTPS; every message is a server.log line (core/log.ts). With `-d` it starts that\n * daemon in the background instead (through systemd where install-server.sh set the unit up) and returns\n * once the socket answers.\n */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { loadConfig } from \"../core/config.js\";\nimport { requireKvm } from \"../core/kvm.js\";\nimport { DNS_RETRY_MS, startDns } from \"../core/dns.js\";\nimport { bootRecovered, pinRunningTaps, settleDeadBoxes } from \"../core/machines.js\";\nimport { clearStagedBackups } from \"../core/backups.js\";\nimport { startBackupStoreWatch } from \"../core/backupStore.js\";\nimport { ensureHostNetwork } from \"../core/network.js\";\nimport { restoreRelay } from \"../core/relay.js\";\nimport { startIdleWatch } from \"../core/idle.js\";\nimport { startRelayWatch } from \"../core/relayWatch.js\";\nimport { log } from \"../core/log.js\";\nimport { refuseSecondDaemon, startDetached } from \"../daemon.js\";\nimport { listen } from \"../listen.js\";\nimport { VERSION } from \"../version.js\";\n\n// Set once the foreground daemon is on its way: its errors are then log lines (server.log), where a\n// subcommand's (start -d included) are plain `error: …` for the terminal.\nlet daemon = false;\nexport const isDaemon = (): boolean => daemon;\n\nexport const startCommand = new Command(\"start\")\n .description(\"run the daemon in the foreground; -d starts it in the background and returns\")\n .option(\"-d, --detach\", \"start the daemon in the background (through systemd when install-server.sh set it up) and return once it answers\")\n .option(\"--socket <path>\", \"socket to listen on (default: $KVBOX_HOME/server.sock)\")\n .action(async (opts: { detach?: boolean; socket?: string }) => {\n if (opts.detach) {\n const started = await startDetached(paths());\n if (started.alreadyRunning !== undefined) {\n console.log(`kvbox-server ${started.alreadyRunning} is already running (pid ${started.pid})`);\n return;\n }\n console.log(`kvbox-server started (pid ${started.pid}), listening on ${started.socketPath}${started.viaUnit ? \" (through systemd)\" : \"\"}`);\n if (started.viaGroup !== undefined) console.log(`started through the ${started.viaGroup} group, which this shell does not have yet (log out and back in to get it)`);\n return;\n }\n // Before anything is touched: settling boxes and clearing staged backups belong to the running one (#159).\n if (opts.socket === undefined) await refuseSecondDaemon(paths());\n daemon = true;\n await requireKvm(); // a daemon without /dev/kvm would only fail at the first kvbox new (#61)\n // Before listening: boxes whose Firecracker died with the host (#29), so a listing cannot get to them first.\n const settled = await settleDeadBoxes(paths());\n // A backup or restore cut short by the restart never finishes: the control plane marks a backup failed.\n await clearStagedBackups(paths()).catch((err: unknown) => log.warn(`staged backups not cleared: ${(err as Error).message}`));\n const { socketPath, https } = await listen(opts.socket ? { socketPath: opts.socket } : {});\n log.info(`kvbox-server ${VERSION} listening on ${socketPath} (pid ${process.pid})`);\n if (https) {\n const cfg = await loadConfig(paths());\n log.info(`control plane ${cfg.controlPlane?.name}: answering on ${https.url}`);\n }\n // The bridge vanishes on host reboot; recreate it. Not fatal: ls/status must still work.\n try {\n const cfg = await loadConfig(paths());\n const state = await ensureHostNetwork(cfg);\n log.info(`host network: bridge ${cfg.bridge} ${state}`);\n await pinRunningTaps(paths());\n } catch (err) {\n log.warn(`host network not ready (${(err as Error).message}); run: kvbox-server net up`);\n }\n // The tunnel's firewall rule goes with the reboot too (#114); the box rules above are re-pinned the same way.\n try {\n const relay = await restoreRelay(paths());\n if (relay) log.info(`relay ${relay.name}: the control plane may reach this host through the tunnel again`);\n } catch (err) {\n log.warn(`the control plane may not reach this host through its relay (${(err as Error).message}); run: kvbox-server relay <join string>`);\n }\n // Box names inside boxes (#97), on the bridge address, so it needs the bridge. Not fatal either: a box\n // whose resolver gets no answer here asks the next one, only <name>.kvbox stops resolving. Without the\n // bridge yet (a box boot recreates it), the bind is tried again until it holds.\n let dnsWarned = false;\n const bindDns = (): void => {\n loadConfig(paths())\n .then(async (cfg) => {\n await startDns({ host: cfg.gateway });\n log.info(`box names: <name>.kvbox answered on ${cfg.gateway}`);\n })\n .catch((err: Error) => {\n if (!dnsWarned) log.warn(`box names (<name>.kvbox) do not resolve yet (${err.message}); retrying`);\n dnsWarned = true;\n setTimeout(bindDns, DNS_RETRY_MS).unref();\n });\n };\n bindDns();\n // A relay tunnel that stops carrying traffic is redialed (#50); idle when the host has no relay.\n startRelayWatch();\n // Boxes with an idle timeout are hibernated once their network goes quiet (#47).\n startIdleWatch();\n // A backup store's Garage is started again after a reboot or a crash; idle when the host is not a store.\n startBackupStoreWatch();\n const recovery = await bootRecovered(settled, paths());\n if (recovery) {\n for (const box of recovery.booted) log.info(`box ${box} was running when it went down; booted it again`);\n for (const box of recovery.leftStopped) log.info(`box ${box} was in standby when it went down; its memory is gone, left stopped`);\n for (const f of recovery.failed) log.warn(`box ${f.box} was running when it went down and did not come back: ${f.error}`);\n }\n });\n","/**\n * Host state layout. The filesystem is the database and `~/.kvbox` is its root.\n * This module is dependency-free so both the CLI (socket path, cli.json)\n * and core (everything else) can use it without crossing the layer boundary.\n *\n * `KVBOX_HOME` overrides the root, mainly for tests.\n */\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport function kvboxHome(): string {\n return process.env[\"KVBOX_HOME\"] ?? join(homedir(), \".kvbox\");\n}\n\nexport function paths(home: string = kvboxHome()) {\n return {\n home,\n config: join(home, \"config.json\"),\n /** The host's ledgers (SQLite via node:sqlite): usage events today. Boxes and snapshots stay files; see server core/db.ts. */\n db: join(home, \"kvbox.db\"),\n serverSock: join(home, \"server.sock\"),\n serverPid: join(home, \"server.pid\"),\n serverLog: join(home, \"server.log\"),\n /**\n * The host's self-update (`POST /update`, the control plane's admin): `update.json` is its state\n * (install-server.sh --update writes it), `update/` holds the downloaded script and its log.\n */\n updateState: join(home, \"update.json\"),\n updateDir: join(home, \"update\"),\n updateScript: join(home, \"update\", \"install-server.sh\"),\n updateLog: join(home, \"update\", \"update.log\"),\n /** The CLI's login to the control plane (`kvbox login`): url, bearer token, user. Mode 600. */\n cli: join(home, \"cli.json\"),\n /** The CLI's last look at npm for a newer @kvbox/cli: `{checkedAt, latest}`, at most once a day (cli update.ts). */\n updateCheck: join(home, \"update-check.json\"),\n ssh: join(home, \"ssh\"),\n sshKey: join(home, \"ssh\", \"id_ed25519\"),\n /** The device key signed by the control plane's CA (#51); ssh loads it by itself next to `-i id_ed25519`. */\n sshCert: join(home, \"ssh\", \"id_ed25519-cert.pub\"),\n /** Host keys of the cloud boxes this laptop connected to, one entry per box (`connect`, #21). */\n sshKnownHosts: join(home, \"ssh\", \"known_hosts\"),\n /** The host's self-signed TLS identity for the control plane (`kvbox-server join`): pinned there by fingerprint. */\n tls: join(home, \"tls\"),\n tlsKey: join(home, \"tls\", \"key.pem\"),\n tlsCert: join(home, \"tls\", \"cert.pem\"),\n /** The host's WireGuard tunnel to its relay (`kvbox-server relay`, #50): the conf net-setup.sh installs for wg-quick. Mode 600. */\n relay: join(home, \"relay\"),\n relayConf: join(home, \"relay\", \"kvbox.conf\"),\n bin: join(home, \"bin\"),\n firecracker: join(home, \"bin\", \"firecracker\"),\n /** Firecracker's snapshot-editor, from the same release: merges a diff snapshot onto a full memory image. */\n snapshotEditor: join(home, \"bin\", \"snapshot-editor\"),\n /** Garage, on a host that is a backup store (`kvbox-server backup setup` downloads it). */\n garage: join(home, \"bin\", \"garage\"),\n /** The store's Garage as this host runs it: its configuration, pid and log. The data is on the disk the operator named. */\n backupStore: {\n dir: join(home, \"backup-store\"),\n conf: join(home, \"backup-store\", \"garage.toml\"),\n pid: join(home, \"backup-store\", \"garage.pid\"),\n log: join(home, \"backup-store\", \"garage.log\"),\n },\n assets: join(home, \"assets\"),\n kernel: join(home, \"assets\", \"vmlinux\"),\n /** Symlink to the current base image, assets/rootfs-<version>.ext4; boxes keep using the version they were made from. */\n rootfs: join(home, \"assets\", \"rootfs.ext4\"),\n baseImage: (version: string) => join(home, \"assets\", `rootfs-${version}.ext4`),\n /**\n * Every other image (#87), one dir each so nothing collides with the base's `rootfs-*.ext4`:\n * assets/images/<image>/rootfs-<version>.ext4, and rootfs.ext4 there the symlink to its current one.\n */\n images: join(home, \"assets\", \"images\"),\n image: (image: string) => ({\n dir: join(home, \"assets\", \"images\", image),\n rootfs: join(home, \"assets\", \"images\", image, \"rootfs.ext4\"),\n version: (version: string) => join(home, \"assets\", \"images\", image, `rootfs-${version}.ext4`),\n }),\n machines: join(home, \"machines\"),\n snapshots: join(home, \"snapshots\"),\n /** Boxes and snapshots are filed by owner: machines/<owner>/<name>. The owner is part of a box's identity. */\n ownerMachines: (owner: string) => join(home, \"machines\", owner),\n ownerSnapshots: (owner: string) => join(home, \"snapshots\", owner),\n machine: (owner: string, name: string) => {\n const dir = join(home, \"machines\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n /** The box's own environment variables (#87), merged over its owner's at boot. Mode 600: values in the clear. */\n env: join(dir, \"env.json\"),\n /** The box's writable layer, stacked on the read-only base image inside the guest. */\n overlay: join(dir, \"overlay.ext4\"),\n /** A restore's disk while it downloads (a backup's chunks), renamed over `overlay` once complete. */\n restoring: join(dir, \"overlay.ext4.restore\"),\n /**\n * The box's memory as of its last snapshot (a hard link to that snapshot's `mem`, never modified).\n * The next snapshot is a diff of the pages dirtied since, merged onto this. Absent after a boot.\n */\n memBase: join(dir, \"mem.base\"),\n /** `kvbox vm fork` (#79): the source's VM state, captured here and gone once the box runs. Its memory is `memBase`. */\n forkVmstate: join(dir, \"fork.vmstate\"),\n /** `kvbox hibernate`: the box's memory image and VM state while it is hibernated; gone again after `wake` or `stop`. */\n hibernateDir: join(dir, \"hibernate\"),\n hibernateVmstate: join(dir, \"hibernate\", \"vmstate\"),\n hibernateMem: join(dir, \"hibernate\", \"mem\"),\n sock: join(dir, \"fc.sock\"),\n /** Firecracker's vsock endpoint: the host connects here to reach kvbox-agent inside the box (core/agent.ts). */\n vsock: join(dir, \"vsock.sock\"),\n log: join(dir, \"fc.log\"),\n /**\n * An attached volume's drive as Firecracker sees it (#52): a symlink in the box dir to the volume's\n * disk, given to Firecracker by its relative name (`volumeDriveRel`), so a snapshot's vmstate names\n * it relative to whichever box dir it is restored into. There it is a same-size empty placeholder.\n */\n volumeDrive: (volume: string) => join(dir, volumeDriveRel(volume)),\n };\n },\n /** Volumes are filed like boxes, by owner: volumes/<owner>/<name> (#52). */\n volumes: join(home, \"volumes\"),\n ownerVolumes: (owner: string) => join(home, \"volumes\", owner),\n volume: (owner: string, name: string) => {\n const dir = join(home, \"volumes\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n /** The volume itself: a sparse ext4 the guest sees as a whole disk. */\n disk: join(dir, \"disk.ext4\"),\n /** A restore's disk while it downloads (a backup's chunks), renamed over `disk` once complete. */\n restoring: join(dir, \"disk.ext4.restore\"),\n };\n },\n /** Each owner's environment variables as the control plane last sent them (#88): env/<owner>.json, mode 600. */\n env: join(home, \"env\"),\n ownerEnv: (owner: string) => join(home, \"env\", `${owner}.json`),\n /**\n * Backups in progress (decision \"Backups: encrypted 4 MiB chunks in object storage\"): backups/<id>/ holds the\n * copy of the box's disk being uploaded and its chunk list, gone once the upload ends. Nothing here outlives\n * a daemon restart.\n */\n backups: join(home, \"backups\"),\n backup: (id: string) => {\n const dir = join(home, \"backups\", id);\n return { dir, disk: join(dir, \"disk.ext4\"), chunks: join(dir, \"chunks.json\") };\n },\n snapshot: (owner: string, name: string) => {\n const dir = join(home, \"snapshots\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n vmstate: join(dir, \"vmstate\"),\n mem: join(dir, \"mem\"),\n /** The box's own environment variables when it was taken (#87); a restore starts with them. */\n env: join(dir, \"env.json\"),\n /** Copy of the box's overlay at the moment of the snapshot; the base image is referenced by version in meta.json. */\n overlay: join(dir, \"overlay.ext4\"),\n };\n },\n } as const;\n}\n\nexport type Paths = ReturnType<typeof paths>;\n\n/** The file name of a volume's drive inside a box dir (relative: how Firecracker is given it). */\nexport function volumeDriveRel(volume: string): string {\n return `volume-${volume}.ext4`;\n}\n\n/** Where a volume is mounted inside the box (the image's kvbox-volumes.service, by label). */\nexport function volumeMountPath(volume: string): string {\n return `/mnt/${volume}`;\n}\n","/** `~/.kvbox/config.json`: asset paths, subnet, default size, owner. Written with defaults on first run. */\nimport { chmod, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { DEFAULT_SIZE, SIZE_NAMES } from \"@kvbox/shared/sizes\";\nimport { PricingSchema } from \"@kvbox/shared/usage\";\nimport { LOCAL_OWNER_RE, REALM_RE, localOwner } from \"./refs.js\";\n\n/** What an hour of each resource costs, for `kvbox vm usage`'s estimated cost. Absent by default: no cost row. */\nexport { PricingSchema, type Pricing } from \"@kvbox/shared/usage\";\n\n/** The control plane this host joined (`kvbox-server join`, #18): where it is, what it calls itself, and the secret it presents. */\nexport const ControlPlaneSchema = z.object({\n url: z.string().url(),\n /** The realm name: boxes the control plane creates are owned by `<user>@<name>`, a directory name on disk. */\n name: z.string().regex(REALM_RE),\n /** Minted at join; every HTTPS call from the control plane carries it as a bearer. */\n secret: z.string().min(1),\n /** The address the control plane reaches this host at. */\n advertise: z.string().min(1),\n port: z.number().int().positive().default(7777),\n});\nexport type ControlPlane = z.infer<typeof ControlPlaneSchema>;\n\n/**\n * The relay this host reaches the internet through (`kvbox-server relay`, #50): a public VM that owns\n * `publicIp` and forwards it down a WireGuard tunnel to `tunnelIp`. The tunnel's private key is not\n * here: it lives in the wg-quick conf under relay/. `join` advertises `publicIp` by default.\n */\nexport const RelaySchema = z.object({\n name: z.string().min(1),\n publicIp: z.string().min(1),\n tunnelIp: z.string().min(1),\n /** `<relay-ip>:<port>` the tunnel dials. */\n endpoint: z.string().min(1),\n});\nexport type Relay = z.infer<typeof RelaySchema>;\n\n/**\n * This host as a backup store (`kvbox-server backup setup`, core/backupStore.ts): where Garage keeps its\n * data, and the one S3 key of its bucket, which the control plane holds too and signs chunk URLs with.\n */\nexport const BackupStoreSchema = z.object({\n /** A directory on the disk bought for backups. */\n path: z.string().min(1),\n bucket: z.string().min(1),\n region: z.string().min(1),\n accessKey: z.string().min(1),\n secretKey: z.string().min(1),\n /** Whether the control plane took the store; false after a setup that could not reach it. */\n registered: z.boolean().default(false),\n});\nexport type BackupStore = z.infer<typeof BackupStoreSchema>;\n\nexport const ConfigSchema = z.object({\n kernel: z.string(),\n rootfs: z.string(),\n firecracker: z.string(),\n snapshotEditor: z.string().optional(), // default: bin/snapshot-editor next to firecracker\n bridge: z.string().default(\"kvbox0\"),\n subnet: z.string().default(\"172.30.0.0/24\"),\n gateway: z.string().default(\"172.30.0.1\"),\n defaultSize: z.enum(SIZE_NAMES as [string, ...string[]]).default(DEFAULT_SIZE),\n /** Who boxes made over the local socket belong to: the Unix user running the server unless set here. No `@`, no `/`. */\n owner: z.string().regex(LOCAL_OWNER_RE, \"owner: letters, digits, '.', '_', '-'; no '@' or '/'\").default(localOwner),\n pricing: PricingSchema.optional(),\n /** What a new box gets when `new` does not say (#47): seconds without network traffic before it is hibernated; 0: never. */\n autoHibernateSec: z.number().int().min(0).default(0),\n /**\n * GiB of disk `kvbox volume create` leaves free for the boxes' overlays and snapshots (#52): a volume is\n * refused when it could not fill up with that much still free. 0 only on a host whose disk is for tests.\n */\n volumeHeadroomGib: z.number().int().min(0).default(20),\n /** Absent until the host joins a control plane; then the server also listens on HTTPS. */\n controlPlane: ControlPlaneSchema.optional(),\n /** Absent unless the host sits behind a relay. */\n relay: RelaySchema.optional(),\n /** Absent unless the host is a backup store. */\n backupStore: BackupStoreSchema.optional(),\n});\nexport type Config = z.infer<typeof ConfigSchema>;\n\n/** Write config.json back, whole or not at all. Mode 600: once joined it holds the host's secret. */\nexport async function saveConfig(cfg: Config, p: Paths = paths()): Promise<void> {\n const parsed = ConfigSchema.parse(cfg);\n const tmp = `${p.config}.tmp`;\n await writeFile(tmp, JSON.stringify(parsed, null, 2) + \"\\n\", { mode: 0o600 });\n await chmod(tmp, 0o600); // writeFile's mode applies to a new file only\n await rename(tmp, p.config);\n}\n\nexport function defaultConfig(p: Paths = paths()): Config {\n return ConfigSchema.parse({\n kernel: p.kernel,\n rootfs: p.rootfs,\n firecracker: p.firecracker,\n snapshotEditor: p.snapshotEditor,\n owner: localOwner(),\n });\n}\n\nexport async function loadConfig(p: Paths = paths()): Promise<Config> {\n try {\n const raw = await readFile(p.config, \"utf8\");\n return ConfigSchema.parse(JSON.parse(raw));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n const cfg = defaultConfig(p);\n await writeFile(p.config, JSON.stringify(cfg, null, 2) + \"\\n\");\n return cfg;\n }\n throw err;\n }\n}\n","/**\n * Fixed box sizes. Firecracker backs guest memory lazily and the disk is a sparse overlay on the\n * shared base image, so a box only costs what the guest actually touches.\n */\nexport const SIZES = {\n xs: { vcpu: 1, memMib: 2048, diskGib: 8 },\n s: { vcpu: 2, memMib: 4096, diskGib: 8 },\n m: { vcpu: 4, memMib: 8192, diskGib: 16 },\n l: { vcpu: 8, memMib: 16384, diskGib: 32 },\n} as const;\n\nexport type SizeName = keyof typeof SIZES;\nexport const SIZE_NAMES = Object.keys(SIZES) as SizeName[];\nexport const DEFAULT_SIZE: SizeName = \"s\";\n\nexport function isSizeName(value: string): value is SizeName {\n return value in SIZES;\n}\n\n/**\n * \"16GB\", \"16G\", \"16\", \"4096MB\", \"4096M\", \"0.5GB\" -> MiB. A bare number is GB: that is how\n * people say it (\"16gb\", \"4 vcpu 16gb\"). Returns undefined when it is not a size.\n */\nexport function parseMib(text: string): number | undefined {\n const m = /^\\s*(\\d+(?:\\.\\d+)?)\\s*([gm]i?b?)?\\s*$/i.exec(text);\n if (!m) return undefined;\n const n = Number(m[1]);\n const unit = (m[2] ?? \"g\").toLowerCase();\n const mib = unit.startsWith(\"m\") ? n : n * 1024;\n return Number.isInteger(mib) && mib > 0 ? mib : undefined;\n}\n","/**\n * Summing a box's usage ledger: one pure function over its state-change rows, used by the host\n * (`kvbox vm usage`, `GET /usage`) and by the control plane over the rows it pulled (#42). A row\n * opens an interval that lasts until the next row; the sizes ride on every row so a rescale\n * changes the rate from that moment on. Pricing is per resource-hour (decision \"Usage is priced\n * per resource-hour\").\n */\nimport { z } from \"zod\";\nimport type { BoxStatus, BoxUsage, UsageDay, UsageDayItem, VolumeUsage } from \"./api.js\";\n\nexport type UsageState = \"running\" | \"standby\" | \"hibernated\" | \"stopped\";\n\n/** One state change of a box. */\nexport interface UsageEvent {\n at: string;\n state: UsageState;\n vcpu: number;\n memMib: number;\n diskGib: number;\n /** What made it: new, start, stop, pause, resume, hibernate, wake, rescale, update, rm, server (a stop the server did not see). */\n by: string;\n}\n\n/**\n * What an hour of each resource costs. A volume (#91) is an hour of its existence plus an hour of each\n * GiB of its size; a price list from before volumes charges nothing for them. A box's own disk is billed\n * only beyond `diskIncludedGib` (decision \"8 GB of box disk included\"): `diskGibHours` counts what is above it.\n */\nexport const PricingSchema = z.object({\n currency: z.string().min(1),\n vcpuHour: z.number().nonnegative(),\n ramGibHour: z.number().nonnegative(),\n diskGibHour: z.number().nonnegative(),\n volumeHour: z.number().nonnegative().default(0),\n volumeGibHour: z.number().nonnegative().default(0),\n diskIncludedGib: z.number().int().nonnegative().default(0),\n /**\n * Object storage (#182): an hour of a slug's storage existing, whatever it holds, which covers its\n * hidden box and the first `storageIncludedGib` of its size; each GiB above that is `storageGibHour`.\n * A price list from before object storage charges nothing for it.\n */\n storageHour: z.number().nonnegative().default(0),\n storageGibHour: z.number().nonnegative().default(0),\n storageIncludedGib: z.number().int().nonnegative().default(0),\n});\nexport type Pricing = z.infer<typeof PricingSchema>;\n\n/**\n * `GET /pricing` on the control plane: the price list, and the credit a user's first saved card adds\n * (`KVBOX_CLOUD_WELCOME_CREDIT`, 0 for none), which the web app's activation page shows.\n */\nexport const PriceListSchema = PricingSchema.extend({ welcomeCredit: z.number().nonnegative() });\nexport type PriceList = z.infer<typeof PriceListSchema>;\n\nexport interface UsageWindow {\n from: string;\n to: string;\n pricing?: Pricing | undefined;\n}\n\nexport interface UsageTotals {\n seconds: Record<UsageState, number>;\n vcpuHours: number;\n ramGibHours: number;\n diskGibHours: number;\n cost?: { amount: number; currency: string };\n /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */\n estimatedStops: number;\n /** The first recorded moment, null when nothing is recorded. */\n historyFrom: string | null;\n}\n\nconst HOUR_MS = 3_600_000;\n\nexport const round = (n: number, places: number) => Math.round(n * 10 ** places) / 10 ** places;\n\n/**\n * Each event opens an interval that lasts until the next one (or `to`); intervals are clipped to the\n * window, so the event before `from` supplies the state the window starts in. Time before the first\n * event belongs to no state: it was never recorded. Running hours earn vCPU and RAM; standby hours\n * earn RAM (the memory is still held) but no vCPU; every hour the box exists earns disk (its overlay\n * is there while it is hibernated or stopped too), the GiB above the price list's `diskIncludedGib`\n * only, interval by interval (a rescale moves it). A repeated state continues it.\n */\nexport function computeUsage(events: readonly UsageEvent[], w: UsageWindow): UsageTotals {\n const sorted = [...events].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const from = Date.parse(w.from);\n const to = Date.parse(w.to);\n const ms: Record<UsageState, number> = { running: 0, standby: 0, hibernated: 0, stopped: 0 };\n let vcpuHours = 0;\n let ramGibHours = 0;\n let diskGibHours = 0;\n const included = w.pricing?.diskIncludedGib ?? 0;\n sorted.forEach((e, i) => {\n const start = Math.max(Date.parse(e.at), from);\n const next = sorted[i + 1];\n const end = Math.min(next === undefined ? to : Date.parse(next.at), to);\n if (end <= start) return;\n const h = (end - start) / HOUR_MS;\n ms[e.state] += end - start;\n if (e.state === \"running\") vcpuHours += h * e.vcpu;\n if (e.state === \"running\" || e.state === \"standby\") ramGibHours += (h * e.memMib) / 1024;\n diskGibHours += h * Math.max(0, e.diskGib - included);\n });\n const totals: UsageTotals = {\n seconds: {\n running: Math.round(ms.running / 1000),\n standby: Math.round(ms.standby / 1000),\n hibernated: Math.round(ms.hibernated / 1000),\n stopped: Math.round(ms.stopped / 1000),\n },\n vcpuHours: round(vcpuHours, 3),\n ramGibHours: round(ramGibHours, 3),\n diskGibHours: round(diskGibHours, 3),\n // Inside the window only: rows may be dated after `to` (a ledger counted up to its last pull, #172).\n estimatedStops: sorted.filter((e) => e.state === \"stopped\" && e.by === \"server\" && e.at >= w.from && e.at < w.to).length,\n historyFrom: sorted[0]?.at ?? null,\n };\n if (w.pricing !== undefined) totals.cost = { amount: round(costOf(totals, w.pricing), 4), currency: w.pricing.currency };\n return totals;\n}\n\n/** The price of a set of resource-hours; totals over several boxes are summed the same way. */\nexport function costOf(t: Pick<UsageTotals, \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">, pricing: Pricing): number {\n return t.vcpuHours * pricing.vcpuHour + t.ramGibHours * pricing.ramGibHour + t.diskGibHours * pricing.diskGibHour;\n}\n\n/** Add up several boxes' totals (hours and seconds; the cost is recomputed from the hours when priced). */\nexport function sumUsage(items: readonly Pick<UsageTotals, \"seconds\" | \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">[], pricing?: Pricing): Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> {\n const sum: Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> = {\n seconds: { running: 0, standby: 0, hibernated: 0, stopped: 0 },\n vcpuHours: 0,\n ramGibHours: 0,\n diskGibHours: 0,\n };\n for (const t of items) {\n for (const s of Object.keys(sum.seconds) as UsageState[]) sum.seconds[s] += t.seconds[s];\n sum.vcpuHours += t.vcpuHours;\n sum.ramGibHours += t.ramGibHours;\n sum.diskGibHours += t.diskGibHours;\n }\n sum.vcpuHours = round(sum.vcpuHours, 3);\n sum.ramGibHours = round(sum.ramGibHours, 3);\n sum.diskGibHours = round(sum.diskGibHours, 3);\n if (pricing !== undefined) sum.cost = { amount: round(costOf(sum, pricing), 4), currency: pricing.currency };\n return sum;\n}\n\n/**\n * The window a `GET /usage` call asks for: `since` and `until` as the user wrote them (any Date.parse\n * form), defaulting to the start of the current calendar month (UTC, what a bill covers) and now.\n */\nexport function usageWindow(since: string | undefined, until: string | undefined, now = new Date()): { from: string; to: string } {\n const parse = (name: string, value: string): string => {\n const t = Date.parse(value);\n if (Number.isNaN(t)) throw new Error(`${name}: \"${value}\" is not a date; write it like 2026-10-19 or 2026-10-19T08:00:00Z`);\n return new Date(t).toISOString();\n };\n const from = since === undefined ? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString() : parse(\"since\", since);\n const to = until === undefined ? now.toISOString() : parse(\"until\", until);\n return { from, to };\n}\n\n/** A ledger row as the host stores it: the event plus whose box it is. */\nexport interface LedgerRow extends UsageEvent {\n /** The host ledger the row came from, when rows of several hosts are mixed: box ids are only unique within one. */\n ledger?: string;\n boxId: string;\n owner: string;\n name: string;\n}\n\n/**\n * Rows of many boxes → one `BoxUsage` per box id, in owner/name order: the report both the host\n * (`GET /usage`) and the control plane build. A box's `rm` row ends its time: nothing accrues after\n * it, and a box gone before the window opened (or made after it closed) is left out. `live` says what\n * a box that still exists is doing now; one not in it reads its state off its last row, `removed`\n * when that row is the `rm`. A name removed and made again is two boxes (two ids); rows carrying a\n * `ledger` are grouped by ledger and box id, so two hosts' boxes never merge.\n */\nexport function groupUsage(\n rows: readonly LedgerRow[],\n window: { from: string; to: string },\n pricing: Pricing | undefined,\n live: ReadonlyMap<string, BoxStatus> = new Map(),\n): BoxUsage[] {\n const byBox = new Map<string, LedgerRow[]>();\n for (const r of rows) {\n const key = r.ledger === undefined ? r.boxId : `${r.ledger}:${r.boxId}`;\n const list = byBox.get(key);\n if (list === undefined) byBox.set(key, [r]);\n else list.push(r);\n }\n const out: BoxUsage[] = [];\n for (const events of byBox.values()) {\n events.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const first = events[0]!;\n const last = events[events.length - 1]!;\n const id = last.boxId;\n const removed = last.by === \"rm\" && !live.has(id);\n const to = removed && last.at < window.to ? last.at : window.to;\n if (first.at >= to || (removed && last.at <= window.from)) continue;\n const totals = computeUsage(events, { from: window.from, to, pricing });\n const status: BoxUsage[\"status\"] = live.get(id) ?? (removed ? \"removed\" : last.state);\n out.push({ id, name: last.name, owner: last.owner, status, ...totals });\n }\n return out.sort(usageOrder);\n}\n\n/** The order `groupUsage` returns boxes in: owner, name, then the older of a name made twice first. */\nexport const usageOrder = (a: Pick<BoxUsage, \"owner\" | \"name\" | \"historyFrom\">, b: Pick<BoxUsage, \"owner\" | \"name\" | \"historyFrom\">): number =>\n a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name) || (a.historyFrom ?? \"\").localeCompare(b.historyFrom ?? \"\");\n\n// ---- volumes (#91) -------------------------------------------------------------------------------\n\n/** One change of a volume: made, resized, or removed. The size rides on every row like a box's. */\nexport interface VolumeEvent {\n at: string;\n sizeGib: number;\n by: \"create\" | \"resize\" | \"rm\";\n}\n\n/** A volume ledger row as the host stores it: the event plus whose volume it is. */\nexport interface VolumeLedgerRow extends VolumeEvent {\n /** The host ledger the row came from, when rows of several hosts are mixed: volume ids are only unique within one. */\n ledger?: string;\n volumeId: string;\n owner: string;\n name: string;\n}\n\nexport interface VolumeTotals {\n volumeHours: number;\n volumeGibHours: number;\n cost?: { amount: number; currency: string };\n}\n\n/**\n * A volume costs for every hour it exists, whatever it holds and whether a box has it: each row opens\n * an interval that lasts until the next one (or `to`), the `rm` row ends the time, intervals are clipped\n * to the window. The GiB-hours are of the size, a reservation on the host's disk.\n */\nexport function computeVolumeUsage(events: readonly VolumeEvent[], w: UsageWindow): VolumeTotals {\n const sorted = [...events].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const from = Date.parse(w.from);\n const to = Date.parse(w.to);\n let hours = 0;\n let gibHours = 0;\n sorted.forEach((e, i) => {\n if (e.by === \"rm\") return;\n const start = Math.max(Date.parse(e.at), from);\n const next = sorted[i + 1];\n const end = Math.min(next === undefined ? to : Date.parse(next.at), to);\n if (end <= start) return;\n const h = (end - start) / HOUR_MS;\n hours += h;\n gibHours += h * e.sizeGib;\n });\n const totals: VolumeTotals = { volumeHours: round(hours, 3), volumeGibHours: round(gibHours, 3) };\n if (w.pricing !== undefined) totals.cost = { amount: round(volumeCostOf(totals, w.pricing), 4), currency: w.pricing.currency };\n return totals;\n}\n\nexport function volumeCostOf(t: Pick<VolumeTotals, \"volumeHours\" | \"volumeGibHours\">, pricing: Pricing): number {\n return t.volumeHours * pricing.volumeHour + t.volumeGibHours * pricing.volumeGibHour;\n}\n\n/**\n * Rows of many volumes → one `VolumeUsage` per volume id, like `groupUsage`: a volume whose `rm` row is\n * before the window, or whose first row is after it, is left out; a name removed and made again is two.\n */\nexport function groupVolumeUsage(rows: readonly VolumeLedgerRow[], window: { from: string; to: string }, pricing: Pricing | undefined): VolumeUsage[] {\n const byVolume = new Map<string, VolumeLedgerRow[]>();\n for (const r of rows) {\n const key = r.ledger === undefined ? r.volumeId : `${r.ledger}:${r.volumeId}`;\n const list = byVolume.get(key);\n if (list === undefined) byVolume.set(key, [r]);\n else list.push(r);\n }\n const out: VolumeUsage[] = [];\n for (const events of byVolume.values()) {\n events.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const first = events[0]!;\n const last = events[events.length - 1]!;\n const removed = last.by === \"rm\";\n const to = removed && last.at < window.to ? last.at : window.to;\n if (first.at >= to || (removed && last.at <= window.from)) continue;\n const totals = computeVolumeUsage(events, { from: window.from, to, pricing });\n out.push({ id: last.volumeId, name: last.name, owner: last.owner, sizeGib: last.sizeGib, status: removed ? \"removed\" : \"present\", ...totals, historyFrom: first.at });\n }\n return out.sort(usageOrder);\n}\n\n/**\n * Object storage's volume rows as `computeVolumeUsage` prices them (#182): the storage prices in the\n * volume prices' place, and each row's size cut to what is billed beyond the included GiB. The hours\n * that come out are the storage's, the GiB-hours those of the billed GiB only.\n */\nexport function storagePricing(pricing: Pricing): Pricing {\n return { ...pricing, volumeHour: pricing.storageHour, volumeGibHour: pricing.storageGibHour };\n}\nexport function billedStorageRows<R extends VolumeEvent>(rows: readonly R[], pricing: Pricing): R[] {\n return rows.map((r) => ({ ...r, sizeGib: Math.max(0, r.sizeGib - pricing.storageIncludedGib) }));\n}\n\n/** Totals of a report: the boxes' sums plus the volumes', one cost for both when priced. */\nexport function reportTotals(\n boxes: readonly Pick<UsageTotals, \"seconds\" | \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">[],\n volumes: readonly Pick<VolumeTotals, \"volumeHours\" | \"volumeGibHours\">[],\n pricing?: Pricing,\n): Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> & Pick<VolumeTotals, \"volumeHours\" | \"volumeGibHours\"> {\n const { cost: _boxes, ...sum } = sumUsage(boxes);\n const vol = { volumeHours: round(volumes.reduce((n, v) => n + v.volumeHours, 0), 3), volumeGibHours: round(volumes.reduce((n, v) => n + v.volumeGibHours, 0), 3) };\n const out = { ...sum, ...vol };\n if (pricing !== undefined) return { ...out, cost: { amount: round(costOf(sum, pricing) + volumeCostOf(vol, pricing), 4), currency: pricing.currency } };\n return out;\n}\n\n// ---- per day -------------------------------------------------------------------------------------\n\nconst DAY_MS = 24 * HOUR_MS;\n\n/** The UTC days a window touches, each clipped to it: `[date, from, to]`. */\nexport function windowDays(window: { from: string; to: string }): { date: string; from: string; to: string }[] {\n const from = Date.parse(window.from);\n const to = Date.parse(window.to);\n const out: { date: string; from: string; to: string }[] = [];\n for (let day = Math.floor(from / DAY_MS) * DAY_MS; day < to; day += DAY_MS) {\n const start = Math.max(day, from);\n const end = Math.min(day + DAY_MS, to);\n if (end > start) out.push({ date: new Date(day).toISOString().slice(0, 10), from: new Date(start).toISOString(), to: new Date(end).toISOString() });\n }\n return out;\n}\n\n/** Rows grouped per ledger and id, each group sorted by time: what the day loop walks. */\nfunction sortedGroups<R extends { at: string; ledger?: string }>(rows: readonly R[], idOf: (r: R) => string): R[][] {\n const groups = new Map<string, R[]>();\n for (const r of rows) {\n const key = r.ledger === undefined ? idOf(r) : `${r.ledger}:${idOf(r)}`;\n const list = groups.get(key);\n if (list === undefined) groups.set(key, [r]);\n else list.push(r);\n }\n return [...groups.values()].map((list) => list.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0)));\n}\n\n/**\n * One box's or volume's cost on each day, as `groupUsage` / `groupVolumeUsage` would price it over that\n * day alone: its `rm` row ends its time, it is absent before its first row and after an `rm` before the\n * day. Only the rows that matter to a day are handed to `price` (the one the day opens in, those inside\n * it), found with a pointer that moves forward with the days: the work is the rows plus the days, not\n * their product.\n */\nfunction costPerDay<R extends { at: string; by: string }>(\n events: readonly R[],\n days: readonly { from: string; to: string }[],\n price: (events: readonly R[], w: { from: string; to: string }) => number,\n ledgerEnd?: string,\n): (number | null)[] {\n const first = events[0]!;\n const last = events[events.length - 1]!;\n const removed = last.by === \"rm\";\n let open = 0;\n return days.map((day) => {\n let to = removed && last.at < day.to ? last.at : day.to;\n if (ledgerEnd !== undefined && ledgerEnd < to) to = ledgerEnd;\n if (to <= day.from) return null;\n if (first.at >= to || (removed && last.at <= day.from)) return null;\n while (open + 1 < events.length && events[open + 1]!.at <= day.from) open++;\n let end = open;\n while (end < events.length && events[end]!.at < to) end++;\n return price(events.slice(open, Math.max(end, open + 1)), { from: day.from, to });\n });\n}\n\n/**\n * The same rows as a report, cut into UTC days: each day's boxes and volumes priced over that day\n * alone, the way `groupUsage` / `groupVolumeUsage` price a window (a removed box stops at its `rm`, a\n * box made later is absent before its first row). Rows must cover the whole window, the row before it\n * included, as `usageReport` reads them. Rows are grouped and sorted once, not once per day. `ends`\n * (ledger → time) is where a ledger's rows stop counting: nothing of it accrues after, as when the\n * window given to `groupUsage` is cut there.\n */\nexport function dailyUsage(\n boxRows: readonly LedgerRow[],\n volumeRows: readonly VolumeLedgerRow[],\n window: { from: string; to: string },\n pricing: Pricing,\n ends: ReadonlyMap<string, string> = new Map(),\n): UsageDay[] {\n const days = windowDays(window);\n const perDay: { boxes: UsageDayItem[]; volumes: UsageDayItem[] }[] = days.map(() => ({ boxes: [], volumes: [] }));\n for (const events of sortedGroups(boxRows, (r) => r.boxId)) {\n const last = events[events.length - 1]!;\n costPerDay(events, days, (e, w) => computeUsage(e, { ...w, pricing }).cost?.amount ?? 0, ends.get(last.ledger ?? \"\")).forEach((cost, i) => {\n if (cost !== null) perDay[i]!.boxes.push({ id: last.boxId, name: last.name, owner: last.owner, removed: last.by === \"rm\", cost });\n });\n }\n for (const events of sortedGroups(volumeRows, (r) => r.volumeId)) {\n const last = events[events.length - 1]!;\n costPerDay(events, days, (e, w) => computeVolumeUsage(e, { ...w, pricing }).cost?.amount ?? 0, ends.get(last.ledger ?? \"\")).forEach((cost, i) => {\n if (cost !== null) perDay[i]!.volumes.push({ id: last.volumeId, name: last.name, owner: last.owner, removed: last.by === \"rm\", cost });\n });\n }\n const byCost = (a: UsageDayItem, b: UsageDayItem) => b.cost - a.cost || a.name.localeCompare(b.name);\n return days.map((day, i) => {\n const { boxes, volumes } = perDay[i]!;\n const cost = round([...boxes, ...volumes].reduce((n, item) => n + item.cost, 0), 4);\n return { ...day, cost, currency: pricing.currency, boxes: boxes.sort(byCost), volumes: volumes.sort(byCost) };\n });\n}\n","/**\n * Who a box belongs to. Names are unique per owner, not per host, so a box is addressed as\n * `owner/name`; a bare `name` means the caller's own. The owner is part of the box's identity and\n * lives with it on disk (machines/<owner>/<name>, `owner` in meta.json), never in a database.\n * Decision \"Owner realms\": a bare owner is local to this host (the Unix user running kvbox-server);\n * a control plane's users arrive as `user@<control plane>` later (#18), so the two never collide.\n */\nimport { userInfo } from \"node:os\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\n\nexport interface BoxRef {\n owner: string;\n name: string;\n /** How the caller wrote it: `lab1` for their own, `user2/lab1` for someone else's. Set by parseRef, used in messages. */\n display?: string;\n}\n\n/** The ref as the caller knows it (see BoxRef.display); bare name when nothing else is known. */\nexport function shown(ref: BoxRef): string {\n return ref.display ?? ref.name;\n}\n\n/** A local owner is a Unix user name: no `@` (that marks a control-plane realm) and no `/`. */\nexport const LOCAL_OWNER_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}$/;\n/** A realm: a control plane's name as hosts qualify owners with it (`kvbox.sh`). A path segment later, so nothing but a host name. */\nexport const REALM_RE = /^[A-Za-z0-9.-]{1,128}$/;\n/** Any owner, local or `user@realm`. */\nexport const OWNER_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}(@[A-Za-z0-9.-]{1,128})?$/;\n\n/** The Unix user running this server: what boxes made over the local socket belong to. */\nexport function localOwner(): string {\n try {\n const name = userInfo().username;\n if (LOCAL_OWNER_RE.test(name)) return name;\n } catch {\n /* no passwd entry */\n }\n const env = process.env[\"USER\"];\n return env !== undefined && LOCAL_OWNER_RE.test(env) ? env : \"kvbox\";\n}\n\n/**\n * Who a listing is for: one owner, every owner of a realm (`{ realm }`: the control plane reconciling\n * its index, #20), or everyone (`null`: the host owner's own accounting).\n */\nexport type ListScope = string | { realm: string } | null;\n\nexport function inScope(owner: string, scope: ListScope): boolean {\n if (scope === null) return true;\n if (typeof scope === \"string\") return owner === scope;\n return realmOf(owner) === scope.realm;\n}\n\n/** The control plane an owner belongs to (`alice@kvbox.sh` → `kvbox.sh`); null for a local owner. */\nexport function realmOf(owner: string): string | null {\n const at = owner.indexOf(\"@\");\n return at === -1 ? null : owner.slice(at + 1);\n}\n\n/**\n * `lab1` → the caller's box; `user2/lab1` → that owner's. A caller from a control plane (`user@realm`)\n * can only name owners of that realm: the control plane never sees the host owner's local boxes or\n * another control plane's. The host owner over the socket is not restricted.\n */\nexport function parseRef(text: string, caller: string): BoxRef {\n const slash = text.indexOf(\"/\");\n if (slash === -1) return { owner: caller, name: text, display: text };\n const owner = text.slice(0, slash);\n const name = text.slice(slash + 1);\n if (!OWNER_RE.test(owner) || name.length === 0 || name.includes(\"/\")) {\n throw new KvboxError(`invalid box reference \"${text}\": use <name> or <owner>/<name>`);\n }\n const realm = realmOf(caller);\n if (realm !== null && realmOf(owner) !== realm) {\n throw new KvboxError(`invalid box reference \"${text}\": ${owner} is not in your realm`);\n }\n return { owner, name, display: owner === caller ? name : text };\n}\n\n/**\n * The owner a caller names for a new box (`kvbox vm fork --org`, #79): a bare slug, kept inside the\n * caller's realm (`acme` from `alice@kvbox.sh` is `acme@kvbox.sh`). The host owner over the socket\n * names a local owner as it is.\n */\nexport function ownerFor(slug: string, caller: string): string {\n if (!LOCAL_OWNER_RE.test(slug)) throw new KvboxError(`invalid owner \"${slug}\": a bare slug, without '@' or '/'`);\n const realm = realmOf(caller);\n return realm === null ? slug : `${slug}@${realm}`;\n}\n\n/** `owner/name`: how a ref is written down (snapshot sources, box sources, admin listings). */\nexport function refKey(ref: BoxRef): string {\n return `${ref.owner}/${ref.name}`;\n}\n","/**\n * Firecracker needs /dev/kvm. A daemon that cannot open it starts fine and only fails at the first\n * `kvbox new`, with an opaque firecracker 400 (#61): the usual cause is a shell that logged in\n * before the user was added to the kvm group, so the daemon it spawned runs without that group.\n * Checked once at `kvbox-server start`, before the socket is bound, and told in plain words.\n */\nimport { access, constants, readFile, stat } from \"node:fs/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\n\nexport const KVM_DEVICE = \"/dev/kvm\";\n\n/** The group's name for a gid from /etc/group, `kvm` when the file does not say. */\nexport async function groupName(gid: number, groupFile = \"/etc/group\"): Promise<string> {\n const text = await readFile(groupFile, \"utf8\").catch(() => \"\");\n for (const line of text.split(\"\\n\")) {\n const [name, , id] = line.split(\":\");\n if (id !== undefined && Number.parseInt(id, 10) === gid && name) return name;\n }\n return \"kvm\";\n}\n\n/** Resolves when this process can open the device for reading and writing; a KvboxError saying what to do otherwise. */\nexport async function requireKvm(device = KVM_DEVICE, groupFile = \"/etc/group\"): Promise<void> {\n try {\n await access(device, constants.R_OK | constants.W_OK);\n return;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n throw new KvboxError(`${device} is missing: this machine has no KVM, so boxes cannot run here (enable virtualization in the BIOS, then install-server.sh checks the rest)`);\n }\n if (code !== \"EACCES\" && code !== \"EPERM\") throw new KvboxError(`cannot open ${device}: ${(err as Error).message}`);\n }\n const owner = await stat(device).then((s) => groupName(s.gid, groupFile), () => \"kvm\");\n throw new KvboxError(\n `cannot start: this process is not allowed to open ${device}, so no box could run. ` +\n `It was started from a shell without the ${owner} group (a login from before you were added to it). ` +\n `Log out and back in, or start it from a shell that has the group: sg ${owner} -c \"kvbox-server start -d\"`,\n );\n}\n","/**\n * Box names inside boxes (#97): `<name>.kvbox` resolves to the box of that name with the asker's owner.\n * A small DNS server on the bridge address, reached on port 53 through net-setup.sh's redirect to\n * DNS_PORT (the daemon is not root). The image lists it first and 1.1.1.1 second, so it answers only\n * `.kvbox` names and REFUSED to everything else, which sends the guest's resolver straight to the next\n * server: internet lookups never depend on this daemon. The asker is known by its source address.\n * Only A records; a name is not an access grant (boxes stay isolated from each other).\n */\nimport { createSocket, type Socket } from \"node:dgram\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { boxListVersionNow, listMachineRefs, readMachineMeta } from \"./state.js\";\n\n/** Where the listener binds on the bridge address; net-setup.sh redirects port 53 there (keep both in step). */\nexport const DNS_PORT = 10053;\nexport const DNS_SUFFIX = \".kvbox\";\n/** How often the daemon tries the bind again while the bridge address does not exist. */\nexport const DNS_RETRY_MS = 10_000;\nconst TTL_SEC = 5;\n/**\n * How long one scan of the boxes answers every lookup when nothing changed. Every create and rm goes\n * through this daemon and moves the box list's version, which re-reads at once (a removed box's IP goes\n * to the next box, of any owner); this is only the backstop for a change made behind its back.\n */\nconst BOXES_FRESH_MS = 60_000;\n\nconst TYPE_A = 1;\nconst CLASS_IN = 1;\nconst RCODE = { ok: 0, nxDomain: 3, refused: 5 } as const;\n\nexport interface Query {\n id: number;\n /** Recursion desired, echoed back. */\n rd: boolean;\n name: string;\n type: number;\n class: number;\n /** The question section as received, echoed in the answer. */\n question: Buffer;\n}\n\n/** The first question of a standard query, or null when the packet is not one we can answer. */\nexport function parseQuery(msg: Buffer): Query | null {\n if (msg.length < 12) return null;\n const flags = msg.readUInt16BE(2);\n const isResponse = flags & 0x8000;\n const opcode = (flags >> 11) & 0xf;\n if (isResponse || opcode !== 0 || msg.readUInt16BE(4) < 1) return null;\n const labels: string[] = [];\n let at = 12;\n for (;;) {\n if (at >= msg.length) return null;\n const len = msg[at]!;\n at += 1;\n if (len === 0) break;\n if (len > 63 || at + len > msg.length) return null; // compression pointers never appear in a question\n labels.push(msg.subarray(at, at + len).toString(\"latin1\"));\n at += len;\n }\n if (at + 4 > msg.length) return null;\n return {\n id: msg.readUInt16BE(0),\n rd: Boolean(flags & 0x0100),\n name: labels.join(\".\").toLowerCase(),\n type: msg.readUInt16BE(at),\n class: msg.readUInt16BE(at + 2),\n question: msg.subarray(12, at + 4),\n };\n}\n\n/** A response to `q`: the question echoed, plus one A record when `ip` is given. */\nexport function buildAnswer(q: Query, rcode: number, ip?: string): Buffer {\n const header = Buffer.alloc(12);\n header.writeUInt16BE(q.id, 0);\n // QR, AA (we own .kvbox), RD echoed; RA off: we never recurse.\n header.writeUInt16BE(0x8000 | 0x0400 | (q.rd ? 0x0100 : 0) | rcode, 2);\n header.writeUInt16BE(1, 4);\n header.writeUInt16BE(ip ? 1 : 0, 6);\n if (!ip) return Buffer.concat([header, q.question]);\n const rr = Buffer.alloc(16);\n rr.writeUInt16BE(0xc00c, 0); // the name: a pointer to the question's\n rr.writeUInt16BE(TYPE_A, 2);\n rr.writeUInt16BE(CLASS_IN, 4);\n rr.writeUInt32BE(TTL_SEC, 6);\n rr.writeUInt16BE(4, 10);\n ip.split(\".\").forEach((o, i) => rr.writeUInt8(Number(o), 12 + i));\n return Buffer.concat([header, q.question, rr]);\n}\n\nexport interface BoxAddress {\n name: string;\n owner: string;\n ip: string;\n /** The IPs of the boxes linked into this one (#98): they see its name across slugs. */\n linkedFrom?: readonly string[];\n}\n\n/** `alice@kvbox.sh` → `alice`: the slug a name's second label spells. */\nconst slugOf = (owner: string) => owner.split(\"@\")[0]!.toLowerCase();\n\n/** A `.kvbox` name in class IN: the only questions worth looking at the boxes for. */\nexport const isOurs = (q: Query) => q.class === CLASS_IN && q.name.endsWith(DNS_SUFFIX);\n\n/**\n * What to answer `asker` (a source address) about `q`. `db.kvbox` is the asker's owner's box `db`;\n * `db.acme.kvbox` is slug `acme`'s: the asker's own slug (an org's boxes asking about each other), or\n * another slug's box the asker is linked into (#98, the link is the grant). Not ours:\n * REFUSED. Ours but the asker is no box, or no such box it may see: NXDOMAIN, the same for a name\n * another owner uses, so names cannot be probed across owners. A name that exists but a type other\n * than A: no records.\n */\nexport function answerFor(q: Query, asker: string, boxes: readonly BoxAddress[]): { rcode: number; ip?: string } {\n if (!isOurs(q)) return { rcode: RCODE.refused };\n const [name, slug, ...rest] = q.name.slice(0, -DNS_SUFFIX.length).split(\".\");\n const from = boxes.find((b) => b.ip === asker);\n let box: BoxAddress | undefined;\n if (from && rest.length === 0) {\n box =\n slug === undefined || slug === slugOf(from.owner)\n ? boxes.find((b) => b.owner === from.owner && b.name === name)\n : boxes.find((b) => slugOf(b.owner) === slug && b.name === name && b.linkedFrom?.includes(asker));\n }\n if (!box) return { rcode: RCODE.nxDomain };\n return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };\n}\n\nasync function boxAddresses(p: Paths): Promise<BoxAddress[]> {\n const out: BoxAddress[] = [];\n for (const ref of await listMachineRefs(p)) {\n const meta = await readMachineMeta(ref, p).catch(() => null); // a half-written box is not an answer\n if (meta) out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...(meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {}) });\n }\n return out;\n}\n\n/**\n * `load` again only when the box list's `version` moved or `freshMs` passed, its result shared by every\n * lookup meanwhile, the ones waiting on a scan in flight included. A failed scan is not kept: the next\n * lookup tries again.\n */\nexport function sharedBoxes(\n load: () => Promise<BoxAddress[]>,\n freshMs = BOXES_FRESH_MS,\n version: () => number = boxListVersionNow,\n): () => Promise<BoxAddress[]> {\n let last: { at: number; version: number; list: Promise<BoxAddress[]> } | null = null;\n return () => {\n if (!last || last.version !== version() || Date.now() - last.at > freshMs) {\n // The version is taken before the scan: a change during it makes the next lookup scan again.\n const entry = { at: Date.now(), version: version(), list: load() };\n last = entry;\n entry.list.catch(() => {\n if (last === entry) last = null;\n });\n }\n return last.list;\n };\n}\n\nexport interface DnsOptions {\n /** The bridge address. */\n host: string;\n port?: number;\n boxes?: () => Promise<BoxAddress[]>;\n p?: Paths;\n}\n\n/** Bind and answer until closed. Rejects when the address cannot be bound (no bridge yet, port taken). */\nexport async function startDns(opts: DnsOptions): Promise<{ socket: Socket; close: () => Promise<void> }> {\n const p = opts.p ?? paths();\n const boxes = sharedBoxes(opts.boxes ?? (() => boxAddresses(p)));\n const socket = createSocket(\"udp4\");\n socket.on(\"message\", (msg, rinfo) => {\n const q = parseQuery(msg);\n if (!q) return; // nothing a resolver sends us; it moves on after its timeout\n const reply = (a: { rcode: number; ip?: string }) => socket.send(buildAnswer(q, a.rcode, a.ip), rinfo.port, rinfo.address);\n // Every internet lookup of every box comes here first: refused at once, without touching the boxes.\n if (!isOurs(q)) return reply({ rcode: RCODE.refused });\n void boxes()\n .then((list) => answerFor(q, rinfo.address, list))\n .catch((): { rcode: number; ip?: string } => ({ rcode: RCODE.refused }))\n .then(reply);\n });\n await new Promise<void>((resolve, reject) => {\n socket.once(\"error\", (err) => {\n socket.close(); // a caller that retries must not pile up dead sockets\n reject(err);\n });\n socket.bind(opts.port ?? DNS_PORT, opts.host, () => {\n socket.removeAllListeners(\"error\");\n socket.on(\"error\", () => {}); // a send to a box that went away must not crash the daemon\n resolve();\n });\n });\n return { socket, close: () => new Promise<void>((resolve) => socket.close(() => resolve())) };\n}\n","/**\n * The `~/.kvbox` layout and the per-box / per-snapshot `meta.json` files.\n * The server is the only writer; every read is validated with zod.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { mkdir, readFile, readdir, rename, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { insertVolumeEvent } from \"./db.js\";\nimport type { BoxRef } from \"./refs.js\";\n\nexport const MachineMetaSchema = z.object({\n /** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */\n id: z.string(),\n name: z.string(),\n /** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */\n owner: z.string(),\n ip: z.string(),\n mac: z.string(),\n pid: z.number().int().nullable(), // null: stopped on purpose, disk kept\n /**\n * The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot\n * the number can name some other process; a pid from another boot is dead whatever `kill -0` says.\n * Absent (boxes launched before #29): the pid alone decides.\n */\n bootId: z.string().optional(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n createdAt: z.string(),\n source: z.string(),\n /** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */\n base: z.string(),\n /** The image (#87), when not the base one: assets/images/<image>/rootfs-<base>.ext4. `vm update` keeps it. */\n image: z.string().optional(),\n /** The image's connect line with its secrets masked and `${BOX}` unfilled (#87, `maskedUrl`). Absent: the image declares none. */\n url: z.string().optional(),\n /**\n * Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at\n * each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file\n * is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.\n */\n memSnapshots: z.number().int().optional(),\n /** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */\n paused: z.boolean().optional(),\n /**\n * authorized_keys lines the box gets on top of the host's own key, as the control plane sent them\n * at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so\n * `start` has to send the same lines again. Absent: host key only.\n */\n sshKeys: z.array(z.string()).optional(),\n /**\n * The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,\n * or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.\n */\n sshKeysStale: z.boolean().optional(),\n /** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */\n sshPort: z.number().int().optional(),\n /**\n * Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,\n * each host port the box's for its life. DNATed while the box runs, rebuilt from here with its\n * current IP every time it comes up. Absent: none.\n */\n ports: z.array(z.object({ guestPort: z.number().int(), hostPort: z.number().int(), proto: z.enum([\"tcp\", \"udp\"]), closed: z.literal(true).optional() })).optional(),\n /** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */\n autoHibernateSec: z.number().int().positive().optional(),\n /**\n * A script inside the box auto-hibernate asks instead of watching the tap (#102, core/idle.ts): run by\n * kvbox-agent, exit 0 = idle. A new box gets its image's `idle` (image.json); `kvbox vm set --idle-check`\n * changes it. The one place the host looks. Absent: the traffic rule.\n */\n idleCheck: z.string().optional(),\n /**\n * Names of the owner's volumes attached to the box (#52), in the order they were attached, which is\n * their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a\n * volume's meta.json does not say. Absent: none.\n */\n volumes: z.array(z.string()).optional(),\n /**\n * Links into this box (#98, `kvbox vm link`): box `owner/name`, at `ip`, may open TCP connections to\n * `port`. The rule is open while this box runs, rebuilt from here at every boot; `ip` is the other\n * box's, fixed for its life, and checked against its meta.json before a rule opens. `stale`: that box\n * was removed but the rule would not close; kept only so this box's next stop closes it, never opened\n * again, never listed (a new box of the same name may get the same IP). Absent: none.\n */\n links: z.array(z.object({ owner: z.string(), name: z.string(), ip: z.string(), port: z.number().int(), stale: z.literal(true).optional() })).optional(),\n});\nexport type MachineMeta = z.infer<typeof MachineMetaSchema>;\n\n/** A volume (#52): its own meta.json next to its disk under volumes/<owner>/<name>. Which box has it is the box's meta.json. */\nexport const VolumeMetaSchema = z.object({\n /** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n sizeGib: z.number().int(),\n createdAt: z.string(),\n});\nexport type VolumeMeta = z.infer<typeof VolumeMetaSchema>;\n\n/** 6 lowercase hex chars: 16M values per host, 9 chars as a tap name, well inside Linux's 15-char limit. */\nexport const BOX_ID_RE = /^[0-9a-f]{6}$/;\n\n/** A fresh id no box on the host has (`taken`: every id in use, so a draw can be retried). */\nexport function newBoxId(taken: ReadonlySet<string>): string {\n for (;;) {\n const id = randomBytes(3).toString(\"hex\");\n if (!taken.has(id)) return id;\n }\n}\n\nexport const SnapshotMetaSchema = z.object({\n name: z.string(),\n owner: z.string(),\n /** The box it was taken from, as owner/name. */\n source: z.string(),\n base: z.string(),\n /** As in a box's meta.json (#87). */\n image: z.string().optional(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n sizeBytes: z.number().int(),\n createdAt: z.string(),\n /**\n * The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate\n * and their mounts in the memory image, but their data is not here. A box restored from the snapshot\n * gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.\n */\n volumes: z.array(z.object({ name: z.string(), sizeGib: z.number().int() })).optional(),\n});\nexport type SnapshotMeta = z.infer<typeof SnapshotMetaSchema>;\n\n/** Create every directory of the layout. Idempotent; called by `kvbox-server start`. */\nexport async function ensureLayout(p: Paths = paths()): Promise<Paths> {\n for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n }\n return p;\n}\n\nasync function readJson<T>(file: string, schema: z.ZodType<T>): Promise<T> {\n return schema.parse(JSON.parse(await readFile(file, \"utf8\")));\n}\n\nasync function listDirs(dir: string): Promise<string[]> {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n}\n\nexport async function readMachineMeta(ref: BoxRef, p: Paths = paths()) {\n return readJson(p.machine(ref.owner, ref.name).meta, MachineMetaSchema);\n}\n\nlet boxListVersion = 0;\n/** Moves whenever a box's meta.json is written or its dir removed: a cache of the box list (core/dns.ts) re-reads when it has. */\nexport const boxListVersionNow = () => boxListVersion;\nexport const boxListChanged = () => void (boxListVersion += 1);\n\n/** Whole or not at all: a listing reading the box at the same moment sees the old meta or the new, never a cut one. */\nexport async function writeMachineMeta(meta: MachineMeta, p: Paths = paths()) {\n const m = p.machine(meta.owner, meta.name);\n await mkdir(m.dir, { recursive: true });\n const tmp = `${m.meta}.tmp`;\n await writeFile(tmp, JSON.stringify(meta, null, 2) + \"\\n\");\n await rename(tmp, m.meta);\n boxListChanged();\n}\n\n/** Every box on the host, all owners: machines/<owner>/<name>. */\nexport async function listMachineRefs(p: Paths = paths()) {\n return listRefs(p.machines);\n}\n\nexport async function readSnapshotMeta(ref: BoxRef, p: Paths = paths()) {\n return readJson(p.snapshot(ref.owner, ref.name).meta, SnapshotMetaSchema);\n}\n\n/** `s` is where the snapshot's files are: its own dir, or the temp dir a replace captures into (#83). */\nexport async function writeSnapshotMeta(meta: SnapshotMeta, p: Paths = paths(), s = p.snapshot(meta.owner, meta.name)) {\n await mkdir(s.dir, { recursive: true });\n await writeFile(s.meta, JSON.stringify(meta, null, 2) + \"\\n\");\n}\n\n/** Skips the dot dirs a replace works in (`.<name>.new-<box id>`, `.<name>.old-<box id>`, #83): no snapshot name starts with a dot. */\nexport async function listSnapshotRefs(p: Paths = paths()) {\n return (await listRefs(p.snapshots)).filter((ref) => !ref.name.startsWith(\".\"));\n}\n\n/**\n * A volume made before #91 has no `id`: it gets one here, written back, and the `create` ledger row it\n * never had, dated when the volume was made, so it is listed, billed and bootable like any other.\n */\nexport async function readVolumeMeta(ref: BoxRef, p: Paths = paths()): Promise<VolumeMeta> {\n const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z.string().optional() }));\n if (raw.id !== undefined) return { ...raw, id: raw.id };\n const taken = new Set<string>();\n for (const other of await listVolumeRefs(p)) {\n try {\n const j = JSON.parse(await readFile(p.volume(other.owner, other.name).meta, \"utf8\")) as { id?: unknown };\n if (typeof j.id === \"string\") taken.add(j.id);\n } catch {\n /* an unreadable volume holds no id to avoid */\n }\n }\n const meta: VolumeMeta = { ...raw, id: newBoxId(taken) };\n await writeVolumeMeta(meta, p);\n insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: meta.createdAt, sizeGib: meta.sizeGib, by: \"create\" }, p);\n return meta;\n}\n\nexport async function writeVolumeMeta(meta: VolumeMeta, p: Paths = paths()) {\n const v = p.volume(meta.owner, meta.name);\n await mkdir(v.dir, { recursive: true, mode: 0o700 });\n await writeFile(v.meta, JSON.stringify(meta, null, 2) + \"\\n\");\n}\n\nexport async function listVolumeRefs(p: Paths = paths()) {\n return listRefs(p.volumes);\n}\n\n/** Two levels: <root>/<owner>/<name>. */\nasync function listRefs(root: string): Promise<BoxRef[]> {\n const out: BoxRef[] = [];\n for (const owner of await listDirs(root)) {\n for (const name of await listDirs(`${root}/${owner}`)) {\n out.push({ owner, name });\n }\n }\n return out;\n}\n\n/** True when a pid is alive (signal 0). */\nexport function pidAlive(pid: number | null): boolean {\n if (pid === null || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nlet bootId: { id: string | undefined } | undefined;\n\n/** This boot's id (undefined where the kernel does not expose one). Read once: it cannot change under a running process. */\nexport function currentBootId(): string | undefined {\n if (bootId === undefined) {\n try {\n bootId = { id: readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\").trim() };\n } catch {\n bootId = { id: undefined };\n }\n }\n return bootId.id;\n}\n\n/** True when the box's Firecracker is still there: its pid is alive and was launched in this boot. */\nexport function vmAlive(meta: Pick<MachineMeta, \"pid\" | \"bootId\">): boolean {\n if (meta.bootId !== undefined && meta.bootId !== currentBootId()) return false;\n return pidAlive(meta.pid);\n}\n\n/** When the host booted, from /proc/stat's btime (null where there is none). */\nexport function hostBootTime(): Date | null {\n try {\n const m = /^btime (\\d+)$/m.exec(readFileSync(\"/proc/stat\", \"utf8\"));\n return m ? new Date(Number(m[1]) * 1000) : null;\n } catch {\n return null;\n }\n}\n","/**\n * `~/.kvbox/kvbox.db`: the host's ledgers, through Node's built-in SQLite (node:sqlite, Node >= 22.13;\n * no dependency). Decision \"Hosts keep boxes as files + SQLite ledgers\": a box is still its directory\n * and meta.json, the database only holds what has to be appended to over time and summed later.\n * First table: `usage_events`, one row per state change of a box, the source of `kvbox vm usage`.\n *\n * One handle per database file for the life of the process; WAL so readers never block the writer.\n * The file is created 0600 before SQLite opens it, so the -wal and -shm files it makes next to it\n * inherit the mode.\n */\nimport { chmodSync, closeSync, mkdirSync, openSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport type { UsageEvent, UsageState, VolumeLedgerRow } from \"@kvbox/shared/usage\";\nimport { inScope, type ListScope } from \"./refs.js\";\n\n/** Each entry upgrades the schema one version; `schema_version` records how far a file has come. */\nconst MIGRATIONS: string[] = [\n `create table usage_events (\n id integer primary key,\n box_id text not null,\n owner text not null,\n name text not null,\n at text not null,\n state text not null,\n vcpu integer not null,\n mem_mib integer not null,\n disk_gib integer not null,\n by text not null\n );\n create index usage_events_box_at on usage_events (box_id, at);`,\n // The ledger's identity (#42): a control plane keys pulled rows by it, so a re-join is recognised\n // and a fresh ledger (KVBOX_HOME wiped) restarts its cursor instead of waiting for ids it already saw.\n `create table ledger (id text not null);\n insert into ledger (id) values (lower(hex(randomblob(16))));\n create index usage_events_at on usage_events (at);`,\n // Volumes (#91): a row per create, resize and rm, the size from that moment on. Its own table and\n // ids, pulled by the control plane like usage_events, in the same ledger.\n `create table volume_events (\n id integer primary key,\n volume_id text not null,\n owner text not null,\n name text not null,\n at text not null,\n size_gib integer not null,\n by text not null\n );\n create index volume_events_volume_at on volume_events (volume_id, at);`,\n];\n\nconst handles = new Map<string, DatabaseSync>();\n\nexport function openDb(p: Paths = paths()): DatabaseSync {\n const have = handles.get(p.db);\n if (have !== undefined) return have;\n mkdirSync(dirname(p.db), { recursive: true, mode: 0o700 });\n closeSync(openSync(p.db, \"a\", 0o600));\n chmodSync(p.db, 0o600);\n const db = new DatabaseSync(p.db);\n db.exec(\"pragma journal_mode = wal\");\n db.exec(\"pragma busy_timeout = 5000\");\n migrate(db);\n handles.set(p.db, db);\n return db;\n}\n\n/** Close the handle for this home (tests; the daemon keeps its open until exit). */\nexport function closeDb(p: Paths = paths()): void {\n const db = handles.get(p.db);\n if (db === undefined) return;\n db.close();\n handles.delete(p.db);\n}\n\nfunction migrate(db: DatabaseSync): void {\n db.exec(\"create table if not exists schema_version (version integer not null)\");\n const row = db.prepare(\"select version from schema_version\").get() as { version: number } | undefined;\n let version = row?.version ?? 0;\n if (row === undefined) db.prepare(\"insert into schema_version (version) values (0)\").run();\n while (version < MIGRATIONS.length) {\n db.exec(\"begin\");\n try {\n db.exec(MIGRATIONS[version]!);\n version += 1;\n db.prepare(\"update schema_version set version = ?\").run(version);\n db.exec(\"commit\");\n } catch (err) {\n db.exec(\"rollback\");\n throw err;\n }\n }\n}\n\n/**\n * `kvbox-server rename-realm`: every ledger row of an owner in realm `from` now names the same slug in `to`.\n * Ids do not move, so the control plane's pull cursors stay right. Returns how many rows changed.\n */\nexport function renameLedgerRealm(from: string, to: string, p: Paths = paths()): number {\n const db = openDb(p);\n let rows = 0;\n db.exec(\"begin\");\n try {\n for (const table of [\"usage_events\", \"volume_events\"]) {\n const res = db\n .prepare(`update ${table} set owner = substr(owner, 1, length(owner) - length(?)) || ? where substr(owner, -length(?)) = ?`)\n .run(`@${from}`, `@${to}`, `@${from}`, `@${from}`);\n rows += Number(res.changes);\n }\n db.exec(\"commit\");\n } catch (err) {\n db.exec(\"rollback\");\n throw err;\n }\n return rows;\n}\n\n// ---- usage_events --------------------------------------------------------------------------------\n\nexport type { UsageEvent, UsageState };\n\n/** States in which a Firecracker process exists: a run that `closeOpenRun` has to close if that process died. */\nconst LIVE_STATES: readonly UsageState[] = [\"running\", \"standby\"];\n\nexport interface UsageEventRow extends UsageEvent {\n /** The box's id. Owner and name ride along so the ledger reads alone after a box is gone. */\n boxId: string;\n owner: string;\n name: string;\n}\n\ninterface Raw {\n id: number;\n box_id: string;\n owner: string;\n name: string;\n at: string;\n state: string;\n vcpu: number;\n mem_mib: number;\n disk_gib: number;\n by: string;\n}\n\nfunction fromRaw(r: Raw): UsageEventRow {\n return { boxId: r.box_id, owner: r.owner, name: r.name, at: r.at, state: r.state as UsageState, vcpu: r.vcpu, memMib: r.mem_mib, diskGib: r.disk_gib, by: r.by };\n}\n\nfunction lastEvent(boxId: string, db: DatabaseSync): UsageEventRow | undefined {\n const raw = db.prepare(\"select * from usage_events where box_id = ? order by at desc, id desc limit 1\").get(boxId) as Raw | undefined;\n return raw === undefined ? undefined : fromRaw(raw);\n}\n\nfunction insertRaw(e: UsageEventRow, db: DatabaseSync): void {\n db.prepare(\n \"insert into usage_events (box_id, owner, name, at, state, vcpu, mem_mib, disk_gib, by) values (?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n ).run(e.boxId, e.owner, e.name, e.at, e.state, e.vcpu, e.memMib, e.diskGib, e.by);\n}\n\n/**\n * Append a state change. A `running` on top of an open run (running or standby) means the box stopped\n * without the server knowing (Firecracker died, host rebooted): that run is closed first, dated now, by\n * `server`. The one exception is a resume, the legitimate way from standby back to running.\n */\nexport function insertUsageEvent(e: UsageEventRow, p: Paths = paths()): void {\n const db = openDb(p);\n if (e.state === \"running\" && e.by !== \"resume\") closeOpenRun(e.boxId, e.at, p);\n insertRaw(e, db);\n}\n\n/** If the box's last event has a live process (running or standby), add the `stopped` the server never saw, at `at`. True when one was added. */\nexport function closeOpenRun(boxId: string, at: string, p: Paths = paths()): boolean {\n const db = openDb(p);\n const last = lastEvent(boxId, db);\n if (last === undefined || !LIVE_STATES.includes(last.state)) return false;\n insertRaw({ ...last, at, state: \"stopped\", by: \"server\" }, db);\n return true;\n}\n\n/**\n * The run a host shutdown cut (#29): a run that began before the host booted cannot have outlived the\n * boot, so it ends at `bootAt`; one that began after it (Firecracker crashed since) ends `now`.\n */\nexport function closeRunCutByBoot(boxId: string, bootAt: string, now: string, p: Paths = paths()): boolean {\n const last = lastEvent(boxId, openDb(p));\n return closeOpenRun(boxId, last !== undefined && last.at < bootAt ? bootAt : now, p);\n}\n\n/** The box's events from `since` on, oldest first. */\nexport function usageEventsFor(boxId: string, since: string, p: Paths = paths()): UsageEventRow[] {\n const rows = openDb(p).prepare(\"select * from usage_events where box_id = ? and at >= ? order by at, id\").all(boxId, since) as unknown as Raw[];\n return rows.map(fromRaw);\n}\n\n/** A ledger row with its id: the cursor a control plane pulls by (#42). */\nexport type UsageEventWithId = UsageEventRow & { id: number };\n\nconst withId = (r: Raw): UsageEventWithId => ({ ...fromRaw(r), id: r.id });\n\n/** This home's ledger id, made with the database; it changes only when the database is recreated. */\nexport function ledgerId(p: Paths = paths()): string {\n return (openDb(p).prepare(\"select id from ledger\").get() as { id: string }).id;\n}\n\n/**\n * Rows after `after` by id (the order they were written in, so a puller never misses one), at\n * most `limit`, of the owners in `scope`. The id is monotonic: a pull is resumable and a repeat\n * is a no-op on the other side.\n */\nexport function usageEventsAfter(after: number, limit: number, scope: ListScope, p: Paths = paths()): UsageEventWithId[] {\n const db = openDb(p);\n const rows = (scope === null\n ? db.prepare(\"select * from usage_events where id > ? order by id limit ?\").all(after, limit)\n : typeof scope === \"string\"\n ? db.prepare(\"select * from usage_events where id > ? and owner = ? order by id limit ?\").all(after, scope, limit)\n : db.prepare(\"select * from usage_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?\").all(after, `@${scope.realm}`, `@${scope.realm}`, limit)) as unknown as Raw[];\n return rows.map(withId);\n}\n\n/**\n * The rows of the owners in `scope` that a report over the window needs, in time order: those inside\n * it plus each box's last row before it (the state the window opens in). The host-wide report (#41).\n */\nexport function usageEventsInScope(scope: ListScope, window: { from: string; to: string }, p: Paths = paths()): UsageEventWithId[] {\n const rows = openDb(p)\n .prepare(\n `select * from usage_events where at < ? and (at >= ? or id in (select max(id) from usage_events where at < ? group by box_id))\n order by at, id`,\n )\n .all(window.to, window.from, window.from) as unknown as Raw[];\n return rows.filter((r) => inScope(r.owner, scope)).map(withId);\n}\n\n// ---- volume_events (#91) -------------------------------------------------------------------------\n\nexport type VolumeEventWithId = VolumeLedgerRow & { id: number };\n\ninterface RawVolume {\n id: number;\n volume_id: string;\n owner: string;\n name: string;\n at: string;\n size_gib: number;\n by: string;\n}\n\nconst volumeWithId = (r: RawVolume): VolumeEventWithId => ({ id: r.id, volumeId: r.volume_id, owner: r.owner, name: r.name, at: r.at, sizeGib: r.size_gib, by: r.by as VolumeLedgerRow[\"by\"] });\n\nexport function insertVolumeEvent(e: VolumeLedgerRow, p: Paths = paths()): void {\n openDb(p)\n .prepare(\"insert into volume_events (volume_id, owner, name, at, size_gib, by) values (?, ?, ?, ?, ?, ?)\")\n .run(e.volumeId, e.owner, e.name, e.at, e.sizeGib, e.by);\n}\n\n/** Rows after `after` by id, at most `limit`, of the owners in `scope`: the control plane's pull, like `usageEventsAfter`. */\nexport function volumeEventsAfter(after: number, limit: number, scope: ListScope, p: Paths = paths()): VolumeEventWithId[] {\n const db = openDb(p);\n const rows = (scope === null\n ? db.prepare(\"select * from volume_events where id > ? order by id limit ?\").all(after, limit)\n : typeof scope === \"string\"\n ? db.prepare(\"select * from volume_events where id > ? and owner = ? order by id limit ?\").all(after, scope, limit)\n : db.prepare(\"select * from volume_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?\").all(after, `@${scope.realm}`, `@${scope.realm}`, limit)) as unknown as RawVolume[];\n return rows.map(volumeWithId);\n}\n\n/** The volume rows a report over the window needs: those inside it plus each volume's last row before it. */\nexport function volumeEventsInScope(scope: ListScope, window: { from: string; to: string }, p: Paths = paths()): VolumeEventWithId[] {\n const rows = openDb(p)\n .prepare(\n `select * from volume_events where at < ? and (at >= ? or id in (select max(id) from volume_events where at < ? group by volume_id))\n order by at, id`,\n )\n .all(window.to, window.from, window.from) as unknown as RawVolume[];\n return rows.filter((r) => inScope(r.owner, scope)).map(volumeWithId);\n}\n\n","/**\n * Create, list and destroy boxes: what spikes #4 and #6 did by hand.\n * See architecture \"Process model\". The server is the only writer of ~/.kvbox/machines.\n */\nimport { spawn } from \"node:child_process\";\nimport { closeSync, existsSync, openSync, statSync } from \"node:fs\";\nimport { link, mkdir, readFile, rename, rm, truncate, writeFile } from \"node:fs/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { parseDuration } from \"@kvbox/shared/duration\";\nimport { MAX_BOX_LINKS, MAX_BOX_PORTS, type BoxStatus, type CreateMachineRequest, type ForkMachineRequest, type LinkRequest, type Machine, type PortsRequest, type RecoveryReport, type RescaleMachineRequest, type SetMachineRequest, type SshKeysApplied, type TrustCaReport, type Volume } from \"@kvbox/shared/api\";\nimport { paths, volumeDriveRel, type Paths } from \"@kvbox/shared/paths\";\nimport { SIZES, isSizeName } from \"@kvbox/shared/sizes\";\nimport { caLineFor, isCaLine, parseSshPublicKey, sshKeyFingerprint } from \"@kvbox/shared/ssh\";\nimport { dropVolumes, isNoAgent, isUnknownOp, setAuthorizedKeys, setEnv, setIdentity } from \"./agent.js\";\nimport { copyBoxEnv, envForBoot, mergeBoxEnv, readBoxEnvFile, readOwnerEnv, writeBoxEnv } from \"./env.js\";\nimport { assertOverlayCapable, baseVersionOf, currentImage, imageEnv, imageFile, imageFileFor, imageKey, imageLabel, imageManifest, maskedUrl, urlFor, type ImageManifest } from \"./images.js\";\nimport { assertCanGrow, attachedBox, getVolume, growVolume, captureDrivesOf, placeholderDrives, placeVolumeDrives, readVolume, volumeDriveId, volumeSummaries, type VolumeDrive } from \"./volumes.js\";\nimport { assertRoomFor } from \"./capacity.js\";\nimport { closeOpenRun, closeRunCutByBoot, insertUsageEvent, type UsageState } from \"./db.js\";\nimport { inScope, ownerFor, parseRef, realmOf, refKey, shown, type BoxRef, type ListScope } from \"./refs.js\";\nimport { loadConfig, type Config } from \"./config.js\";\nimport { locked, withBoxLock, withHostLock, withSnapshotLock } from \"./locks.js\";\nimport { run } from \"./exec.js\";\nimport { ext4Usage } from \"./ext4.js\";\nimport { captureBox } from \"./snapshots.js\";\nimport { FirecrackerClient } from \"./firecracker.js\";\nimport { attachTap, bridgeExists, closeLink, closeProxy, createTap, deleteTap, ensureHostNetwork, listeningPorts, macFor, nextFreeIp, openLink, openProxy, pickSshPort, pinTap, tapName, type Link, type Proxy } from \"./network.js\";\nimport {\n boxListChanged,\n listMachineRefs,\n newBoxId,\n currentBootId,\n hostBootTime,\n pidAlive,\n readMachineMeta,\n readSnapshotMeta,\n vmAlive,\n writeMachineMeta,\n type MachineMeta,\n type SnapshotMeta,\n} from \"./state.js\";\nimport { log } from \"./log.js\";\n\n/** Box names double as guest hostnames; short and plain on purpose. */\nconst NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;\nconst AUTO_PREFIX = \"box\";\n/** Every box's vsock address. Firecracker's vsock is per process, so the number need not be unique on the host. */\nconst GUEST_CID = 3;\n/** The overlay drive's path as Firecracker sees it: relative to the box dir, see spawnFirecracker. */\nconst OVERLAY_REL = \"overlay.ext4\";\n\n/** Every id in use on the host, so a new draw can avoid them. */\nconst idsInUse = (metas: MachineMeta[]) => new Set(metas.map((m) => m.id));\n/** Every public port a box on the host holds, running or not (its SSH port and the ones it published): a port stays the box's for its life. */\nconst publicPortsInUse = (metas: MachineMeta[]) => metas.flatMap((m) => [...(m.sshPort === undefined ? [] : [m.sshPort]), ...(m.ports ?? []).map((f) => f.hostPort)]);\n\n/**\n * A box made through a control plane (its owner is `user@realm`) is reached from the internet:\n * it gets the control plane's authorized_keys lines and a public SSH port on the host (#49).\n * A box the host owner makes over the socket keeps the host key only and no public port.\n */\nconst isCloudBox = (owner: string) => realmOf(owner) !== null;\n\ntype Forwarded = Pick<MachineMeta, \"id\" | \"ip\" | \"sshPort\" | \"ports\" | \"links\">;\n\n/** Every forward the box has on the host: its public SSH port (#49) and the ports it published (#30). */\nfunction boxProxies(meta: Forwarded): Proxy[] {\n const ssh: Proxy[] = meta.sshPort === undefined ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];\n // a closed port (#173) keeps its host port and has no rule\n return [...ssh, ...(meta.ports ?? []).filter((f) => !f.closed).map((f) => ({ box: meta.id, boxIp: meta.ip, hostPort: f.hostPort, guestPort: f.guestPort, proto: f.proto }))];\n}\n\n/** The links into the box (#98) as host rules, with its current IP. */\nfunction boxLinks(meta: Forwarded): Link[] {\n return (meta.links ?? []).map((l) => ({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }));\n}\n\n/**\n * The links into the box that may open now. A linked box's IP goes to the next box when it is removed:\n * a link opens only while that box still has it.\n */\nexport async function standingLinks(meta: Forwarded, p: Paths): Promise<Link[]> {\n const links = boxLinks(meta);\n const stands = await Promise.all(\n (meta.links ?? []).map(async (l) => !l.stale && (await readMachineMeta({ owner: l.owner, name: l.name }, p).catch(() => null))?.ip === l.ip),\n );\n return links.filter((_, i) => stands[i]);\n}\n\n/**\n * Open the box's public ports and the links into it (after Firecracker is up), always with its current\n * IP; nothing to do for a box without any.\n */\nasync function openPorts(meta: Forwarded, cfg: Config, p: Paths): Promise<void> {\n for (const proxy of boxProxies(meta)) await openProxy(proxy, cfg);\n for (const link of await standingLinks(meta, p)) {\n // a link that cannot open (a host network from before #98) costs that link, never the box's boot\n await openLink(link, cfg).catch((err: Error) => log.warn(`could not open the link from ${link.fromIp}: ${err.message}`));\n }\n}\n\n/** Close them (the box is going down); a failure here is logged, the box's own state change goes on. */\nasync function closePorts(meta: Forwarded, cfg: Config): Promise<void> {\n for (const proxy of boxProxies(meta)) {\n await closeProxy(proxy, cfg).catch((err: Error) => log.warn(`could not close port ${proxy.hostPort}: ${err.message}`));\n }\n for (const link of boxLinks(meta)) {\n await closeLink(link, cfg).catch((err: Error) => log.warn(`could not close the link from ${link.fromIp}: ${err.message}`));\n }\n}\n\n/** Public ports drawn but not in any meta.json yet: the next draw must see them too. */\nconst reservedPorts = new Set<number>();\n\n/**\n * `count` fresh public ports: random, never 22, not another box's, not something the host listens\n * on (#49, #30). Drawn under the host's `ports` lock and held in `reservedPorts` until the caller has\n * written them to meta.json and calls `release`, so two boxes drawing at once never get the same one.\n */\nasync function drawPorts(count: number, p: Paths): Promise<{ ports: number[]; release: () => void }> {\n return withHostLock(\"ports\", async () => {\n // Reservations first: one released while the metas are read was written before its release, but\n // that write may be the half-written meta.json the read skipped.\n const reserved = [...reservedPorts];\n const taken = new Set([...reserved, ...publicPortsInUse(await readAllMeta(p)), ...(await listeningPorts())]);\n const ports: number[] = [];\n for (let i = 0; i < count; i++) {\n const port = pickSshPort(taken);\n taken.add(port);\n ports.push(port);\n }\n for (const port of ports) reservedPorts.add(port);\n return { ports, release: () => ports.forEach((port) => reservedPorts.delete(port)) };\n });\n}\n\n/**\n * The disk's size, what the box uses of it and what its sparse file occupies on the host (#115).\n * The usage is the filesystem's own count, read from the file (core/ext4.ts): what the guest's `df`\n * says, give or take a journal commit. Host allocation is a different number: Firecracker's block\n * device has no discard, so it only grows while the box runs, and `kvbox stop` trims it back\n * (compactDisk). It stands in for the usage only when the file cannot be read as ext4.\n */\nfunction diskStats(disk: string): { diskBytes: number; diskUsedBytes: number; diskHostBytes: number } {\n try {\n const st = statSync(disk);\n const diskHostBytes = st.blocks * 512;\n const fs = ext4Usage(disk);\n return { diskBytes: st.size, diskUsedBytes: fs ? Math.min(fs.usedBytes, st.size) : diskHostBytes, diskHostBytes };\n } catch {\n return { diskBytes: 0, diskUsedBytes: 0, diskHostBytes: 0 };\n }\n}\n\n/**\n * Give the host back what the guest freed. Firecracker's block device has no discard, so a box's\n * sparse disk file only grows while it runs; on the unmounted disk, e2fsck's discard punches a hole\n * for every free block. `-f`: without it a clean filesystem is skipped, discard included. `-p`: only\n * the fixes that need nobody's say, a journal replay after a power cut among them (what the guest\n * kernel would do at its next mount). Exit 1 and 2 are \"fixed\"; anything else throws.\n */\nexport async function compactDisk(file: string): Promise<void> {\n await run([\"e2fsck\", \"-f\", \"-p\", \"-E\", \"discard\", file], { okExitCodes: [1, 2], timeoutMs: 10 * 60_000 });\n}\n\n/** Whole GiB of the box's overlay (its size as the guest sees it, not what it occupies). */\nfunction diskGibOf(meta: MachineMeta, p: Paths): number {\n try {\n return Math.round(statSync(p.machine(meta.owner, meta.name).overlay).size / 1024 ** 3);\n } catch {\n return 0;\n }\n}\n\n/**\n * Append the box's state change to the usage ledger (core/db.ts). Bookkeeping never fails the\n * operation it records: a ledger problem is logged and the box carries on.\n */\nexport function recordState(meta: MachineMeta, state: UsageState, by: string, p: Paths, at = new Date().toISOString()): void {\n try {\n insertUsageEvent({ boxId: meta.id, owner: meta.owner, name: meta.name, at, state, by, vcpu: meta.vcpu, memMib: meta.memMib, diskGib: diskGibOf(meta, p) }, p);\n } catch (err) {\n log.warn(`usage ledger: ${(err as Error).message}`);\n }\n}\n\n/** No process, but a memory dump in the box dir: `kvbox hibernate` left it, `wake` continues from it. */\nfunction isHibernated(meta: MachineMeta, p: Paths): boolean {\n return !vmAlive(meta) && existsSync(p.machine(meta.owner, meta.name).hibernateVmstate);\n}\n\nexport function statusOf(meta: MachineMeta, p: Paths = paths()): BoxStatus {\n if (vmAlive(meta)) return meta.paused ? \"standby\" : \"running\";\n return isHibernated(meta, p) ? \"hibernated\" : \"stopped\";\n}\n\n/** \"box lab1 is stopped\" / \"is in standby\" / \"is hibernated\", for refusals. */\nexport function stateMessage(ref: BoxRef, status: BoxStatus): string {\n return `box ${shown(ref)} is ${status === \"standby\" ? \"in standby\" : status}`;\n}\n\nfunction toMachine(meta: MachineMeta, p: Paths = paths()): Machine {\n const alive = vmAlive(meta);\n // A pid the server set that is no longer alive: Firecracker died on its own (crash, host reboot,\n // kill). The ledger's open run is closed now, by `server`: the box's stop time is estimated, and\n // `usage` says so. Nothing is written to meta.json here (listing stays read-only on the state dir).\n if (!alive && meta.pid !== null) {\n try {\n closeOpenRun(meta.id, new Date().toISOString(), p);\n } catch (err) {\n log.warn(`usage ledger: ${(err as Error).message}`);\n }\n }\n return {\n id: meta.id,\n name: meta.name,\n owner: meta.owner,\n ip: meta.ip,\n mac: meta.mac,\n pid: alive ? meta.pid : null,\n vcpu: meta.vcpu,\n memMib: meta.memMib,\n ...diskStats(p.machine(meta.owner, meta.name).overlay),\n base: meta.base,\n ...(meta.image !== undefined ? { image: meta.image } : {}),\n ...(meta.url !== undefined ? { url: urlFor(meta.url, meta.name) } : {}),\n createdAt: meta.createdAt,\n source: meta.source,\n status: statusOf(meta, p),\n ...(meta.sshPort === undefined ? {} : { sshPort: meta.sshPort }),\n ...(meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {}),\n ...(meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {}),\n ...(meta.idleCheck !== undefined ? { idleCheck: meta.idleCheck } : {}),\n ...(meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {}),\n ...(meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}),\n };\n}\n\n/** A linked box as its target's owner names it: `api`, or `<slug>/api` for another slug's (#98). */\nconst linkFrom = (l: { owner: string; name: string }, owner: string) => (l.owner === owner ? l.name : `${l.owner.split(\"@\")[0]}/${l.name}`);\n\n/**\n * The idle timeout a new box gets (#47): the request's, else the host's default; 0 is stored as absent.\n * An image whose manifest says `autoHibernate: false` (#87) skips the host's default: nothing wakes it;\n * one that gives a duration (`\"10m\"`, #102) has it instead of the host's default.\n */\nfunction autoHibernateFor(req: CreateMachineRequest, cfg: Config, manifest: ImageManifest = {}): number | undefined {\n if (req.autoHibernateSec !== undefined) return req.autoHibernateSec || undefined;\n if (manifest.autoHibernate === false) return undefined;\n if (typeof manifest.autoHibernate === \"string\") return parseDuration(manifest.autoHibernate) || undefined;\n return cfg.autoHibernateSec || undefined;\n}\n\nasync function readAllMeta(p: Paths): Promise<MachineMeta[]> {\n const metas: MachineMeta[] = [];\n for (const ref of await listMachineRefs(p)) {\n try {\n metas.push(await readMachineMeta(ref, p));\n } catch (err) {\n log.warn(`skipping machines/${refKey(ref)}: ${(err as Error).message}`);\n }\n }\n return metas;\n}\n\n/** The boxes of one owner, or every box on the host when `owner` is null (the host operator's view). */\nexport async function listMachines(scope: ListScope, p: Paths = paths()): Promise<Machine[]> {\n return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));\n}\n\nexport async function getMachine(ref: BoxRef, p: Paths = paths()): Promise<Machine> {\n return toMachine(await readMeta(ref, p), p);\n}\n\nfunction pickName(requested: string | undefined, taken: Set<string>): string {\n if (requested !== undefined) {\n if (!NAME_RE.test(requested)) {\n throw new KvboxError(`invalid box name \"${requested}\": 1-12 chars, lowercase letters, digits and '-', starting with a letter or digit`);\n }\n if (taken.has(requested)) throw new KvboxError(`box ${requested} already exists`);\n return requested;\n }\n for (let i = 1; ; i++) {\n const candidate = `${AUTO_PREFIX}${i}`;\n if (!taken.has(candidate)) return candidate;\n }\n}\n\n/** Lines a box's authorized_keys may hold: the host's key plus what the control plane sends. */\nexport const MAX_SSH_KEY_LINES = 8;\n/** The kernel command line is 2 KB on x86; the rest of ours is ~200 bytes, so the key blob gets this much. */\nconst MAX_SSH_KEYS_B64 = 1500;\n\n/** The authorized_keys lines a box holds: the host's own key first, then what the control plane gave it. Checked, never written unchecked. */\nexport function authorizedKeysLines(hostKey: string, extra: readonly string[]): string[] {\n const lines = [hostKey.trim(), ...extra.map((l) => l.trim())];\n if (lines.some((l) => l === \"\" || /[\\r\\n]/.test(l))) throw new KvboxError(\"sshKeys: every entry must be one non-empty authorized_keys line\");\n if (lines.length > MAX_SSH_KEY_LINES) {\n throw new KvboxError(`a box takes at most ${MAX_SSH_KEY_LINES - 1} SSH keys on top of the host's own; ${extra.length} were given`);\n }\n return lines;\n}\n\n/**\n * The `kvbox.sshkey=` value: the host's own public key and every extra authorized_keys line, as\n * base64 of the whole file (one line each, trailing newline). kvbox-init in the image decodes it\n * verbatim into the kvbox user's authorized_keys at every boot, so `cert-authority …` lines work\n * without an image change. Checked before Firecracker starts.\n */\nexport function authorizedKeysB64(hostKey: string, extra: readonly string[]): string {\n const lines = authorizedKeysLines(hostKey, extra);\n const b64 = Buffer.from(lines.join(\"\\n\") + \"\\n\").toString(\"base64\");\n if (b64.length > MAX_SSH_KEYS_B64) {\n throw new KvboxError(`the SSH keys for this box do not fit the kernel command line (${b64.length} bytes encoded, ${MAX_SSH_KEYS_B64} at most); use fewer or shorter keys`);\n }\n return b64;\n}\n\nexport function bootArgs(name: string, ip: string, cfg: Config, pubkeyB64: string): string {\n // Firecracker appends `pci=off root=/dev/vda ro` itself. ip= is read by the guest kernel,\n // kvbox.name= / kvbox.sshkey= by kvbox-init on first boot (the kvbox-images contract).\n // /sbin/overlay-init in the image stacks the box's disk (/dev/vdb) on the read-only base before\n // systemd starts.\n const args = `console=ttyS0 reboot=k panic=1 init=/sbin/overlay-init kvbox.overlay=/dev/vdb ip=${ip}::${cfg.gateway}:255.255.255.0:${name}:eth0:off kvbox.name=${name} kvbox.sshkey=${pubkeyB64}`;\n return process.arch === \"arm64\" ? `keep_bootcon ${args}` : args;\n}\n\nexport { baseVersionOf };\n\n/** The box's writable disk: a sparse ext4 of `gib` GiB, ready in milliseconds and occupying a few MB until written to. */\nexport async function createOverlay(file: string, gib: number): Promise<void> {\n await writeFile(file, \"\", { mode: 0o600 });\n await truncate(file, gib * 1024 ** 3);\n // -F: it is a file, not a block device. -m 0: no blocks held back for root, the whole disk is the box's.\n // Lazy init: the inode tables are zeroed by the guest kernel as it goes, so mkfs writes almost nothing.\n await run([\"mkfs.ext4\", \"-q\", \"-F\", \"-m\", \"0\", \"-L\", \"kvbox-box\", \"-E\", \"lazy_itable_init=1,lazy_journal_init=1\", file]);\n}\n\nasync function waitFor(pred: () => boolean, timeoutMs: number, stepMs = 50): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (pred()) return true;\n await sleep(stepMs);\n }\n return pred();\n}\n\nasync function tailOf(file: string, lines = 5): Promise<string> {\n try {\n return (await readFile(file, \"utf8\")).trim().split(\"\\n\").slice(-lines).join(\"\\n\");\n } catch {\n return \"\";\n }\n}\n\ninterface LaunchSpec {\n id: string;\n name: string;\n owner: string;\n ip: string;\n mac: string;\n vcpu: number;\n memMib: number;\n base: string;\n /** The image when not the base one (#87); `base` is its version. */\n image?: string | undefined;\n /** See MachineMetaSchema (#49). */\n sshKeys?: string[] | undefined;\n sshPort?: number | undefined;\n /** Attached volumes, in drive order (#52); a cold boot gives Firecracker one drive each. */\n volumes?: string[] | undefined;\n}\n\n/**\n * Spawn Firecracker detached for box `name` and wait for its API socket. Returns the pid; the\n * caller kills it on any later failure. Its working directory is the box dir and the overlay drive\n * is given as a relative path (OVERLAY_REL): a snapshot's vmstate stores drive paths verbatim, so a\n * relative one resolves to whichever box dir the snapshot is restored into.\n */\nasync function spawnFirecracker(ref: BoxRef, cfg: Config, p: Paths): Promise<number> {\n const m = p.machine(ref.owner, ref.name);\n await rm(m.sock, { force: true });\n await rm(m.vsock, { force: true });\n const logFd = openSync(m.log, \"a\");\n let child;\n try {\n child = spawn(cfg.firecracker, [\"--api-sock\", m.sock, \"--id\", ref.name, \"--level\", \"Error\"], {\n cwd: m.dir,\n detached: true,\n stdio: [\"ignore\", logFd, logFd],\n });\n } finally {\n closeSync(logFd);\n }\n child.unref();\n const pid = child.pid;\n if (pid === undefined) throw new KvboxError(\"could not start firecracker\");\n if (!(await waitFor(() => existsSync(m.sock), 3000))) {\n killQuietly(pid);\n throw new KvboxError(`firecracker did not open its API socket; last log lines:\\n${await tailOf(m.log)}`);\n }\n return pid;\n}\n\nfunction killQuietly(pid: number): void {\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n /* already gone */\n }\n}\n\n/** Spawn Firecracker, configure it over its socket, InstanceStart. Returns the pid. Caller rolls back on throw. */\nasync function launch(spec: LaunchSpec, tap: string, cfg: Config, pubkeyB64: string, p: Paths): Promise<number> {\n const m = p.machine(spec.owner, spec.name);\n const baseFile = imageFileFor(spec, p);\n // Before the process: a volume that is gone is a plain refusal, nothing to clean up.\n const volumes = await placeVolumeDrives(spec, p);\n const pid = await spawnFirecracker(spec, cfg, p);\n try {\n const fc = new FirecrackerClient(m.sock);\n try {\n await fc.bootSource(cfg.kernel, bootArgs(spec.name, spec.ip, cfg, pubkeyB64));\n await fc.rootDrive(baseFile);\n await fc.overlayDrive(OVERLAY_REL);\n // /dev/vdc and up, in attachment order; the image mounts each at /mnt/<name> by its label.\n for (const v of volumes) await fc.volumeDrive(volumeDriveId(v.name), volumeDriveRel(v.name));\n await fc.machineConfig(spec.vcpu, spec.memMib);\n await fc.networkInterface(\"eth0\", tap, spec.mac);\n await fc.vsock(GUEST_CID, m.vsock);\n await fc.start();\n } finally {\n await fc.close();\n }\n return pid;\n } catch (err) {\n killQuietly(pid);\n throw err;\n }\n}\n\n/** A frozen VM on disk: a snapshot's files, or a hibernated box's own dump. `label` names it in errors. */\ninterface MemoryImage {\n vmstate: string;\n mem: string;\n label: string;\n /** Volumes the image was frozen with (#52): placeholders are in place, the guest's mounts of them are dropped after the restore. */\n volumes?: readonly VolumeDrive[] | undefined;\n}\n\n/**\n * Spawn Firecracker and restore the image into it, still paused, with this box's tap and vsock\n * in place of the source box's. Drive paths cannot be overridden at load, and need not be: the\n * vmstate names the overlay relative to the box dir, so it already resolves to this box's copy.\n * Returns the pid; the caller resumes and rolls back on throw.\n */\nasync function loadSnapshot(spec: LaunchSpec, image: MemoryImage, tap: string, cfg: Config, p: Paths): Promise<number> {\n const m = p.machine(spec.owner, spec.name);\n const pid = await spawnFirecracker(spec, cfg, p);\n try {\n const fc = new FirecrackerClient(m.sock);\n try {\n await fc.snapshotLoad({\n snapshotPath: image.vmstate,\n memFilePath: image.mem,\n tap: { ifaceId: \"eth0\", hostDevName: tap },\n vsockPath: m.vsock,\n trackDirtyPages: true,\n resume: false,\n });\n } finally {\n await fc.close();\n }\n return pid;\n } catch (err) {\n killQuietly(pid);\n throw err;\n }\n}\n\n/** The base image version `kvbox new` uses right now (what `assets/rootfs.ext4` points at). */\nexport async function currentBaseVersion(p: Paths = paths()): Promise<string> {\n return (await currentImage(undefined, await loadConfig(p), p)).version;\n}\n\n/** The host's own public key line: every box on the host trusts it (that is how local `connect` works). */\nasync function readHostPubkey(p: Paths): Promise<string> {\n try {\n return (await readFile(`${p.sshKey}.pub`, \"utf8\")).trim();\n } catch {\n throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);\n }\n}\n\nfunction assertAssets(cfg: Config): void {\n for (const [what, file] of [[\"kernel\", cfg.kernel], [\"base image\", cfg.rootfs], [\"firecracker\", cfg.firecracker]] as const) {\n if (!existsSync(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);\n }\n}\n\n/**\n * `owner` is who the box belongs to: the caller, as the route resolved it (the host owner over the\n * local socket). `req.owner` is not read here on purpose: a caller does not get to pick.\n */\nexport async function createMachine(req: CreateMachineRequest, owner: string, p: Paths = paths()): Promise<Machine> {\n const cfg = await loadConfig(p);\n if (req.from !== undefined) return restoreMachine(req.from, owner, req, cfg, p);\n const sizeName = req.size ?? cfg.defaultSize;\n if (!isSizeName(sizeName)) throw new KvboxError(`unknown size \"${sizeName}\"; use one of ${Object.keys(SIZES).join(\", \")}`);\n const size = SIZES[sizeName];\n assertAssets(cfg);\n await assertRoomFor(size.vcpu, size.memMib, req.force ?? false, { owner }, \"new\", p);\n const sshKeys = isCloudBox(owner) && req.sshKeys !== undefined && req.sshKeys.length > 0 ? req.sshKeys : undefined;\n authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []); // refuse bad lines before anything exists\n\n const existing = await readAllMeta(p);\n // names are per owner; IPs, taps and public ports are per host\n const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));\n const id = newBoxId(idsInUse(existing));\n const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);\n\n const image = imageKey(req.image);\n const base = await currentImage(image, cfg, p);\n await assertOverlayCapable(base.file, image, base.version);\n // The image's manifest (#87): its variables' defaults and generated secrets join the caller's -e ones.\n const manifest = await imageManifest(base.file);\n // A name the owner's list already has stays the owner's (it would lose to the box's own at boot).\n const env = imageEnv(manifest, name, req.env ?? [], (await readOwnerEnv(owner, p).catch(() => null))?.vars ?? []);\n const now = new Date().toISOString();\n const autoHibernateSec = autoHibernateFor(req, cfg, manifest);\n const vars = env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now }));\n const machine = await bootInto(\n { id, name, owner, ip, mac: macFor(ip), vcpu: size.vcpu, memMib: size.memMib, base: base.version, image, sshKeys },\n // The image is shared read-only by every box; only the box's own writes land in its overlay.\n async (m) => {\n await createOverlay(m.overlay, size.diskGib);\n // A secret the host made up (or a default made from one) is kept as one: `connect` hands it over this once.\n if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);\n },\n { source: \"base\", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },\n cfg,\n p,\n );\n return env.connect === undefined ? machine : { ...machine, connect: env.connect };\n}\n\n/** A box about to exist: everything but the public SSH port, which is drawn when its dir is made. */\ntype NewBox = Omit<LaunchSpec, \"sshPort\">;\ntype BoxDir = ReturnType<Paths[\"machine\"]>;\n/** What a new box's meta.json says about where it came from. */\ntype Origin = Pick<MachineMeta, \"source\" | \"autoHibernateSec\" | \"idleCheck\" | \"url\">;\n\n/**\n * Boot `box` fresh (`new`, a cold fork): `prepare` puts its overlay in its new dir. On any failure\n * nothing of it is left: no process, tap, forwards or dir.\n */\nasync function bootInto(box: NewBox, prepare: (m: BoxDir) => Promise<void>, origin: Origin, cfg: Config, p: Paths): Promise<Machine> {\n const { id, ip, owner, name } = box;\n const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);\n const m = p.machine(owner, name);\n await ensureHostNetwork(cfg);\n await mkdir(m.dir, { recursive: true, mode: 0o700 });\n let tapCreated = false;\n let pid: number | undefined;\n let sshPort: number | undefined;\n let drawn: Awaited<ReturnType<typeof drawPorts>> | undefined;\n try {\n drawn = isCloudBox(owner) ? await drawPorts(1, p) : undefined;\n sshPort = drawn?.ports[0];\n await prepare(m);\n const tap = await createTap(box, cfg);\n tapCreated = true;\n const spec: LaunchSpec = { ...box, sshPort };\n pid = await launch(spec, tap, cfg, keysB64, p);\n await openPorts(spec, cfg, p);\n void pushEnvAfterBoot(spec, pid, m.vsock, p);\n const meta: MachineMeta = { ...spec, pid, bootId: currentBootId(), createdAt: new Date().toISOString(), ...origin };\n await writeMachineMeta(meta, p);\n recordState(meta, \"running\", \"new\", p, meta.createdAt);\n return toMachine(meta, p);\n } catch (err) {\n // leave nothing half-made behind\n if (pid !== undefined) killQuietly(pid);\n await closePorts({ id, ip, sshPort }, cfg);\n if (tapCreated) await deleteTap(id, cfg).catch(() => undefined);\n await rm(m.dir, { recursive: true, force: true });\n boxListChanged();\n throw err;\n } finally {\n drawn?.release();\n }\n}\n\nasync function readSnap(ref: BoxRef, p: Paths): Promise<SnapshotMeta> {\n // A dot dir is a replace's work in progress (#83), never a snapshot.\n if (ref.name.startsWith(\".\")) throw new NotFoundError(`snapshot ${shown(ref)}`);\n try {\n return await readSnapshotMeta(ref, p);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") throw new NotFoundError(`snapshot ${shown(ref)}`);\n throw err;\n }\n}\n\n/** a.b.c.d/len -> len */\nfunction prefixLenOf(subnet: string): number {\n return Number(subnet.split(\"/\")[1]);\n}\n\n/**\n * `kvbox new --from <snapshot>`: a warm box. The snapshot's memory and overlay come back exactly as\n * frozen, processes included, under a new name, IP and MAC. The guest itself still remembers the\n * source box's identity, so its tap stays off the bridge until kvbox-agent (reached over vsock, not\n * the network) has applied the new one and set the clock. Sub-second: the memory file is mapped,\n * not read, and the overlay copy is sparse.\n */\nasync function restoreMachine(fromText: string, owner: string, req: CreateMachineRequest, cfg: Config, p: Paths): Promise<Machine> {\n const from = parseRef(fromText, owner);\n // A `snapshots new --replace` of this snapshot waits until its files are copied and loaded (#83).\n return withSnapshotLock(from, () => restoreFrom(from, owner, req, cfg, p));\n}\n\nasync function restoreFrom(from: BoxRef, owner: string, req: CreateMachineRequest, cfg: Config, p: Paths): Promise<Machine> {\n const snap = await readSnap(from, p);\n if (req.size !== undefined) {\n throw new KvboxError(`--size cannot be combined with --from: a restored box has the snapshot's size (${shown(from)}: ${snap.vcpu} vCPU, ${snap.memMib} MiB)`);\n }\n assertAssets(cfg);\n if (!existsSync(imageFile(snap.image, snap.base, p))) {\n throw new KvboxError(`snapshot ${shown(from)} stacks on ${imageLabel(snap.image)} ${snap.base}, which is gone from ${p.assets}`);\n }\n // A restored database box stays awake like a new one of its image.\n const manifest = await imageManifest(imageFile(snap.image, snap.base, p));\n if (req.image !== undefined && imageKey(req.image) !== snap.image) {\n throw new KvboxError(`--base cannot be combined with --from: a restored box has the snapshot's image (${shown(from)}: ${imageLabel(snap.image)})`);\n }\n await assertRoomFor(snap.vcpu, snap.memMib, req.force ?? false, { owner }, \"new\", p);\n // The lines are kept so a later cold boot (`stop`, `start`) writes them like a fresh box; the\n // restored guest gets them through kvbox-agent (#63).\n const sshKeys = isCloudBox(owner) && req.sshKeys !== undefined && req.sshKeys.length > 0 ? req.sshKeys : undefined;\n authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);\n\n const existing = await readAllMeta(p);\n const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));\n // A restored box is a new box: its own id, never the source box's (a snapshot carries none).\n const id = newBoxId(idsInUse(existing));\n const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);\n const s = p.snapshot(from.owner, from.name);\n // The variables the box will have: the snapshot's, `-e` ones over them (as `mergeBoxEnv` writes them).\n const given = new Set((req.env ?? []).map((v) => v.name));\n const vars = [...(await readBoxEnvFile(s.env)).filter((v) => !given.has(v.name)), ...(req.env ?? []).map((v) => ({ ...v, secret: false }))];\n return restoreInto(\n { id, name, owner, ip, mac: macFor(ip), vcpu: snap.vcpu, memMib: snap.memMib, base: snap.base, image: snap.image, sshKeys },\n async (m) => {\n await run([\"cp\", \"--sparse=always\", \"--reflink=auto\", s.overlay, m.overlay]);\n // The snapshot's own variables (#87), with `-e` ones over them.\n await copyBoxEnv(s.env, m.env);\n if (req.env?.length) await mergeBoxEnv({ owner, name }, req.env, p);\n // The box's memory lineage starts at the snapshot's image: its first snapshot is a diff merged onto it.\n await link(s.mem, m.memBase);\n // The vmstate names the source's volume drives; a new box never comes with a volume (decision\n // \"A snapshot captures the box, never its volume\"), so each gets an empty file of the same size.\n await placeholderDrives(m.dir, snap.volumes ?? []);\n return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };\n },\n { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },\n cfg,\n p,\n );\n}\n\n/**\n * Bring `box` up from a frozen image under its own identity (`new --from`, a warm fork). `prepare`\n * fills its new dir (overlay and `mem.base`) and names the image to load. On any failure nothing of\n * it is left: no process, tap, forwards or dir. With `keysOrFail`, a guest that keeps the authorized_keys\n * it was frozen with is such a failure, and the string leads its message.\n */\nasync function restoreInto(box: NewBox, prepare: (m: BoxDir) => Promise<MemoryImage>, origin: Origin, cfg: Config, p: Paths, keysOrFail?: string): Promise<Machine> {\n const { id, ip, owner, name } = box;\n const m = p.machine(owner, name);\n await ensureHostNetwork(cfg);\n await mkdir(m.dir, { recursive: true, mode: 0o700 });\n let tapCreated = false;\n let pid: number | undefined;\n let sshPort: number | undefined;\n let drawn: Awaited<ReturnType<typeof drawPorts>> | undefined;\n try {\n drawn = isCloudBox(owner) ? await drawPorts(1, p) : undefined;\n sshPort = drawn?.ports[0];\n const image = await prepare(m);\n const tap = await createTap(box, cfg, { detached: true });\n tapCreated = true;\n const spec: LaunchSpec = { ...box, sshPort };\n pid = await loadSnapshot(spec, image, tap, cfg, p);\n await resumeVm(m.sock);\n await introduce(spec, m.vsock, cfg, {\n silent: `nothing answered on the restored box's control channel for 3 s; the restored box was discarded, try again`,\n noAnswer: \"the restored box was discarded. kvbox-agent inside it took the request but gave no answer; try again, and if it keeps happening look at the box's journal (kvbox exec <box> -- sudo journalctl -u kvbox-agent) on a box started from the same snapshot.\",\n });\n // The guest woke up with the authorized_keys the image froze; give it the current ones (#63).\n const stale = await pushAuthorizedKeys(box, m.vsock, p);\n if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);\n // And with the source's volumes mounted, over placeholders now: drop those mounts (#52).\n if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);\n // And with the variables of the moment it was frozen: give it its owner's list of today (#88).\n await pushEnv(box, m.vsock, p);\n await attachTap(box, cfg);\n await openPorts(spec, cfg, p);\n const meta: MachineMeta = { ...spec, pid, bootId: currentBootId(), createdAt: new Date().toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : undefined };\n await writeMachineMeta(meta, p);\n recordState(meta, \"running\", \"new\", p, meta.createdAt);\n return toMachine(meta, p);\n } catch (err) {\n if (pid !== undefined) killQuietly(pid);\n await closePorts({ id, ip, sshPort }, cfg);\n if (tapCreated) await deleteTap(id, cfg).catch(() => undefined);\n await rm(m.dir, { recursive: true, force: true });\n boxListChanged();\n throw err;\n } finally {\n drawn?.release();\n }\n}\n\n/**\n * `kvbox vm fork <box> [name]` (#79): a new box, `owner`'s, from `ref` as it is right now, on this\n * host, and no snapshot left behind. A running or paused source is copied warm, straight into the new\n * box's dir: the copy carries on from the same instant, processes included, under its own name, IP\n * and MAC like `new --from`, and the source is frozen only as long as a snapshot freezes it. A stopped\n * source is copied cold: its overlay, then a fresh boot. A hibernated one is refused (decision\n * c6d662d8). Under the source's lock, so it cannot change state halfway.\n */\nexport const forkMachine = locked(async function forkMachine(ref: BoxRef, owner: string, req: ForkMachineRequest, p: Paths = paths()): Promise<Machine> {\n const src = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const status = statusOf(src, p);\n if (status === \"hibernated\") throw new KvboxError(`${stateMessage(ref, status)}; a fork copies a running or a stopped box (kvbox wake ${shown(ref)} first)`);\n const warm = status !== \"stopped\";\n const srcDisk = p.machine(src.owner, src.name).overlay;\n let shape = { vcpu: src.vcpu, memMib: src.memMib };\n let growTo: number | undefined;\n if (req.size !== undefined) {\n if (warm) {\n throw new KvboxError(`--size cannot be combined with forking a running box: the copy keeps its memory, so its size (${shown(ref)}: ${src.vcpu} vCPU, ${src.memMib} MiB); kvbox vm rescale the copy afterwards`);\n }\n if (!isSizeName(req.size)) throw new KvboxError(`unknown size \"${req.size}\"; use one of ${Object.keys(SIZES).join(\", \")}`);\n const preset = SIZES[req.size];\n const diskGib = Math.round(statSync(srcDisk).size / 1024 ** 3);\n if (preset.diskGib < diskGib) throw new KvboxError(`box ${shown(ref)} has a ${diskGib} GB disk and a disk cannot shrink; size ${req.size} has ${preset.diskGib} GB`);\n shape = { vcpu: preset.vcpu, memMib: preset.memMib };\n growTo = preset.diskGib > diskGib ? preset.diskGib : undefined;\n }\n assertAssets(cfg);\n imageFileFor(src, p);\n await assertRoomFor(shape.vcpu, shape.memMib, req.force ?? false, { owner }, \"new\", p);\n const sshKeys = isCloudBox(owner) && req.sshKeys !== undefined && req.sshKeys.length > 0 ? req.sshKeys : undefined;\n authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);\n\n const existing = await readAllMeta(p);\n const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));\n const id = newBoxId(idsInUse(existing));\n const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);\n const box: NewBox = { id, name, owner, ip, mac: macFor(ip), ...shape, base: src.base, image: src.image, sshKeys };\n const srcEnv = p.machine(src.owner, src.name).env;\n // Ports and subdomains are not copied: each is one box's alone.\n const origin: Origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || undefined, idleCheck: src.idleCheck, url: src.url };\n\n if (!warm) {\n return bootInto(\n box,\n async (m) => {\n await run([\"cp\", \"--sparse=always\", \"--reflink=auto\", srcDisk, m.overlay]);\n if (growTo !== undefined) await growDisk(m.overlay, growTo);\n await copyBoxEnv(srcEnv, m.env);\n },\n origin,\n cfg,\n p,\n );\n }\n // The capture lands in the new box's dir: its memory image is the new box's mem.base (and, hard-linked,\n // the source's), so a fork costs what a snapshot costs and leaves nothing to clean up but the VM state.\n const srcVolumes = await captureDrivesOf(src, p);\n const machine = await restoreInto(\n box,\n async (m) => {\n await captureBox(src, { vmstate: m.forkVmstate, mem: m.memBase, overlay: m.overlay }, cfg, p);\n await copyBoxEnv(srcEnv, m.env);\n // The source's volume drives are in the captured state; the copy gets placeholders, not the data (#52).\n await placeholderDrives(m.dir, srcVolumes);\n return { vmstate: m.forkVmstate, mem: m.memBase, label: `box ${shown(ref)}`, volumes: srcVolumes };\n },\n origin,\n cfg,\n p,\n // The copy froze the source slug's CA line; left in place, that slug's members could open a box of\n // another slug. Such a fork is discarded rather than kept stale; a cold fork boots with the new line.\n owner === src.owner ? undefined : `box ${shown(ref)} was not forked into ${owner}: the copy would still let ${src.owner} in (stop the box and fork it cold, which boots with ${owner}'s keys)`,\n );\n await rm(p.machine(owner, name).forkVmstate, { force: true });\n return machine;\n});\n\n/**\n * Hand the restored guest its identity through kvbox-agent. The agent is already running (it was\n * in memory at the snapshot), but the vsock path to it comes up with the VM, so refused connections\n * are retried for a moment. Once it has accepted, it gets a generous wait: the guest's memory is\n * paged in from the snapshot file on first touch, which on a cold, busy disk can take seconds\n * (seen on the dev host right after install-server.sh had written a new base image).\n */\nconst AGENT_REPLY_MS = 20_000;\n\nasync function introduce(spec: LaunchSpec, vsock: string, cfg: Config, failure: { silent: string; noAnswer: string }): Promise<void> {\n const id = { name: spec.name, ip: spec.ip, prefixLen: prefixLenOf(cfg.subnet), gateway: cfg.gateway, mac: spec.mac, time: Math.floor(Date.now() / 1000) };\n const deadline = Date.now() + 3000;\n for (;;) {\n try {\n await setIdentity(vsock, id, AGENT_REPLY_MS);\n return;\n } catch (err) {\n const msg = (err as Error).message;\n const transient = /unreachable|refused|before the guest accepted/.test(msg);\n if (transient && Date.now() < deadline) {\n await sleep(100);\n continue;\n }\n if (transient) throw new KvboxError(`${msg}\\n ${failure.silent}`);\n throw new KvboxError(`${msg}\\n ${failure.noAnswer}`);\n }\n }\n}\n\n/**\n * Hand a live guest its current authorized_keys through kvbox-agent (base v0.6.0 and later): a\n * restored or woken box has the file it was frozen with, which may predate a CA change (#63, #55).\n * Never fails the caller. The reason is returned (and logged) when the guest keeps its old file: an\n * image whose agent does not know the request, or one that did not answer; a boot fixes both.\n */\nexport async function pushAuthorizedKeys(box: Pick<MachineMeta, \"owner\" | \"name\" | \"sshKeys\">, vsock: string, p: Paths): Promise<string | undefined> {\n try {\n await setAuthorizedKeys(vsock, authorizedKeysLines(await readHostPubkey(p), box.sshKeys ?? []), AGENT_REPLY_MS);\n return undefined;\n } catch (err) {\n const why = isUnknownOp(err)\n ? `its image predates base v0.6.0, whose kvbox-agent can replace authorized_keys (kvbox vm update ${shown(box)} moves it onto the current base)`\n : (err as Error).message;\n log.warn(`box ${shown(box)} keeps the authorized_keys it was frozen with: ${why}`);\n return why;\n }\n}\n\n/**\n * A box restored from an image frozen with volumes attached (#52) still has them mounted, over empty\n * placeholder disks now: ask kvbox-agent (base v0.9.0 and later) to drop those mounts, so a program\n * touching the path gets an error instead of a dead filesystem. Never fails the restore: an older\n * image keeps the dead mounts until the box's next cold boot, and the warning says so.\n */\nasync function dropGuestVolumes(box: Pick<MachineMeta, \"owner\" | \"name\">, vsock: string): Promise<void> {\n try {\n await dropVolumes(vsock, AGENT_REPLY_MS);\n } catch (err) {\n const why = isUnknownOp(err)\n ? `its image predates base v0.9.0, whose kvbox-agent can unmount them (kvbox vm update ${shown(box)} moves it onto the current base)`\n : (err as Error).message;\n log.warn(`box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);\n }\n}\n\n/**\n * Hand a live guest its owner's environment variables (#88, base v0.10.0 and later). Never fails the\n * caller: a local owner has no list and nothing is sent; a cloud owner's box always gets one, empty\n * when the slug never set a variable, so a box forked from another slug's box loses that slug's\n * files. A guest that cannot take it keeps the files it has until its next boot, which the warning says.\n */\nasync function pushEnv(box: Pick<MachineMeta, \"owner\" | \"name\">, vsock: string, p: Paths): Promise<void> {\n const vars = await envForBoot(box, p);\n if (vars === null) return;\n try {\n await setEnv(vsock, vars, AGENT_REPLY_MS);\n } catch (err) {\n warnEnv(box, vars, err);\n }\n}\n\n/** An image older than the request is only worth a warning when there was something to hand over. */\nfunction warnEnv(box: Pick<MachineMeta, \"owner\" | \"name\">, vars: readonly unknown[], err: unknown): void {\n if (isUnknownOp(err)) {\n if (vars.length === 0) return;\n log.warn(`box ${shown(box)} did not get its environment variables: its image predates base v0.10.0, whose kvbox-agent takes them (kvbox vm update ${shown(box)} moves it onto the current base)`);\n return;\n }\n log.warn(`box ${shown(box)} did not get its environment variables: ${(err as Error).message}`);\n}\n\n/** How long a cold boot may take before kvbox-agent listens: the box boots in seconds, a busy host is slower. */\nconst ENV_BOOT_WAIT_MS = 120_000;\n\n/**\n * After a cold boot (`new`, `start`) the guest's kvbox-agent listens a few seconds after the VM starts:\n * wait for it in the background and hand it the owner's list then. `new` and `start` do not wait for\n * it; the app service comes up with last boot's /etc/kvbox/env and the agent restarts it if the list\n * changed (decision \"Env vars belong to a slug…\"). The list is read again at every attempt, so a change\n * made while the guest boots is what it gets; the loop ends when `pid`, the Firecracker process it was\n * started for, is gone: the box was stopped, or restarted and a new loop owns the new boot (the vsock\n * path is the same for every boot of a box, so it tells the two apart no better than the list does).\n * Exported for its test; `timing` is the test's shortcut.\n */\nexport function pushEnvAfterBoot(box: Pick<MachineMeta, \"owner\" | \"name\">, pid: number, vsock: string, p: Paths, timing = { replyMs: AGENT_REPLY_MS, waitMs: ENV_BOOT_WAIT_MS }): Promise<void> {\n return (async () => {\n const deadline = Date.now() + timing.waitMs;\n for (;;) {\n if (!pidAlive(pid)) return;\n const vars = await envForBoot(box, p);\n if (vars === null) return;\n try {\n await setEnv(vsock, vars, timing.replyMs);\n return;\n } catch (err) {\n if (!pidAlive(pid)) return;\n if (isNoAgent(err) && Date.now() < deadline) {\n await sleep(500);\n continue;\n }\n warnEnv(box, vars, err);\n return;\n }\n }\n })();\n}\n\nasync function resumeVm(sock: string): Promise<void> {\n const fc = new FirecrackerClient(sock);\n try {\n await fc.resume();\n } finally {\n await fc.close();\n }\n}\n\n/**\n * Clean guest shutdown (Ctrl+Alt+Del), SIGKILL after `graceMs`; tap removed; disk and meta kept.\n * A box in standby is unfrozen first, so the guest can actually act on the key.\n */\nasync function shutdown(meta: MachineMeta, cfg: Config, p: Paths, graceMs: number): Promise<void> {\n const pid = meta.pid;\n if (vmAlive(meta)) {\n const fc = new FirecrackerClient(p.machine(meta.owner, meta.name).sock);\n try {\n if (meta.paused) await fc.resume();\n await fc.sendCtrlAltDel();\n } catch {\n process.kill(pid!, \"SIGTERM\");\n } finally {\n await fc.close();\n }\n await waitDead(pid!, graceMs);\n }\n await cleanupProcess(meta, cfg, p);\n}\n\n/** Wait `graceMs` for the process to go, then SIGKILL it. */\nasync function waitDead(pid: number, graceMs: number): Promise<void> {\n if (!(await waitFor(() => !pidAlive(pid), graceMs, 100))) {\n killQuietly(pid);\n await waitFor(() => !pidAlive(pid), 1000, 50);\n }\n}\n\n/** After Firecracker is gone: the public port, the tap and the sockets it left behind. */\nasync function cleanupProcess(meta: MachineMeta, cfg: Config, p: Paths): Promise<void> {\n await closePorts(meta, cfg);\n await deleteTap(meta.id, cfg);\n const m = p.machine(meta.owner, meta.name);\n await rm(m.sock, { force: true });\n await rm(m.vsock, { force: true });\n}\n\n/**\n * `kvbox stop`: clean shutdown, disk kept. A hibernated box has no process to shut down; its memory\n * dump is discarded instead, which for the guest is a power cut (files intact, what was in memory gone).\n */\nexport const stopMachine = locked(async function stopMachine(ref: BoxRef, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const m = p.machine(ref.owner, ref.name);\n if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);\n await shutdown(meta, cfg, p, 10_000);\n // Best effort, and only here: the restarts (rescale, update, volume attach) shut down and boot\n // again at once, a stop is when the box has the time. A problem is logged and the stop stands.\n await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${(err as Error).message}`));\n await rm(m.hibernateDir, { recursive: true, force: true });\n // A stopped box boots from scratch next time, so its memory lineage (see state.ts memSnapshots) starts over.\n await rm(m.memBase, { force: true });\n const stopped: MachineMeta = { ...meta, pid: null, memSnapshots: undefined, paused: undefined };\n await writeMachineMeta(stopped, p);\n recordState(stopped, \"stopped\", \"stop\", p);\n return toMachine(stopped, p);\n});\n\n/**\n * `kvbox start`: boot a stopped box. Its size counts against the host like a new box's (#37);\n * `force` skips that, and the restarts that only give a running box back its own room (rescale,\n * update, volume attach, recovery after a host reboot) pass it.\n */\nexport const startMachine = locked(async function startMachine(ref: BoxRef, p: Paths = paths(), force: boolean = false): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n if (vmAlive(meta)) throw new KvboxError(`box ${shown(ref)} is already ${meta.paused ? \"up, in standby (kvbox resume \" + shown(ref) + \")\" : \"running\"}`);\n if (isHibernated(meta, p)) {\n throw new KvboxError(`${stateMessage(ref, \"hibernated\")}: kvbox wake ${shown(ref)} continues where it left off; to boot fresh instead, kvbox stop ${shown(ref)} first (discards its memory)`);\n }\n assertAssets(cfg);\n await assertRoomFor(meta.vcpu, meta.memMib, force, meta, \"start\", p);\n const keysB64 = authorizedKeysB64(await readHostPubkey(p), meta.sshKeys ?? []);\n await ensureHostNetwork(cfg);\n const tap = await createTap(meta, cfg);\n let pid: number | undefined;\n try {\n pid = await launch(meta, tap, cfg, keysB64, p);\n await openPorts(meta, cfg, p);\n void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);\n // kvbox-init writes the file from the command line; a VM just launched is never paused\n const started: MachineMeta = { ...meta, pid, bootId: currentBootId(), sshKeysStale: undefined, paused: undefined };\n await writeMachineMeta(started, p);\n recordState(started, \"running\", \"start\", p);\n return toMachine(started, p);\n } catch (err) {\n if (pid !== undefined) killQuietly(pid);\n await closePorts(meta, cfg);\n await deleteTap(meta.id, cfg).catch(() => undefined);\n throw err;\n }\n});\n\n/**\n * Replace the authorized_keys lines the box gets on top of the host's key (the control plane's\n * `rewrite-boxes`: a new CA line for the box's owner). Checked like at `new`, before anything is\n * written. A running box gets them through kvbox-agent right away; any other state gets them when\n * it next runs (`applied` says when).\n */\nexport const setSshKeys = locked(async function setSshKeys(ref: BoxRef, sshKeys: readonly string[], p: Paths = paths()): Promise<{ machine: Machine; applied: SshKeysApplied }> {\n const meta = await readMeta(ref, p);\n // Like `new`: a local box trusts this host's key and nothing else; only a cloud box carries lines.\n if (!isCloudBox(meta.owner)) throw new KvboxError(`box ${shown(ref)} is local: it trusts this host's key, there are no authorized_keys lines to replace`);\n // A cloud box with the host's key alone would be open to nobody who logs in: one bad call must not do that fleet-wide.\n if (sshKeys.length === 0) throw new KvboxError(\"sshKeys: at least one authorized_keys line (the box would keep only the host's own key)\");\n authorizedKeysB64(await readHostPubkey(p), sshKeys);\n const { meta: updated, applied } = await applySshKeys(meta, sshKeys, p);\n return { machine: toMachine(updated, p), applied };\n});\n\n/**\n * Write new `sshKeys` into meta.json and get them to the guest: through kvbox-agent when the box\n * runs, else at its next start (kvbox-init), wake or resume (the `sshKeysStale` flag makes those\n * push). A running box whose agent could not take them is `later`: its next stop and start.\n */\nasync function applySshKeys(meta: MachineMeta, sshKeys: readonly string[], p: Paths): Promise<{ meta: MachineMeta; applied: SshKeysApplied; why?: string }> {\n const status = statusOf(meta, p);\n let updated: MachineMeta = { ...meta, sshKeys: [...sshKeys], sshKeysStale: status === \"stopped\" ? undefined : true };\n let applied: SshKeysApplied = status === \"stopped\" ? \"start\" : status === \"standby\" ? \"resume\" : status === \"hibernated\" ? \"wake\" : \"later\";\n let why: string | undefined;\n if (status === \"running\") {\n why = await pushAuthorizedKeys(updated, p.machine(meta.owner, meta.name).vsock, p);\n if (why === undefined) {\n updated = { ...updated, sshKeysStale: undefined };\n applied = \"now\";\n }\n }\n await writeMachineMeta(updated, p);\n return why === undefined ? { meta: updated, applied } : { meta: updated, applied, why };\n}\n\n/**\n * `kvbox-server trust-ca` (#55): every cloud box on this host trusts `publicKey` as the CA for its\n * owner, in place of the CA line it had (one CA per box, as at `new`; the old CA is out, which is\n * the point after a leak, and a laptop renews its certificate at the next refused connect). Local\n * boxes are untouched. A box that is not running gets the line when it next runs.\n */\nexport async function trustCa(publicKeyText: string, p: Paths = paths()): Promise<TrustCaReport> {\n const publicKey = parseSshPublicKey(publicKeyText);\n const report: TrustCaReport = { publicKey, fingerprint: sshKeyFingerprint(publicKey), updated: [], pending: [], failed: [], local: 0, skipped: [] };\n const hostKey = await readHostPubkey(p);\n for (const listed of await readAllMeta(p)) {\n if (!isCloudBox(listed.owner)) {\n report.local++;\n continue;\n }\n const box = refKey(listed);\n try {\n await withBoxLock(listed, async () => {\n const meta = await readMeta(listed, p); // again, under the lock: the listing may be stale by now\n // A cloud box made without a CA line (a managed service's, #173) opens to no certificate: it gets none now either.\n if (!(meta.sshKeys ?? []).some(isCaLine)) {\n report.skipped!.push(box);\n return;\n }\n const sshKeys = [...(meta.sshKeys ?? []).filter((l) => !isCaLine(l)), caLineFor(meta.owner, publicKey)];\n authorizedKeysLines(hostKey, sshKeys);\n const { applied, why } = await applySshKeys(meta, sshKeys, p);\n if (applied === \"now\") report.updated.push(box);\n else report.pending.push(why === undefined ? { box, when: applied } : { box, when: applied, why });\n });\n } catch (err) {\n report.failed.push({ box, error: (err as Error).message });\n }\n }\n return report;\n}\n\n/** `kvbox pause`: freeze the VM in place. Memory and processes stay, no CPU is used; `resume` is instant. */\nexport const pauseMachine = locked(async function pauseMachine(ref: BoxRef, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const status = statusOf(meta, p);\n if (status === \"standby\") throw new KvboxError(`${stateMessage(ref, status)} already`);\n if (status === \"hibernated\") throw new KvboxError(`${stateMessage(ref, status)}; kvbox wake ${shown(ref)} brings it back`);\n if (status === \"stopped\") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be paused`);\n const fc = new FirecrackerClient(p.machine(ref.owner, ref.name).sock);\n try {\n await fc.pause();\n } finally {\n await fc.close();\n }\n const paused: MachineMeta = { ...meta, paused: true };\n await writeMachineMeta(paused, p);\n recordState(paused, \"standby\", \"pause\", p);\n return toMachine(paused, p);\n});\n\n/** `kvbox resume`: unfreeze a box in standby. */\nexport const resumeMachine = locked(async function resumeMachine(ref: BoxRef, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const status = statusOf(meta, p);\n if (status === \"running\") throw new KvboxError(`${stateMessage(ref, status)} already`);\n if (status === \"hibernated\") throw new KvboxError(`${stateMessage(ref, status)}, not in standby; kvbox wake ${shown(ref)} brings it back`);\n if (status === \"stopped\") throw new KvboxError(`${stateMessage(ref, status)}, not in standby; kvbox start ${shown(ref)} boots it`);\n const m = p.machine(ref.owner, ref.name);\n await resumeVm(m.sock);\n // Keys changed while it was frozen (#55): the agent can take them now.\n const stale = meta.sshKeysStale ? await pushAuthorizedKeys(meta, m.vsock, p) : undefined;\n const running: MachineMeta = { ...meta, paused: undefined, sshKeysStale: stale ? true : undefined };\n await writeMachineMeta(running, p);\n recordState(running, \"running\", \"resume\", p);\n return toMachine(running, p);\n});\n\n/**\n * `kvbox hibernate`: write the VM's memory and state into the box's own dir, then end the Firecracker\n * process. The host gets the RAM back; `wake` loads the image into a new process and the guest carries\n * on from the same instant. A snapshot that is not named and not copied: the overlay stays where it is.\n * Works from running or standby. The dump is a full one (the box's diff lineage ends here; wake starts\n * a new one from this image), sparse once the untouched pages are punched out.\n * `by` names who asked in the ledger: `hibernate` for a caller, `auto-hibernate` for core/idle.ts.\n */\nexport const hibernateMachine = locked(async function hibernateMachine(ref: BoxRef, p: Paths = paths(), by: string = \"hibernate\"): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const status = statusOf(meta, p);\n if (status === \"hibernated\") throw new KvboxError(`${stateMessage(ref, status)} already`);\n if (status === \"stopped\") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);\n const m = p.machine(ref.owner, ref.name);\n await rm(m.hibernateDir, { recursive: true, force: true });\n await mkdir(m.hibernateDir, { recursive: true, mode: 0o700 });\n const fc = new FirecrackerClient(m.sock);\n try {\n try {\n await fc.pause();\n await fc.snapshotCreate(m.hibernateVmstate, m.hibernateMem, \"Full\");\n } catch (err) {\n // Leave the box as it was: running, or in standby if it already was.\n await rm(m.hibernateDir, { recursive: true, force: true });\n if (!meta.paused) await fc.resume().catch(() => undefined);\n throw err;\n }\n } finally {\n await fc.close();\n }\n killQuietly(meta.pid!);\n await waitFor(() => !pidAlive(meta.pid), 5000, 50);\n await cleanupProcess(meta, cfg, p);\n // Pages the guest never touched are zeros in a full dump: punch them out so the image costs what was used.\n await run([\"fallocate\", \"--dig-holes\", m.hibernateMem]);\n await rm(m.memBase, { force: true });\n const hibernated: MachineMeta = { ...meta, pid: null, memSnapshots: undefined, paused: undefined };\n await writeMachineMeta(hibernated, p);\n recordState(hibernated, \"hibernated\", by, p);\n return toMachine(hibernated, p);\n});\n\n/**\n * `kvbox wake`: a hibernated box runs again from its memory image, same name, IP and MAC, so the guest\n * needs no new identity; kvbox-agent is still told, which is how its clock catches up on the time it\n * slept. The image becomes the box's memory lineage base (its next snapshot is a diff), like a box\n * restored from a snapshot. On failure the image is kept and the box stays hibernated.\n */\nexport const wakeMachine = locked(async function wakeMachine(ref: BoxRef, p: Paths = paths(), force: boolean = false): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const status = statusOf(meta, p);\n if (status === \"running\" || status === \"standby\") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated`);\n if (status === \"stopped\") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated; kvbox start ${shown(ref)} boots it`);\n assertAssets(cfg);\n if (!existsSync(imageFile(meta.image, meta.base, p))) {\n throw new KvboxError(`box ${shown(ref)} stacks on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);\n }\n // Hibernated, it reserved nothing; awake it takes its size again (#37).\n await assertRoomFor(meta.vcpu, meta.memMib, force, meta, \"start\", p);\n const m = p.machine(ref.owner, ref.name);\n await ensureHostNetwork(cfg);\n const tap = await createTap(meta, cfg, { detached: true });\n let pid: number | undefined;\n let stale: string | undefined;\n try {\n const spec: LaunchSpec = { id: meta.id, name: meta.name, owner: meta.owner, ip: meta.ip, mac: meta.mac, vcpu: meta.vcpu, memMib: meta.memMib, base: meta.base };\n pid = await loadSnapshot(spec, { vmstate: m.hibernateVmstate, mem: m.hibernateMem, label: `box ${shown(ref)}'s memory image` }, tap, cfg, p);\n await resumeVm(m.sock);\n await introduce(spec, m.vsock, cfg, {\n silent: `nothing answered on the box's control channel for 3 s; it stays hibernated, try kvbox wake ${shown(ref)} again`,\n noAnswer: `the box stays hibernated. kvbox-agent inside it took the request but gave no answer; try kvbox wake ${shown(ref)} again`,\n });\n // The guest's authorized_keys are the ones it slept with; the CA may have changed meanwhile (#55).\n stale = await pushAuthorizedKeys(meta, m.vsock, p);\n await attachTap(meta, cfg);\n await openPorts(meta, cfg, p);\n } catch (err) {\n if (pid !== undefined) killQuietly(pid);\n await closePorts(meta, cfg);\n await deleteTap(meta.id, cfg).catch(() => undefined);\n throw err;\n }\n // The image is now the lineage base; the hibernate dir goes, the hard link keeps the data.\n await rm(m.memBase, { force: true });\n await link(m.hibernateMem, m.memBase);\n await rm(m.hibernateDir, { recursive: true, force: true });\n const running: MachineMeta = { ...meta, pid, bootId: currentBootId(), memSnapshots: 1, paused: undefined, sshKeysStale: stale ? true : undefined };\n await writeMachineMeta(running, p);\n recordState(running, \"running\", \"wake\", p);\n return toMachine(running, p);\n});\n\n/**\n * Change a box's shape or base. Both only take effect at boot (Firecracker fixes vCPU and memory\n * when the VM starts, the base is stacked by overlay-init), so a running box is shut down and\n * started again; a stopped one just gets its meta updated. `whileStopped` runs in between, for\n * work that needs the disk unmounted. Returns the box, running again if it was.\n */\nasync function applyAtNextBoot(\n meta: MachineMeta,\n changes: Partial<MachineMeta>,\n by: \"rescale\" | \"update\" | \"attach\" | \"detach\" | \"restore\" | \"grow\",\n cfg: Config,\n p: Paths,\n whileStopped?: () => Promise<void>,\n): Promise<Machine> {\n const wasRunning = vmAlive(meta);\n if (wasRunning) {\n await shutdown(meta, cfg, p, 10_000);\n await rm(p.machine(meta.owner, meta.name).memBase, { force: true });\n }\n const updated: MachineMeta = { ...meta, ...changes, pid: null, memSnapshots: undefined, paused: undefined };\n await writeMachineMeta(updated, p);\n if (whileStopped) {\n try {\n await whileStopped();\n } catch (err) {\n // The change did not happen: the box keeps what it had, its ledger says it stopped, and one that\n // was running runs again (a box left down by a failed grow would be billed as running).\n const before: MachineMeta = { ...meta, pid: null, memSnapshots: undefined, paused: undefined };\n await writeMachineMeta(before, p);\n if (wasRunning) {\n recordState(before, \"stopped\", by, p);\n await startMachine(meta, p, true).catch((e: Error) => {\n throw new KvboxError(`${(err as Error).message}; and box ${shown(meta)} could not be started again: ${e.message}`);\n });\n }\n throw err;\n }\n }\n // The new shape is on this row (after the disk grew), so usage rates change from here on.\n recordState(updated, \"stopped\", by, p);\n // The box was running, so its room was its own (a rescale that grows checked the new shape first).\n return wasRunning ? startMachine(meta, p, true) : toMachine(updated, p);\n}\n\n/** A hibernated box's memory image fits its current shape and base; neither can change under it. */\nfunction assertNotHibernated(meta: MachineMeta, p: Paths): void {\n if (isHibernated(meta, p)) {\n throw new KvboxError(`${stateMessage(meta, \"hibernated\")}; its memory image was made with its current shape and base: kvbox wake ${shown(meta)} first`);\n }\n}\n\n/** `kvbox vm update <box>`: move the box onto the current version of its image (the one new boxes of that image get). Its overlay (its own writes) stays. */\nexport const updateMachine = locked(async function updateMachine(ref: BoxRef, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n assertNotHibernated(meta, p);\n assertAssets(cfg);\n // The current version of the box's own image (#87): a postgres box never lands on the base one.\n const base = await currentImage(meta.image, cfg, p);\n if (base.version === meta.base) return toMachine(meta, p);\n await assertOverlayCapable(base.file, meta.image, base.version);\n return applyAtNextBoot(meta, { base: base.version }, \"update\", cfg, p);\n});\n\n/**\n * `kvbox vm rescale <box>`: new vCPU count, memory and/or disk. The disk can only grow: the overlay\n * file is extended and its ext4 resized while the box is down (e2fsck first, resize2fs refuses\n * a filesystem that was mounted since its last check).\n */\nexport const rescaleMachine = locked(async function rescaleMachine(ref: BoxRef, req: RescaleMachineRequest, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n assertNotHibernated(meta, p);\n const disk = p.machine(ref.owner, ref.name).overlay;\n const currentDiskGib = Math.round(statSync(disk).size / 1024 ** 3);\n const preset = req.size !== undefined && isSizeName(req.size) ? SIZES[req.size] : undefined;\n const target = {\n vcpu: req.vcpu ?? preset?.vcpu ?? meta.vcpu,\n memMib: req.memMib ?? preset?.memMib ?? meta.memMib,\n diskGib: req.diskGib ?? preset?.diskGib ?? currentDiskGib,\n };\n if (target.diskGib < currentDiskGib) {\n throw new KvboxError(`box ${shown(ref)} has a ${currentDiskGib} GB disk and a disk cannot shrink; ${target.diskGib} GB is smaller`);\n }\n const changes: Partial<MachineMeta> = {};\n if (target.vcpu !== meta.vcpu) changes.vcpu = target.vcpu;\n if (target.memMib !== meta.memMib) changes.memMib = target.memMib;\n const growTo = target.diskGib > currentDiskGib ? target.diskGib : undefined;\n if (Object.keys(changes).length === 0 && growTo === undefined) return toMachine(meta, p);\n // A running box that grows needs the room now (its own size is given back at the restart); a\n // stopped one is checked when it starts (#37).\n if (vmAlive(meta) && (target.vcpu > meta.vcpu || target.memMib > meta.memMib)) {\n await assertRoomFor(target.vcpu, target.memMib, req.force ?? false, meta, \"rescale\", p);\n }\n return applyAtNextBoot(meta, changes, \"rescale\", cfg, p, growTo === undefined ? undefined : () => growDisk(disk, growTo));\n});\n\n/**\n * A backup's restore (decision \"Backups: encrypted 4 MiB chunks in object storage\"): `file`, a complete\n * disk built beside the box's own, becomes the box's disk, and `vars` its own variables (null: none).\n * The base it stacks on comes with it. Like a rescale: a running box is shut down and started again, a\n * stopped one stays stopped, a hibernated one is refused (its memory belongs to the disk it has). A disk\n * that has grown since the backup keeps its size: the restored filesystem is grown into it.\n */\nexport const replaceDisk = locked(async function replaceDisk(\n ref: BoxRef,\n file: string,\n disk: { base: string; image?: string | undefined; vars: BoxVarList | null },\n p: Paths = paths(),\n): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n assertNotHibernated(meta, p);\n const m = p.machine(ref.owner, ref.name);\n const currentGib = Math.round(statSync(m.overlay).size / 1024 ** 3);\n const restoredGib = Math.round(statSync(file).size / 1024 ** 3);\n return applyAtNextBoot(meta, { base: disk.base, image: disk.image }, \"restore\", cfg, p, async () => {\n if (disk.vars === null) await rm(m.env, { force: true });\n else await writeBoxEnv(ref, disk.vars, p);\n await rename(file, m.overlay);\n if (currentGib > restoredGib) await growDisk(m.overlay, currentGib);\n });\n});\n\ntype BoxVarList = Parameters<typeof writeBoxEnv>[1];\n\n/**\n * `kvbox volume attach <volume> <box>` (#52): the volume becomes one more drive of the box, which the\n * guest mounts at /mnt/<volume> at boot. Firecracker cannot add a drive to a running VM, so a running\n * box is shut down cleanly and started again; a stopped one just gets its meta updated; a hibernated\n * one is refused (its memory image has the drives it was frozen with). The volume must be the box\n * owner's and attached to no other box.\n */\nexport const attachVolume = locked(async function attachVolume(ref: BoxRef, volume: BoxRef, p: Paths = paths()): Promise<Machine> {\n const cfg = await loadConfig(p);\n // The claim first: one box per volume is decided by reading every box's meta.json, so the check and\n // the write that records the volume on this box happen under the host lock, which keeps two attaches\n // (or an attach and a `volume rm`) from both passing the check. The restart that gives the box the\n // drive takes seconds and only this box's lock, so it runs outside; until then the box lists a volume\n // it does not have yet, as a stopped box does.\n const claimed = await withHostLock(\"volumes\", async () => {\n const meta = await readMeta(ref, p);\n if (volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is ${volume.owner}'s; a box only takes its own owner's volumes`);\n await readVolume(volume, p);\n const holder = await attachedBox(volume, p);\n if (holder === meta.name) throw new KvboxError(`volume ${shown(volume)} is already attached to box ${shown(ref)}`);\n if (holder !== null) throw new KvboxError(`volume ${shown(volume)} is attached to box ${holder}; a volume attaches to one box at a time (kvbox volume detach ${shown(volume)} first)`);\n assertNotHibernated(meta, p);\n const updated: MachineMeta = { ...meta, volumes: [...(meta.volumes ?? []), volume.name] };\n await writeMachineMeta(updated, p);\n return updated;\n });\n return applyAtNextBoot(claimed, {}, \"attach\", cfg, p);\n});\n\n/**\n * `kvbox volume detach <volume>` (#52): the drive goes at the box's next boot, which a running box gets\n * now. The data stays on the volume. No host lock: the volume is let go by the meta write, which comes\n * after the running box is down, so an attach elsewhere sees it either held or free of a stopped VM.\n */\nexport const detachVolume = locked(async function detachVolume(ref: BoxRef, volume: BoxRef, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n if (!meta.volumes?.includes(volume.name) || volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is not attached to box ${shown(ref)}`);\n assertNotHibernated(meta, p);\n const kept = meta.volumes.filter((v) => v !== volume.name);\n return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : undefined }, \"detach\", cfg, p, () => rm(p.machine(ref.owner, ref.name).volumeDrive(volume.name), { force: true }));\n});\n\n/**\n * `kvbox volume grow <volume> <GB>` (#147): the volume's file is extended and its ext4 grown into it,\n * which needs it unmounted. A detached volume, or one on a stopped box, just grows; a running box is\n * shut down cleanly and started again, like an attach; a hibernated one is refused. A volume never shrinks.\n */\nexport async function resizeVolume(volume: BoxRef, sizeGib: number, p: Paths = paths()): Promise<Volume> {\n await assertCanGrow(volume, sizeGib, p); // before any box is stopped for it\n const holder = await attachedBox(volume, p);\n if (holder === null) {\n // Detached: the host lock an attach claims under, so no box boots with the disk mid-resize.\n return growVolume(volume, sizeGib, p, async () => {\n const now = await attachedBox(volume, p);\n if (now !== null) throw new KvboxError(`volume ${shown(volume)} was just attached to box ${now}; try again`);\n });\n }\n const box: BoxRef = { owner: volume.owner, name: holder };\n return withBoxLock(box, async () => {\n const meta = await readMeta(box, p);\n if (!meta.volumes?.includes(volume.name)) throw new KvboxError(`volume ${shown(volume)} was just detached from box ${holder}; try again`);\n assertNotHibernated(meta, p);\n const cfg = await loadConfig(p);\n let grown: Volume | undefined;\n await applyAtNextBoot(meta, {}, \"grow\", cfg, p, async () => {\n grown = await growVolume(volume, sizeGib, p);\n });\n return { ...grown!, attachedTo: holder };\n });\n}\n\n/**\n * A volume backup's restore (#168): `file`, a complete disk built beside the volume's own, becomes the\n * volume's disk. Like a grow: a detached volume, or one on a stopped box, is just swapped; a running box\n * that holds it is shut down cleanly and started again; a hibernated one is refused. A volume that has\n * grown since the backup keeps its size: the restored filesystem is grown into it, before the swap, so a\n * grow that fails leaves the volume as it was.\n */\nexport async function replaceVolumeDisk(volume: BoxRef, file: string, p: Paths = paths()): Promise<Volume> {\n const grow = async () => {\n const meta = await readVolume(volume, p);\n if (meta.sizeGib * 1024 ** 3 > statSync(file).size) await growDisk(file, meta.sizeGib);\n };\n // The file is this restore's own: grown (an e2fsck of the whole disk) before any lock is taken or box\n // stopped; under the lock only a `volume grow` that came in between grows it again.\n await grow();\n const swap = async () => {\n await grow();\n await rename(file, p.volume(volume.owner, volume.name).disk);\n };\n const holder = await attachedBox(volume, p);\n if (holder === null) {\n // Detached: the host lock an attach claims under, so no box boots with the disk mid-swap.\n await withHostLock(\"volumes\", async () => {\n const now = await attachedBox(volume, p);\n if (now !== null) throw new KvboxError(`volume ${shown(volume)} was just attached to box ${now}; try again`);\n await swap();\n });\n return getVolume(volume, p);\n }\n const box: BoxRef = { owner: volume.owner, name: holder };\n await withBoxLock(box, async () => {\n const meta = await readMeta(box, p);\n if (!meta.volumes?.includes(volume.name)) throw new KvboxError(`volume ${shown(volume)} was just detached from box ${holder}; try again`);\n assertNotHibernated(meta, p);\n await applyAtNextBoot(meta, {}, \"restore\", await loadConfig(p), p, swap);\n });\n return getVolume(volume, p);\n}\n\n/** `kvbox vm set <box>`: settings the VM itself never sees, so they apply in any state and at once. */\nexport const setMachine = locked(async function setMachine(ref: BoxRef, req: SetMachineRequest, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const next: MachineMeta = { ...meta };\n if (req.autoHibernateSec !== undefined) next.autoHibernateSec = req.autoHibernateSec || undefined;\n if (req.idleCheck !== undefined) next.idleCheck = req.idleCheck || undefined;\n await writeMachineMeta(next, p);\n return toMachine(next, p);\n});\n\ntype PortKey = { guestPort: number; proto: \"tcp\" | \"udp\" };\nconst portKeys = (req: PortsRequest): PortKey[] => {\n const keys = req.ports.map((x) => ({ guestPort: x.guestPort, proto: x.proto ?? \"tcp\" }));\n return keys.filter((k, i) => keys.findIndex((o) => o.guestPort === k.guestPort && o.proto === k.proto) === i);\n};\nconst samePort = (a: PortKey) => (b: PortKey) => a.guestPort === b.guestPort && a.proto === b.proto;\n\n/**\n * `kvbox vm proxy add` (#30): publish box ports on the host's public address, each on a host port\n * drawn at random. All or nothing: if one forward cannot be opened, the ones this call opened are\n * closed and nothing is stored. A box that is not running keeps them in meta.json; they open when\n * it next runs, like its SSH port. A port closed but kept (`rm` with `keep`, #173) opens again on the\n * host port it always had.\n */\nexport const addPorts = locked(async function addPorts(ref: BoxRef, req: PortsRequest, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const current = meta.ports ?? [];\n const wanted = portKeys(req);\n const isClosed = (k: PortKey) => current.some((f) => samePort(k)(f) && f.closed);\n const reopened = wanted.filter(isClosed);\n const fresh = wanted.filter((w) => !current.some(samePort(w)));\n const already = wanted.find((w) => current.some(samePort(w)) && !isClosed(w));\n if (already) throw new KvboxError(`box ${shown(ref)} already publishes port ${already.guestPort} (${already.proto})`);\n // The box's SSH forward already accepts 22/tcp into it; a second forward to 22 would share that\n // FORWARD rule, and closing it would cut the box's SSH.\n if (meta.sshPort !== undefined && wanted.some(samePort({ guestPort: 22, proto: \"tcp\" }))) {\n throw new KvboxError(`box ${shown(ref)} already reaches port 22 from outside on port ${meta.sshPort} (kvbox connect)`);\n }\n if (current.length + fresh.length > MAX_BOX_PORTS) {\n throw new KvboxError(`a box publishes at most ${MAX_BOX_PORTS} ports; box ${shown(ref)} has ${current.length}`);\n }\n const drawn = await drawPorts(fresh.length, p);\n const opened: Proxy[] = [];\n try {\n const added = fresh.map((w, i) => ({ ...w, hostPort: drawn.ports[i]! }));\n const open = ({ closed: _closed, ...f }: NonNullable<MachineMeta[\"ports\"]>[number]) => f;\n const again = current.filter((f) => reopened.some(samePort(f))).map(open);\n if (vmAlive(meta)) {\n for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: [...again, ...added] })) {\n await openProxy(proxy, cfg);\n opened.push(proxy);\n }\n }\n const next: MachineMeta = { ...meta, ports: [...current.map((f) => (reopened.some(samePort(f)) ? open(f) : f)), ...added] };\n await writeMachineMeta(next, p);\n return toMachine(next, p);\n } catch (err) {\n // Nothing stored, so nothing may stay open: a rule meta.json does not name could never be removed.\n for (const proxy of opened) await closeProxy(proxy, cfg).catch(() => undefined);\n throw err;\n } finally {\n drawn.release();\n }\n});\n\n/**\n * `kvbox vm proxy rm` (#30): stop publishing box ports. Their host ports go back to the pool, unless\n * `keep` (#173): then each stays the box's, closed, until it is published again or removed for good.\n */\nexport const removePorts = locked(async function removePorts(ref: BoxRef, req: PortsRequest, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const current = meta.ports ?? [];\n const gone = portKeys(req);\n const missing = gone.find((g) => !current.some(samePort(g)));\n if (missing) throw new KvboxError(`box ${shown(ref)} does not publish port ${missing.guestPort} (${missing.proto})`);\n const removed = current.filter((f) => gone.some(samePort(f)));\n // Closed first: a rule that would not go keeps the port in meta.json, so trying again finds it.\n // Closed whether or not the box runs: one whose Firecracker died never ran cleanupProcess, and its\n // rules would outlive the port's return to the pool. Closing what is not there is fine.\n for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: removed })) await closeProxy(proxy, cfg);\n const kept = req.keep\n ? current.map((f) => (gone.some(samePort(f)) ? { ...f, closed: true as const } : f))\n : current.filter((f) => !gone.some(samePort(f)));\n const next: MachineMeta = { ...meta, ports: kept.length > 0 ? kept : undefined };\n await writeMachineMeta(next, p);\n return toMachine(next, p);\n});\n\n// ── links between boxes (#98) ─────────────────────────────────────────────────\n\n/**\n * The box a link comes from: by name (the caller's), `<owner>/<name>` over the socket, or `fromOwner`'s slug\n * from a control plane. Into a cloud box, a slug without a realm is taken in the target's, as `linkFrom`\n * shows it: what `vm links` lists over the socket can be unlinked as written.\n */\nfunction linkSource(req: LinkRequest, caller: string, target: string): BoxRef {\n if (req.fromOwner !== undefined) return { owner: ownerFor(req.fromOwner, caller), name: req.from, display: `${req.fromOwner}/${req.from}` };\n const ref = parseRef(req.from, caller);\n const realm = realmOf(target);\n return realm !== null && realmOf(ref.owner) === null && req.from.includes(\"/\") ? { ...ref, owner: `${ref.owner}@${realm}` } : ref;\n}\n\n/**\n * `kvbox vm link <from> <box> --port <port>` (#98): box `from` may open TCP connections to `port` of\n * this box, through the host, nothing else. Stored here; open while this box runs.\n */\nexport const addLink = locked(async function addLink(ref: BoxRef, req: LinkRequest, caller: string, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const fromRef = linkSource(req, caller, meta.owner);\n if (fromRef.owner === meta.owner && fromRef.name === meta.name) throw new KvboxError(`box ${shown(ref)} already reaches itself`);\n const from = await readMeta(fromRef, p);\n // A control plane never sees this host's own boxes, nor they its: neither side could name the other's box.\n if (realmOf(from.owner) !== realmOf(meta.owner)) {\n throw new KvboxError(`box ${shown(fromRef)} and box ${shown(ref)} belong to different realms (one is this host's, one a control plane's); a link joins boxes of one realm`);\n }\n // a stale entry of the same rule (a removed box of that name had this IP) gives way to the new link\n const links = (meta.links ?? []).filter((l) => !(l.stale && l.owner === from.owner && l.name === from.name && l.ip === from.ip && l.port === req.port));\n const same = (l: NonNullable<MachineMeta[\"links\"]>[number]) => !l.stale && l.owner === from.owner && l.name === from.name && l.port === req.port;\n if (links.some(same)) throw new KvboxError(`box ${shown(fromRef)} already reaches box ${shown(ref)} on port ${req.port}`);\n if (links.length >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${shown(ref)} has ${links.length}`);\n const added = { owner: from.owner, name: from.name, ip: from.ip, port: req.port };\n const cfg = await loadConfig(p);\n if (vmAlive(meta)) await openLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg);\n const next: MachineMeta = { ...meta, links: [...links, added] };\n try {\n await writeMachineMeta(next, p);\n } catch (err) {\n // Nothing stored, so nothing may stay open: a rule meta.json does not name could never be removed.\n await closeLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg).catch(() => undefined);\n throw err;\n }\n return toMachine(next, p);\n});\n\n/** `kvbox vm unlink <from> <box> --port <port>` (#98). The rule closes whether or not the box runs. */\nexport const removeLink = locked(async function removeLink(ref: BoxRef, req: LinkRequest, caller: string, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const fromRef = linkSource(req, caller, meta.owner);\n const links = meta.links ?? [];\n const gone = links.filter((l) => !l.stale && l.owner === fromRef.owner && l.name === fromRef.name && l.port === req.port);\n if (gone.length === 0) throw new KvboxError(`box ${shown(fromRef)} is not linked to box ${shown(ref)} on port ${req.port}`);\n const cfg = await loadConfig(p);\n // Closed first: a rule that would not go keeps the link in meta.json, so trying again finds it.\n for (const l of gone) await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg);\n const kept = links.filter((l) => !gone.includes(l));\n const next: MachineMeta = { ...meta, links: kept.length > 0 ? kept : undefined };\n await writeMachineMeta(next, p);\n return toMachine(next, p);\n});\n\n/** Extend a box's (unmounted) ext4 disk file to `gib` GiB. */\nexport async function growDisk(file: string, gib: number): Promise<void> {\n await truncate(file, gib * 1024 ** 3);\n await run([\"e2fsck\", \"-f\", \"-p\", file], { okExitCodes: [1] });\n await run([\"resize2fs\", file]);\n}\n\nasync function readMeta(ref: BoxRef, p: Paths): Promise<MachineMeta> {\n try {\n return await readMachineMeta(ref, p);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") throw new NotFoundError(`box ${shown(ref)}`);\n throw err;\n }\n}\n\n/** `kvbox vm rm`: the box, then the links it had into other boxes (#98), each under that box's own lock. */\nexport async function destroyMachine(ref: BoxRef, p: Paths = paths()): Promise<void> {\n const gone = await destroyBox(ref, p);\n await dropLinksFrom(gone, p);\n}\n\nconst destroyBox = locked(async function destroyBox(ref: BoxRef, p: Paths = paths()): Promise<MachineMeta> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n await shutdown(meta, cfg, p, 2000);\n // Its IP is free once the dir goes: no rule may still let that IP into another box by then. A box\n // this stops short of removing stays in the ledger, stopped.\n await closeLinksFrom(meta, cfg, p).catch((err: unknown) => {\n recordState(meta, \"stopped\", \"stop\", p);\n throw err;\n });\n // The ledger keeps the box's history after it is gone: a final row, while the disk is still there to measure.\n recordState(meta, \"stopped\", \"rm\", p);\n await rm(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });\n boxListChanged(); // its IP is free for the next box: no name may still point there\n return meta;\n});\n\nconst linkOf = (gone: MachineMeta) => (l: { owner: string; name: string; ip: string }) => l.owner === gone.owner && l.name === gone.name && l.ip === gone.ip;\n\n/**\n * Close every rule from `gone`'s IP into another box, without the targets' locks (`link rm` is idempotent),\n * before its dir goes. One that will not close stops the rm: the box keeps its dir, and so its IP.\n */\nasync function closeLinksFrom(gone: MachineMeta, cfg: Config, p: Paths): Promise<void> {\n const isGone = linkOf(gone);\n for (const ref of await listMachineRefs(p)) {\n const meta = await readMachineMeta(ref, p).catch(() => null);\n for (const l of meta?.links?.filter(isGone) ?? []) {\n await closeLink({ box: meta!.id, fromIp: l.ip, toIp: meta!.ip, port: l.port }, cfg).catch((err: Error) => {\n throw new KvboxError(`box ${shown(gone)} is stopped but not removed: could not close its link into ${shown(meta!)} (${err.message}); try again`);\n });\n }\n }\n}\n\n/**\n * Then each link from the removed box leaves its target's meta.json, under that box's lock. Its rule is\n * closed again first (a target that booted meanwhile may have opened it); one that will not close keeps\n * its entry, so the target's next stop or unlink still finds it, and it never opens again (standingLinks).\n */\nasync function dropLinksFrom(gone: MachineMeta, p: Paths): Promise<void> {\n const cfg = await loadConfig(p);\n const isGone = linkOf(gone);\n for (const ref of await listMachineRefs(p)) {\n await withBoxLock(ref, async () => {\n const meta = await readMachineMeta(ref, p).catch(() => null);\n if (!meta?.links?.some(isGone)) return;\n const stuck = new Set<NonNullable<MachineMeta[\"links\"]>[number]>();\n for (const l of meta.links.filter(isGone)) {\n await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg).catch((err: Error) => {\n stuck.add(l);\n log.warn(`could not close the link from removed box ${gone.name} into ${meta.name}: ${err.message}`);\n });\n }\n const kept = meta.links.filter((l) => !isGone(l) || stuck.has(l)).map((l) => (stuck.has(l) ? { ...l, stale: true as const } : l));\n await writeMachineMeta({ ...meta, links: kept.length > 0 ? kept : undefined }, p);\n }).catch((err: Error) => log.warn(`links of removed box ${gone.name}: ${err.message}`));\n }\n}\n\n// ── after the host was down (#29) ─────────────────────────────────────────────\n/** Boxes booted at once when the server brings them back: each boot is a burst of disk and CPU. */\nconst RECOVERY_CONCURRENCY = 2;\n\n/**\n * At server start, the boxes whose Firecracker died with an earlier boot of the host: meta.json still\n * names a pid, but from another boot. Each one's open run in the ledger is closed (at the host's boot\n * when it predates it) and its memory image goes: the next boot is fresh. A box that was in standby\n * lost its memory with the process, so it is left stopped; the others keep the old pid and boot id,\n * which mark them as not brought back yet, and are returned to be booted (`bootRecovered`). A box\n * whose Firecracker died earlier in this boot (a crash) is not touched: it reads as stopped, as it has\n * since. Done before the server listens, so a listing cannot close those runs at \"now\" first.\n */\nexport async function settleDeadBoxes(p: Paths = paths()): Promise<{ boot: BoxRef[]; leftStopped: string[] }> {\n const now = new Date().toISOString();\n const bootAt = hostBootTime()?.toISOString() ?? now;\n const boot: BoxRef[] = [];\n const leftStopped: string[] = [];\n for (const meta of await readAllMeta(p)) {\n if (!cutByReboot(meta) || vmAlive(meta)) continue;\n try {\n closeRunCutByBoot(meta.id, bootAt, now, p);\n } catch (err) {\n log.warn(`usage ledger: ${(err as Error).message}`);\n }\n await rm(p.machine(meta.owner, meta.name).memBase, { force: true });\n if (meta.paused) {\n await writeMachineMeta({ ...meta, pid: null, bootId: undefined, memSnapshots: undefined, paused: undefined }, p);\n leftStopped.push(refKey(meta));\n } else {\n await writeMachineMeta({ ...meta, memSnapshots: undefined }, p);\n boot.push({ owner: meta.owner, name: meta.name });\n }\n }\n return { boot, leftStopped };\n}\n\n/** A pid launched in another boot of the host (or before #29, with no boot id): the reboot ended it. */\nfunction cutByReboot(meta: MachineMeta): boolean {\n return meta.pid !== null && meta.bootId !== currentBootId();\n}\n\n/**\n * At server start: pin the tap of every box that runs (#98). A server restart leaves the boxes running,\n * so after an upgrade their taps are the old code's, unpinned, and `link add` refuses while one is on the\n * bridge. A failure is logged; that box stays unpinned until it restarts.\n */\nexport async function pinRunningTaps(p: Paths = paths()): Promise<void> {\n const cfg = await loadConfig(p);\n if (!bridgeExists(cfg.bridge)) return;\n for (const meta of await readAllMeta(p)) {\n if (!vmAlive(meta) || !existsSync(`/sys/class/net/${tapName(meta.id)}`)) continue;\n await pinTap(meta, cfg).catch((err: Error) => log.warn(`could not pin box ${meta.name}'s tap: ${err.message}`));\n }\n}\n\nlet recovery: RecoveryReport | null = null;\nlet recoveryStopping = false;\nlet recoveryRun: Promise<unknown> = Promise.resolve();\n\n/** What `bootRecovered` did at this server's start (`/health`); null when nothing needed it. */\nexport function lastRecovery(): RecoveryReport | null {\n return recovery;\n}\n\n/**\n * For the server's shutdown: boot no further box, and resolve once the boots under way have written\n * their pid to meta.json (exiting halfway would leave a Firecracker no meta.json names). The boxes\n * not reached keep their old boot id, so the next server start brings them back.\n */\nexport async function stopRecovery(): Promise<void> {\n recoveryStopping = true;\n await recoveryRun;\n}\n\n/**\n * Boot the boxes `settleDeadBoxes` found, a few at a time, like `kvbox start` (fresh boot, current\n * SSH lines). A box someone started while it waited its turn now has this boot's id and is skipped.\n * One that does not come up is reported, never fatal: the server keeps serving.\n */\nexport async function bootRecovered(settled: { boot: readonly BoxRef[]; leftStopped: readonly string[] }, p: Paths = paths()): Promise<RecoveryReport | null> {\n const refs = settled.boot;\n if (refs.length === 0 && settled.leftStopped.length === 0) return null;\n const booted: string[] = [];\n const failed: RecoveryReport[\"failed\"] = [];\n const queue = [...refs];\n const worker = async () => {\n for (let ref = queue.shift(); ref !== undefined && !recoveryStopping; ref = queue.shift()) {\n try {\n if (!cutByReboot(await readMeta(ref, p))) continue;\n // It was running when the host went down: it gets its room back, as it had it.\n await startMachine(ref, p, true);\n booted.push(refKey(ref));\n } catch (err) {\n failed.push({ box: refKey(ref), error: (err as Error).message });\n }\n }\n };\n const run = Promise.all(Array.from({ length: Math.min(RECOVERY_CONCURRENCY, refs.length) }, worker));\n recoveryRun = run;\n await run;\n recovery = { at: new Date().toISOString(), booted, leftStopped: [...settled.leftStopped], failed };\n return recovery;\n}\n","/** Auto-hibernate's durations: the host checks once a minute, so minutes are the unit. */\nconst UNIT_SEC: Record<string, number> = { m: 60, h: 3600, d: 86400 };\n\n/** \"30m\", \"4h\", \"1d\", \"1h30m\" -> seconds; undefined when it is not such a duration. */\nexport function parseDuration(text: string): number | undefined {\n const t = text.trim().toLowerCase();\n if (!/^(\\d+[mhd])+$/.test(t)) return undefined;\n let sec = 0;\n for (const [, n, unit] of t.matchAll(/(\\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit!]!;\n return sec;\n}\n","/**\n * Wire shapes of the kvbox HTTP API, shared by the client (src/cli) and the\n * server (src/server). Validated with zod on both sides because the client\n * may be talking to an older or newer server.\n */\nimport { z } from \"zod\";\nimport { SIZE_NAMES } from \"./sizes.js\";\n\nexport const SizeSchema = z.enum(SIZE_NAMES as [string, ...string[]]);\n\n/** The guest account every box has; `ssh` logs in as it. */\nexport const BOX_SSH_USER = \"kvbox\";\n\n/**\n * A box's state. `running`: Firecracker up, guest executing. `standby`: Firecracker up but frozen (kvbox\n * pause): memory and processes kept, no CPU. `hibernated`: no process; memory dumped to the box's dir\n * (kvbox hibernate), wake continues where it left off. `stopped`: no process, memory gone, next start boots.\n * `unknown`: only from the control plane, for a box whose host did not answer in time (#20).\n */\nexport const BoxStatusSchema = z.enum([\"running\", \"standby\", \"hibernated\", \"stopped\", \"unknown\"]);\nexport type BoxStatus = z.infer<typeof BoxStatusSchema>;\n\n/** A published box port's protocol (#30). */\nexport const PortProtoSchema = z.enum([\"tcp\", \"udp\"]);\nexport type PortProto = z.infer<typeof PortProtoSchema>;\n\n/** At most this many published ports per box (#30): room for a lab of services, not for draining the host's range. */\nexport const MAX_BOX_PORTS = 16;\n\n/**\n * A box port published on the host's public address (#30, `kvbox vm proxy`): `hostPort` on the\n * host reaches `guestPort` in the box. The host port is drawn at random and stays the box's.\n */\nexport const PortForwardSchema = z.object({\n guestPort: z.number().int().min(1).max(65535),\n hostPort: z.number().int(),\n proto: PortProtoSchema,\n /** The host's public address; only the control plane fills it in, as for `ssh`. */\n address: z.string().optional(),\n /**\n * Closed but kept (#173): nothing reaches the box through it, and the host port stays the box's, so\n * publishing the same box port again opens the same number. Absent: open while the box runs.\n */\n closed: z.literal(true).optional(),\n});\nexport type PortForward = z.infer<typeof PortForwardSchema>;\n\n/** `POST /machines/:name/ports` adds these, `DELETE` removes them; the answer is the box. */\nexport const PortsRequest = z.object({\n ports: z.array(z.object({ guestPort: z.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),\n /** `DELETE` only (#173): close the ports but keep their host ports for the box (`closed`). */\n keep: z.boolean().optional(),\n});\nexport type PortsRequest = z.infer<typeof PortsRequest>;\n\nconst BoxPortSchema = z.number().int().min(1).max(65535);\n\n/** At most this many links into one box (#98). */\nexport const MAX_BOX_LINKS = 32;\n\n/**\n * A link into a box (#98, `kvbox vm link`): box `from` may open TCP connections to this box's `port`,\n * over the host's bridge, nothing else. `from` is the box's name when it has the same owner, else\n * `<slug>/<name>`. Same host only.\n */\nexport const BoxLinkSchema = z.object({ from: z.string(), port: BoxPortSchema });\nexport type BoxLink = z.infer<typeof BoxLinkSchema>;\n\n/**\n * `POST /machines/:name/links` adds a link into `:name`, `DELETE` removes it; the answer is the box.\n * `from` is a box name, or `<owner>/<name>` over the socket. Through a control plane, `fromOwner` is\n * its slug, bare (like ForkMachineRequest's `owner`); the host qualifies it with the caller's realm.\n */\nexport const LinkRequest = z.object({ from: z.string().min(1), fromOwner: z.string().optional(), port: BoxPortSchema });\nexport type LinkRequest = z.infer<typeof LinkRequest>;\n\n/** `PUT /machines/:name/subdomain` (#31): claim `<name>.kvbox.app` for the box, serving `port`. */\nexport const ClaimSubdomainRequest = z.object({ name: z.string(), port: BoxPortSchema });\nexport type ClaimSubdomainRequest = z.infer<typeof ClaimSubdomainRequest>;\n\n/** `POST /machines/:name/subdomain/port`: the default port changes. */\nexport const SubdomainPortRequest = z.object({ port: BoxPortSchema });\nexport type SubdomainPortRequest = z.infer<typeof SubdomainPortRequest>;\n\n/** `POST /machines/:name/subdomain/routes`: `<name>.<sub>.kvbox.app` serves `port`. */\nexport const SubdomainRouteRequest = z.object({ name: z.string(), port: BoxPortSchema });\nexport type SubdomainRouteRequest = z.infer<typeof SubdomainRouteRequest>;\n\n/**\n * A box's HTTPS subdomain (#31): `url` serves the box's `port`, each route's `url` its own port.\n * `owner` is the box's slug (a user's or an org's), `box` its name.\n */\nexport const SubdomainSchema = z.object({\n owner: z.string(),\n box: z.string(),\n subdomain: z.string(),\n port: BoxPortSchema,\n url: z.string(),\n routes: z.array(z.object({ name: z.string(), port: BoxPortSchema, url: z.string() })),\n});\nexport type Subdomain = z.infer<typeof SubdomainSchema>;\n\n/** `POST /machines/:name/domains` (#89): serve the box at `domain`, on `port` (default: its subdomain's). */\nexport const AddDomainRequest = z.object({ domain: z.string(), port: BoxPortSchema.optional() });\nexport type AddDomainRequest = z.infer<typeof AddDomainRequest>;\n\n/**\n * A custom domain (#89). `pending` until its A record gives the edge's address and its TXT record\n * `_kvbox.<domain>` holds the slug's token (checked when added and every minute after), then `live`: the edge serves it and Traefik gets its certificate by HTTP-01.\n * `www` is true when `www.<domain>` points here too and is served as the same site. `records` is what\n * to set at the domain's DNS; `error` why it is still pending.\n */\nexport const DomainSchema = z.object({\n owner: z.string(),\n box: z.string(),\n domain: z.string(),\n port: BoxPortSchema,\n status: z.enum([\"pending\", \"live\"]),\n www: z.boolean(),\n url: z.string(),\n error: z.string().nullable(),\n records: z.array(z.object({ type: z.enum([\"A\", \"TXT\", \"CNAME\"]), name: z.string(), value: z.string() })),\n createdAt: z.string(),\n});\nexport type Domain = z.infer<typeof DomainSchema>;\n\n/**\n * A wake hook (#101): a URL that wakes one box when called, for GitHub webhooks, cron or any other\n * automation. Calls are signed with the hook's secret, as GitHub signs (`X-Hub-Signature-256`) or as a\n * bearer; the secret is shown once, when the hook is made. `lastCalledAt` is the last call that passed\n * the signature check.\n */\nexport const WakeHookSchema = z.object({\n id: z.string(),\n owner: z.string(),\n box: z.string(),\n url: z.string(),\n createdBy: z.string().nullable(),\n createdAt: z.string(),\n lastCalledAt: z.string().nullable(),\n});\nexport type WakeHook = z.infer<typeof WakeHookSchema>;\n/** What `POST /machines/:name/hooks` answers: the hook and its secret, the only time it is shown. */\nexport const CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z.string() });\nexport type CreatedWakeHook = z.infer<typeof CreatedWakeHookSchema>;\n/** What a call to a hook answers (202): what was asked of the box, `none` with the reason when nothing was. */\nexport const WakeHookCallSchema = z.object({\n box: z.string(),\n action: z.enum([\"wake\", \"resume\", \"none\"]),\n reason: z.string().optional(),\n});\nexport type WakeHookCall = z.infer<typeof WakeHookCallSchema>;\n\n/**\n * Backups (decision \"Backups: encrypted 4 MiB chunks in object storage\"; format in `@kvbox/shared/backup`):\n * the control plane's only. A backup is the box's disk and its own variables at one instant, never its\n * memory or volumes; `running` until the host has uploaded every new chunk.\n */\nexport const BACKUP_STATUSES = [\"running\", \"ready\", \"failed\"] as const;\n/** What a backup is of: a box's disk, or a volume's (#168). */\nexport const BACKUP_KINDS = [\"box\", \"volume\"] as const;\nexport type BackupKind = (typeof BACKUP_KINDS)[number];\nexport const BackupSchema = z.object({\n id: z.string(),\n owner: z.string(),\n box: z.string(),\n status: z.enum(BACKUP_STATUSES),\n /** Why it failed; null otherwise. */\n error: z.string().nullable(),\n /** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */\n base: z.string().nullable(),\n image: z.string().optional(),\n vcpu: z.number().int().nullable(),\n memMib: z.number().int().nullable(),\n /** The disk's size. */\n diskBytes: z.number().int().nullable(),\n /** What it holds: the slots that are not all zeros. */\n dataBytes: z.number().int().nullable(),\n /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */\n uploadedBytes: z.number().int().nullable(),\n createdBy: z.string().nullable(),\n createdAt: z.string(),\n finishedAt: z.string().nullable(),\n});\nexport type Backup = z.infer<typeof BackupSchema>;\n\n/** Control plane → host, `POST /machines/:name/backup`: take the box's disk and name its chunks. */\nexport const HostBackupRequest = z.object({ id: z.string(), key: z.string() });\nexport type HostBackupRequest = z.infer<typeof HostBackupRequest>;\n/** The host's answer: the disk as chunk names (null: a slot of zeros), its variables sealed, and what the box was. */\nexport const HostBackupManifestSchema = z.object({\n id: z.string(),\n sizeBytes: z.number().int(),\n chunks: z.array(z.string().nullable()),\n env: z.string().nullable(),\n base: z.string(),\n image: z.string().optional(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n});\nexport type HostBackupManifest = z.infer<typeof HostBackupManifestSchema>;\n/**\n * `POST /backups/:id/upload`: a signed PUT URL per chunk the store does not have yet. `pin` is the sha256\n * fingerprint (`AA:BB:…`) of the certificate the store answers with: a store is another host, whose\n * certificate is self-signed, so the URLs are trusted by that fingerprint alone.\n */\nexport const HostUploadRequest = z.object({ key: z.string(), urls: z.record(z.string(), z.string()), pin: z.string().optional() });\nexport type HostUploadRequest = z.infer<typeof HostUploadRequest>;\n/** What was uploaded: the count, the total and each chunk's stored size (what storage is billed on). */\nexport const HostUploadResultSchema = z.object({ chunks: z.number().int(), bytes: z.number().int(), sizes: z.record(z.string(), z.number().int()) });\nexport type HostUploadResult = z.infer<typeof HostUploadResultSchema>;\n/**\n * `POST /machines/:name/restore`: the disk a backup describes, as a signed GET URL per slot that is\n * not zeros. The host builds it beside the box's disk, then swaps it in (a running box restarts).\n */\nexport const HostRestoreRequest = z.object({\n /** The backup's id: its variables were sealed under it. */\n id: z.string(),\n key: z.string(),\n sizeBytes: z.number().int().positive(),\n base: z.string(),\n image: z.string().optional(),\n env: z.string().nullable(),\n chunks: z.array(z.object({ index: z.number().int().nonnegative(), hash: z.string(), url: z.string() })),\n /** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */\n pin: z.string().optional(),\n});\nexport type HostRestoreRequest = z.infer<typeof HostRestoreRequest>;\n\n/**\n * A volume's backup (#168): the same chunks, stores and limits as a box's, of the volume's disk alone. It\n * has no base, shape or variables: a volume is only data.\n */\nexport const VolumeBackupSchema = z.object({\n id: z.string(),\n owner: z.string(),\n volume: z.string(),\n status: z.enum(BACKUP_STATUSES),\n /** Why it failed; null otherwise. */\n error: z.string().nullable(),\n /** The volume's size when taken. */\n diskBytes: z.number().int().nullable(),\n /** What it holds: the slots that are not all zeros. */\n dataBytes: z.number().int().nullable(),\n /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */\n uploadedBytes: z.number().int().nullable(),\n createdBy: z.string().nullable(),\n createdAt: z.string(),\n finishedAt: z.string().nullable(),\n});\nexport type VolumeBackup = z.infer<typeof VolumeBackupSchema>;\n/** The host's answer to `POST /volumes/:name/backup` (the request is a box's, `HostBackupRequest`): the disk as chunk names. */\nexport const HostVolumeBackupManifestSchema = z.object({ id: z.string(), sizeBytes: z.number().int(), chunks: z.array(z.string().nullable()) });\nexport type HostVolumeBackupManifest = z.infer<typeof HostVolumeBackupManifestSchema>;\n/**\n * `POST /volumes/:name/restore`: like a box's, without what a volume does not have. The host builds the\n * disk beside the volume's, then swaps it in (a running box that holds the volume restarts).\n */\nexport const HostVolumeRestoreRequest = z.object({\n id: z.string(),\n key: z.string(),\n sizeBytes: z.number().int().positive(),\n chunks: z.array(z.object({ index: z.number().int().nonnegative(), hash: z.string(), url: z.string() })),\n pin: z.string().optional(),\n});\nexport type HostVolumeRestoreRequest = z.infer<typeof HostVolumeRestoreRequest>;\n\n/**\n * A backup store (decision \"Backup stores: Garage on our own disks…\"): a host with a disk for backups,\n * running Garage there (`kvbox-server backup setup`). Chunks reach it through the host's own HTTPS port,\n * under the bucket's name as the first path segment, which is why the name is fixed.\n */\nexport const BACKUP_STORE_BUCKET = \"kvbox-backups\";\nexport const BACKUP_STORE_REGION = \"kvbox\";\n/** `kvbox-server backup setup`, over the host's socket. */\n/** `newStore`: the store's disk is gone for good; start a new store at the path (its backups are lost). */\nexport const BackupStoreSetupRequest = z.object({ path: z.string().min(1), force: z.boolean().optional(), newStore: z.boolean().optional() });\nexport type BackupStoreSetupRequest = z.infer<typeof BackupStoreSetupRequest>;\n/** What a host says about its store (`kvbox-server backup status`); the secret key is never in it. */\nexport const BackupStoreStatusSchema = z.object({\n path: z.string(),\n bucket: z.string(),\n accessKey: z.string(),\n /** Whether Garage is running and can store. */\n running: z.boolean(),\n /** The filesystem the path is on. */\n totalBytes: z.number().int(),\n freeBytes: z.number().int(),\n /** What the bucket holds, when Garage answers. */\n objects: z.number().int().optional(),\n storedBytes: z.number().int().optional(),\n /** Whether the control plane took the store's registration at setup. */\n registered: z.boolean().optional(),\n});\nexport type BackupStoreStatus = z.infer<typeof BackupStoreStatusSchema>;\n/** Host → control plane, `PUT /hosts/self/backup-store` by the host secret: the key the control plane signs chunk URLs with. */\nexport const BackupStoreRegistration = z.object({ bucket: z.string().min(1), region: z.string().min(1), accessKey: z.string().min(1), secretKey: z.string().min(1) });\nexport type BackupStoreRegistration = z.infer<typeof BackupStoreRegistration>;\n/** A store as the admin sees it (`GET /admin/backup-stores`): no secret. */\nexport const CloudBackupStoreSchema = z.object({\n id: z.string(),\n /** Null while no host serves it (its host left; it comes back when a host registers its key and secret again). */\n host: z.string().nullable(),\n endpoint: z.string().nullable(),\n bucket: z.string(),\n accessKey: z.string(),\n createdAt: z.string(),\n /** The host answered a poll in the last minute and its Garage runs. */\n live: z.boolean(),\n /** From the host's last poll; null when it never reported a store. */\n totalBytes: z.number().int().nullable(),\n freeBytes: z.number().int().nullable(),\n /** Ready backups kept here, and what their chunks take (encrypted, compressed). */\n backups: z.number().int(),\n storedBytes: z.number().int(),\n /** 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). */\n boxes: z.number().int(),\n volumes: z.number().int(),\n /** When the newest ready backup kept here finished; null when it keeps none. */\n lastBackupAt: z.string().nullable(),\n});\nexport type CloudBackupStore = z.infer<typeof CloudBackupStoreSchema>;\n\n/**\n * What a store keeps for one box or one volume (#168), as the admin sees it\n * (`GET /admin/backup-stores/:id/items`).\n */\nexport const StoredItemSchema = z.object({\n kind: z.enum(BACKUP_KINDS),\n owner: z.string(),\n name: z.string(),\n /** The host the box (or volume) is on now; null when it is gone (its backups stay). */\n host: z.string().nullable(),\n /** It is on the store's own host: losing that host loses it and its backups together. */\n sameHost: z.boolean(),\n /** Ready backups kept here, and what they added to the store together (encrypted, compressed). */\n backups: z.number().int(),\n uploadedBytes: z.number().int(),\n /** The newest backup sent here, whatever became of it. */\n latest: z.object({ id: z.string(), status: z.enum(BACKUP_STATUSES), error: z.string().nullable(), createdAt: z.string() }),\n});\nexport type StoredItem = z.infer<typeof StoredItemSchema>;\n\n/** A backup that failed lately, for the admin (`GET /admin/backups/failed`). */\nexport const FailedBackupSchema = z.object({\n id: z.string(),\n owner: z.string(),\n /** What it was a backup of: a box or a volume (#168), and its name. */\n kind: z.enum(BACKUP_KINDS),\n name: z.string(),\n error: z.string().nullable(),\n /** 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. */\n host: z.string().nullable(),\n store: z.string().nullable(),\n createdAt: z.string(),\n});\nexport type FailedBackup = z.infer<typeof FailedBackupSchema>;\n\nexport const MachineSchema = z.object({\n /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */\n id: z.string(),\n name: z.string(),\n /** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */\n owner: z.string(),\n ip: z.string(),\n mac: z.string(),\n pid: z.number().int().nullable(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n diskBytes: z.number().int(), // the box's own writable disk, as the guest sees it\n diskUsedBytes: z.number().int(), // what the box uses of it: the filesystem's own count, like the guest's `df` (#115)\n /** 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. */\n diskHostBytes: z.number().int().optional(),\n base: z.string(), // version of the image the box's overlay stacks on\n /** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */\n image: z.string().optional(),\n createdAt: z.string(),\n source: z.string(), // \"base\", \"snapshot:<owner/name>\" or \"fork:<owner/name>\" (#79)\n status: BoxStatusSchema,\n /**\n * Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made\n * through a control plane have one; the control plane adds the host's address for `connect` (#21).\n */\n sshPort: z.number().int().optional(),\n /**\n * Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only\n * the control plane fills it in (a host does not know its own public address); absent for a box\n * whose host reported no port or did not answer.\n */\n ssh: z.object({ host: z.string(), port: z.number().int(), user: z.string() }).optional(),\n /** Box ports published on the host (#30). Absent: none. */\n ports: z.array(PortForwardSchema).optional(),\n /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /**\n * The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box\n * links to, and a volume attaches to, only a box on the same host.\n */\n host: z.string().optional(),\n /** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */\n country: z.string().optional(),\n /**\n * The kind of managed service the box runs (`postgres`, `redis`, `storage`). Only an admin's\n * `GET /machines?all=1` lists such boxes, so a host's boxes add up; every other listing hides them.\n */\n managed: z.string().optional(),\n /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */\n autoHibernateSec: z.number().int().positive().optional(),\n /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */\n idleCheck: z.string().optional(),\n /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */\n volumes: z.array(z.object({ name: z.string(), sizeGib: z.number().int(), mountPath: z.string() })).optional(),\n /** Boxes that may reach this one, each on one port (#98). Absent: none. */\n links: z.array(BoxLinkSchema).optional(),\n /** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */\n url: z.string().optional(),\n /**\n * Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it\n * serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.\n */\n connect: z.string().optional(),\n});\nexport type Machine = z.infer<typeof MachineSchema>;\n\n/**\n * A volume (#52): a disk of its own, created apart from any box, attached to one box at a time and\n * kept when that box goes. `attachedTo` is the box's name (same owner), null when detached.\n */\nexport const VolumeSchema = z.object({\n /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n sizeGib: z.number().int(),\n /** What the sparse file really occupies on the host. */\n usedBytes: z.number().int(),\n attachedTo: z.string().nullable(),\n createdAt: z.string(),\n /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */\n host: z.string().optional(),\n});\nexport type Volume = z.infer<typeof VolumeSchema>;\n\n/** Volume sizes: whole GiB, at least 1, at most 4 TiB. */\nexport const MAX_VOLUME_GIB = 4096;\n/** Volume names are mount directories (/mnt/<name>) and go into an ext4 label: as plain as box names. */\nexport const VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;\nexport const VOLUME_NAME_RULE = \"1-12 chars, lowercase letters, digits and '-', starting with a letter or digit\";\n\nexport const CreateVolumeRequest = z.object({\n name: z.string(),\n sizeGib: z.number().int().min(1).max(MAX_VOLUME_GIB),\n /**\n * Through a control plane (#91): the box this volume is for, so it is made on that box's host; the\n * control plane requires it (a volume attaches only to a box on its own host, so one made for no box\n * could never attach) and the CLI attaches right after. A host ignores it.\n */\n box: z.string().optional(),\n});\nexport type CreateVolumeRequest = z.infer<typeof CreateVolumeRequest>;\n\n/** `POST /volumes/:name/attach`: the box, as the caller names it (a bare name is the caller's own). */\nexport const AttachVolumeRequest = z.object({\n box: z.string(),\n});\nexport type AttachVolumeRequest = z.infer<typeof AttachVolumeRequest>;\n\n/** `POST /volumes/:name/resize` (#147): the new size, larger than the current one. A volume never shrinks. */\nexport const ResizeVolumeRequest = z.object({\n sizeGib: z.number().int().min(1).max(MAX_VOLUME_GIB),\n});\nexport type ResizeVolumeRequest = z.infer<typeof ResizeVolumeRequest>;\n\n/**\n * `POST /machines/:name/scripts/:script` on a host (#173): run the script the box's image names `:script`\n * in its image.json, through kvbox-agent, with `input` on its stdin. The answer is what it printed.\n */\nexport const RunScriptRequest = z.object({ input: z.unknown().optional() });\nexport type RunScriptRequest = z.infer<typeof RunScriptRequest>;\nexport const ScriptOutputSchema = z.object({ output: z.unknown() });\nexport type ScriptOutput = z.infer<typeof ScriptOutputSchema>;\n\n/**\n * Environment variables (#88), through the control plane: a slug's list. A secret's value is never\n * sent back by any route (`value` absent), only that it is set.\n */\nexport const EnvVarSchema = z.object({\n name: z.string(),\n value: z.string().optional(),\n secret: z.boolean(),\n updatedAt: z.string(),\n});\nexport type EnvVar = z.infer<typeof EnvVarSchema>;\n\n/**\n * A box's own variables (#87), `GET /machines/:name/env`: kept on the box's host beside its meta.json,\n * merged over its owner's list at every boot. A secret's value is never sent back.\n */\nexport const BoxEnvSchema = z.object({\n box: z.string(),\n vars: z.array(EnvVarSchema),\n});\nexport type BoxEnv = z.infer<typeof BoxEnvSchema>;\n\n/** What `POST` and `DELETE /machines/:name/env/:var` answer (the body of a POST is a SetEnvRequest); the box gets it when it next starts. */\nexport const BoxEnvChangeSchema = z.object({\n box: z.string(),\n name: z.string(),\n /** Whether the box is running now: the change waits for its next start. */\n running: z.boolean(),\n});\nexport type BoxEnvChange = z.infer<typeof BoxEnvChangeSchema>;\n\n/** `PUT /env/:name` on the control plane. */\nexport const SetEnvRequest = z.object({\n value: z.string(),\n secret: z.boolean().optional(),\n});\nexport type SetEnvRequest = z.infer<typeof SetEnvRequest>;\n\n/** What `PUT` and `DELETE /env/:name` answer: whose list changed and how many boxes get it when they next start. */\nexport const EnvChangeSchema = z.object({\n owner: z.string(),\n name: z.string(),\n boxes: z.number().int(),\n});\nexport type EnvChange = z.infer<typeof EnvChangeSchema>;\n\n/**\n * `POST /env` on a host: an owner's whole list, values in the clear (the host admin is trusted, decision\n * \"Env vars belong to a slug…\"). `version` only grows; a host keeps the higher of what it has and this.\n */\nexport const HostEnvRequest = z.object({\n version: z.number().int().min(0),\n vars: z.array(z.object({ name: z.string(), value: z.string() })),\n});\nexport type HostEnvRequest = z.infer<typeof HostEnvRequest>;\n\n/** `GET /env` on a host: which list version it holds per owner (the realm's, without `X-Kvbox-Owner`). */\nexport const HostEnvVersionsSchema = z.array(z.object({ owner: z.string(), version: z.number().int() }));\nexport type HostEnvVersions = z.infer<typeof HostEnvVersionsSchema>;\n\nexport const CreateMachineRequest = z.object({\n name: z.string().optional(),\n /** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */\n owner: z.string().optional(),\n size: SizeSchema.optional(),\n from: z.string().optional(),\n force: z.boolean().optional(),\n /**\n * Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends\n * its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every\n * boot (#49); a host older than that ignores them.\n */\n sshKeys: z.array(z.string()).optional(),\n /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */\n autoHibernateSec: z.number().int().min(0).optional(),\n /**\n * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the\n * control plane reads it; a host has one place to put a box.\n */\n near: z.string().optional(),\n /**\n * Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,\n * `@kvbox/shared/country`. Only the control plane reads it.\n */\n country: z.string().optional(),\n /**\n * Place the box on the host of this name and nowhere else (`kvbox new --host kvbox2`, a hidden flag):\n * an admin's, to try a host out. Only the control plane reads it, and refuses it from anyone else.\n */\n host: z.string().optional(),\n /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */\n image: z.string().optional(),\n /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */\n env: z.array(z.object({ name: z.string(), value: z.string() })).optional(),\n});\nexport type CreateMachineRequest = z.infer<typeof CreateMachineRequest>;\n\n/**\n * `POST /machines/:name/fork` (#79): a new box from `:name` as it is right now. A running or paused\n * source is copied warm (memory and disk, processes keep running); a stopped one cold (its disk, then a\n * fresh boot). Absent fields come from the source: its size and its auto-hibernate.\n */\nexport const ForkMachineRequest = z.object({\n name: z.string().optional(),\n /**\n * The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host\n * qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.\n */\n owner: z.string().optional(),\n /** A cold fork only: a warm one keeps the source's vCPU and memory. */\n size: SizeSchema.optional(),\n force: z.boolean().optional(),\n /** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */\n sshKeys: z.array(z.string()).optional(),\n autoHibernateSec: z.number().int().min(0).optional(),\n});\nexport type ForkMachineRequest = z.infer<typeof ForkMachineRequest>;\n\n/**\n * `POST /machines/:name/ssh-keys` on a host (orgs phase 4): replace the authorized_keys lines the box\n * gets on top of the host's own key. Takes effect at the box's next boot (kvbox-init rewrites the\n * file from the kernel command line); a running or hibernated box keeps its current file until then.\n */\nexport const SetSshKeysRequest = z.object({\n sshKeys: z.array(z.string()),\n});\nexport type SetSshKeysRequest = z.infer<typeof SetSshKeysRequest>;\n\n/** `kvbox vm rescale`: a preset and/or explicit values; explicit ones win. Anything omitted stays as it is. */\nexport const RescaleMachineRequest = z.object({\n size: SizeSchema.optional(),\n vcpu: z.number().int().min(1).max(64).optional(),\n memMib: z.number().int().min(256).optional(),\n diskGib: z.number().int().min(1).optional(),\n /** Skip the capacity guard when a running box grows (#37). */\n force: z.boolean().optional(),\n});\nexport type RescaleMachineRequest = z.infer<typeof RescaleMachineRequest>;\n\n/** `POST /machines/:name/start` and `/wake`: `force` skips the capacity guard (#37). Both take no body too. */\nexport const StartMachineRequest = z.object({\n force: z.boolean().optional(),\n});\nexport type StartMachineRequest = z.infer<typeof StartMachineRequest>;\n\n/** `kvbox vm set`: settings that change nothing in the running VM. Anything omitted stays as it is. */\nexport const SetMachineRequest = z.object({\n /** Seconds without network traffic before the box is hibernated (#47); 0: never. */\n autoHibernateSec: z.number().int().min(0).optional(),\n /** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; \"\": none, back to network traffic. */\n idleCheck: z.union([z.literal(\"\"), z.string().max(255).regex(/^\\/[^\\0\\n]*$/, \"an absolute path inside the box\")]).optional(),\n});\nexport type SetMachineRequest = z.infer<typeof SetMachineRequest>;\n\nexport const SnapshotSchema = z.object({\n name: z.string(),\n owner: z.string(),\n source: z.string(), // the box it was taken from, as owner/name\n base: z.string(), // version of the image the overlay stacks on; a restore needs the same one\n /** As in MachineSchema: the image when it is not the base one (#87). */\n image: z.string().optional(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n sizeBytes: z.number().int(), // what vmstate + mem + overlay really occupy on the host\n createdAt: z.string(),\n});\nexport type Snapshot = z.infer<typeof SnapshotSchema>;\n\nexport const CreateSnapshotRequest = z.object({\n box: z.string(),\n name: z.string(),\n /** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */\n replace: z.boolean().optional(),\n});\nexport type CreateSnapshotRequest = z.infer<typeof CreateSnapshotRequest>;\n\n/**\n * The host's disk as volumes see it (#91). Volumes are sparse, so what they promise (`volumesGib`,\n * the sum of their sizes) and what they hold (`volumesUsedGib`) differ; a host may promise at most\n * the disk its boxes, snapshots and base images do not use, less `headroomGib` (@kvbox/shared/capacity `sellableGib`).\n */\nexport const DiskCapacitySchema = z.object({\n totalGib: z.number().int(),\n freeGib: z.number().int(),\n volumesGib: z.number().int(),\n volumesUsedGib: z.number().int(),\n headroomGib: z.number().int(),\n});\nexport type DiskCapacity = z.infer<typeof DiskCapacitySchema>;\n\nexport const CapacitySchema = z.object({\n hostMemMib: z.number().int(),\n hostCores: z.number().int(),\n reservedMemMib: z.number().int(),\n reservedVcpu: z.number().int(),\n running: z.number().int(),\n /** Absent on a host from before volumes (#91): it cannot take one. */\n disk: DiskCapacitySchema.optional(),\n /**\n * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.\n * Absent on a host from before images: it has only the base.\n */\n images: z.array(z.object({ name: z.string(), version: z.string() })).optional(),\n /** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */\n version: z.string().optional(),\n /** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */\n backupStore: z.object({ totalBytes: z.number().int(), freeBytes: z.number().int(), running: z.boolean() }).optional(),\n /** 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. */\n storeClient: z.boolean().optional(),\n});\nexport type Capacity = z.infer<typeof CapacitySchema>;\n\n/**\n * `GET /images` on the control plane: what a new box can boot from (`kvbox new --base <name>`), across\n * the hosts answering now. `version` is the newest a host offers; null for the base on a host from\n * before images, which does not say. The base comes first.\n */\nexport const ImageSchema = z.object({ name: z.string(), version: z.string().nullable() });\nexport type Image = z.infer<typeof ImageSchema>;\n\n/**\n * The index kvbox-images publishes with every release (`releases/download/index/images.json`): the\n * latest version of each guest image. `base` is the base rootfs, `kernel` the guest kernel, the rest\n * are the images of `kvbox new --base <name>` and the managed kinds. `minServer` is the oldest\n * kvbox-server that can run that version. install-server.sh installs by it; the control plane reads\n * it to say which hosts are behind (`GET /admin/images`).\n */\nexport const ImageIndexSchema = z.object({\n updatedAt: z.string(),\n images: z.record(z.string(), z.object({ version: z.string().min(1), minServer: z.string().min(1).optional() })),\n});\nexport type ImageIndex = z.infer<typeof ImageIndexSchema>;\n\n/**\n * `GET /admin/images`: the index as the control plane last read it. Without one (not published yet,\n * or never reached) `updatedAt` and `checkedAt` are null and `images` is empty. `checkedAt` is when\n * the control plane last read it successfully; a failed refresh keeps the older copy and its time.\n */\nexport const LatestImagesSchema = z.object({\n updatedAt: z.string().nullable(),\n images: ImageIndexSchema.shape.images,\n checkedAt: z.string().nullable(),\n});\nexport type LatestImages = z.infer<typeof LatestImagesSchema>;\n\n/**\n * What the server did at its last start about boxes whose Firecracker had died (host reboot or crash,\n * #29). Boxes are `owner/name`. `leftStopped`: they were in standby, their memory went with the process.\n */\nexport const RecoveryReportSchema = z.object({\n at: z.string(),\n booted: z.array(z.string()),\n leftStopped: z.array(z.string()),\n failed: z.array(z.object({ box: z.string(), error: z.string() })),\n});\nexport type RecoveryReport = z.infer<typeof RecoveryReportSchema>;\n\n/**\n * The host's last self-update (`install-server.sh --update`, started by the control plane's\n * `POST /admin/hosts/:name/update`), as `$KVBOX_HOME/update.json` holds it. The script writes it at\n * its start and its end; the daemon only reads it. `needsManual` names what the update left alone\n * because it needs root (a changed network script, the systemd unit, the /usr/local/bin links): run\n * install-server.sh on the host by hand for those.\n */\nexport const HostUpdateSchema = z.object({\n state: z.enum([\"running\", \"done\", \"failed\"]),\n startedAt: z.string(),\n finishedAt: z.string().nullable(),\n /** kvbox-server's version when the update started, and when it ended (null while running or when it failed before). */\n from: z.string(),\n to: z.string().nullable(),\n error: z.string().nullable(),\n needsManual: z.array(z.string()),\n});\nexport type HostUpdate = z.infer<typeof HostUpdateSchema>;\n\nexport const HealthSchema = z.object({\n ok: z.literal(true),\n version: z.string(),\n pid: z.number().int(),\n /** Base image version new boxes get (null when the host has no usable base image yet). */\n base: z.string().nullable(),\n /** Owner that boxes made over the local socket get (the Unix user running the server). */\n owner: z.string(),\n /** The control plane this host joined (null when none). */\n controlPlane: z\n .object({\n /** Realm name, e.g. kvbox.sh. */\n name: z.string(),\n url: z.string(),\n /** Where this host answers the control plane. */\n hostUrl: z.string(),\n })\n .nullable(),\n /** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */\n relay: z\n .object({\n name: z.string(),\n /** The public IP the relay owns for this host. */\n publicIp: z.string(),\n /** The relay's WireGuard endpoint the tunnel dials. */\n endpoint: z.string(),\n /** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */\n restarts: z.number().int().optional(),\n lastRestartAt: z.string().nullable().optional(),\n })\n .nullable()\n .optional(),\n /** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */\n recovery: RecoveryReportSchema.nullable().optional(),\n /** The last self-update; null when none ran. Older servers omit it. */\n update: HostUpdateSchema.nullable().optional(),\n});\nexport type Health = z.infer<typeof HealthSchema>;\n\n/**\n * `kvbox vm usage <box>`: how long the box spent in each state over a window and what that adds up\n * to. Hours are fractional; the CLI rounds. `cost` is present only when the host prices usage.\n * `historyFrom` is the first recorded moment, null when nothing is recorded yet.\n */\nexport const MachineUsageSchema = z.object({\n name: z.string(),\n owner: z.string(),\n status: BoxStatusSchema,\n window: z.object({ from: z.string(), to: z.string() }),\n seconds: z.object({\n running: z.number().int(),\n standby: z.number().int(),\n hibernated: z.number().int(),\n stopped: z.number().int(),\n }),\n vcpuHours: z.number(),\n ramGibHours: z.number(),\n diskGibHours: z.number(),\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */\n estimatedStops: z.number().int(),\n historyFrom: z.string().nullable(),\n});\nexport type MachineUsage = z.infer<typeof MachineUsageSchema>;\n\n/** What a running box says about itself through kvbox-agent's `stats` (base v0.7.0 and later). */\nexport const GuestStatsSchema = z.object({\n /** Load average over 1, 5 and 15 minutes. */\n load: z.tuple([z.number(), z.number(), z.number()]),\n cpus: z.number().int(),\n memTotalMib: z.number().int(),\n /** Total minus available: page cache counts as free. */\n memUsedMib: z.number().int(),\n /** The box's root, which is its overlay disk: the box's own writes, not the shared base. */\n diskTotalBytes: z.number().int(),\n diskUsedBytes: z.number().int(),\n uptimeSec: z.number().int(),\n});\nexport type GuestStats = z.infer<typeof GuestStatsSchema>;\n\n/** `GET /machines/:name/stats` (#67): `stats` is null when the box's image predates the request. */\nexport const MachineStatsSchema = z.object({\n name: z.string(),\n owner: z.string(),\n stats: GuestStatsSchema.nullable(),\n});\nexport type MachineStats = z.infer<typeof MachineStatsSchema>;\n\n/** A box's state as the usage ledger tells it: a box status, or `removed` when its last row is the `rm`. */\nexport const UsageStatusSchema = z.enum([...BoxStatusSchema.options, \"removed\"]);\nexport type UsageStatus = z.infer<typeof UsageStatusSchema>;\n\n/** One box's share of a `GET /usage` report (#41, #42): the same figures as `MachineUsage`, over the report's window. */\nexport const BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({\n /** The host's box id; a name removed and recreated appears twice, with two ids. */\n id: z.string(),\n status: UsageStatusSchema,\n /** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /**\n * Through a control plane: the username that made the box (#60), absent when the box is gone from\n * the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.\n */\n createdBy: z.string().optional(),\n});\nexport type BoxUsage = z.infer<typeof BoxUsageSchema>;\n\n/**\n * `GET /usage?since=&until=`: every box of the caller over the window (removed ones included) and\n * the totals. On a host over its socket: the host owner's boxes; through a control plane: every slug\n * the user can read (`X-Kvbox-Org` narrows to one). `cost` is present when the answering side prices usage.\n */\n/**\n * One volume's share of a `GET /usage` report (#91): the hours it existed over the window and its\n * GiB-hours (its size, not what it holds: a volume is a reservation). `removed` when its last row is\n * the `rm`. The price is per volume-hour plus per GiB-hour (decision \"Cloud pricing v1\").\n */\nexport const VolumeUsageSchema = z.object({\n /** The host's volume id; a name removed and made again appears twice, with two ids. */\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /** The size at the end of the window (or when removed). */\n sizeGib: z.number().int(),\n status: z.enum([\"present\", \"removed\"]),\n volumeHours: z.number(),\n volumeGibHours: z.number(),\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n historyFrom: z.string().nullable(),\n});\nexport type VolumeUsage = z.infer<typeof VolumeUsageSchema>;\n\n/** A box's or a volume's share of one day in `days`: what it cost that day, and nothing else. */\nexport const UsageDayItemSchema = z.object({\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n /** Removed by the end of the report's window. */\n removed: z.boolean(),\n cost: z.number(),\n});\nexport type UsageDayItem = z.infer<typeof UsageDayItemSchema>;\n\n/**\n * One UTC day of a `GET /usage?by=day` report (control plane only): its cost, and each box and volume\n * that existed that day with its share, most expensive first. The first and last day are clipped to\n * the window (today ends now). Every day of the window is listed, an empty one included.\n */\nexport const UsageDaySchema = z.object({\n /** `YYYY-MM-DD`, UTC. */\n date: z.string(),\n from: z.string(),\n to: z.string(),\n cost: z.number(),\n currency: z.string(),\n boxes: z.array(UsageDayItemSchema),\n volumes: z.array(UsageDayItemSchema),\n /** Object storage that existed that day (#182); absent on a day without any. */\n storage: z.array(UsageDayItemSchema).optional(),\n});\nexport type UsageDay = z.infer<typeof UsageDaySchema>;\n\n/** The longest window `?by=day` takes: a quarter of daily rows. */\nexport const MAX_USAGE_DAYS = 93;\n\nexport const UsageReportSchema = z.object({\n window: z.object({ from: z.string(), to: z.string() }),\n boxes: z.array(BoxUsageSchema),\n /** Absent from a side older than #91. */\n volumes: z.array(VolumeUsageSchema).optional(),\n /**\n * Object storage (#182, control plane only): one row per storage a slug has or had, shaped like a\n * volume's. `volumeHours` are the hours it existed, `volumeGibHours` those of the GiB beyond the\n * included ones, `sizeGib` its whole size. Absent when there is none.\n */\n storage: z.array(VolumeUsageSchema).optional(),\n /** With `?by=day` only, oldest day first. */\n days: z.array(UsageDaySchema).optional(),\n totals: z.object({\n seconds: MachineUsageSchema.shape.seconds,\n vcpuHours: z.number(),\n ramGibHours: z.number(),\n diskGibHours: z.number(),\n volumeHours: z.number().optional(),\n volumeGibHours: z.number().optional(),\n /** Boxes, volumes and object storage together. */\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n }),\n});\nexport type UsageReport = z.infer<typeof UsageReportSchema>;\n\n/**\n * `GET /usage/events?after=<id>&limit=<n>` on a host (#42): the ledger rows after `after`, oldest\n * first, as the control plane pulls them. `next` is the last row's id (the cursor to store), equal\n * to `after` when there was nothing new. Over HTTPS only rows of the caller's realm come back.\n * `ledger` names the host's ledger: row ids are unique only within it, and a new one restarts at 1.\n */\nexport const UsageEventRowSchema = z.object({\n id: z.number().int(),\n boxId: z.string(),\n owner: z.string(),\n name: z.string(),\n at: z.string(),\n state: z.enum([\"running\", \"standby\", \"hibernated\", \"stopped\"]),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n diskGib: z.number().int(),\n by: z.string(),\n});\nexport type UsageEventRow = z.infer<typeof UsageEventRowSchema>;\n\nexport const UsageEventsResponseSchema = z.object({\n ledger: z.string().min(1),\n events: z.array(UsageEventRowSchema),\n next: z.number().int(),\n});\nexport type UsageEventsResponse = z.infer<typeof UsageEventsResponseSchema>;\n\n/**\n * `GET /usage/volume-events?after=<id>&limit=<n>` on a host (#91): the volume ledger, pulled like the\n * box ledger and in the same host ledger (one `ledger` id, its own row ids). A row per create, resize\n * and rm, carrying the size from that moment on.\n */\nexport const VolumeEventRowSchema = z.object({\n id: z.number().int(),\n volumeId: z.string(),\n owner: z.string(),\n name: z.string(),\n at: z.string(),\n sizeGib: z.number().int(),\n by: z.enum([\"create\", \"resize\", \"rm\"]),\n});\nexport type VolumeEventRow = z.infer<typeof VolumeEventRowSchema>;\n\nexport const VolumeEventsResponseSchema = z.object({\n ledger: z.string().min(1),\n events: z.array(VolumeEventRowSchema),\n next: z.number().int(),\n});\nexport type VolumeEventsResponse = z.infer<typeof VolumeEventsResponseSchema>;\n\n/**\n * Why a control plane answer is 402, so a client can tell the caller's own account (go and\n * activate it) from a slug it acted on (an org that is off, a balance at zero). The `error`\n * text stays the message to show. Every 402 a signed-in caller gets carries one; the public wake\n * hook's (`POST /hooks/:id`, routes/hooks.ts) has no caller account to speak of and carries none.\n */\nexport const API_ERROR_CODES = [\"account-inactive\", \"org-inactive\", \"out-of-credit\"] as const;\nexport const ApiErrorCodeSchema = z.enum(API_ERROR_CODES);\nexport type ApiErrorCode = z.infer<typeof ApiErrorCodeSchema>;\n\nexport const ApiErrorSchema = z.object({\n error: z.string(),\n code: ApiErrorCodeSchema.optional(),\n});\nexport type ApiError = z.infer<typeof ApiErrorSchema>;\n\n// ---- control plane (kvbox-cloud) ----\n\n/** Where `kvbox login` goes without a URL, and the control plane's own public URL by default. */\nexport const DEFAULT_CLOUD_URL = \"https://api.kvbox.sh\";\n\n/**\n * Who turned a slug (a user or an org) on: a card on file (`card`, #75) or an admin by hand\n * (`admin`, #74). Until one of them does, the account only logs in and looks: every other route\n * answers 402 (decision \"Signup is email + password… inactive until a card is on file\").\n */\nexport const ACTIVATED_BY = [\"card\", \"admin\"] as const;\nexport const ActivatedBySchema = z.enum(ACTIVATED_BY);\nexport type ActivatedBy = z.infer<typeof ActivatedBySchema>;\n\n/** A user account on the control plane; returned by `GET /me`, `GET /users` (#48). */\nexport const CloudUserSchema = z.object({\n /** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */\n username: z.string(),\n /** Display name, free text (\"Alexandru Ghiura\"). */\n name: z.string(),\n /** Login identity, unique. */\n email: z.string(),\n role: z.enum([\"admin\", \"user\"]),\n createdAt: z.string(),\n /**\n * False until a card is on file or an admin activates the account (#74): then only `/me` and\n * `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and\n * gates nobody, hence the defaults: a newer CLI must still parse its answers.\n */\n active: z.boolean().default(true),\n activatedBy: ActivatedBySchema.nullable().default(null),\n /** When too many wrong passwords locked the account (#161); null when it is not locked. Older control planes omit it. */\n lockedAt: z.string().nullable().default(null),\n});\nexport type CloudUser = z.infer<typeof CloudUserSchema>;\n\n// ---- orgs (plan \"Orgs, slugs and roles\") ----\n\nexport const ORG_ROLES = [\"owner\", \"admin\", \"member\"] as const;\nexport const OrgRoleSchema = z.enum(ORG_ROLES);\nexport type OrgRole = z.infer<typeof OrgRoleSchema>;\n\n/** An org as the API shows it; its slug owns boxes the way a username does. */\nexport const CloudOrgSchema = z.object({\n slug: z.string(),\n /** Display name; the slug never changes, this may. */\n name: z.string(),\n createdAt: z.string(),\n /** 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. */\n active: z.boolean().default(true),\n activatedBy: ActivatedBySchema.nullable().default(null),\n});\nexport type CloudOrg = z.infer<typeof CloudOrgSchema>;\n\n/** One of the caller's orgs with their role in it (`GET /orgs`, `GET /me`). */\nexport const OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });\nexport type OrgMembership = z.infer<typeof OrgMembershipSchema>;\n\nexport const OrgMemberSchema = z.object({\n username: z.string(),\n name: z.string(),\n role: OrgRoleSchema,\n addedAt: z.string(),\n});\nexport type OrgMember = z.infer<typeof OrgMemberSchema>;\n\n/** `GET /orgs/:slug`: the org and its members (members and up see it). */\nexport const OrgDetailSchema = CloudOrgSchema.extend({ members: z.array(OrgMemberSchema) });\nexport type OrgDetail = z.infer<typeof OrgDetailSchema>;\n\n/** `POST /orgs`: the caller becomes the org's owner. */\nexport const CreateOrgRequestSchema = z.object({\n slug: z.string().min(1),\n name: z.string().min(1),\n});\nexport type CreateOrgRequest = z.infer<typeof CreateOrgRequestSchema>;\n\n/** `PATCH /orgs/:slug` (owner): the display name. */\nexport const RenameOrgRequestSchema = z.object({ name: z.string().min(1) });\n\n/** `POST /orgs/:slug/members` (admin, owner): an existing user joins, as a member unless said otherwise. */\nexport const AddMemberRequestSchema = z.object({\n username: z.string().min(1),\n role: OrgRoleSchema.default(\"member\"),\n});\nexport type AddMemberRequest = z.infer<typeof AddMemberRequestSchema>;\n\n/** `PATCH /orgs/:slug/members/:username` (owner). */\nexport const SetRoleRequestSchema = z.object({ role: OrgRoleSchema });\n\n/** `GET /me`: the account plus the orgs it belongs to. */\nexport const MeResponseSchema = CloudUserSchema.extend({ orgs: z.array(OrgMembershipSchema) });\nexport type MeResponse = z.infer<typeof MeResponseSchema>;\n\n// ---- prepaid credit (#76) ----\n\n/**\n * `GET /billing/balance`: what a slug (the caller's own, or `X-Kvbox-Org`'s) has left. `balance` is\n * every top-up, plus promo credit (#163), minus what the usage ledger says its boxes cost since\n * `since`, the slug's first credit (null: it never had any); at or below zero the slug cannot start or\n * create anything (402). `topUps` and `spent` are the paid side of it. `promo` is the part of\n * `balance` that came from redeemed codes and expires: it is spent first, and what is left of it is\n * gone at its date.\n */\nexport const BalanceSchema = z.object({\n slug: z.string(),\n balance: z.number(),\n currency: z.string(),\n topUps: z.number(),\n spent: z.number(),\n /** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */\n since: z.string().nullable(),\n /** 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. */\n suspendedAt: z.string().nullable().default(null),\n /** Promo credit left (#163), already counted in `balance`; 0 with none. Absent from a control plane older than this field. */\n promo: z.number().default(0),\n /** When the next promo credit expires; null with none left. */\n promoExpiresAt: z.string().nullable().default(null),\n});\nexport type Balance = z.infer<typeof BalanceSchema>;\n\n/** `POST /admin/billing/top-ups` (platform admin): give a slug money by hand. */\nexport const TopUpRequestSchema = z.object({\n slug: z.string().min(1),\n /** In the control plane's currency; negative corrects a mistake. */\n amount: z.number().finite(),\n note: z.string().max(200).optional(),\n});\nexport type TopUpRequest = z.infer<typeof TopUpRequestSchema>;\n\n/** One top-up as recorded, answered by `POST /admin/billing/top-ups`. */\nexport const TopUpSchema = z.object({\n id: z.string(),\n slug: z.string(),\n amount: z.number(),\n currency: z.string(),\n /** `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. */\n source: z.enum([\"admin\", \"card\", \"trial\", \"transfer\"]),\n note: z.string().nullable(),\n at: z.string(),\n});\nexport type TopUp = z.infer<typeof TopUpSchema>;\n\n// ---- promo codes (#163) ----\n\n/** `POST /admin/billing/codes` (platform admin): make a code worth `amount` that expires on `expiresAt`. */\nexport const CreateCodeRequestSchema = z.object({\n /** In the control plane's currency, cents at most. */\n amount: z.number().positive().multipleOf(0.01, \"amount is in cents at most\"),\n /** 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. */\n expiresAt: z.string().min(1),\n note: z.string().max(200).optional(),\n});\nexport type CreateCodeRequest = z.infer<typeof CreateCodeRequestSchema>;\n\n/** One promo code as the admin sees it. `status`: `unused` can still be redeemed; the other three cannot. */\nexport const CreditCodeSchema = z.object({\n code: z.string(),\n amount: z.number(),\n currency: z.string(),\n expiresAt: z.string(),\n note: z.string().nullable(),\n status: z.enum([\"unused\", \"redeemed\", \"expired\", \"revoked\"]),\n createdBy: z.string(),\n createdAt: z.string(),\n /** Who redeemed it and the slug the credit went to (their own, or an org they own). */\n redeemedBy: z.string().nullable(),\n redeemedSlug: z.string().nullable(),\n redeemedAt: z.string().nullable(),\n revokedAt: z.string().nullable(),\n});\nexport type CreditCode = z.infer<typeof CreditCodeSchema>;\n\n/** `POST /billing/redeem` body: the code, and the org it is for (one the caller owns) when not their own account. */\nexport const RedeemRequestSchema = z.object({\n code: z.string().min(1).max(64),\n org: z.string().min(1).optional(),\n});\nexport type RedeemRequest = z.infer<typeof RedeemRequestSchema>;\n\n/** `POST /billing/redeem` answer: what the code gave, to which slug, and that slug's balance afterwards. */\nexport const RedeemResponseSchema = z.object({\n slug: z.string(),\n amount: z.number(),\n currency: z.string(),\n expiresAt: z.string(),\n balance: BalanceSchema,\n /** The slug was out of credit and this put it back above zero: it may start boxes again. */\n reinstated: z.boolean(),\n});\nexport type RedeemResponse = z.infer<typeof RedeemResponseSchema>;\n\n// ---- card and credit through Stripe (#93) ----\n\n/** The fixed top-up amounts, in the price list's currency (decision \"Card and credit v1\"): no custom amount. */\nexport const TOP_UP_AMOUNTS = [10, 25, 50, 100] as const;\n\n/**\n * `GET /billing`: the caller's own card and balance. `card` is the card Stripe holds as the customer's\n * default, null until one was saved through `POST /billing/card` and accepted; `cardInUse` says the\n * last card saved was refused because another account had already used it, and no other card is on file.\n */\nexport const BillingInfoSchema = z.object({\n card: z.object({ brand: z.string(), last4: z.string() }).nullable(),\n cardInUse: z.boolean(),\n balance: BalanceSchema,\n});\nexport type BillingInfo = z.infer<typeof BillingInfoSchema>;\n\n/** `POST /billing/card`, `/billing/top-up`, `/billing/portal`: where to send the browser (Stripe's hosted page). */\nexport const BillingRedirectSchema = z.object({ url: z.string() });\nexport type BillingRedirect = z.infer<typeof BillingRedirectSchema>;\n\n/** `POST /billing/top-up` body. */\nexport const TopUpCheckoutRequestSchema = z.object({\n amount: z.literal(TOP_UP_AMOUNTS),\n});\nexport type TopUpCheckoutRequest = z.infer<typeof TopUpCheckoutRequestSchema>;\n\n/** `POST /billing/transfers` body: move `amount` of the caller's credit to `org`, which they own. Cents at most. */\nexport const TransferRequestSchema = z.object({\n org: z.string().min(1),\n amount: z.number().positive().multipleOf(0.01, \"amount is in cents at most\"),\n});\nexport type TransferRequest = z.infer<typeof TransferRequestSchema>;\n\n/** `POST /billing/transfers` answer: both balances afterwards, and whether this transfer turned the org on. */\nexport const TransferResponseSchema = z.object({ from: BalanceSchema, to: BalanceSchema, activated: z.boolean() });\nexport type TransferResponse = z.infer<typeof TransferResponseSchema>;\n\n/** `POST /login` body from `kvbox login` (#48); `publicKey` is the user's SSH key to inject into new boxes. */\nexport const LoginRequestSchema = z.object({\n email: z.string().min(1),\n password: z.string().min(1),\n publicKey: z.string().optional(),\n});\nexport type LoginRequest = z.infer<typeof LoginRequestSchema>;\n\n/** `POST /signup` body from the website: a new account with the `user` role; answers like `/login` (logged in at once). */\nexport const SignupRequestSchema = z.object({\n username: z.string().min(1),\n name: z.string().min(1),\n email: z.string().min(1),\n password: z.string().min(1),\n});\nexport type SignupRequest = z.infer<typeof SignupRequestSchema>;\n\n/**\n * `POST /login` answer: the bearer token the CLI stores (#48). With a `publicKey` in the request,\n * also that key signed by the control plane's SSH CA (#51): the `-cert.pub` text and when it expires (ISO).\n */\nexport const LoginResponseSchema = z.object({\n token: z.string(),\n user: CloudUserSchema,\n sshCert: z.string().optional(),\n sshCertExpires: z.string().optional(),\n /** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */\n sshCertPrincipals: z.array(z.string()).optional(),\n});\nexport type LoginResponse = z.infer<typeof LoginResponseSchema>;\n\n/** `POST /ssh/cert` body: one of the caller's uploaded keys to sign again (#51). */\nexport const SshCertRequestSchema = z.object({\n publicKey: z.string().min(1),\n});\nexport type SshCertRequest = z.infer<typeof SshCertRequestSchema>;\n\n/** `POST /ssh/cert` answer: the certificate text, its expiry (ISO) and its principals. */\nexport const SshCertResponseSchema = z.object({\n cert: z.string(),\n expires: z.string(),\n principals: z.array(z.string()),\n});\nexport type SshCertResponse = z.infer<typeof SshCertResponseSchema>;\n\n/** `GET /ssh/ca` answer: the CA's public key, the line boxes trust after `cert-authority `. */\nexport const SshCaResponseSchema = z.object({\n publicKey: z.string(),\n /** 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. */\n retired: z.array(z.object({ publicKey: z.string(), retiredAt: z.string() })).optional(),\n});\nexport type SshCaResponse = z.infer<typeof SshCaResponseSchema>;\n\n/** `GET /hosts/self/ssh-ca` on the control plane, by the host secret: the CA every box should trust (`kvbox-server trust-ca --from-cloud`, #55). */\nexport const HostSshCaResponseSchema = z.object({\n publicKey: z.string(),\n});\n\n/** `GET /ssh/cloud-ca` on a host's socket: what its control plane says the CA is, with the fingerprint to confirm. */\nexport const CloudCaSchema = z.object({\n controlPlane: z.string(),\n publicKey: z.string(),\n fingerprint: z.string(),\n});\nexport type CloudCa = z.infer<typeof CloudCaSchema>;\n\n/** `POST /ssh/trust-ca` on a host's socket (#55): the CA public key (a pasted `cert-authority …` line is accepted too). */\nexport const TrustCaRequestSchema = z.object({\n publicKey: z.string().min(1),\n});\nexport type TrustCaRequest = z.infer<typeof TrustCaRequestSchema>;\n\n/**\n * When a box's new authorized_keys reach the guest: `now` (pushed through kvbox-agent), or at its\n * next `start` (stopped: kvbox-init writes the file at boot), `wake` (hibernated), `resume`\n * (standby), or `later` (running, but its agent could not take them: the next stop and start).\n */\nexport const SshKeysAppliedSchema = z.enum([\"now\", \"start\", \"wake\", \"resume\", \"later\"]);\nexport type SshKeysApplied = z.infer<typeof SshKeysAppliedSchema>;\n\n/** `POST /ssh/trust-ca` answer: every cloud box on the host, by what happened to it. Boxes are `owner/name`. */\nexport const TrustCaReportSchema = z.object({\n publicKey: z.string(),\n fingerprint: z.string(),\n /** The guest trusts the CA now. */\n updated: z.array(z.string()),\n /** meta.json has the line; the guest gets it at `when`. */\n pending: z.array(z.object({ box: z.string(), when: SshKeysAppliedSchema, why: z.string().optional() })),\n failed: z.array(z.object({ box: z.string(), error: z.string() })),\n /** Local boxes, untouched: they trust the host's key only. */\n local: z.number().int(),\n /** Cloud boxes made without a CA line (a managed service's, #173), untouched: no certificate opens them. Absent from older servers. */\n skipped: z.array(z.string()).optional(),\n});\nexport type TrustCaReport = z.infer<typeof TrustCaReportSchema>;\n\n/** `POST /hosts/join` body from `kvbox-server join` (#18); `fingerprint` is the host's TLS cert sha256, colon-separated. */\nexport const HostJoinRequestSchema = z.object({\n token: z.string().min(1),\n name: z.string().min(1),\n url: z.string().url(),\n fingerprint: z.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),\n publicAddress: z.string().min(1),\n /** Where the host is (`kvbox-server join --country`): a code or an English name. */\n country: z.string().optional(),\n});\nexport type HostJoinRequest = z.infer<typeof HostJoinRequestSchema>;\n\n/** `POST /hosts/join` answer: the secret the control plane will present to the host from now on (#18). */\nexport const HostJoinResponseSchema = z.object({\n hostSecret: z.string(),\n controlPlane: z.object({ name: z.string() }),\n});\nexport type HostJoinResponse = z.infer<typeof HostJoinResponseSchema>;\n\n/** A host as the control plane knows it; returned by `GET /hosts` (admin). */\nexport const CloudHostSchema = z.object({\n name: z.string(),\n url: z.string(),\n publicAddress: z.string(),\n joinedAt: z.string(),\n lastSeenAt: z.string().nullable(),\n capacity: CapacitySchema.nullable(),\n /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */\n country: z.string().nullable(),\n /** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */\n region: z.string().nullable(),\n /** 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. */\n version: z.string().nullable(),\n});\nexport type CloudHost = z.infer<typeof CloudHostSchema>;\n\n/**\n * `GET /admin/hosts/:name/info`: what the control plane knows about a host, and what the host says about\n * itself right now (its `/health`: versions, relay, control plane, last update). `health` is null and\n * `error` says why when the host did not answer.\n */\nexport const HostInfoSchema = z.object({\n host: CloudHostSchema,\n health: HealthSchema.nullable(),\n error: z.string().nullable(),\n});\nexport type HostInfo = z.infer<typeof HostInfoSchema>;\n\n/**\n * `PATCH /admin/hosts/:name`: change what the admin may say about a host; a field left out stays as it\n * is, null clears it. `region` is for storages made from now on: one already made keeps its own.\n */\nexport const HostPatchRequest = z\n .object({ country: z.string().nullable().optional(), region: z.string().nullable().optional() })\n .refine((b) => b.country !== undefined || b.region !== undefined, { message: \"give country, region or both\" });\nexport type HostPatchRequest = z.infer<typeof HostPatchRequest>;\n\n/** `GET /countries`: the countries a new box can be placed in now (a live host there), by name. */\nexport const CountrySchema = z.object({ code: z.string(), name: z.string() });\nexport type Country = z.infer<typeof CountrySchema>;\n","/**\n * SSH public keys as text, for the three places that handle the CA's: the control plane writes a\n * box's `cert-authority` line and prints a fingerprint after `ca rotate`, the host builds the same\n * line for every box at `kvbox-server trust-ca`, the CLI shows the fingerprint before asking.\n */\nimport { createHash } from \"node:crypto\";\nimport { KvboxError } from \"./errors.js\";\n\n/** `<type> <base64>[ <comment>]`, one line; the types OpenSSH signs certificates with. */\nexport const SSH_PUBLIC_KEY_RE =\n /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\\.com|sk-ecdsa-sha2-nistp256@openssh\\.com) ([A-Za-z0-9+/]+=*)(?: [^\\r\\n]*)?$/;\n\n/** The key, trimmed, with a leading `cert-authority ` (a pasted authorized_keys line) allowed and dropped. */\nexport function parseSshPublicKey(text: string): string {\n const key = text.trim().replace(/^cert-authority\\s+/, \"\");\n if (!SSH_PUBLIC_KEY_RE.test(key)) {\n throw new KvboxError(\"that is not an SSH public key; expected one line like: ssh-ed25519 AAAA… kvbox-ca@kvbox.sh\");\n }\n return key;\n}\n\n/** `SHA256:<base64, no padding>` of the key blob, what `ssh-keygen -l` prints. */\nexport function sshKeyFingerprint(publicKey: string): string {\n const m = SSH_PUBLIC_KEY_RE.exec(publicKey.trim());\n if (!m) throw new KvboxError(\"cannot fingerprint: not an SSH public key\");\n return `SHA256:${createHash(\"sha256\").update(Buffer.from(m[2]!, \"base64\")).digest(\"base64\").replace(/=+$/, \"\")}`;\n}\n\n/**\n * A box's authorized_keys line for a CA: trust it, but only for certificates naming `principal`\n * (the box's owner, `<slug>@<realm>`); sshd then ignores the login name and matches `principals=`.\n */\nexport function caLineFor(principal: string, caPublicKey: string): string {\n return `cert-authority,principals=\"${principal}\" ${caPublicKey}`;\n}\n\n/** Whether an authorized_keys line is a CA line (any options, the keyword first). */\nexport const isCaLine = (line: string): boolean => /^cert-authority(,|\\s)/.test(line.trim());\n","/**\n * Client for kvbox-agent, the small service every box runs (kvbox-images, /usr/local/sbin/kvbox-agent).\n * It listens on a vsock port, and Firecracker exposes that as a Unix socket next to the box's API\n * socket: connect, send `CONNECT <port>\\n`, get `OK <n>\\n` back once the guest accepted, then the\n * stream is the guest's. The agent speaks one JSON object per line, one request per connection.\n * Vsock does not touch the box's network, so this works whatever the box did to its own eth0.\n */\nimport { connect } from \"node:net\";\nimport { GuestStatsSchema, type GuestStats } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\n\n/** The vsock port kvbox-agent listens on; fixed in the image. */\nexport const AGENT_PORT = 52;\n\nexport interface Identity {\n name: string;\n ip: string;\n prefixLen: number;\n gateway: string;\n mac: string;\n /** Unix seconds for the guest's clock, which stopped at the snapshot. */\n time: number;\n}\n\ntype AgentReply = { ok: true; [k: string]: unknown } | { ok: false; error: string };\n\n/** One request/reply exchange with the agent behind `udsPath`. Rejects on connection errors, timeout or `ok: false`. */\nexport async function agentCall(udsPath: string, req: Record<string, unknown>, timeoutMs = 5000): Promise<Record<string, unknown>> {\n const reply = await new Promise<string>((resolve, reject) => {\n const sock = connect(udsPath);\n let buf = \"\";\n let handshaken = false;\n const fail = (err: Error) => {\n sock.destroy();\n reject(err);\n };\n // Before `OK` the guest has not taken the connection: its vsock driver may not be up yet (a slow boot).\n sock.setTimeout(timeoutMs, () => fail(new KvboxError(handshaken ? `kvbox-agent did not answer within ${timeoutMs} ms` : `the guest did not accept the vsock connection within ${timeoutMs} ms`)));\n sock.once(\"error\", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));\n sock.once(\"connect\", () => sock.write(`CONNECT ${AGENT_PORT}\\n`));\n sock.on(\"data\", (chunk) => {\n buf += chunk.toString(\"utf8\");\n let nl: number;\n while ((nl = buf.indexOf(\"\\n\")) !== -1) {\n const line = buf.slice(0, nl);\n buf = buf.slice(nl + 1);\n if (!handshaken) {\n if (!line.startsWith(\"OK \")) return fail(new KvboxError(`vsock connect refused: ${line}`));\n handshaken = true;\n sock.write(JSON.stringify(req) + \"\\n\");\n } else {\n sock.end();\n return resolve(line);\n }\n }\n });\n sock.once(\"close\", () => {\n if (!handshaken) fail(new KvboxError(\"vsock connection closed before the guest accepted\"));\n else fail(new KvboxError(\"kvbox-agent closed the connection without a reply\"));\n });\n });\n let parsed: AgentReply;\n try {\n parsed = JSON.parse(reply) as AgentReply;\n } catch {\n throw new KvboxError(`kvbox-agent sent something that is not JSON: ${reply}`);\n }\n if (!parsed.ok) throw new KvboxError(`kvbox-agent: ${parsed.error}`);\n return parsed;\n}\n\nexport function ping(udsPath: string, timeoutMs?: number) {\n return agentCall(udsPath, { op: \"ping\" }, timeoutMs);\n}\n\n/** Tell a restored box who it is now; it renames itself, re-addresses eth0 and sets its clock. */\nexport function setIdentity(udsPath: string, id: Identity, timeoutMs?: number) {\n return agentCall(udsPath, { op: \"identity\", ...id }, timeoutMs);\n}\n\n/**\n * Replace the kvbox user's authorized_keys with exactly these lines (base v0.6.0 and later): a\n * restored or woken box has the file it was frozen with, the host has the current one (#63, #55).\n */\nexport function setAuthorizedKeys(udsPath: string, lines: readonly string[], timeoutMs?: number) {\n return agentCall(udsPath, { op: \"authorizedKeys\", lines: [...lines] }, timeoutMs);\n}\n\n/** The box's own load, memory, disk and uptime (base v0.7.0 and later). */\nexport async function stats(udsPath: string, timeoutMs?: number): Promise<GuestStats> {\n const reply = GuestStatsSchema.safeParse(await agentCall(udsPath, { op: \"stats\" }, timeoutMs));\n if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? \"invalid\"}`);\n return reply.data;\n}\n\n/**\n * Force-unmount every volume the guest still has mounted (base v0.9.0 and later, #52): a box restored\n * from a snapshot has the source box's mounts in memory over empty placeholder disks. Answers the paths.\n */\nexport async function dropVolumes(udsPath: string, timeoutMs?: number): Promise<string[]> {\n const reply = await agentCall(udsPath, { op: \"dropVolumes\" }, timeoutMs);\n return Array.isArray(reply[\"dropped\"]) ? reply[\"dropped\"].map(String) : [];\n}\n\n/**\n * Replace the box owner's environment variables (base v0.10.0 and later, #88): the agent writes\n * /etc/kvbox/env and ~/.ssh/environment and restarts kvbox-app when the list changed.\n */\nexport function setEnv(udsPath: string, vars: readonly { name: string; value: string }[], timeoutMs?: number) {\n return agentCall(udsPath, { op: \"env\", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);\n}\n\n/**\n * Whether the box is idle by its own check (#102, base v0.12.0 and later): the agent runs `script` (at\n * most 10 s), exit 0 = idle. Rejects when the script fails to run or an older agent does not know the request.\n */\nexport async function idle(udsPath: string, script: string, timeoutMs = 15_000): Promise<boolean> {\n return (await agentCall(udsPath, { op: \"idle\", path: script }, timeoutMs))[\"idle\"] === true;\n}\n\n/**\n * Run a script the box's image names in its image.json (#173, base v0.14.0 and later): `input` is its\n * stdin as one JSON line, the JSON it prints is the answer. The agent gives it 30 s.\n */\nexport async function runScript(udsPath: string, path: string, input: unknown, timeoutMs = 35_000): Promise<unknown> {\n return (await agentCall(udsPath, { op: \"script\", path, input: input ?? null }, timeoutMs))[\"output\"];\n}\n\n/** An agent from an image older than the request it was sent. */\nexport const isUnknownOp = (err: unknown): boolean => /unknown op/.test((err as Error).message ?? \"\");\n\n/** The guest is still booting (its vsock driver not up yet): a box that is running but cannot be asked anything yet. */\nexport const isGuestBooting = (err: unknown): boolean => /did not accept the vsock connection/.test((err as Error).message ?? \"\");\n\n/**\n * Nothing in the guest took the connection: an image older than kvbox-agent itself (before base\n * v0.5.0), so no vsock listener, a box booted without the vsock socket, or a guest still booting\n * (`isGuestBooting`, which a caller may want to tell apart: a wait for the agent retries on it,\n * `machineStats` reports it).\n */\nexport const isNoAgent = (err: unknown): boolean =>\n /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test((err as Error).message ?? \"\");\n","/**\n * Environment variables (#88). The control plane owns each slug's list and sends this host the whole\n * of it after every change (`POST /env`) and again from its sweep when the host's `version` lags; the\n * host keeps it per owner in env/<owner>.json (mode 600, values in the clear: the host admin can read\n * every box's disk and memory anyway, decision \"Env vars belong to a slug…\"). Every box of that owner\n * gets the list from core/machines.ts when it boots or is restored, through kvbox-agent's `env` request.\n * A running box is not touched: a change applies at its next start.\n */\nimport { existsSync } from \"node:fs\";\nimport { copyFile, mkdir, readFile, readdir, rename, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport type { EnvVar, HostEnvRequest, HostEnvVersions } from \"@kvbox/shared/api\";\nimport { ENV_MAX_VARS, envNameProblem, envValueProblem } from \"@kvbox/shared/env\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { withBoxLock, withHostLock } from \"./locks.js\";\nimport { inScope, OWNER_RE, realmOf, shown, type BoxRef, type ListScope } from \"./refs.js\";\nimport { log } from \"./log.js\";\n\nconst OwnerEnvSchema = z.object({\n /** The control plane's counter for the list; only ever grows. */\n version: z.number().int().min(0),\n vars: z.array(z.object({ name: z.string(), value: z.string() })),\n});\nexport type OwnerEnv = z.infer<typeof OwnerEnvSchema>;\n\n/** The owner's list, or null when the control plane never sent one (a local owner always). */\nexport async function readOwnerEnv(owner: string, p: Paths = paths()): Promise<OwnerEnv | null> {\n try {\n return OwnerEnvSchema.parse(JSON.parse(await readFile(p.ownerEnv(owner), \"utf8\")));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw err;\n }\n}\n\n/**\n * What a box of `owner` is handed when it boots or is restored: the owner's list, or an empty one for a\n * cloud owner the control plane never sent a list for, so a box forked from another slug's box does\n * not keep that slug's files (the agent replaces both with the empty list). Null only for a local\n * owner's box that never had variables of its own; once it had some (env.json exists, even emptied by\n * `env rm`), an empty list, so the guest drops what it was given last.\n */\nexport async function envForBoot(box: BoxRef, p: Paths = paths()): Promise<OwnerEnv[\"vars\"] | null> {\n const env = await readOwnerEnv(box.owner, p).catch(() => null);\n const own = await readBoxEnv(box, p).catch((err: Error) => {\n log.warn(`box ${shown(box)}: its own variables are unreadable, it boots without them: ${err.message}`);\n return [];\n });\n const slug = env?.vars ?? (realmOf(box.owner) !== null ? [] : null);\n if (own.length === 0) return slug ?? (existsSync(p.machine(box.owner, box.name).env) ? [] : null);\n // The box's own win over its owner's (#87): one list, the agent writes it as given.\n const mine = new Set(own.map((v) => v.name));\n return [...(slug ?? []).filter((v) => !mine.has(v.name)), ...own.map((v) => ({ name: v.name, value: v.value }))];\n}\n\n/**\n * A box's own variables (#87): machines/<owner>/<box>/env.json, mode 600, beside a meta.json that stays\n * free of them (meta.json is 0644 and read everywhere). Set at `new -e`, changed by `kvbox env --box`,\n * copied by a snapshot or a fork, gone with the box's dir.\n */\nconst BoxEnvFileSchema = z.object({\n vars: z.array(z.object({ name: z.string(), value: z.string(), secret: z.boolean(), updatedAt: z.string() })),\n});\nexport type BoxVar = z.infer<typeof BoxEnvFileSchema>[\"vars\"][number];\n\nexport async function readBoxEnv(box: BoxRef, p: Paths = paths()): Promise<BoxVar[]> {\n return readBoxEnvFile(p.machine(box.owner, box.name).env);\n}\n\n/** An env.json by its path (a box's or a snapshot's); none is no variables. */\nexport async function readBoxEnvFile(file: string): Promise<BoxVar[]> {\n try {\n return BoxEnvFileSchema.parse(JSON.parse(await readFile(file, \"utf8\"))).vars;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n}\n\n/** The checks `writeBoxEnv` makes, for a caller that must know a list will land before it changes anything. */\nexport function checkBoxEnv(vars: readonly BoxVar[]): void {\n if (vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);\n const seen = new Set<string>();\n for (const v of vars) {\n const problem = envNameProblem(v.name) ?? envValueProblem(v.value);\n if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);\n if (seen.has(v.name)) throw new KvboxError(`${v.name} is given twice`);\n seen.add(v.name);\n }\n}\n\n/** Checked like the owner's list, so a list the guest would refuse never lands. */\nexport async function writeBoxEnv(box: BoxRef, vars: readonly BoxVar[], p: Paths = paths()): Promise<void> {\n checkBoxEnv(vars);\n const file = p.machine(box.owner, box.name).env;\n const tmp = `${file}.tmp`;\n await writeFile(tmp, JSON.stringify({ vars }, null, 2) + \"\\n\", { mode: 0o600 });\n await rename(tmp, file);\n}\n\n/** `given` over the box's variables, each written as not secret: `new --from <snapshot> -e …`. */\nexport async function mergeBoxEnv(box: BoxRef, given: readonly { name: string; value: string }[], p: Paths = paths()): Promise<void> {\n const names = new Set(given.map((v) => v.name));\n const now = new Date().toISOString();\n const kept = (await readBoxEnv(box, p)).filter((v) => !names.has(v.name));\n await writeBoxEnv(box, [...kept, ...given.map((v) => ({ ...v, secret: false, updatedAt: now }))], p);\n}\n\n/** A snapshot or a fork takes its source's variables with it (#87). Nothing to copy: nothing happens. */\nexport async function copyBoxEnv(from: string, to: string): Promise<void> {\n if (!existsSync(from)) return;\n await copyFile(from, to);\n}\n\n/** What `GET /machines/:name/env` answers: the box's own variables, secrets without their value. */\nexport function shownBoxEnv(vars: readonly BoxVar[]): EnvVar[] {\n return vars.map((v) => ({ name: v.name, ...(v.secret ? {} : { value: v.value }), secret: v.secret, updatedAt: v.updatedAt }));\n}\n\n/** `kvbox env set NAME VALUE --box`: add or change one of the box's own variables. Applies at its next start. */\nexport async function setBoxVar(box: BoxRef, name: string, value: string, secret: boolean, p: Paths = paths()): Promise<void> {\n await withBoxLock(box, async () => {\n if (!existsSync(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);\n const vars = (await readBoxEnv(box, p)).filter((v) => v.name !== name);\n await writeBoxEnv(box, [...vars, { name, value, secret, updatedAt: new Date().toISOString() }], p);\n });\n}\n\n/** `kvbox env rm NAME --box`. A name the box does not have is an error, as for the owner's list. */\nexport async function rmBoxVar(box: BoxRef, name: string, p: Paths = paths()): Promise<void> {\n await withBoxLock(box, async () => {\n if (!existsSync(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);\n const vars = await readBoxEnv(box, p);\n if (!vars.some((v) => v.name === name)) throw new NotFoundError(`variable ${name} on box ${shown(box)}`);\n await writeBoxEnv(box, vars.filter((v) => v.name !== name), p);\n });\n}\n\n/**\n * Keep `req` as the owner's list unless the host already holds a newer one (two changes whose pushes\n * crossed). Answers the version the host holds now. Checked like at the control plane, so a list the\n * guest would refuse never lands here.\n */\nexport async function setOwnerEnv(owner: string, req: HostEnvRequest, p: Paths = paths()): Promise<{ version: number }> {\n if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner \"${owner}\"`);\n if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);\n const seen = new Set<string>();\n for (const v of req.vars) {\n const problem = envNameProblem(v.name) ?? envValueProblem(v.value);\n if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);\n if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);\n seen.add(v.name);\n }\n return withHostLock(\"env\", async () => {\n const have = await readOwnerEnv(owner, p);\n if (have !== null && have.version > req.version) return { version: have.version };\n const file = p.ownerEnv(owner);\n await mkdir(p.env, { recursive: true, mode: 0o700 });\n const tmp = `${file}.tmp`;\n await writeFile(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + \"\\n\", { mode: 0o600 });\n await rename(tmp, file);\n return { version: req.version };\n });\n}\n\n/** Which version this host holds for each owner in `scope`: what the control plane's sweep compares. */\nexport async function listEnvVersions(scope: ListScope, p: Paths = paths()): Promise<HostEnvVersions> {\n let files: string[];\n try {\n files = await readdir(p.env);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n const out: HostEnvVersions = [];\n for (const file of files.filter((f) => f.endsWith(\".json\")).sort()) {\n const owner = file.slice(0, -\".json\".length);\n if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;\n const env = await readOwnerEnv(owner, p).catch(() => null);\n if (env !== null) out.push({ owner, version: env.version });\n }\n return out;\n}\n","/**\n * Environment variables (#88): a slug's list (a user's or an org's), which every box of that slug gets\n * at boot. The rules live here so the CLI, the control plane and the host refuse the same things.\n * Inside the box kvbox-agent writes them to `/etc/kvbox/env` (systemd's EnvironmentFile=) and to the\n * kvbox user's `~/.ssh/environment` (sshd): both take any single line literally, so the only rule on a\n * value is that it is one line.\n */\n\n/** A name a shell, systemd and sshd all take: letters, digits and `_`, not starting with a digit. */\nexport const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Names that would break every shell or login in the box; `KVBOX_*` is kept for kvbox itself. */\nexport const ENV_RESERVED = [\"PATH\", \"HOME\", \"USER\", \"SHELL\"] as const;\n\nexport const ENV_MAX_VALUE_BYTES = 4096;\nexport const ENV_MAX_VARS = 100;\n\nexport function envNameProblem(name: string): string | null {\n if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;\n if ((ENV_RESERVED as readonly string[]).includes(name)) return `${name} is the box's own and cannot be set`;\n if (name.startsWith(\"KVBOX_\")) return `${name}: names starting with KVBOX_ are kept for kvbox`;\n return null;\n}\n\nexport function envValueProblem(value: string): string | null {\n if (/[\\n\\r\\0]/.test(value)) return \"a value is one line: no line breaks (base64 a multi-line value such as a key file)\";\n if (Buffer.byteLength(value, \"utf8\") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;\n return null;\n}\n","/**\n * One operation on a box at a time (#64). Every change to a box (its meta.json, its Firecracker process,\n * its memory image) runs under the box's lock, so a background job such as core/idle.ts cannot step into\n * a caller's snapshot, and two read-modify-writes of meta.json cannot lose each other's change.\n * In-process only: the server is the only writer. Reentrant, so an operation that calls another one on\n * the same box (rescale -> start) does not wait on itself.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { refKey, type BoxRef } from \"./refs.js\";\n\n/** box -> the promise the next caller waits on (resolved when the current holder and every earlier waiter are done). */\nconst tails = new Map<string, Promise<void>>();\n/** The boxes the current async call chain already holds. */\nconst held = new AsyncLocalStorage<ReadonlySet<string>>();\n\nexport function withBoxLock<T>(ref: BoxRef, fn: () => Promise<T>): Promise<T> {\n return withLock(refKey(ref), fn);\n}\n\n/**\n * A snapshot's files (#83): a restore reads them while it holds this, so a replace or an rm never swaps\n * or removes them under it. The key's prefix keeps it apart from the box of the same owner/name.\n */\nexport function withSnapshotLock<T>(ref: BoxRef, fn: () => Promise<T>): Promise<T> {\n return withLock(`snapshot:${refKey(ref)}`, fn);\n}\n\n/**\n * A lock for something the whole host shares rather than one box: `ports` guards drawing public\n * ports (#30), which reads every box's meta.json; `volumes` guards which box holds a volume (#52),\n * decided by reading every box's meta.json too, and a volume's files; `env` guards the owners' env files\n * (#88). The key has no '/', so it\n * never meets a box's. Take it inside a box lock, never the other way round, and only around the\n * check and the write it protects: never across a box's restart.\n */\nexport function withHostLock<T>(name: \"ports\" | \"volumes\" | \"env\", fn: () => Promise<T>): Promise<T> {\n return withLock(`host:${name}`, fn);\n}\n\nasync function withLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const mine = held.getStore();\n if (mine?.has(key)) return fn();\n const previous = tails.get(key);\n let release!: () => void;\n const tail = new Promise<void>((resolve) => (release = resolve));\n tails.set(key, tail);\n try {\n await previous;\n return await held.run(new Set([...(mine ?? []), key]), fn);\n } finally {\n release();\n if (tails.get(key) === tail) tails.delete(key);\n }\n}\n\n/** Whether something holds or waits for the box's lock right now. */\nexport function boxBusy(ref: BoxRef): boolean {\n return tails.has(refKey(ref));\n}\n\n/** `fn` with the lock of the box named by its first argument taken around every call. */\nexport function locked<A extends [BoxRef, ...unknown[]], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R> {\n return (...args) => withBoxLock(args[0], () => fn(...args));\n}\n","/**\n * The daemon's log: one line per event, `[time][level]: message`. info goes to stdout, the rest to\n * stderr; under the systemd unit install-server.sh writes, both land in $KVBOX_HOME/server.log.\n * Only `kvbox-server start` logs this way: the one-off subcommands (join, leave, relay, net) print\n * plain text for the terminal, since the CLI relays it to the user.\n */\nexport type Level = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport function formatLine(level: Level, message: string, at: Date = new Date()): string {\n return `[${at.toISOString()}][${level}]: ${message}`;\n}\n\nexport const log = {\n debug(message: string): void {\n console.error(formatLine(\"debug\", message));\n },\n info(message: string): void {\n console.log(formatLine(\"info\", message));\n },\n warn(message: string): void {\n console.error(formatLine(\"warn\", message));\n },\n error(message: string): void {\n console.error(formatLine(\"error\", message));\n },\n};\n","/**\n * Images (#87). A box boots from one read-only image and stacks its own disk on it. The base image is\n * assets/rootfs-<version>.ext4 with assets/rootfs.ext4 the symlink to the one `new` uses; every other\n * image (`postgres`) is assets/images/<image>/rootfs-<version>.ext4 with rootfs.ext4 there its symlink,\n * all put in place by install-server.sh. A box's meta.json names its image (absent: the base) and that\n * image's version; `vm update` moves it to the current version of the same image, never to another.\n *\n * An image may carry /etc/kvbox/image.json, read here with debugfs (no mount): the variables it wants\n * with their defaults, which of them the host generates when the caller gave none, and how to reach what\n * it serves. The host knows nothing else about any image (decision \"A box's own env vars…\").\n */\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { readdir, realpath } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport { z } from \"zod\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { parseDuration } from \"@kvbox/shared/duration\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport type { Config } from \"./config.js\";\nimport { run } from \"./exec.js\";\n\nexport const BASE_IMAGE = \"base\";\n\n/** An image name, as `--base` takes it and as its directory is named. */\nconst IMAGE_RE = /^[a-z][a-z0-9-]{0,30}$/;\n\n/** `assets/…/rootfs-<version>.ext4` -> `<version>`; anything else is not an installed image. */\nexport function baseVersionOf(file: string): string {\n const m = /^rootfs-(.+)\\.ext4$/.exec(basename(file));\n if (!m) throw new KvboxError(`base image ${file} is not versioned (expected assets/rootfs-<version>.ext4); run install-server.sh`);\n return m[1]!;\n}\n\n/** `undefined` and `base` both mean the base image; meta.json stores the base as absent. */\nexport function imageKey(image: string | undefined): string | undefined {\n return image === undefined || image === BASE_IMAGE ? undefined : image;\n}\n\n/** What an image is called in messages. */\nexport const imageLabel = (image: string | undefined) => (imageKey(image) === undefined ? \"base image\" : `image ${image}`);\n\n/** The file of `image` at `version`. */\nexport function imageFile(image: string | undefined, version: string, p: Paths): string {\n const key = imageKey(image);\n return key === undefined ? p.baseImage(version) : p.image(key).version(version);\n}\n\n/** The image a box (or snapshot) stacks on, refused when install-server.sh has since removed it. */\nexport function imageFileFor(meta: { name: string; base: string; image?: string | undefined }, p: Paths): string {\n const file = imageFile(meta.image, meta.base, p);\n if (!existsSync(file)) throw new KvboxError(`box ${meta.name} runs on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);\n return file;\n}\n\n/** Follow an image's symlink to the version a new box gets. */\nexport async function currentImage(image: string | undefined, cfg: Config, p: Paths): Promise<{ version: string; file: string }> {\n const key = imageKey(image);\n if (key !== undefined && !IMAGE_RE.test(key)) throw new KvboxError(`invalid image name \"${image}\"`);\n const link = key === undefined ? cfg.rootfs : p.image(key).rootfs;\n if (key !== undefined && !existsSync(link)) {\n const have = (await listImages(cfg, p)).map((i) => i.name).join(\", \");\n throw new KvboxError(`this host has no image ${key} (it has: ${have}); install-server.sh with IMAGES=\"${key}:<version>\" adds it`);\n }\n const file = await realpath(link);\n const version = baseVersionOf(file);\n const expected = imageFile(key, version, p);\n if (file !== expected) throw new KvboxError(`${imageLabel(key)} ${link} points outside its directory (${file})`);\n return { version, file };\n}\n\n/** Every image a new box can be made from here, base first: what `/capacity` reports to the control plane. */\nexport async function listImages(cfg: Config, p: Paths = paths()): Promise<{ name: string; version: string }[]> {\n const out: { name: string; version: string }[] = [];\n // The version a symlink names, when `currentImage` would take it: inside the image's own directory.\n const versionAt = async (image: string | undefined, link: string) => {\n const file = await realpath(link);\n const version = baseVersionOf(file);\n if (file !== imageFile(image, version, p)) throw new Error(\"outside its directory\");\n return version;\n };\n try {\n out.push({ name: BASE_IMAGE, version: await versionAt(undefined, cfg.rootfs) });\n } catch {\n // no base image yet: a host mid-install; `new` says so itself\n }\n let names: string[] = [];\n try {\n names = (await readdir(p.images)).sort();\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n for (const name of names) {\n if (!IMAGE_RE.test(name) || name === BASE_IMAGE) continue;\n try {\n out.push({ name, version: await versionAt(name, p.image(name).rootfs) });\n } catch {\n // a dir without a current version, or one pointing elsewhere: not an image `new` can use\n }\n }\n return out;\n}\n\nconst overlayCapable = new Map<string, boolean>();\n\n/** An image without /sbin/overlay-init (not built by kvbox-images) would panic at boot. debugfs reads the ext4 without mounting it. */\nexport async function assertOverlayCapable(file: string, image: string | undefined, version: string): Promise<void> {\n let ok = overlayCapable.get(file);\n if (ok === undefined) {\n const { stdout } = await run([\"debugfs\", \"-R\", \"stat /sbin/overlay-init\", file]);\n ok = /Type:\\s+regular/.test(stdout);\n overlayCapable.set(file, ok);\n }\n if (!ok) throw new KvboxError(`${imageLabel(image)} ${version} is not a kvbox image (no /sbin/overlay-init); rerun install-server.sh`);\n}\n\n/** /etc/kvbox/image.json. Every field is optional; the base image has no file at all. */\nexport const ImageManifestSchema = z.object({\n /**\n * false: a new box of this image does not auto-hibernate unless asked (nothing wakes it on a TCP connection).\n * A duration (`\"10m\"`, #102): a new box's idle time unless the caller gave one, instead of the host's default.\n */\n autoHibernate: z.union([z.boolean(), z.string().refine((s) => parseDuration(s) !== undefined, \"a duration like 10m, 4h or 1d\")]).optional(),\n /**\n * A script inside the box that says whether it is idle (#102), exit 0 = idle: a new box's `idleCheck`\n * (meta.json), which auto-hibernate asks through kvbox-agent instead of watching the traffic.\n */\n idle: z.string().optional(),\n /** Variables the box gets unless the caller or its owner set them; a value may name an earlier one, or a generated one, as `${NAME}`. */\n env: z.record(z.string(), z.string()).optional(),\n /** Variables the host fills with a random password when the caller gave none. */\n generate: z.array(z.string()).optional(),\n /** How to reach what the box serves, `${NAME}` taken from its variables and `${BOX}` its name. */\n connect: z.string().optional(),\n /**\n * Scripts in the box the host may run by name through kvbox-agent (#173): `status`, `password`, …\n * The host knows the names only; what each does and answers is the image's.\n */\n scripts: z.record(z.string(), z.string().startsWith(\"/\")).optional(),\n});\nexport type ImageManifest = z.infer<typeof ImageManifestSchema>;\n\nconst manifests = new Map<string, ImageManifest>();\n\n/** The image's manifest, `{}` when it has none. An image file never changes under its name, so it is read once. */\nexport async function imageManifest(file: string): Promise<ImageManifest> {\n const cached = manifests.get(file);\n if (cached !== undefined) return cached;\n // debugfs prints the file to stdout, or nothing (and a message on stderr) when it is not there.\n const { stdout } = await run([\"debugfs\", \"-R\", \"cat /etc/kvbox/image.json\", file]);\n let manifest: ImageManifest = {};\n if (stdout.trim() !== \"\") {\n try {\n manifest = ImageManifestSchema.parse(JSON.parse(stdout));\n } catch (err) {\n throw new KvboxError(`${file}: /etc/kvbox/image.json is not a valid image manifest: ${(err as Error).message}`);\n }\n }\n manifests.set(file, manifest);\n return manifest;\n}\n\n/** `${NAME}` from `vars`; a name that is not there expands to nothing. */\nexport function expand(text: string, vars: ReadonlyMap<string, string>): string {\n return text.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (_, name: string) => vars.get(name) ?? \"\");\n}\n\n/** 24 characters a connection string takes without escaping. */\nexport function generatedSecret(): string {\n return randomBytes(18).toString(\"base64url\");\n}\n\n/**\n * A new box's own variables: the caller's, plus the image's generated secrets and defaults for the\n * ones the caller left out, and the image's `connect` line filled in. `generated` names the variables\n * the host made up. Secrets are made first, so a default can name one (`${POSTGRES_PASSWORD}`), and a\n * default can name an earlier default. `inherited` is the owner's list: a name it has is left to it\n * (and a default may name it), since the box's own variables win over the owner's at boot.\n * `secrets` names what the box keeps as secrets: the generated ones and any default made from one or\n * from an owner's variable. `connect` never holds an owner's value (it may be a secret, which no route\n * answers with): it keeps `${NAME}` for it.\n */\nexport function imageEnv(\n manifest: ImageManifest,\n box: string,\n given: readonly { name: string; value: string }[],\n inherited: readonly { name: string; value: string }[] = [],\n) {\n const vars = new Map([...inherited, ...given].map((v) => [v.name, v.value]));\n const givenNames = new Set(given.map((v) => v.name));\n /** Names whose value is, or is made from, an owner's variable. */\n const owners = new Set(inherited.map((v) => v.name).filter((n) => !givenNames.has(n)));\n const defaults = manifest.env ?? {};\n const added: { name: string; value: string }[] = [];\n const generated: string[] = [];\n for (const name of manifest.generate ?? []) {\n if (vars.has(name) || name in defaults) continue;\n const v = generatedSecret();\n vars.set(name, v);\n added.push({ name, value: v });\n generated.push(name);\n }\n const secrets = new Set<string>();\n for (const [name, value] of Object.entries(defaults)) {\n if (vars.has(name)) continue;\n const v = expand(value, vars);\n vars.set(name, v);\n added.push({ name, value: v });\n const from = namesIn(value);\n if (from.some((n) => owners.has(n))) owners.add(name);\n if (from.some((n) => owners.has(n) || generated.includes(n) || secrets.has(n))) secrets.add(name);\n }\n // A URL's user, password and path take a value only percent-encoded (`p@ss/1` would end the userinfo).\n const encode = manifest.connect !== undefined && /^[a-z][a-z0-9+.-]*:\\/\\//i.test(manifest.connect);\n const connectVars = new Map([...vars].map(([k, v]) => [k, owners.has(k) ? `\\${${k}}` : encode ? encodeURIComponent(v) : v]));\n connectVars.set(\"BOX\", box);\n const connect = manifest.connect === undefined ? undefined : expand(manifest.connect, connectVars);\n return { vars: [...given, ...added], generated, secrets: [...generated, ...secrets], connect };\n}\n\n/** What hides a secret in a box's `url`. */\nexport const MASK = \"****\";\n\n/**\n * The box's `url` (#87): the image's `connect` line with every secret masked, kept in meta.json and shown by\n * `kvbox get` long after `new` printed the real one. A secret is a variable kept as one or one the image\n * generates (a `-e` password included); a name the box does not have (an owner's) and `${BOX}` stay as\n * `${NAME}`, the box's name filled in when it is shown (a fork or a restore has another).\n */\nexport function maskedUrl(manifest: ImageManifest, vars: readonly { name: string; value: string; secret: boolean }[]): string | undefined {\n if (manifest.connect === undefined) return undefined;\n const encode = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(manifest.connect);\n const generated = new Set(manifest.generate ?? []);\n const shown = new Map(vars.map((v) => [v.name, v.secret || generated.has(v.name) ? MASK : encode ? encodeURIComponent(v.value) : v.value]));\n return manifest.connect.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (all, name: string) => (name === \"BOX\" ? all : (shown.get(name) ?? all)));\n}\n\n/** A stored `url` for box `name`. */\nexport const urlFor = (url: string, name: string) => url.replaceAll(\"${BOX}\", name);\n\n/** The `${NAME}`s a manifest value names. */\nfunction namesIn(text: string): string[] {\n return [...text.matchAll(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g)].map((m) => m[1]!);\n}\n","/**\n * The one shell-out helper. Every `firecracker`, `ip`, `ssh`, `cp` call goes\n * through here: argv arrays only (never a shell string), the command is logged,\n * and stderr ends up in the thrown error.\n */\nimport { execFile, spawn } from \"node:child_process\";\nimport { openSync } from \"node:fs\";\nimport { promisify } from \"node:util\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { log } from \"./log.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface RunOptions {\n sudo?: boolean;\n cwd?: string;\n timeoutMs?: number;\n env?: NodeJS.ProcessEnv;\n /** Non-zero exit codes that are not failures (e2fsck: 1 = \"errors corrected\"). */\n okExitCodes?: readonly number[];\n}\n\nexport interface RunResult {\n stdout: string;\n stderr: string;\n}\n\nexport async function run(argv: readonly string[], opts: RunOptions = {}): Promise<RunResult> {\n const [cmd, ...args] = opts.sudo ? [\"sudo\", \"-n\", ...argv] : argv;\n if (!cmd) throw new KvboxError(\"run: empty argv\");\n if (process.env[\"KVBOX_DEBUG\"]) log.debug(`exec ${[cmd, ...args].join(\" \")}`);\n try {\n const { stdout, stderr } = await execFileAsync(cmd, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n timeout: opts.timeoutMs ?? 30_000,\n maxBuffer: 8 * 1024 * 1024,\n });\n return { stdout, stderr };\n } catch (err) {\n const e = err as NodeJS.ErrnoException & { stdout?: string; stderr?: string; code?: number | string };\n if (typeof e.code === \"number\" && opts.okExitCodes?.includes(e.code)) return { stdout: e.stdout ?? \"\", stderr: e.stderr ?? \"\" };\n const detail = (e.stderr ?? e.message ?? \"\").trim();\n throw new KvboxError(`${[cmd, ...args].join(\" \")} failed${detail ? `: ${detail}` : \"\"}`);\n }\n}\n\n/**\n * Start a command that must outlive this process (the self-update, which stops and restarts the daemon):\n * argv only, its own session, stdout and stderr appended to `logFile`. Returns once it is spawned, with its pid.\n */\nexport function spawnDetached(argv: readonly string[], logFile: string, env: NodeJS.ProcessEnv = process.env): Promise<number> {\n const [cmd, ...args] = argv;\n if (!cmd) throw new KvboxError(\"spawnDetached: empty argv\");\n const out = openSync(logFile, \"a\");\n const child = spawn(cmd, args, { detached: true, stdio: [\"ignore\", out, out], env });\n return new Promise((resolve, reject) => {\n child.once(\"error\", (err) => reject(new KvboxError(`${cmd} could not start: ${err.message}`)));\n child.once(\"spawn\", () => {\n child.unref();\n resolve(child.pid ?? -1);\n });\n });\n}\n","/**\n * Volumes (#52): a disk of its own under volumes/<owner>/<name>, a sparse ext4 the guest sees whole,\n * created apart from any box and attached to one box at a time (ext4 is a one-machine filesystem; two\n * guests writing one disk corrupt it). Attaching is the box's business (core/machines.ts: it changes\n * the box's drives, so a running box restarts); this module owns the volume's files and what a box's\n * drives look like. Decision \"A snapshot captures the box, never its volume\".\n */\nimport { existsSync, statSync } from \"node:fs\";\nimport { lstat, mkdir, readdir, rm, statfs, symlink, truncate, writeFile } from \"node:fs/promises\";\nimport { MAX_VOLUME_GIB, VOLUME_NAME_RE, VOLUME_NAME_RULE, type DiskCapacity, type Volume } from \"@kvbox/shared/api\";\nimport { hasDiskRoom, volumeRoomGib } from \"@kvbox/shared/capacity\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { paths, volumeDriveRel, volumeMountPath, type Paths } from \"@kvbox/shared/paths\";\nimport type { VolumeLedgerRow } from \"@kvbox/shared/usage\";\nimport { loadConfig } from \"./config.js\";\nimport { insertVolumeEvent } from \"./db.js\";\nimport { run } from \"./exec.js\";\nimport { withHostLock } from \"./locks.js\";\nimport { inScope, parseRef, shown, type BoxRef, type ListScope } from \"./refs.js\";\nimport { listMachineRefs, listVolumeRefs, newBoxId, readMachineMeta, readVolumeMeta, writeVolumeMeta, type MachineMeta, type VolumeMeta } from \"./state.js\";\nimport { log } from \"./log.js\";\n\n/** The ext4 label the image's kvbox-volumes.service mounts by: 16 bytes at most, hence the short prefix and the 12-char names. */\nexport const volumeLabel = (name: string) => `kv:${name}`;\n\nexport interface VolumeDrive {\n name: string;\n sizeGib: number;\n}\n\n/** What a volume is, from its files; `attachedTo` is looked up in the boxes' meta.json. */\nfunction toVolume(meta: VolumeMeta, attachedTo: string | null, p: Paths): Volume {\n let usedBytes = 0;\n try {\n usedBytes = statSync(p.volume(meta.owner, meta.name).disk).blocks * 512;\n } catch {\n /* a volume whose disk is gone shows as empty */\n }\n return { id: meta.id, name: meta.name, owner: meta.owner, sizeGib: meta.sizeGib, usedBytes, attachedTo, createdAt: meta.createdAt };\n}\n\n/** Append to the volume ledger (core/db.ts, #91). Bookkeeping never fails the operation it records. */\nfunction recordVolume(meta: VolumeMeta, by: VolumeLedgerRow[\"by\"], p: Paths, at = new Date().toISOString()): void {\n try {\n insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at, sizeGib: meta.sizeGib, by }, p);\n } catch (err) {\n log.warn(`volume ledger: ${(err as Error).message}`);\n }\n}\n\n/** Which box holds each of the owner's volumes: volume name -> box name. */\nasync function attachments(owner: string, p: Paths): Promise<Map<string, string>> {\n const out = new Map<string, string>();\n for (const ref of await listMachineRefs(p)) {\n if (ref.owner !== owner) continue;\n try {\n const meta = await readMachineMeta(ref, p);\n for (const v of meta.volumes ?? []) out.set(v, meta.name);\n } catch {\n /* an unreadable box attaches nothing */\n }\n }\n return out;\n}\n\nexport async function readVolume(ref: BoxRef, p: Paths): Promise<VolumeMeta> {\n try {\n return await readVolumeMeta(ref, p);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") throw new NotFoundError(`volume ${shown(ref)}`);\n throw err;\n }\n}\n\nexport async function getVolume(ref: BoxRef, p: Paths = paths()): Promise<Volume> {\n const meta = await readVolume(ref, p);\n return toVolume(meta, (await attachments(ref.owner, p)).get(ref.name) ?? null, p);\n}\n\nexport async function listVolumes(scope: ListScope, p: Paths = paths()): Promise<Volume[]> {\n const out: Volume[] = [];\n const byOwner = new Map<string, Map<string, string>>();\n for (const ref of await listVolumeRefs(p)) {\n if (!inScope(ref.owner, scope)) continue;\n try {\n const meta = await readVolumeMeta(ref, p);\n let attached = byOwner.get(ref.owner);\n if (attached === undefined) {\n attached = await attachments(ref.owner, p);\n byOwner.set(ref.owner, attached);\n }\n out.push(toVolume(meta, attached.get(meta.name) ?? null, p));\n } catch (err) {\n log.warn(`skipping volumes/${ref.owner}/${ref.name}: ${(err as Error).message}`);\n }\n }\n return out.sort((a, b) => a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name));\n}\n\n/**\n * The host's disk as volumes see it (#91): the filesystem holding volumes/, what every volume on the\n * host promises (its size) and holds (its blocks), and the headroom (config.json `volumeHeadroomGib`).\n * `GET /capacity` reports it; the control plane picks a host by it; `createVolume` applies the same rule.\n */\nexport async function diskCapacity(p: Paths = paths()): Promise<DiskCapacity> {\n // the same filesystem either way; volumes/ is made at server start, and a test may ask before\n const st = await statfs(existsSync(p.volumes) ? p.volumes : p.home);\n let volumesGib = 0;\n let usedBytes = 0;\n for (const ref of await listVolumeRefs(p)) {\n try {\n volumesGib += (await readVolumeMeta(ref, p)).sizeGib;\n usedBytes += statSync(p.volume(ref.owner, ref.name).disk).blocks * 512;\n } catch {\n /* an unreadable volume promises nothing it can be charged for */\n }\n }\n return {\n totalGib: Math.floor((st.blocks * st.bsize) / 1024 ** 3),\n freeGib: Math.floor((st.bavail * st.bsize) / 1024 ** 3),\n volumesGib,\n volumesUsedGib: Math.floor(usedBytes / 1024 ** 3),\n headroomGib: (await loadConfig(p)).volumeHeadroomGib,\n };\n}\n\n/**\n * `kvbox volume create`: a sparse ext4 of `sizeGib`, ready in a moment and occupying a few MB until\n * written to. Sparse files fill up later, so the check is what the host can promise, not what it has\n * right now: the sizes of all its volumes together stay under the disk beyond its boxes, snapshots and\n * base images, less the headroom those need (@kvbox/shared/capacity, decision in #91).\n */\nexport async function createVolume(req: { name: string; sizeGib: number }, owner: string, p: Paths = paths()): Promise<Volume> {\n if (!VOLUME_NAME_RE.test(req.name)) {\n throw new KvboxError(`invalid volume name \"${req.name}\": ${VOLUME_NAME_RULE}`);\n }\n if (!Number.isInteger(req.sizeGib) || req.sizeGib < 1 || req.sizeGib > MAX_VOLUME_GIB) {\n throw new KvboxError(`volume size: whole GB between 1 and ${MAX_VOLUME_GIB}`);\n }\n return withHostLock(\"volumes\", () => makeVolume(req, owner, p));\n}\n\nasync function makeVolume(req: { name: string; sizeGib: number }, owner: string, p: Paths): Promise<Volume> {\n const v = p.volume(owner, req.name);\n if (existsSync(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);\n await mkdir(p.ownerVolumes(owner), { recursive: true, mode: 0o700 });\n const disk = await diskCapacity(p);\n if (!hasDiskRoom(disk, req.sizeGib)) {\n throw new KvboxError(\n `not enough disk on this host for a ${req.sizeGib} GB volume: it can still promise ${volumeRoomGib(disk)} GB ` +\n `(${disk.freeGib} GB free, ${disk.volumesGib} GB promised to ${disk.volumesGib === 0 ? \"no volume yet\" : \"its volumes\"}, ${disk.headroomGib} GB kept for its boxes)`,\n );\n }\n const taken = new Set<string>();\n for (const ref of await listVolumeRefs(p)) {\n try {\n taken.add((await readVolumeMeta(ref, p)).id);\n } catch {\n /* an unreadable volume holds no id to avoid */\n }\n }\n // Not recursive: the dir is the claim on the name, and a second claim fails here instead of sharing the file.\n try {\n await mkdir(v.dir, { mode: 0o700 });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") throw new KvboxError(`volume ${req.name} already exists`);\n throw err;\n }\n try {\n await writeFile(v.disk, \"\", { mode: 0o600 });\n await truncate(v.disk, req.sizeGib * 1024 ** 3);\n // -F: a file, not a block device. -m 0: nothing held back for root, the whole disk is the user's.\n // Lazy init: the guest kernel zeroes the inode tables as it goes, so mkfs writes almost nothing.\n await run([\"mkfs.ext4\", \"-q\", \"-F\", \"-m\", \"0\", \"-L\", volumeLabel(req.name), \"-E\", \"lazy_itable_init=1,lazy_journal_init=1\", v.disk]);\n const meta: VolumeMeta = { id: newBoxId(taken), name: req.name, owner, sizeGib: req.sizeGib, createdAt: new Date().toISOString() };\n await writeVolumeMeta(meta, p);\n recordVolume(meta, \"create\", p, meta.createdAt);\n return toVolume(meta, null, p);\n } catch (err) {\n await rm(v.dir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/**\n * `kvbox volume rm`: only a detached volume goes; its data goes with it. The ledger's `rm` row is\n * written first and has to succeed: a volume gone without it would be billed for good (nothing\n * reconciles the ledger with the files), while a row for a volume still here only stops its billing\n * until the retry removes it.\n */\nexport async function deleteVolume(ref: BoxRef, p: Paths = paths()): Promise<void> {\n await withHostLock(\"volumes\", async () => {\n const meta = await readVolume(ref, p);\n const box = (await attachments(ref.owner, p)).get(ref.name);\n if (box !== undefined) throw new KvboxError(`volume ${shown(ref)} is attached to box ${box}; kvbox volume detach ${shown(ref)} first`);\n try {\n insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: new Date().toISOString(), sizeGib: meta.sizeGib, by: \"rm\" }, p);\n } catch (err) {\n throw new KvboxError(`volume ${shown(ref)} was not removed: its ledger row could not be written (${(err as Error).message}); try again`);\n }\n try {\n await rm(p.volume(ref.owner, ref.name).dir, { recursive: true, force: true });\n } catch (err) {\n throw new KvboxError(`volume ${shown(ref)}: its files could not be removed (${(err as Error).message}); it is no longer billed, run kvbox volume rm ${shown(ref)} again`);\n }\n });\n}\n\n/** What `growVolume` will refuse, said before anything is stopped for it: the size and the host's room. */\nexport async function assertCanGrow(ref: BoxRef, sizeGib: number, p: Paths = paths()): Promise<VolumeMeta> {\n const meta = await readVolume(ref, p);\n if (!Number.isInteger(sizeGib) || sizeGib > MAX_VOLUME_GIB) throw new KvboxError(`volume size: whole GB, at most ${MAX_VOLUME_GIB}`);\n if (sizeGib <= meta.sizeGib) {\n throw new KvboxError(`volume ${shown(ref)} is ${meta.sizeGib} GB and a volume only grows; ${sizeGib} GB is ${sizeGib === meta.sizeGib ? \"what it has\" : \"smaller\"}`);\n }\n const disk = await diskCapacity(p);\n const more = sizeGib - meta.sizeGib;\n if (!hasDiskRoom(disk, more)) {\n throw new KvboxError(`not enough disk on this host to grow volume ${shown(ref)} by ${more} GB: it can still promise ${volumeRoomGib(disk)} GB`);\n }\n return meta;\n}\n\n/**\n * Extend the volume's file and grow its ext4 into it (#147). The filesystem must not be mounted: the\n * caller (core/machines.ts `resizeVolume`) has stopped the box holding it. `check` runs under the same\n * host lock, right before the file changes. e2fsck first: resize2fs refuses a filesystem mounted since\n * its last check.\n */\nexport async function growVolume(ref: BoxRef, sizeGib: number, p: Paths = paths(), check?: () => Promise<void>): Promise<Volume> {\n return withHostLock(\"volumes\", async () => {\n const meta = await assertCanGrow(ref, sizeGib, p);\n await check?.();\n const disk = p.volume(ref.owner, ref.name).disk;\n await truncate(disk, sizeGib * 1024 ** 3);\n await run([\"e2fsck\", \"-f\", \"-p\", disk], { okExitCodes: [1] });\n await run([\"resize2fs\", disk]);\n const grown: VolumeMeta = { ...meta, sizeGib };\n await writeVolumeMeta(grown, p);\n recordVolume(grown, \"resize\", p);\n return toVolume(grown, (await attachments(ref.owner, p)).get(ref.name) ?? null, p);\n });\n}\n\n/** The volume a box names: the box owner's, as its meta.json lists it. */\nexport function volumeRef(box: Pick<MachineMeta, \"owner\">, name: string): BoxRef {\n return parseRef(name, box.owner);\n}\n\n/** The box's attached volumes with their sizes, in drive order; a volume whose files are gone is an error. */\nexport async function volumeDrivesOf(box: Pick<MachineMeta, \"owner\" | \"name\" | \"volumes\">, p: Paths): Promise<VolumeDrive[]> {\n const out: VolumeDrive[] = [];\n for (const name of box.volumes ?? []) {\n const ref = volumeRef(box, name);\n let meta: VolumeMeta;\n try {\n meta = await readVolume(ref, p);\n } catch (err) {\n if (err instanceof NotFoundError) throw new KvboxError(`box ${shown(box)} has volume ${name} attached, but the volume is gone from ${p.volumes}`);\n throw err;\n }\n out.push({ name, sizeGib: meta.sizeGib });\n }\n return out;\n}\n\n/**\n * The volume drives the box's VM has, for a capture (a snapshot, a warm fork): its attached volumes, plus\n * the placeholders a restore left in its dir, which stay in the VM's drive set until its next cold boot\n * (placeVolumeDrives removes them then). Recorded with the image so that a restore of it writes a file\n * at every drive path the vmstate names; a capture that forgot them would make an image nothing can load.\n */\nexport async function captureDrivesOf(box: Pick<MachineMeta, \"owner\" | \"name\" | \"volumes\">, p: Paths): Promise<VolumeDrive[]> {\n const drives = await volumeDrivesOf(box, p);\n const named = new Set(drives.map((d) => d.name));\n const dir = p.machine(box.owner, box.name).dir;\n for (const entry of (await readdir(dir).catch(() => [] as string[])).sort()) {\n const m = /^volume-(.+)\\.ext4$/.exec(entry);\n if (!m || named.has(m[1]!)) continue;\n const st = await lstat(`${dir}/${entry}`);\n if (!st.isFile()) continue; // not a placeholder: nothing the VM was given\n drives.push({ name: m[1]!, sizeGib: Math.round(st.size / 1024 ** 3) });\n }\n return drives;\n}\n\n/** What `Machine.volumes` shows for a box: never throws (a listing must not fail on one volume). */\nexport function volumeSummaries(box: Pick<MachineMeta, \"owner\" | \"volumes\">, p: Paths): { name: string; sizeGib: number; mountPath: string }[] | undefined {\n if (!box.volumes?.length) return undefined;\n return box.volumes.map((name) => {\n let sizeGib = 0;\n try {\n sizeGib = Math.round(statSync(p.volume(box.owner, name).disk).size / 1024 ** 3);\n } catch {\n /* gone: shown with size 0 */\n }\n return { name, sizeGib, mountPath: volumeMountPath(name) };\n });\n}\n\n/**\n * Before a box boots: one symlink per attached volume in the box dir, pointing at the volume's disk,\n * and nothing else that looks like a volume drive (a placeholder left by a restore, a link of a volume\n * detached since). Firecracker is then given the links by their relative names.\n */\nexport async function placeVolumeDrives(box: Pick<MachineMeta, \"owner\" | \"name\" | \"volumes\">, p: Paths): Promise<VolumeDrive[]> {\n const m = p.machine(box.owner, box.name);\n const drives = await volumeDrivesOf(box, p);\n await removeVolumeDrives(m.dir, new Set(drives.map((d) => d.name)));\n for (const d of drives) {\n const link = m.volumeDrive(d.name);\n await rm(link, { force: true });\n await symlink(p.volume(box.owner, d.name).disk, link);\n }\n return drives;\n}\n\n/** Every `volume-*.ext4` entry of a box dir whose name is not in `keep`. */\nexport async function removeVolumeDrives(boxDir: string, keep: ReadonlySet<string>): Promise<void> {\n for (const entry of await readdir(boxDir).catch(() => [] as string[])) {\n const m = /^volume-(.+)\\.ext4$/.exec(entry);\n if (m && !keep.has(m[1]!)) await rm(`${boxDir}/${entry}`, { force: true });\n }\n}\n\n/**\n * A box restored from a snapshot (or forked warm) whose source had volumes: the vmstate names their\n * drives and Firecracker refuses to load without a file at each path, so each gets an empty sparse file\n * of the same size. Never written: the guest drops the mounts right after the restore (kvbox-agent\n * `dropVolumes`), and the next cold boot removes them (placeVolumeDrives).\n */\nexport async function placeholderDrives(boxDir: string, volumes: readonly VolumeDrive[]): Promise<void> {\n for (const v of volumes) {\n const file = `${boxDir}/${volumeDriveRel(v.name)}`;\n // Never through a link a leftover dir may hold: a write there would empty the volume it points at.\n await rm(file, { force: true });\n await writeFile(file, \"\", { mode: 0o600 });\n await truncate(file, v.sizeGib * 1024 ** 3);\n }\n}\n\n/**\n * The drive id Firecracker knows a volume by: only letters, digits and underscores are allowed there, so a\n * '-' in the name becomes '_' (no two valid names collide: '_' is not a name character). Nothing keeps\n * the id: a boot sends it again, a snapshot holds its own. The guest mounts by label, not by it.\n */\nexport const volumeDriveId = (name: string) => `vol_${name.replace(/-/g, \"_\")}`;\n\n/** The box holding `ref`, by name, or null when it is detached. */\nexport async function attachedBox(ref: BoxRef, p: Paths): Promise<string | null> {\n return (await attachments(ref.owner, p)).get(ref.name) ?? null;\n}\n","/**\n * The capacity rule both sides apply. Firecracker reserves neither RAM nor cores, so a host counts\n * what its running boxes are sized at and refuses a box that would push the total past\n * memory: host RAM minus 2 GB the host keeps for itself (hard), or\n * vCPU: 2 x host cores (soft: vCPUs time-slice fine, this stops the absurd).\n * The host applies it box by box at `new` (server core/capacity.ts, with the names of the running\n * boxes in the refusal); the control plane applies it to each host's reported totals to choose\n * where a box lands (#20). Decision \"`zbox new` guards host capacity\".\n */\nimport type { Capacity, DiskCapacity } from \"./api.js\";\n\nexport const MEM_HEADROOM_MIB = 2048;\n\n/**\n * Disk for volumes (#91). A volume is sparse, so a host could promise more than it has; the rule is that\n * the sizes of its volumes add up to at most what the disk has beyond its boxes, snapshots and base\n * images (free space plus what the volumes already hold), less the headroom those keep growing into.\n * The host applies it at `volume create` (server core/volumes.ts), the control plane to pick a host.\n */\nexport function sellableGib(d: DiskCapacity): number {\n return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);\n}\n\n/** Whole GiB of volume a host can still promise. Never negative. */\nexport function volumeRoomGib(d: DiskCapacity): number {\n return Math.max(0, sellableGib(d) - d.volumesGib);\n}\n\nexport function hasDiskRoom(d: DiskCapacity, sizeGib: number): boolean {\n return sizeGib <= volumeRoomGib(d);\n}\nexport const VCPU_OVERSUBSCRIPTION = 2;\n\nexport interface Want {\n vcpu: number;\n memMib: number;\n}\n\n/** What a host can still take: memory after the headroom and what is reserved, vCPUs under the cap. Never negative. */\nexport function freeOf(c: Capacity): { memMib: number; vcpu: number } {\n return {\n memMib: Math.max(0, c.hostMemMib - MEM_HEADROOM_MIB - c.reservedMemMib),\n vcpu: Math.max(0, c.hostCores * VCPU_OVERSUBSCRIPTION - c.reservedVcpu),\n };\n}\n\nexport function hasRoom(c: Capacity, want: Want): boolean {\n const free = freeOf(c);\n return want.memMib <= free.memMib && want.vcpu <= free.vcpu;\n}\n","/**\n * The capacity guard. Firecracker reserves neither RAM nor cores on the host, so without a rule\n * of our own the kernel's OOM-killer is what ends an over-full host: a Firecracker process dies\n * and a box vanishes without a trace. Before a box is started (`new`, a restore or fork, `start`,\n * `wake`, a `rescale` that grows a running box: #37), its size is added to what the other\n * running boxes already reserve (their sizes, not what they touch right now) and refuses when\n * memory: reserved + new > host RAM - 2 GB (hard: the host needs room of its own), or\n * vCPU: reserved + new > 2 x host cores (soft: vCPUs time-slice fine, this stops the absurd).\n * `--force` skips both. The constants live in shared/capacity.ts: the control plane applies the same\n * rule to each host's totals to place a box (#20). Decision \"`zbox new` guards host capacity\".\n */\nimport { cpus, totalmem } from \"node:os\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { Capacity } from \"@kvbox/shared/api\";\nimport { MEM_HEADROOM_MIB, VCPU_OVERSUBSCRIPTION } from \"@kvbox/shared/capacity\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { listMachineRefs, readMachineMeta, vmAlive } from \"./state.js\";\nimport { loadConfig } from \"./config.js\";\nimport { listImages } from \"./images.js\";\nimport { diskCapacity } from \"./volumes.js\";\nimport { backupStoreCapacity } from \"./backupStore.js\";\n\nexport { MEM_HEADROOM_MIB, VCPU_OVERSUBSCRIPTION };\n\nexport interface Host {\n memMib: number;\n cores: number;\n}\nexport interface Reservation {\n /** Whose box it is; a refusal names only the caller's own boxes (another user's box names are theirs). */\n owner?: string;\n name: string;\n vcpu: number;\n memMib: number;\n}\n\nexport function hostResources(): Host {\n return { memMib: Math.floor(totalmem() / 1024 ** 2), cores: cpus().length };\n}\n\n/** The sizes of every box whose Firecracker process is alive; a dead pid reserves nothing. */\nexport async function runningReservations(p: Paths = paths()): Promise<Reservation[]> {\n const out: Reservation[] = [];\n for (const ref of await listMachineRefs(p)) {\n try {\n const meta = await readMachineMeta(ref, p);\n if (vmAlive(meta)) out.push({ owner: meta.owner, name: meta.name, vcpu: meta.vcpu, memMib: meta.memMib });\n } catch {\n // unreadable meta: not a running box we can account for\n }\n }\n return out;\n}\n\nexport async function capacity(p: Paths = paths()): Promise<Capacity> {\n const host = hostResources();\n const running = await runningReservations(p);\n return {\n hostMemMib: host.memMib,\n hostCores: host.cores,\n reservedMemMib: running.reduce((n, r) => n + r.memMib, 0),\n reservedVcpu: running.reduce((n, r) => n + r.vcpu, 0),\n running: running.length,\n disk: await diskCapacity(p),\n // What a box can be made from here (#87): the control plane places `--base postgres` by it.\n images: await listImages(await loadConfig(p), p),\n ...(await backupStoreCapacity(p).then((store) => (store ? { backupStore: store } : {}))),\n // Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).\n storeClient: true,\n };\n}\n\nfunction gb(mib: number): string {\n const g = mib / 1024;\n return `${Number.isInteger(g) ? g : g.toFixed(1)} GB`;\n}\n\nfunction describeRunning(running: Reservation[], viewer: string | undefined): string {\n if (running.length === 0) return \"no box is running\";\n const own = viewer === undefined ? running : running.filter((r) => r.owner === viewer);\n const others = running.length - own.length;\n const named = own.map((r) => `${r.name} ${r.vcpu} vCPU/${gb(r.memMib)}`);\n if (others > 0) named.push(`${others} ${others === 1 ? \"box\" : \"boxes\"} of other users`);\n const list = named.join(\", \");\n const vcpu = running.reduce((n, r) => n + r.vcpu, 0);\n const mem = running.reduce((n, r) => n + r.memMib, 0);\n return `${running.length} running ${running.length === 1 ? \"box reserves\" : \"boxes reserve\"} ${vcpu} vCPU and ${gb(mem)} (${list})`;\n}\n\n/** What the refusal suggests: `new` can pick a smaller size, `start` and `wake` cannot, `rescale` can ask for less. */\nexport type RoomFor = \"new\" | \"start\" | \"rescale\";\n\nconst HINTS: Record<RoomFor, string> = {\n new: \"stop or remove a box (kvbox stop, kvbox rm), pick a smaller --size, or pass --force to start it anyway\",\n start: \"stop or remove a box (kvbox stop, kvbox rm), or pass --force to start it anyway\",\n rescale: \"stop or remove a box (kvbox stop, kvbox rm), ask for less, or pass --force to rescale it anyway\",\n};\n\n/**\n * Why a box of `want` cannot start on `host` next to `running`, or undefined when it can.\n * `viewer` is the box's owner: only their boxes are named, the rest are counted. Pure, so the rule\n * is testable without a host.\n */\nexport function roomFor(\n host: Host,\n running: Reservation[],\n want: { vcpu: number; memMib: number },\n opts: { viewer?: string; by?: RoomFor } = {},\n): string | undefined {\n const { viewer, by = \"new\" } = opts;\n const reservedMem = running.reduce((n, r) => n + r.memMib, 0);\n const reservedVcpu = running.reduce((n, r) => n + r.vcpu, 0);\n const memLimit = host.memMib - MEM_HEADROOM_MIB;\n const vcpuLimit = host.cores * VCPU_OVERSUBSCRIPTION;\n const hint = HINTS[by];\n if (reservedMem + want.memMib > memLimit) {\n return (\n `not enough memory for a ${gb(want.memMib)} box: ${describeRunning(running, viewer)}; ` +\n `this host has ${gb(host.memMib)} and keeps ${gb(MEM_HEADROOM_MIB)} for itself, so boxes may reserve ${gb(memLimit)} in total. ` +\n hint\n );\n }\n if (reservedVcpu + want.vcpu > vcpuLimit) {\n return (\n `too many vCPUs for a ${want.vcpu} vCPU box: ${describeRunning(running, viewer)}; ` +\n `this host has ${host.cores} cores and allows ${vcpuLimit} vCPUs in total (${VCPU_OVERSUBSCRIPTION}x). ` +\n hint\n );\n }\n return undefined;\n}\n\n/**\n * Throws (HTTP 400, exit 1) when the host cannot take a box of this size for `box`'s owner; `force`\n * skips the check. A named `box` is left out of what is reserved: a rescale checks the new shape\n * in place of the old one (#37).\n */\nexport async function assertRoomFor(\n vcpu: number,\n memMib: number,\n force: boolean,\n box: { owner: string; name?: string },\n by: RoomFor,\n p: Paths = paths(),\n): Promise<void> {\n if (force) return;\n const running = (await runningReservations(p)).filter((r) => box.name === undefined || !(r.owner === box.owner && r.name === box.name));\n const reason = roomFor(hostResources(), running, { vcpu, memMib }, { viewer: box.owner, by });\n if (reason !== undefined) throw new KvboxError(reason);\n}\n","/**\n * This host as a backup store (decision \"Backup stores: Garage on our own disks…\"): `kvbox-server backup\n * setup --path <dir>` runs Garage with its data on a disk the operator bought for backups, makes one\n * bucket and one key, and tells the control plane, which from then on signs chunk URLs with that key.\n *\n * Garage is not ours to write, only to run: one node that is the whole cluster, listening on localhost.\n * It is started detached, like Firecracker, so it outlives a daemon restart; the daemon starts it again\n * when it finds it gone (a reboot, a crash). Chunks reach it through the host's own HTTPS listener\n * (`storeProxy`): a request whose path starts with the bucket's name is piped to Garage untouched, so\n * the certificate the control plane already pins and the port the relay already forwards serve it, and\n * Garage itself checks the signature of every request.\n */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { chmod, mkdir, readFile, rename, rm, stat, statfs, writeFile } from \"node:fs/promises\";\nimport { request as httpRequest, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { userInfo } from \"node:os\";\nimport { isAbsolute, join } from \"node:path\";\nimport { pipeline } from \"node:stream\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { request } from \"undici\";\nimport { BACKUP_STORE_BUCKET, BACKUP_STORE_REGION, type BackupStoreRegistration, type BackupStoreSetupRequest, type BackupStoreStatus, type Capacity } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { loadConfig, saveConfig, type BackupStore, type Config } from \"./config.js\";\nimport { run, spawnDetached } from \"./exec.js\";\nimport { log } from \"./log.js\";\nimport { pidAlive } from \"./state.js\";\n\n/** The Garage every store runs; the same release as the `garage` box image. A new one: change it and both checksums; each store takes it when its daemon next starts. */\nexport const GARAGE_VERSION = \"2.5.0\";\nconst GARAGE_SHA256: Record<string, { arch: string; sha256: string }> = {\n x64: { arch: \"x86_64\", sha256: \"2ff667286217cd73ebcb1c03af993822365000441dfe31a80cb64c5189a9dea8\" },\n arm64: { arch: \"aarch64\", sha256: \"69b6040cef428b993500c17dd0d0c1240acf2f3f667b9b05ceba4b9660db4e8c\" },\n};\n/** Garage on this host: S3 for the proxy, RPC for its own command line. Localhost only. */\nexport const GARAGE_S3_PORT = 3900;\nconst GARAGE_RPC_PORT = 3901;\n/** The name of the one key a store has: the control plane's. */\nconst KEY_NAME = \"kvbox-control-plane\";\n/** How long Garage may take to answer after it is started. */\nconst START_WAIT_MS = 60_000;\n/** How often the daemon looks whether Garage is still there. */\nexport const WATCH_MS = 30_000;\n\n/** What setup needs from the outside world; tests hand in fakes. */\nexport interface StoreDeps {\n /** Put Garage `GARAGE_VERSION` at `p.garage` unless it is there already; whether it put a new binary there. */\n install: (p: Paths) => Promise<boolean>;\n /** Start Garage detached; its pid. */\n start: (p: Paths) => Promise<number>;\n /** Whether the Garage started here is still there. */\n running: (p: Paths) => Promise<boolean>;\n /** Stop the Garage started here, and wait until it is gone. */\n stop: (p: Paths) => Promise<void>;\n /** One admin call (`garage json-api <operation> [body]`): its JSON answer. */\n api: (p: Paths, operation: string, body?: unknown) => Promise<unknown>;\n /** One `garage` command line call, for what the admin API does not do in one step. */\n cli: (p: Paths, args: readonly string[]) => Promise<string>;\n /** Tell the control plane (`PUT /hosts/self/backup-store`). */\n register: (cfg: Config, body: BackupStoreRegistration) => Promise<void>;\n /** The filesystem a path is on. */\n device: (path: string) => Promise<number>;\n}\n\nconst garage = (p: Paths, args: readonly string[], timeoutMs = 20_000) => run([p.garage, \"-c\", p.backupStore.conf, ...args], { timeoutMs });\n\nexport const realDeps: StoreDeps = {\n install: installGarage,\n start: (p) => spawnDetached([p.garage, \"-c\", p.backupStore.conf, \"server\"], p.backupStore.log),\n running: (p) => garageRunning(p),\n stop: stopGarage,\n api: async (p, operation, body) => {\n const { stdout } = await garage(p, [\"json-api\", operation, ...(body === undefined ? [] : [JSON.stringify(body)])]);\n const text = stdout.trim();\n return text === \"\" ? null : (JSON.parse(text) as unknown);\n },\n cli: async (p, args) => (await garage(p, args)).stdout,\n register: registerWithControlPlane,\n device: async (path) => (await stat(path)).dev,\n};\n\n/** The file beside the binary saying which Garage it is: a `GARAGE_VERSION` bump then reaches hosts that have one. */\nconst versionFile = (p: Paths) => `${p.garage}.version`;\n\n/** Download Garage's own static binary and keep it only if it is the file we expect; false when that version is there already. */\nexport async function installGarage(p: Paths): Promise<boolean> {\n if (existsSync(p.garage) && (await readFile(versionFile(p), \"utf8\").catch(() => \"\")).trim() === GARAGE_VERSION) return false;\n const build = GARAGE_SHA256[process.arch];\n if (!build) throw new KvboxError(`there is no Garage build for this machine (${process.arch})`);\n const url = `https://garagehq.deuxfleurs.fr/_releases/v${GARAGE_VERSION}/${build.arch}-unknown-linux-musl/garage`;\n const res = await fetch(url, { signal: AbortSignal.timeout(300_000) }).catch((err: Error) => {\n throw new KvboxError(`could not download Garage from ${url} (${err.message})`);\n });\n if (!res.ok) throw new KvboxError(`could not download Garage from ${url}: HTTP ${res.status}`);\n const bytes = Buffer.from(await res.arrayBuffer());\n const got = createHash(\"sha256\").update(bytes).digest(\"hex\");\n if (got !== build.sha256) throw new KvboxError(`the Garage download is not the expected file (sha256 ${got}); nothing was installed`);\n await mkdir(p.bin, { recursive: true });\n const tmp = `${p.garage}.tmp`;\n await writeFile(tmp, bytes, { mode: 0o755 });\n await chmod(tmp, 0o755);\n await rename(tmp, p.garage);\n await writeFile(versionFile(p), `${GARAGE_VERSION}\\n`);\n return true;\n}\n\nasync function registerWithControlPlane(cfg: Config, body: BackupStoreRegistration): Promise<void> {\n const cp = cfg.controlPlane;\n if (!cp) throw new KvboxError(\"this host has not joined a control plane\");\n const res = await request(`${cp.url}/hosts/self/backup-store`, {\n method: \"PUT\",\n headers: { authorization: `Bearer ${cp.secret}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n headersTimeout: 10_000,\n bodyTimeout: 10_000,\n }).catch((err: Error) => {\n throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);\n });\n const text = await res.body.text();\n if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not know backup stores yet: it is older than this host`);\n if (res.statusCode < 200 || res.statusCode >= 300) {\n let error: unknown;\n try {\n error = (JSON.parse(text) as { error?: unknown }).error;\n } catch {\n // not JSON: the status says enough\n }\n throw new KvboxError(typeof error === \"string\" ? error : `${cp.name} answered ${res.statusCode}`);\n }\n}\n\n/** Garage's configuration for a store whose files are under `path`. */\nexport function garageToml(path: string): string {\n const q = (s: string) => JSON.stringify(s);\n return [\n \"# written by kvbox-server backup setup: this host's backup store\",\n `metadata_dir = ${q(join(path, \"meta\"))}`,\n `data_dir = ${q(join(path, \"data\"))}`,\n 'db_engine = \"lmdb\"',\n \"metadata_fsync = true\",\n \"data_fsync = true\",\n \"replication_factor = 1\",\n `rpc_bind_addr = \"127.0.0.1:${GARAGE_RPC_PORT}\"`,\n `rpc_public_addr = \"127.0.0.1:${GARAGE_RPC_PORT}\"`,\n `rpc_secret_file = ${q(join(path, \"rpc_secret\"))}`,\n \"\",\n \"[s3_api]\",\n `s3_region = ${q(BACKUP_STORE_REGION)}`,\n `api_bind_addr = \"127.0.0.1:${GARAGE_S3_PORT}\"`,\n \"\",\n ].join(\"\\n\");\n}\n\nasync function readPid(p: Paths): Promise<number | null> {\n const n = Number((await readFile(p.backupStore.pid, \"utf8\").catch(() => \"\")).trim());\n return Number.isInteger(n) && n > 0 ? n : null;\n}\n\n/** Whether the Garage this daemon started is still there: its pid lives and is Garage, not a pid reused since a reboot. */\nexport async function garageRunning(p: Paths = paths()): Promise<boolean> {\n const pid = await readPid(p);\n if (!pidAlive(pid)) return false;\n const cmdline = await readFile(`/proc/${pid}/cmdline`, \"utf8\").catch(() => null);\n return cmdline === null || cmdline.split(\"\\0\")[0] === p.garage;\n}\n\n/** Stop the Garage started here (SIGTERM), waiting until it is gone. */\nexport async function stopGarage(p: Paths): Promise<void> {\n const pid = await readPid(p);\n if (pid === null || !(await garageRunning(p))) return;\n // `garageRunning` gives an unreadable command line the benefit of the doubt; a kill does not.\n const cmdline = await readFile(`/proc/${pid}/cmdline`, \"utf8\").catch(() => null);\n if (cmdline?.split(\"\\0\")[0] !== p.garage) throw new KvboxError(`cannot tell whether pid ${pid} is this host's Garage, so it was not stopped; stop Garage by hand and run this again`);\n process.kill(pid, \"SIGTERM\");\n const until = Date.now() + 15_000;\n while (pidAlive(pid)) {\n if (Date.now() > until) throw new KvboxError(`Garage (pid ${pid}) did not stop within 15s`);\n await sleep(200);\n }\n await rm(p.backupStore.pid, { force: true });\n}\n\n/** Start Garage unless it runs, and wait until it answers. */\nasync function ensureGarage(p: Paths, deps: StoreDeps): Promise<void> {\n if (!(await deps.running(p))) {\n const pid = await deps.start(p);\n await writeFile(p.backupStore.pid, `${pid}\\n`);\n }\n const until = Date.now() + START_WAIT_MS;\n for (;;) {\n try {\n await deps.cli(p, [\"status\"]);\n return;\n } catch (err) {\n if (Date.now() > until) throw new KvboxError(`Garage did not answer after ${START_WAIT_MS / 1000}s (see ${p.backupStore.log}): ${(err as Error).message}`);\n await sleep(500);\n }\n }\n}\n\n/**\n * `kvbox-server backup setup`: make this host a backup store with its data under `req.path`, or, run\n * again with the same path, finish a setup that stopped half way (every step is safe to repeat) and\n * register the store with the control plane again.\n */\nexport function setupBackupStore(req: BackupStoreSetupRequest, p: Paths = paths(), deps: StoreDeps = realDeps): Promise<BackupStoreStatus> {\n return serial(() => setup(req, p, deps));\n}\n\n/**\n * One store step at a time in this daemon: a setup, or the watch starting Garage again. Two of them at\n * once would each start a Garage (the loser exits, and its pid may be the one kept) or each make a key.\n */\nlet turn: Promise<unknown> = Promise.resolve();\nfunction serial<T>(step: () => Promise<T>): Promise<T> {\n const mine = turn.then(step, step);\n turn = mine.catch(() => undefined);\n return mine;\n}\n\nasync function setup(req: BackupStoreSetupRequest, p: Paths, deps: StoreDeps): Promise<BackupStoreStatus> {\n const path = req.path.replace(/\\/+$/, \"\") || \"/\";\n if (!isAbsolute(path) || /[\"\\\\\\n\\0]/.test(path)) throw new KvboxError(`${req.path} is not a path a store can use: give the full path of a directory on the backup disk`);\n const cfg = await loadConfig(p);\n if (!cfg.controlPlane) throw new KvboxError(\"this host has not joined a control plane, which is what takes backups; run kvbox-server join first\");\n if (cfg.backupStore && cfg.backupStore.path !== path) {\n throw new KvboxError(`this host already is a backup store, with its data in ${cfg.backupStore.path}; a host has one store`);\n }\n const dir = await stat(path).catch(() => null);\n if (!dir?.isDirectory()) throw new KvboxError(`${path} is not a directory: mount the backup disk and give a directory on it`);\n if (!req.force && (await deps.device(path)) === (await deps.device(p.home))) {\n throw new KvboxError(`${path} is on the same disk as this host's boxes, so the backups would be lost with them; mount a disk for backups there, or pass --force to use it anyway`);\n }\n\n // A store set up before whose files are not at the path: its disk is not mounted, or another (empty)\n // one is. Nothing is written or started there unless the operator says the old disk is gone for good:\n // a new store makes a new key, and the control plane then forgets every backup the old one kept.\n if (cfg.backupStore && !req.newStore && !existsSync(join(path, \"rpc_secret\"))) throw notTheStoreDisk(path);\n\n const newBinary = await deps.install(p);\n await mkdir(p.backupStore.dir, { recursive: true, mode: 0o700 });\n try {\n for (const sub of [\"meta\", \"data\"]) await mkdir(join(path, sub), { recursive: true, mode: 0o700 });\n const rpcSecret = join(path, \"rpc_secret\");\n if (!existsSync(rpcSecret)) await writeFile(rpcSecret, `${randomBytes(32).toString(\"hex\")}\\n`, { mode: 0o600 });\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"EACCES\" && code !== \"EPERM\" && code !== \"EROFS\") throw err;\n const user = userInfo().username;\n throw new KvboxError(`kvbox-server (user ${user}) cannot write in ${path}: make the directory ${user}'s (sudo chown ${user} ${path}) and run this again`);\n }\n // A Garage still running from a setup that stopped half way may have its data elsewhere (another\n // --path that time): it is started again on this configuration rather than trusted.\n const conf = garageToml(path);\n const had = await readFile(p.backupStore.conf, \"utf8\").catch(() => null);\n await writeFile(p.backupStore.conf, conf, { mode: 0o600 });\n if ((newBinary || (had !== null && had !== conf)) && (await deps.running(p))) await deps.stop(p);\n await ensureGarage(p, deps);\n\n // The layout says which nodes hold data: this one, alone. A disk that held a store before comes with its own.\n const layout = (await deps.api(p, \"GetClusterLayout\")) as { version?: number } | null;\n if ((layout?.version ?? 0) === 0) {\n const node = (await deps.cli(p, [\"node\", \"id\", \"-q\"])).trim().split(\"@\")[0]!;\n const fs = await statfs(path);\n await deps.cli(p, [\"layout\", \"assign\", \"-z\", \"kvbox\", \"-c\", String(fs.blocks * fs.bsize), node]);\n await deps.cli(p, [\"layout\", \"apply\", \"--version\", \"1\"]);\n }\n const bucket = await bucketInfo(p, deps).then(async (info) => info ?? ((await deps.api(p, \"CreateBucket\", { globalAlias: BACKUP_STORE_BUCKET })) as { id: string }));\n\n // The key is made once and kept here too, so a second setup registers the same one, as long as Garage\n // still has it: a disk that was replaced (or wiped) comes with an empty Garage, which needs a key of its\n // own. Registering it tells the control plane the store was made anew.\n let store: BackupStore;\n if (cfg.backupStore && (await hasKey(p, deps, cfg.backupStore.accessKey))) {\n store = cfg.backupStore;\n } else {\n if (cfg.backupStore && !req.newStore) {\n // Another store's disk: stop the Garage just started on it, so this host does not serve it as its own.\n await deps.stop(p);\n throw notTheStoreDisk(path);\n }\n if (cfg.backupStore) log.warn(`backup store: a new store in ${path} replaces the one with key ${cfg.backupStore.accessKey}; the backups kept on the old disk are gone`);\n const key = (await deps.api(p, \"CreateKey\", { name: KEY_NAME })) as { accessKeyId: string; secretAccessKey: string };\n store = { path, bucket: BACKUP_STORE_BUCKET, region: BACKUP_STORE_REGION, accessKey: key.accessKeyId, secretKey: key.secretAccessKey, registered: false };\n }\n await deps.api(p, \"AllowBucketKey\", { bucketId: bucket.id, accessKeyId: store.accessKey, permissions: { read: true, write: true, owner: false } });\n // Read again: the download and Garage's start take minutes, and config.json may have changed meanwhile.\n const now = await loadConfig(p);\n // Not registered until the control plane says so this time: a failed attempt must not keep an earlier yes.\n await saveConfig({ ...now, backupStore: { ...store, registered: false } }, p);\n log.info(`backup store: Garage keeps its data in ${path}`);\n\n try {\n await deps.register(now, { bucket: store.bucket, region: store.region, accessKey: store.accessKey, secretKey: store.secretKey });\n } catch (err) {\n throw new KvboxError(`the store is set up, but the control plane did not take it: ${(err as Error).message}. Run the same command again once that is solved`);\n }\n await saveConfig({ ...(await loadConfig(p)), backupStore: { ...store, registered: true } }, p);\n log.info(`backup store: registered with ${now.controlPlane?.name ?? cfg.controlPlane.name}`);\n return backupStoreStatus(p, deps);\n}\n\nconst notTheStoreDisk = (path: string) =>\n new KvboxError(\n `${path} does not hold this host's backup store: is its disk mounted there? Mount it and run this again. If that disk is gone for good, pass --new-store to start a new store here (the backups kept on the old disk can no longer be restored)`,\n );\n\n/** Whether Garage knows the access key `id`. */\nasync function hasKey(p: Paths, deps: StoreDeps, id: string): Promise<boolean> {\n const keys = (await deps.api(p, \"ListKeys\")) as { id: string }[] | null;\n return (keys ?? []).some((k) => k.id === id);\n}\n\nasync function bucketInfo(p: Paths, deps: StoreDeps): Promise<{ id: string; objects?: number; bytes?: number } | null> {\n try {\n return (await deps.api(p, \"GetBucketInfo\", { globalAlias: BACKUP_STORE_BUCKET })) as { id: string; objects?: number; bytes?: number };\n } catch (err) {\n if (/not found|nosuchbucket/i.test((err as Error).message)) return null;\n throw err;\n }\n}\n\n/** `kvbox-server backup status`: where the store is, whether Garage runs, how full its disk is. */\nexport async function backupStoreStatus(p: Paths = paths(), deps: StoreDeps = realDeps): Promise<BackupStoreStatus> {\n const store = (await loadConfig(p)).backupStore;\n if (!store) throw new KvboxError(\"this host is not a backup store; make it one with: kvbox-server backup setup --path <directory on the backup disk>\");\n const fs = await statfs(store.path).catch(() => null);\n const running = await deps.running(p);\n const info = running ? await bucketInfo(p, deps).catch(() => null) : null;\n return {\n path: store.path,\n bucket: store.bucket,\n accessKey: store.accessKey,\n running: running && info !== null,\n totalBytes: fs ? fs.blocks * fs.bsize : 0,\n freeBytes: fs ? fs.bavail * fs.bsize : 0,\n ...(info ? { objects: info.objects ?? 0, storedBytes: info.bytes ?? 0 } : {}),\n registered: store.registered,\n };\n}\n\n/** What `/capacity` says about the store, for the control plane to pick one with room; undefined on a host without one. */\nexport async function backupStoreCapacity(p: Paths = paths(), deps: Pick<StoreDeps, \"running\"> = realDeps): Promise<Capacity[\"backupStore\"]> {\n const store = (await loadConfig(p)).backupStore;\n if (!store) return undefined;\n const fs = await statfs(store.path).catch(() => null);\n return { totalBytes: fs ? fs.blocks * fs.bsize : 0, freeBytes: fs ? fs.bavail * fs.bsize : 0, running: fs !== null && (await deps.running(p)) };\n}\n\n/**\n * At daemon start and every `WATCH_MS` after: a store's Garage that is gone (a reboot, a crash) is\n * started again. A disk that is not mounted is left alone, so Garage never starts empty beside it.\n */\nexport function reviveBackupStore(p: Paths = paths(), deps: StoreDeps = realDeps): Promise<\"none\" | \"running\" | \"started\" | \"upgraded\" | \"no-disk\"> {\n return serial(() => revive(p, deps));\n}\n\n/** Homes whose Garage this daemon has made sure is `GARAGE_VERSION`: once per run, so a failed download does not repeat every tick. */\nconst upgraded = new Set<string>();\n/** Homes where a new binary was installed and Garage has not been started on it yet. */\nconst restartDue = new Set<string>();\n\nasync function revive(p: Paths, deps: StoreDeps): Promise<\"none\" | \"running\" | \"started\" | \"upgraded\" | \"no-disk\"> {\n const store = (await loadConfig(p)).backupStore;\n if (!store) return \"none\";\n if (!upgraded.has(p.home)) {\n upgraded.add(p.home);\n const fresh = await deps.install(p).catch((err: Error) => {\n log.warn(`backup store: Garage ${GARAGE_VERSION} could not be installed, the one there keeps running (${err.message})`);\n return false;\n });\n if (fresh) restartDue.add(p.home);\n }\n // A new binary is owed a start until one happens: not beside a disk that is not mounted, so a later tick does it.\n if (restartDue.has(p.home) && existsSync(join(store.path, \"rpc_secret\"))) {\n if (await deps.running(p)) await deps.stop(p);\n const pid = await deps.start(p);\n await writeFile(p.backupStore.pid, `${pid}\\n`);\n restartDue.delete(p.home);\n return \"upgraded\";\n }\n if (await deps.running(p)) return \"running\";\n if (!existsSync(join(store.path, \"rpc_secret\"))) return \"no-disk\";\n await rm(p.backupStore.pid, { force: true });\n const pid = await deps.start(p);\n await writeFile(p.backupStore.pid, `${pid}\\n`);\n return \"started\";\n}\n\nlet watch: NodeJS.Timeout | undefined;\n/** Keep the store's Garage up for as long as the daemon runs; says once when the disk is missing. */\nexport function startBackupStoreWatch(p: Paths = paths()): void {\n let warned = false;\n const tick = (): void => {\n reviveBackupStore(p)\n .then((state) => {\n if (state === \"started\") log.info(\"backup store: Garage was not running; started it\");\n if (state === \"upgraded\") log.info(`backup store: Garage ${GARAGE_VERSION} installed and started`);\n if (state === \"no-disk\" && !warned) log.warn(\"backup store: its disk is not mounted, so Garage is not started; backups to this host fail until it is back\");\n warned = state === \"no-disk\";\n })\n .catch((err: Error) => log.warn(`backup store: Garage did not start (${err.message})`));\n };\n tick();\n watch ??= setInterval(tick, WATCH_MS);\n watch.unref();\n}\n\n/** Whether a request to the HTTPS listener is for the store: `/<bucket>/…`, the path-style URLs the control plane signs. */\nexport function isStoreRequest(url: string | undefined): boolean {\n return url !== undefined && (url.startsWith(`/${BACKUP_STORE_BUCKET}/`) || url.startsWith(`/${BACKUP_STORE_BUCKET}?`) || url === `/${BACKUP_STORE_BUCKET}`);\n}\n\n/**\n * Whether the HTTPS listener hands this request to Garage: a store path, on a host that is a store (its\n * Garage configuration is written by the first setup). On any other host it goes to the app, so nothing\n * that happens to listen on the store's port here is reachable without a credential.\n */\nexport function forStore(url: string | undefined, p: Paths = paths()): boolean {\n return isStoreRequest(url) && existsSync(p.backupStore.conf);\n}\n\n/**\n * Pipe one request to Garage and its answer back, headers as they came: Garage checks the signature\n * over the `Host` the caller used, so nothing may be rewritten. No kvbox credential is asked for:\n * a signed URL is the credential, and Garage refuses anything else.\n */\nexport function storeProxy(req: IncomingMessage, res: ServerResponse, port = GARAGE_S3_PORT): void {\n const up = httpRequest({ host: \"127.0.0.1\", port, method: req.method, path: req.url, headers: req.headers }, (answer) => {\n res.writeHead(answer.statusCode ?? 502, answer.headers);\n // Either side ending early ends the other: a Garage that dies mid-answer resets the caller (who\n // retries at once), a caller that goes away closes the connection to Garage.\n pipeline(answer, res, (err) => {\n if (err) res.destroy();\n });\n });\n up.on(\"error\", () => {\n if (res.headersSent) return res.destroy();\n res.writeHead(503, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"this host's backup store is not running\" }));\n });\n res.once(\"close\", () => {\n if (!res.writableFinished) up.destroy();\n });\n req.pipe(up);\n}\n","/**\n * An ext4 image's own accounting, read from the file without mounting it: its size and what the\n * filesystem holds.\n *\n * Firecracker's block device has no discard, so a box's sparse disk file only ever grows while the\n * box runs, and its allocation on the host (st_blocks) says nothing about what the guest still uses\n * (#115). The group descriptors do: their free-block counts are journaled metadata, written back\n * within seconds of a change, so on a running box they are at most a journal commit behind the\n * guest's `df`; on a stopped box they are exact. The superblock's own free count is not used: ext4\n * only writes that at unmount.\n */\nimport { closeSync, openSync, readSync } from \"node:fs\";\n\nconst SUPERBLOCK_OFFSET = 1024;\nconst EXT4_MAGIC = 0xef53;\n/** Group descriptors spread over the disk instead of one table after the superblock; mke2fs never sets it at box sizes. */\nconst INCOMPAT_META_BG = 0x10;\nconst INCOMPAT_64BIT = 0x80;\n\nexport interface Ext4Usage {\n /** Block count times block size: the disk as the guest's `df` sizes it. */\n sizeBytes: number;\n /** Blocks in use. Matches `df` \"Used\": the overlay is made with `-m 0`, so no blocks are held back for root. */\n usedBytes: number;\n}\n\n/** `null` when the file is missing, not ext4, or laid out in a way this reader does not know. */\nexport function ext4Usage(file: string): Ext4Usage | null {\n let fd: number | undefined;\n try {\n fd = openSync(file, \"r\");\n const sb = Buffer.alloc(1024);\n if (readSync(fd, sb, 0, sb.length, SUPERBLOCK_OFFSET) !== sb.length) return null;\n if (sb.readUInt16LE(0x38) !== EXT4_MAGIC) return null;\n const incompat = sb.readUInt32LE(0x60);\n if (incompat & INCOMPAT_META_BG) return null;\n const is64 = (incompat & INCOMPAT_64BIT) !== 0;\n const blockSize = 1024 << sb.readUInt32LE(0x18);\n const blocks = sb.readUInt32LE(0x04) + (is64 ? sb.readUInt32LE(0x150) * 2 ** 32 : 0);\n const firstDataBlock = sb.readUInt32LE(0x14);\n const blocksPerGroup = sb.readUInt32LE(0x20);\n const descSize = is64 ? sb.readUInt16LE(0xfe) : 32;\n if (blocksPerGroup === 0 || descSize < 32) return null;\n const groups = Math.ceil((blocks - firstDataBlock) / blocksPerGroup);\n // The descriptor table is the block after the superblock's.\n const table = Buffer.alloc(groups * descSize);\n if (readSync(fd, table, 0, table.length, (firstDataBlock + 1) * blockSize) !== table.length) return null;\n let free = 0;\n for (let g = 0; g < groups; g++) {\n const at = g * descSize;\n free += table.readUInt16LE(at + 0x0c) + (descSize >= 64 ? table.readUInt16LE(at + 0x2c) * 65536 : 0);\n }\n return { sizeBytes: blocks * blockSize, usedBytes: (blocks - free) * blockSize };\n } catch {\n return null;\n } finally {\n if (fd !== undefined) closeSync(fd);\n }\n}\n","/**\n * Snapshots: a running box frozen into `snapshots/<name>/` as vmstate + mem (a complete memory image)\n * + a copy of the box's overlay. The base image is referenced by version, not copied, so a snapshot costs\n * what the guest touched (memory pages + overlay blocks), not the box's size.\n *\n * Memory is captured incrementally. Boxes run with dirty page tracking, so Firecracker can write only\n * the pages dirtied since the last snapshot (a \"Diff\": sub-second, sparse) instead of dumping all of\n * guest memory (~10 s frozen for 4 GB). A diff is only a complete image when merged onto the previous\n * one, so each box keeps `mem.base`, a hard link to its last snapshot's `mem`, and the merge happens\n * after the box is already running again. See state.ts `memSnapshots` for the bookkeeping.\n */\nimport { existsSync } from \"node:fs\";\nimport { link, mkdir, readdir, rename, rm, stat } from \"node:fs/promises\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport type { CreateSnapshotRequest, Snapshot } from \"@kvbox/shared/api\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { loadConfig, type Config } from \"./config.js\";\nimport { run } from \"./exec.js\";\nimport { FirecrackerClient } from \"./firecracker.js\";\nimport { withBoxLock, withSnapshotLock } from \"./locks.js\";\nimport { inScope, parseRef, refKey, shown, type BoxRef, type ListScope } from \"./refs.js\";\nimport { copyBoxEnv } from \"./env.js\";\nimport { captureDrivesOf } from \"./volumes.js\";\nimport {\n listSnapshotRefs,\n readMachineMeta,\n readSnapshotMeta,\n vmAlive,\n writeMachineMeta,\n writeSnapshotMeta,\n type MachineMeta,\n type SnapshotMeta,\n} from \"./state.js\";\nimport { log } from \"./log.js\";\n\n/** Snapshot names are directory names shown in tables: letters, digits, dots, dashes, underscores. */\nconst NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;\n\nfunction toSnapshot(meta: SnapshotMeta): Snapshot {\n return {\n name: meta.name,\n owner: meta.owner,\n source: meta.source,\n base: meta.base,\n ...(meta.image !== undefined ? { image: meta.image } : {}),\n vcpu: meta.vcpu,\n memMib: meta.memMib,\n sizeBytes: meta.sizeBytes,\n createdAt: meta.createdAt,\n };\n}\n\n/** One owner's snapshots, or every snapshot on the host when `owner` is null. */\nexport async function listSnapshots(scope: ListScope, p: Paths = paths()): Promise<Snapshot[]> {\n const out: Snapshot[] = [];\n for (const ref of await listSnapshotRefs(p)) {\n if (!inScope(ref.owner, scope)) continue;\n try {\n out.push(toSnapshot(await readSnapshotMeta(ref, p)));\n } catch (err) {\n log.warn(`skipping snapshots/${refKey(ref)}: ${(err as Error).message}`);\n }\n }\n return out;\n}\n\n/** Bytes the snapshot really occupies: its files are sparse, so allocated blocks, not sizes. */\nasync function usedBytes(dir: string): Promise<number> {\n let total = 0;\n for (const entry of await readdir(dir)) {\n total += (await stat(`${dir}/${entry}`)).blocks * 512;\n }\n return total;\n}\n\nasync function readBox(ref: BoxRef, p: Paths): Promise<MachineMeta> {\n try {\n return await readMachineMeta(ref, p);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") throw new NotFoundError(`box ${shown(ref)}`);\n throw err;\n }\n}\n\n/** The snapshot belongs to `owner` (the caller); `req.box` may name another owner's box as owner/name. */\nexport async function saveSnapshot(req: CreateSnapshotRequest, owner: string, p: Paths = paths()): Promise<Snapshot> {\n if (!NAME_RE.test(req.name)) {\n throw new KvboxError(`invalid snapshot name \"${req.name}\": 1-64 chars, lowercase letters, digits, '.', '_' and '-', starting with a letter or digit`);\n }\n const ref = parseRef(req.box, owner);\n return withBoxLock(ref, () => snapshotBox(ref, req, owner, p));\n}\n\nasync function snapshotBox(ref: BoxRef, req: CreateSnapshotRequest, owner: string, p: Paths): Promise<Snapshot> {\n const box = await readBox(ref, p);\n if (!vmAlive(box)) {\n if (existsSync(p.machine(box.owner, box.name).hibernateVmstate)) {\n throw new KvboxError(`box ${req.box} is hibernated; a snapshot freezes a running box (kvbox wake ${req.box} first)`);\n }\n throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);\n }\n const final = p.snapshot(owner, req.name);\n if (existsSync(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);\n // A replace (#83) captures beside the old snapshot, which stays whole and restorable until the new one\n // is complete. Named after the box: two replaces of one name from two boxes never share it.\n const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;\n const cfg = await loadConfig(p);\n\n if (s !== final) await rm(s.dir, { recursive: true, force: true }); // left by a replace the daemon never finished\n await mkdir(s.dir, { recursive: true, mode: 0o700 });\n try {\n // The VM's volume drives (attached ones, placeholders of a restore) end up in the vmstate; a restore\n // needs their names and sizes for the placeholders (#52).\n const volumes = await captureDrivesOf(box, p);\n await captureBox(box, s, cfg, p);\n // The box's own variables go with it (#87): a postgres box's data was made with its password.\n await copyBoxEnv(p.machine(box.owner, box.name).env, s.env);\n const meta: SnapshotMeta = {\n ...(volumes.length > 0 ? { volumes } : {}),\n name: req.name,\n owner,\n source: refKey(box),\n base: box.base,\n ...(box.image !== undefined ? { image: box.image } : {}),\n vcpu: box.vcpu,\n memMib: box.memMib,\n sizeBytes: await usedBytes(s.dir),\n createdAt: new Date().toISOString(),\n };\n await writeSnapshotMeta(meta, p, s);\n if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);\n return toSnapshot(meta);\n } catch (err) {\n await rm(s.dir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/**\n * Move the complete snapshot at `from` into `ref`'s name, the old one (if any) out of the way first.\n * Under the snapshot's lock, so a restore never reads half of each; the old files are removed after.\n * The old one's dir is named after the box like `from`: a replace from another box that swaps while\n * this one still removes never has its old dir (its rollback) removed under it.\n */\nasync function swapIn(ref: BoxRef, from: string, boxId: string, p: Paths): Promise<void> {\n const to = p.snapshot(ref.owner, ref.name).dir;\n const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;\n await withSnapshotLock(ref, async () => {\n await rm(old, { recursive: true, force: true });\n const hadOld = existsSync(to);\n if (hadOld) await rename(to, old);\n try {\n await rename(from, to);\n } catch (err) {\n if (hadOld) await rename(old, to);\n throw err;\n }\n });\n await rm(old, { recursive: true, force: true });\n}\n\n/** Where a capture writes: a snapshot's files, or a fork's own box dir (#79). */\nexport interface Capture {\n vmstate: string;\n /** Becomes a complete memory image, hard-linked as the box's `mem.base`. */\n mem: string;\n overlay: string;\n}\n\n/**\n * Freeze the running (or paused) `box` into `to`: VM state, a complete memory image and a copy of its\n * overlay, all of the same instant. The box carries on as it was. The caller holds the box's lock and\n * removes `to`'s files on a throw; the box's memory lineage is left consistent either way.\n */\nexport async function captureBox(box: MachineMeta, to: Capture, cfg: Config, p: Paths): Promise<void> {\n const m = p.machine(box.owner, box.name);\n const fc = new FirecrackerClient(m.sock);\n let lineageTouched = false;\n try {\n const since = box.memSnapshots ?? 0;\n // A diff is standalone right after boot, or once merged onto the previous image. Otherwise (a\n // lineage broken by an earlier failure) dump everything.\n const mode: \"Diff\" | \"Full\" = since === 0 || existsSync(m.memBase) ? \"Diff\" : \"Full\";\n\n // The guest is frozen for the whole capture so memory and overlay describe the same instant.\n // A box in standby (kvbox pause) is frozen already and stays that way afterwards.\n let failure: unknown;\n await fc.pause();\n try {\n await fc.snapshotCreate(to.vmstate, to.mem, mode);\n lineageTouched = true; // Firecracker reset its dirty bitmap: the box's next diff is relative to this image\n await run([\"cp\", \"--sparse=always\", \"--reflink=auto\", m.overlay, to.overlay]);\n } catch (err) {\n failure = err;\n } finally {\n if (!box.paused) await fc.resume();\n }\n if (lineageTouched) {\n // Recorded before anything else can fail: memSnapshots > 0 without mem.base reads as a broken\n // lineage, and the next snapshot falls back to a full dump instead of a diff missing pages.\n await writeMachineMeta({ ...box, memSnapshots: since + 1 }, p);\n }\n if (failure !== undefined) throw failure;\n\n if (mode === \"Full\") {\n // A full dump is dense; pages the guest never touched are zeros, so punch them out.\n await run([\"fallocate\", \"--dig-holes\", to.mem]);\n } else if (since > 0) {\n await mergeOntoPrevious(m.memBase, to.mem, cfg.snapshotEditor ?? p.snapshotEditor);\n }\n await rm(m.memBase, { force: true });\n await link(to.mem, m.memBase);\n } catch (err) {\n // The diff that was just discarded took pages with it: never let the next diff build on the old image.\n if (lineageTouched) await rm(m.memBase, { force: true }).catch(() => undefined);\n throw err;\n } finally {\n await fc.close();\n }\n}\n\n/**\n * Turn the diff at `diffFile` into a complete image: copy the previous image and apply the diff's pages\n * over it. Holes in the diff are untouched pages; a page dirtied to zeros is data and overwrites.\n */\nasync function mergeOntoPrevious(previous: string, diffFile: string, editor: string): Promise<void> {\n if (!existsSync(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);\n const merged = `${diffFile}.merged`;\n await run([\"cp\", \"--sparse=always\", \"--reflink=auto\", previous, merged]);\n await run([editor, \"edit-memory\", \"rebase\", \"--memory-path\", merged, \"--diff-path\", diffFile]);\n await rename(merged, diffFile);\n}\n\nexport async function deleteSnapshot(ref: BoxRef, p: Paths = paths()): Promise<void> {\n const dir = p.snapshot(ref.owner, ref.name).dir;\n if (ref.name.startsWith(\".\") || !existsSync(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);\n await withSnapshotLock(ref, () => rm(dir, { recursive: true, force: true }));\n}\n","/**\n * Client for one Firecracker process's API socket. Ten-odd endpoints, all\n * PUT/PATCH with JSON bodies, so a thin wrapper over undici beats an SDK.\n */\nimport { Agent, request } from \"undici\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { log } from \"./log.js\";\n\n/** Said once per daemon: every box on a host that cannot do Async would repeat the same line. */\nlet syncFallbackLogged = false;\n\nexport class FirecrackerClient {\n private readonly agent: Agent;\n\n constructor(readonly socketPath: string) {\n this.agent = new Agent({ connect: { socketPath } });\n }\n\n private async call(method: \"GET\" | \"PUT\" | \"PATCH\", path: string, body?: unknown): Promise<unknown> {\n const res = await request(`http://localhost${path}`, {\n dispatcher: this.agent,\n method,\n headers: body === undefined ? {} : { \"content-type\": \"application/json\" },\n body: body === undefined ? null : JSON.stringify(body),\n });\n const text = await res.body.text();\n if (res.statusCode >= 300) {\n throw new KvboxError(`firecracker ${method} ${path} -> ${res.statusCode}: ${text}`);\n }\n return text ? JSON.parse(text) : undefined;\n }\n\n bootSource(kernelImagePath: string, bootArgs: string) {\n return this.call(\"PUT\", \"/boot-source\", { kernel_image_path: kernelImagePath, boot_args: bootArgs });\n }\n\n /** /dev/vda: the shared base image, read-only. Firecracker adds `root=/dev/vda ro` to the boot args to match. */\n rootDrive(pathOnHost: string) {\n return this.drive(\"rootfs\", pathOnHost, { root: true, readOnly: true, engine: \"Sync\" });\n }\n\n /** The box's own writable disk, /dev/vdb: the guest stacks it on the base as an overlay. */\n overlayDrive(pathOnHost: string) {\n return this.writableDrive(\"overlay\", pathOnHost);\n }\n\n /** A volume (#52): /dev/vdc and up, in the order they are added; the guest mounts it by label. */\n volumeDrive(id: string, pathOnHost: string) {\n return this.writableDrive(id, pathOnHost);\n }\n\n /**\n * A drive the guest writes to gets the Async engine (io_uring, #175): with Sync, Firecracker's one\n * VMM thread sits in the write or the fsync and the box's network waits behind it, seconds under a\n * heavy write. The base image stays on Sync, which is the faster of the two for reads the host has\n * cached. A host that cannot do Async (kernel before 5.10.51, io_uring turned off) keeps Sync.\n * The engine is part of a snapshot: a box frozen on Sync wakes on Sync, until its next cold boot.\n */\n private async writableDrive(id: string, pathOnHost: string) {\n const opts = { root: false, readOnly: false };\n try {\n return await this.drive(id, pathOnHost, { ...opts, engine: \"Async\" });\n } catch (asyncErr) {\n // Not told apart by its wording: whatever was wrong, Sync either works or gives the real error.\n const done = await this.drive(id, pathOnHost, { ...opts, engine: \"Sync\" });\n if (!syncFallbackLogged) {\n syncFallbackLogged = true;\n log.warn(`this host cannot give box disks the Async engine, they keep Sync (heavy writes in a box can stall its network): ${(asyncErr as Error).message}`);\n }\n return done;\n }\n }\n\n private drive(id: string, pathOnHost: string, opts: { root: boolean; readOnly: boolean; engine: \"Sync\" | \"Async\" }) {\n return this.call(\"PUT\", `/drives/${id}`, {\n drive_id: id,\n path_on_host: pathOnHost,\n is_root_device: opts.root,\n is_read_only: opts.readOnly,\n // \"Unsafe\" (the default) acks guest flushes without doing anything, so the last journal\n // commit of a clean shutdown can be lost when the guest resets and Firecracker exits.\n // Writeback makes a guest flush a real fsync; a box's writes must survive `kvbox stop`.\n cache_type: \"Writeback\",\n io_engine: opts.engine,\n });\n }\n\n /**\n * The host's control channel into the box: Firecracker listens on `udsPath`, a connection there\n * followed by `CONNECT <port>\\n` reaches whatever listens on that vsock port in the guest (kvbox-agent).\n */\n vsock(guestCid: number, udsPath: string) {\n return this.call(\"PUT\", \"/vsock\", { guest_cid: guestCid, uds_path: udsPath });\n }\n\n machineConfig(vcpuCount: number, memSizeMib: number) {\n // Dirty page tracking lets a snapshot write only the pages the guest touched since the last one\n // (a \"Diff\" snapshot) instead of dumping all of guest memory: sub-second instead of ~10 s frozen.\n return this.call(\"PUT\", \"/machine-config\", { vcpu_count: vcpuCount, mem_size_mib: memSizeMib, track_dirty_pages: true });\n }\n\n networkInterface(ifaceId: string, hostDevName: string, guestMac: string) {\n return this.call(\"PUT\", `/network-interfaces/${ifaceId}`, {\n iface_id: ifaceId,\n host_dev_name: hostDevName,\n guest_mac: guestMac,\n });\n }\n\n start() {\n return this.call(\"PUT\", \"/actions\", { action_type: \"InstanceStart\" });\n }\n\n /** Ask the guest to shut down cleanly (systemd handles Ctrl+Alt+Del as poweroff on Firecracker). */\n sendCtrlAltDel() {\n return this.call(\"PUT\", \"/actions\", { action_type: \"SendCtrlAltDel\" });\n }\n\n pause() {\n return this.call(\"PATCH\", \"/vm\", { state: \"Paused\" });\n }\n\n resume() {\n return this.call(\"PATCH\", \"/vm\", { state: \"Resumed\" });\n }\n\n /**\n * Full: all of guest memory, dense (seconds for a 4 GB box). Diff: only pages dirtied since the last\n * snapshot (or since boot), written sparse; needs dirty page tracking and resets its bitmap.\n */\n snapshotCreate(snapshotPath: string, memFilePath: string, type: \"Full\" | \"Diff\" = \"Full\") {\n return this.call(\"PUT\", \"/snapshot/create\", {\n snapshot_type: type,\n snapshot_path: snapshotPath,\n mem_file_path: memFilePath,\n });\n }\n\n /**\n * Restore a snapshot into this (fresh) process. The memory file is mapped privately: the guest's\n * writes never reach the snapshot. The vmstate carries the source box's tap and vsock paths; the\n * overrides point them at this box's. Drive paths are not overridable here: the vmstate names the overlay relative to the box dir (spawnFirecracker).\n */\n snapshotLoad(opts: {\n snapshotPath: string;\n memFilePath: string;\n tap: { ifaceId: string; hostDevName: string };\n vsockPath: string;\n /** Required for diff snapshots later: the flag is not part of the vmstate. */\n trackDirtyPages: boolean;\n resume: boolean;\n }) {\n return this.call(\"PUT\", \"/snapshot/load\", {\n snapshot_path: opts.snapshotPath,\n mem_backend: { backend_type: \"File\", backend_path: opts.memFilePath },\n network_overrides: [{ iface_id: opts.tap.ifaceId, host_dev_name: opts.tap.hostDevName }],\n vsock_override: { uds_path: opts.vsockPath },\n track_dirty_pages: opts.trackDirtyPages,\n resume_vm: opts.resume,\n });\n }\n\n info() {\n return this.call(\"GET\", \"/\");\n }\n\n async close() {\n await this.agent.close();\n }\n}\n","/**\n * Host networking: bridge `kvbox0`, one tap `kv-<box id>` per box, IP allocation\n * inside the subnet. Everything that needs root goes through one script,\n * `net-setup.sh`, which re-execs itself with `sudo -n` when run from here.\n * `install-server.sh` installs a root-owned copy at PRIVILEGED_SCRIPT plus a\n * sudoers rule for exactly that path; the package copy is the dev fallback.\n */\nimport { randomInt } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { Config } from \"./config.js\";\nimport { run } from \"./exec.js\";\n\nexport const TAP_PREFIX = \"kv-\";\nexport const PRIVILEGED_SCRIPT = \"/usr/local/lib/kvbox/net-setup.sh\";\n\ntype NetConfig = Pick<Config, \"bridge\" | \"subnet\" | \"gateway\">;\n\nexport function tapName(box: string): string {\n // Linux interface names are limited to 15 characters.\n return `${TAP_PREFIX}${box}`.slice(0, 15);\n}\n\n/** The script to run: KVBOX_NET_SETUP override, the root-owned install, else the package copy (dist/ or src/core/). */\nexport function netSetupScript(): string {\n const override = process.env[\"KVBOX_NET_SETUP\"];\n if (override) return override;\n if (existsSync(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;\n for (const rel of [\"../scripts/net-setup.sh\", \"../../scripts/net-setup.sh\"]) {\n const candidate = fileURLToPath(new URL(rel, import.meta.url));\n if (existsSync(candidate)) return candidate;\n }\n throw new KvboxError(\"net-setup.sh not found next to kvbox-server\");\n}\n\nexport function bridgeExists(bridge: string): boolean {\n return existsSync(`/sys/class/net/${bridge}`);\n}\n\nfunction netRun(cfg: NetConfig, args: string[]) {\n return run([netSetupScript(), ...args], {\n env: { ...process.env, KVBOX_BRIDGE: cfg.bridge, KVBOX_SUBNET: cfg.subnet, KVBOX_GATEWAY: cfg.gateway },\n }).catch((err: Error) => {\n throw new KvboxError(\n `${err.message}\\n (root is needed for host networking; install-server.sh sets up a sudoers rule for ${PRIVILEGED_SCRIPT})`,\n );\n });\n}\n\n/** The host's end of a relay tunnel (core/relay.ts, #50): `relay up <conf> | down`, root via the script. */\nexport async function netSetup(cfg: NetConfig, args: string[]): Promise<void> {\n await netRun(cfg, args);\n}\n\n/** Run `net-setup.sh up` when the bridge is missing, which is the case after every host reboot. */\nexport async function ensureHostNetwork(cfg: NetConfig): Promise<\"present\" | \"created\"> {\n if (bridgeExists(cfg.bridge)) return \"present\";\n await netRun(cfg, [\"up\"]);\n return \"created\";\n}\n\n/** The box behind a tap: the tap lets it send as this IP and MAC only (#98, a link trusts the source IP). */\nexport interface TapBox {\n id: string;\n ip: string;\n mac: string;\n}\n\n/**\n * Create the box's tap (owned by this user) and return its name. Plugged into the bridge unless\n * `detached`: a box restored from a snapshot still carries the source box's MAC and IP, so its tap\n * stays off the switch until kvbox-agent has given it its own (attachTap).\n */\nexport async function createTap(box: TapBox, cfg: NetConfig, opts: { detached?: boolean } = {}): Promise<string> {\n const tap = tapName(box.id);\n await netRun(cfg, [\"tap\", \"add\", tap, box.ip, box.mac, ...(opts.detached ? [\"detached\"] : [])]);\n return tap;\n}\n\nexport async function attachTap(box: TapBox, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"tap\", \"attach\", tapName(box.id), box.ip, box.mac]);\n}\n\n/** Pin a tap already on the bridge (a box running from before the pin, #98); `attachTap` pins the others. */\nexport async function pinTap(box: TapBox, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"tap\", \"pin\", tapName(box.id), box.ip, box.mac]);\n}\n\nexport async function deleteTap(box: string, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"tap\", \"del\", tapName(box)]);\n}\n\n// ── public ports (#49) ────────────────────────────────────────────────────────\n/** Where a box's public SSH port is drawn from: high, random, and never 22 (which every bot scans). */\nexport const SSH_PORT_MIN = 20000;\nexport const SSH_PORT_MAX = 60000;\n\n/**\n * A random port in [SSH_PORT_MIN, SSH_PORT_MAX] that is not in `taken` (other boxes' ports and\n * whatever listens on the host). Random so two boxes never get adjacent, guessable ports; after\n * a few unlucky draws it walks the range from a random start so a crowded host still gets one.\n */\nexport function pickSshPort(taken: ReadonlySet<number>): number {\n const span = SSH_PORT_MAX - SSH_PORT_MIN + 1;\n for (let i = 0; i < 32; i++) {\n const port = SSH_PORT_MIN + randomInt(span);\n if (!taken.has(port)) return port;\n }\n const start = randomInt(span);\n for (let i = 0; i < span; i++) {\n const port = SSH_PORT_MIN + ((start + i) % span);\n if (!taken.has(port)) return port;\n }\n throw new KvboxError(`no free port left between ${SSH_PORT_MIN} and ${SSH_PORT_MAX} on this host`);\n}\n\n/** Local ports out of `ss -ltnH` / `ss -lunH` output (one socket per line, the address in the 4th column). */\nexport function parseListeningPorts(ssOutput: string): Set<number> {\n const ports = new Set<number>();\n for (const line of ssOutput.split(\"\\n\")) {\n const cols = line.trim().split(/\\s+/);\n const local = cols[3];\n if (!local) continue;\n const port = Number(local.slice(local.lastIndexOf(\":\") + 1));\n if (Number.isInteger(port) && port > 0) ports.add(port);\n }\n return ports;\n}\n\n/**\n * TCP and UDP ports something on the host listens on right now, so a box's public port never\n * shadows one: a UDP forward drawn onto, say, WireGuard's random port would swallow the relay tunnel.\n * One set for both protocols: a port either one uses is not drawn.\n */\nexport async function listeningPorts(): Promise<Set<number>> {\n const ports = new Set<number>();\n for (const flags of [\"-ltnH\", \"-lunH\"]) {\n try {\n for (const port of parseListeningPorts((await run([\"ss\", flags])).stdout)) ports.add(port);\n } catch {\n // no ss: the draw still avoids other boxes' ports\n }\n }\n return ports;\n}\n\nexport interface Proxy {\n /** Box id; the rules are tagged `kvbox:<id>` so `status` and `down` find them. */\n box: string;\n boxIp: string;\n hostPort: number;\n guestPort: number;\n /** tcp unless said otherwise (#30 publishes UDP too). */\n proto?: \"tcp\" | \"udp\";\n}\n\nconst proxyArgs = (p: Proxy) => [p.box, p.boxIp, String(p.hostPort), String(p.guestPort), p.proto ?? \"tcp\"];\n\n/** DNAT `hostPort` on every non-bridge interface of the host to `boxIp:guestPort`. Idempotent. */\nexport async function openProxy(proxy: Proxy, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"proxy\", \"add\", ...proxyArgs(proxy)]);\n}\n\nexport interface Link {\n /** The target box's id: the rule is tagged `kvbox:<id>`, like its forwards. */\n box: string;\n fromIp: string;\n toIp: string;\n port: number;\n}\n\nconst linkArgs = (l: Link) => [l.box, l.fromIp, l.toIp, String(l.port)];\n\n/** Let `fromIp` open TCP connections to `toIp:port` through the host (#98). Idempotent. */\nexport async function openLink(link: Link, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"link\", \"add\", ...linkArgs(link)]);\n}\n\n/** Remove what `openLink` added, and its open connections; nothing to remove is fine. */\nexport async function closeLink(link: Link, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"link\", \"rm\", ...linkArgs(link)]);\n}\n\n/** Remove what `openProxy` added; nothing to remove is fine. */\nexport async function closeProxy(proxy: Proxy, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"proxy\", \"rm\", ...proxyArgs(proxy)]);\n}\n\n// ── addresses ────────────────────────────────────────────────────────────────\nconst ipToInt = (ip: string) => ip.split(\".\").reduce((acc, o) => (acc << 8) + Number(o), 0) >>> 0;\nconst intToIp = (n: number) => [24, 16, 8, 0].map((s) => (n >>> s) & 255).join(\".\");\n\n/** Lowest free host address in `subnet` (a.b.c.d/len), skipping network, gateway (.1) and broadcast. */\nexport function nextFreeIp(subnet: string, inUse: readonly string[]): string {\n const [base, lenStr] = subnet.split(\"/\");\n const len = Number(lenStr);\n if (!base || !Number.isInteger(len) || len < 8 || len > 30) throw new KvboxError(`bad subnet: ${subnet}`);\n const mask = len === 0 ? 0 : (~0 << (32 - len)) >>> 0;\n const network = (ipToInt(base) & mask) >>> 0;\n const broadcast = (network | (~mask >>> 0)) >>> 0;\n const used = new Set(inUse.map(ipToInt));\n for (let n = network + 2; n < broadcast; n++) {\n if (!used.has(n)) return intToIp(n);\n }\n throw new KvboxError(`no free IP left in ${subnet}`);\n}\n\n/** Locally administered MAC derived from the IP: 06:00:<a>:<b>:<c>:<d>, unique per box and readable. */\nexport function macFor(ip: string): string {\n const hex = ip.split(\".\").map((o) => Number(o).toString(16).padStart(2, \"0\").toUpperCase());\n return [\"06\", \"00\", ...hex].join(\":\");\n}\n","/**\n * Box backups on the host (decision \"Backups: encrypted 4 MiB chunks in object storage\"; format in\n * `@kvbox/shared/backup`). The control plane drives every step and holds every key; the host never\n * holds bucket credentials, only the signed URLs it is handed for one backup or one restore.\n *\n * 1. `stageBackup`: the box's disk is copied into backups/<id>/ (a running box is paused for the copy,\n * like a snapshot, so the copy is one instant), then cut into slots and each slot named. The answer\n * is the list of names: the control plane works out which ones the bucket lacks.\n * 2. `uploadBackup`: those chunks, sealed, go to the signed PUT URLs; the staging dir goes.\n * 3. `restoreBackup`: the reverse, beside the box's disk while the box keeps running; then the box is\n * stopped, the disk swapped in and the box started again (`replaceDisk`).\n *\n * `downloadDisk` and `stageBackup` know nothing about which box the disk ends up in, so moving a box to\n * another host is a backup here and a download there.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, open, readdir, readFile, rm, stat, statfs, writeFile } from \"node:fs/promises\";\nimport { basename, join } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport type { HostBackupManifest, HostBackupRequest, HostRestoreRequest, HostUploadRequest, HostUploadResult, HostVolumeBackupManifest, HostVolumeRestoreRequest, Machine, Volume } from \"@kvbox/shared/api\";\nimport { BACKUP_ID_RE, backupKeys, CHUNK_HASH_RE, CHUNK_SIZE, chunkCount, chunkName, isZero, openChunk, openText, sealChunk, sealText, type BackupKeys } from \"@kvbox/shared/backup\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { loadConfig } from \"./config.js\";\nimport { checkBoxEnv, readBoxEnvFile } from \"./env.js\";\nimport { cloneDisk } from \"./clone.js\";\nimport { FirecrackerClient } from \"./firecracker.js\";\nimport { imageFile, imageLabel } from \"./images.js\";\nimport { withBoxLock, withHostLock } from \"./locks.js\";\nimport { recordState, replaceDisk, replaceVolumeDisk } from \"./machines.js\";\nimport { refKey, shown, type BoxRef } from \"./refs.js\";\nimport { listMachineRefs, listVolumeRefs, readMachineMeta, vmAlive, writeMachineMeta, type MachineMeta } from \"./state.js\";\nimport { chunkFetcher } from \"./storeFetch.js\";\nimport { attachedBox, readVolume } from \"./volumes.js\";\n\n/** Chunks in flight at once, each way. */\nconst PARALLEL = 4;\n/** Tries per chunk before the whole upload or download gives up. */\nconst TRIES = 4;\n/** How long one chunk's request may take. */\nconst CHUNK_TIMEOUT_MS = 120_000;\n\n/**\n * Refuse a copy of `bytes` into `dir` that would leave the filesystem every box's disk lives on with\n * less than config.json `volumeHeadroomGib` free: a full disk fails other boxes' writes.\n */\nasync function assertRoom(dir: string, bytes: number, what: string, p: Paths): Promise<void> {\n const st = await statfs(dir);\n const free = st.bavail * st.bsize;\n const headroom = (await loadConfig(p)).volumeHeadroomGib * 1024 ** 3;\n if (free - bytes < headroom) {\n const gib = (n: number) => (n / 1024 ** 3).toFixed(1);\n const needs = bytes === 0 ? \"cannot be made:\" : `needs ${gib(bytes)} GiB and`;\n throw new KvboxError(`${what} ${needs} this host has ${gib(free)} GiB free (keeping ${gib(headroom)} GiB spare); try again when it has room`);\n }\n}\n\nfunction checkId(id: string): void {\n if (!BACKUP_ID_RE.test(id)) throw new KvboxError(`not a backup id: ${id}`);\n}\n\nasync function readBox(ref: BoxRef, p: Paths): Promise<MachineMeta> {\n try {\n return await readMachineMeta(ref, p);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") throw new NotFoundError(`box ${shown(ref)}`);\n throw err;\n }\n}\n\n/** Every chunk name of a disk file, in slot order; null for a slot of zeros. */\nexport async function chunkNames(file: string, keys: BackupKeys): Promise<{ sizeBytes: number; chunks: (string | null)[] }> {\n const { size } = await stat(file);\n const chunks: (string | null)[] = [];\n const fh = await open(file, \"r\");\n try {\n const buf = Buffer.alloc(CHUNK_SIZE);\n for (let i = 0; i < chunkCount(size); i++) {\n const slot = await readSlot(fh, buf, i, size);\n chunks.push(isZero(slot) ? null : chunkName(keys, slot));\n }\n } finally {\n await fh.close();\n }\n return { sizeBytes: size, chunks };\n}\n\nasync function readSlot(fh: Awaited<ReturnType<typeof open>>, buf: Buffer, index: number, size: number): Promise<Buffer> {\n const length = Math.min(CHUNK_SIZE, size - index * CHUNK_SIZE);\n let got = 0;\n while (got < length) {\n const { bytesRead } = await fh.read(buf, got, length - got, index * CHUNK_SIZE + got);\n if (bytesRead === 0) break;\n got += bytesRead;\n }\n return buf.subarray(0, length);\n}\n\n/**\n * Step 1: clone the box's disk into the backup's own dir and name its chunks. Under the box's lock while\n * the clone is made; a running box is frozen for it only (a moment: `cloneDisk`), so what is uploaded is\n * the disk of one instant, like after a power cut.\n */\nexport async function stageBackup(ref: BoxRef, req: HostBackupRequest, p: Paths = paths()): Promise<HostBackupManifest> {\n checkId(req.id);\n const keys = backupKeys(req.key);\n const s = p.backup(req.id);\n await rm(s.dir, { recursive: true, force: true });\n await mkdir(s.dir, { recursive: true, mode: 0o700 });\n try {\n const { meta, envText } = await withBoxLock(ref, async () => {\n const meta = await readBox(ref, p);\n const m = p.machine(meta.owner, meta.name);\n // The copy is a reflink clone (core/clone.ts; a host that cannot make one takes no backups), which\n // takes almost no room when it is made: only the headroom has to be free, for what the clone grows\n // by while the box keeps writing during the upload (#185).\n await assertRoom(s.dir, 0, `a backup of box ${shown(ref)}`, p);\n await frozenClone(meta, m.overlay, s.disk, p);\n const envText = existsSync(m.env) ? await readFile(m.env, \"utf8\") : null;\n return { meta, envText };\n });\n const { sizeBytes, chunks } = await chunkNames(s.disk, keys);\n await writeFile(s.chunks, JSON.stringify({ chunks }), { mode: 0o600 });\n return {\n id: req.id,\n sizeBytes,\n chunks,\n env: envText === null ? null : sealText(keys, envText, `env:${req.id}`),\n base: meta.base,\n ...(meta.image !== undefined ? { image: meta.image } : {}),\n vcpu: meta.vcpu,\n memMib: meta.memMib,\n };\n } catch (err) {\n await rm(s.dir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/** Clone `from` to `to` as one instant of it: a running box that writes to it is paused for the clone. */\nasync function frozenClone(box: MachineMeta, from: string, to: string, p: Paths): Promise<void> {\n if (!vmAlive(box) || box.paused) return cloneDisk(from, to);\n const fc = new FirecrackerClient(p.machine(box.owner, box.name).sock);\n try {\n await fc.pause();\n try {\n await cloneDisk(from, to);\n } finally {\n await resumeAfterCopy(fc, box, p);\n }\n } finally {\n await fc.close();\n }\n}\n\n/**\n * A volume's backup, step 1 (#168): the same as a box's, of the volume's disk. The box that holds the\n * volume is the one that writes to it, so the clone is made under that box's lock, with that box paused\n * when it runs; a detached volume is cloned under the host lock an attach claims under. Steps 2 and 3 of\n * the upload are a box's (`uploadBackup`, `dropBackup`): a staged disk does not know what it came from.\n */\nexport async function stageVolumeBackup(ref: BoxRef, req: HostBackupRequest, p: Paths = paths()): Promise<HostVolumeBackupManifest> {\n checkId(req.id);\n const keys = backupKeys(req.key);\n await readVolume(ref, p);\n const from = p.volume(ref.owner, ref.name).disk;\n const s = p.backup(req.id);\n await rm(s.dir, { recursive: true, force: true });\n await mkdir(s.dir, { recursive: true, mode: 0o700 });\n try {\n await assertRoom(s.dir, 0, `a backup of volume ${shown(ref)}`, p);\n const holder = await attachedBox(ref, p);\n if (holder === null) {\n await withHostLock(\"volumes\", async () => {\n const now = await attachedBox(ref, p);\n if (now !== null) throw new KvboxError(`volume ${shown(ref)} was just attached to box ${now}; try again`);\n await cloneDisk(from, s.disk);\n });\n } else {\n const box: BoxRef = { owner: ref.owner, name: holder };\n await withBoxLock(box, async () => {\n const meta = await readBox(box, p);\n if (!meta.volumes?.includes(ref.name)) throw new KvboxError(`volume ${shown(ref)} was just detached from box ${holder}; try again`);\n await frozenClone(meta, from, s.disk, p);\n });\n }\n const { sizeBytes, chunks } = await chunkNames(s.disk, keys);\n await writeFile(s.chunks, JSON.stringify({ chunks }), { mode: 0o600 });\n return { id: req.id, sizeBytes, chunks };\n } catch (err) {\n await rm(s.dir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/**\n * A box frozen for its copy runs again. Tried twice; a box whose Firecracker is still alive but will not\n * resume is marked paused (meta.json and the usage ledger, like `kvbox pause`), so listings show it frozen\n * and `kvbox resume` can try again. One whose Firecracker died is left to show as stopped. Either way the\n * backup fails.\n */\nasync function resumeAfterCopy(fc: FirecrackerClient, meta: MachineMeta, p: Paths): Promise<void> {\n try {\n await fc.resume();\n } catch {\n try {\n await fc.resume();\n } catch (err) {\n const why = (err as Error).message;\n if (!vmAlive(meta)) throw new KvboxError(`box ${shown(meta)} stopped while its disk was copied for the backup (${why}); kvbox start ${shown(meta)}`);\n const paused: MachineMeta = { ...meta, paused: true };\n await writeMachineMeta(paused, p);\n recordState(paused, \"standby\", \"backup\", p);\n throw new KvboxError(`box ${shown(meta)} was paused for its backup and did not resume (${why}); kvbox resume ${shown(meta)}`);\n }\n }\n}\n\n/**\n * Step 2: seal and PUT each chunk the control plane asked for (the ones the bucket lacks), then drop\n * the staging dir. A chunk that fails is tried again a few times; one that keeps failing fails the\n * whole upload and leaves the dir for the control plane's `DELETE /backups/:id`.\n */\n/** Uploads in flight, by backup id: `dropBackup` aborts one, so a dropped backup stops putting chunks no row will count. */\nconst uploads = new Map<string, AbortController>();\n\nexport async function uploadBackup(id: string, req: HostUploadRequest, p: Paths = paths()): Promise<HostUploadResult> {\n checkId(id);\n const abort = new AbortController();\n uploads.get(id)?.abort();\n uploads.set(id, abort);\n try {\n return await uploadOnce(id, req, abort.signal, p);\n } finally {\n if (uploads.get(id) === abort) uploads.delete(id);\n }\n}\n\nasync function uploadOnce(id: string, req: HostUploadRequest, signal: AbortSignal, p: Paths): Promise<HostUploadResult> {\n const s = p.backup(id);\n if (!existsSync(s.chunks)) throw new NotFoundError(`backup ${id}`);\n const keys = backupKeys(req.key);\n const { chunks } = JSON.parse(await readFile(s.chunks, \"utf8\")) as { chunks: (string | null)[] };\n const slotOf = new Map<string, number>();\n chunks.forEach((name, i) => {\n if (name !== null && !slotOf.has(name)) slotOf.set(name, i);\n });\n const work = Object.entries(req.urls).map(([name, url]) => {\n const index = slotOf.get(name);\n if (index === undefined) throw new KvboxError(`backup ${id} has no chunk ${name.slice(0, 12)}`);\n return { name, url, index };\n });\n const { size } = await stat(s.disk);\n const fetchChunk = await chunkFetcher(req.pin, work[0]?.url, p);\n const fh = await open(s.disk, \"r\");\n let bytes = 0;\n const sizes: Record<string, number> = {};\n try {\n await pool(work, async ({ name, url, index }) => {\n const slot = Buffer.from(await readSlot(fh, Buffer.alloc(CHUNK_SIZE), index, size));\n const sealed = await sealChunk(keys, name, slot);\n await withTries(`upload of chunk ${index}`, async () => {\n const res = await fetchChunk(url, { method: \"PUT\", body: sealed, signal: AbortSignal.any([signal, AbortSignal.timeout(CHUNK_TIMEOUT_MS)]) });\n if (!res.ok) throw new Error(`storage answered ${res.status}: ${(await res.text()).slice(0, 200)}`);\n }, signal);\n bytes += sealed.length;\n sizes[name] = sealed.length;\n });\n } finally {\n await fh.close();\n }\n await rm(s.dir, { recursive: true, force: true });\n return { chunks: work.length, bytes, sizes };\n}\n\n/** A backup the control plane gave up on: its staging dir goes. Nothing there is not fine. */\nexport async function dropBackup(id: string, p: Paths = paths()): Promise<void> {\n checkId(id);\n uploads.get(id)?.abort();\n await rm(p.backup(id).dir, { recursive: true, force: true });\n}\n\n/**\n * Backups and restores a daemon restart cut short: nothing will upload the staged copies, and a half\n * downloaded disk (with the box's variables in the clear beside it) will never be swapped in.\n */\nexport async function clearStagedBackups(p: Paths = paths()): Promise<void> {\n await rm(p.backups, { recursive: true, force: true });\n const prefix = basename(p.machine(\"x\", \"x\").restoring);\n for (const ref of await listMachineRefs(p)) {\n const dir = p.machine(ref.owner, ref.name).dir;\n for (const f of await readdir(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm(join(dir, f), { force: true });\n }\n const volumePrefix = basename(p.volume(\"x\", \"x\").restoring);\n for (const ref of await listVolumeRefs(p)) {\n const dir = p.volume(ref.owner, ref.name).dir;\n for (const f of await readdir(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await rm(join(dir, f), { force: true });\n }\n}\n\n/**\n * A disk of `sizeBytes` at `file`, made from chunks at signed GET URLs: each is opened with the slug's\n * key and checked against its name before it is written into its slot. Slots not listed stay holes\n * (zeros). Throws, leaving `file` for the caller to remove, when a chunk cannot be fetched or opened.\n */\nexport async function downloadDisk(file: string, req: Pick<HostRestoreRequest, \"key\" | \"sizeBytes\" | \"chunks\" | \"pin\">, p: Paths = paths()): Promise<void> {\n const keys = backupKeys(req.key);\n const slots = chunkCount(req.sizeBytes);\n for (const c of req.chunks) {\n if (c.index >= slots) throw new KvboxError(`chunk ${c.index} is past the end of a ${req.sizeBytes}-byte disk`);\n if (!CHUNK_HASH_RE.test(c.hash)) throw new KvboxError(`chunk ${c.index}: not a chunk name`);\n }\n const fetchChunk = await chunkFetcher(req.pin, req.chunks[0]?.url, p);\n await writeFile(file, \"\", { mode: 0o600 });\n const fh = await open(file, \"r+\");\n try {\n await fh.truncate(req.sizeBytes);\n await pool(req.chunks, async ({ index, hash, url }) => {\n const plain = await withTries(`download of chunk ${index}`, async () => {\n const res = await fetchChunk(url, { signal: AbortSignal.timeout(CHUNK_TIMEOUT_MS) });\n if (!res.ok) throw new Error(`storage answered ${res.status}`);\n return Buffer.from(await res.arrayBuffer());\n });\n const slot = await openChunk(keys, hash, plain);\n const want = Math.min(CHUNK_SIZE, req.sizeBytes - index * CHUNK_SIZE);\n if (slot.length !== want) throw new KvboxError(`chunk ${index}: ${slot.length} bytes where the disk has room for ${want}`);\n await fh.write(slot, 0, slot.length, index * CHUNK_SIZE);\n });\n } finally {\n await fh.close();\n }\n}\n\n/** Boxes with a restore in flight: one at a time per box, since the download runs outside the box's lock. */\nconst restoring = new Set<string>();\n/** Boxes holding a volume whose restore is in flight (how many such restores): the swap stops them, so they are busy too. */\nconst holding = new Map<string, number>();\n\n/** Whether a restore of the box, or of a volume it holds, is downloading or swapping right now. */\nexport function restoreRunning(ref: BoxRef): boolean {\n return restoring.has(refKey(ref)) || holding.has(refKey(ref));\n}\n\n/**\n * Step 3: the box's disk and own variables become the backup's. The download happens beside the\n * box's disk while it keeps running; only the swap stops it (`replaceDisk`). A second restore of the\n * same box while one runs is refused, and each restore downloads into a file of its own, so two\n * never write into one disk.\n */\nexport async function restoreBackup(ref: BoxRef, req: HostRestoreRequest, p: Paths = paths()): Promise<Machine> {\n checkId(req.id);\n const k = refKey(ref);\n if (restoring.has(k)) throw new KvboxError(`a restore of box ${shown(ref)} is already running; wait for it to finish`);\n restoring.add(k);\n try {\n return await restoreOnce(ref, req, p);\n } finally {\n restoring.delete(k);\n }\n}\n\nasync function restoreOnce(ref: BoxRef, req: HostRestoreRequest, p: Paths): Promise<Machine> {\n const meta = await readBox(ref, p);\n if (!vmAlive(meta) && existsSync(p.machine(ref.owner, ref.name).hibernateVmstate)) {\n throw new KvboxError(`box ${shown(ref)} is hibernated; its memory belongs to the disk it has: kvbox wake ${shown(ref)} or kvbox stop ${shown(ref)} first`);\n }\n if (!existsSync(imageFile(req.image, req.base, p))) {\n throw new KvboxError(`this backup stacks on ${imageLabel(req.image)} ${req.base}, which this host does not have`);\n }\n const keys = backupKeys(req.key);\n const m = p.machine(ref.owner, ref.name);\n // A backup of an earlier, bigger box of the name would make this one bigger than its plan allows.\n const current = (await stat(m.overlay)).size;\n if (req.sizeBytes > current) {\n const gb = (n: number) => `${Math.ceil(n / 1024 ** 3)}GB`;\n throw new KvboxError(`this backup's disk is ${gb(req.sizeBytes)} and box ${shown(ref)}'s is ${gb(current)}: kvbox vm rescale ${shown(ref)} --disk ${gb(req.sizeBytes)} first`);\n }\n const file = `${m.restoring}.${randomBytes(4).toString(\"hex\")}`;\n const envFile = `${file}.env`;\n try {\n let vars = null;\n if (req.env !== null) {\n // Checked like any box's variables before anything is swapped.\n await writeFile(envFile, openText(keys, req.env, `env:${req.id}`), { mode: 0o600 });\n vars = await readBoxEnvFile(envFile);\n checkBoxEnv(vars); // now, not after replaceDisk has shut the box down\n }\n await assertRoom(m.dir, req.chunks.length * CHUNK_SIZE, `a restore of box ${shown(ref)}`, p);\n await downloadDisk(file, req, p);\n return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);\n } finally {\n await rm(file, { force: true });\n await rm(envFile, { force: true });\n }\n}\n\n/**\n * A volume's restore (#168): its disk becomes the backup's. Like a box's: the download happens beside\n * the volume's disk while the box that holds it keeps running on the old one; only the swap stops that\n * box (`replaceVolumeDisk`). One at a time per volume.\n */\nexport async function restoreVolumeBackup(ref: BoxRef, req: HostVolumeRestoreRequest, p: Paths = paths()): Promise<Volume> {\n checkId(req.id);\n const k = `volume:${refKey(ref)}`;\n if (restoring.has(k)) throw new KvboxError(`a restore of volume ${shown(ref)} is already running; wait for it to finish`);\n restoring.add(k);\n const v = p.volume(ref.owner, ref.name);\n const file = `${v.restoring}.${randomBytes(4).toString(\"hex\")}`;\n let held: string | null = null;\n try {\n const meta = await readVolume(ref, p);\n // Said before anything is downloaded; `replaceVolumeDisk` checks again under the box's lock.\n const holder = await attachedBox(ref, p);\n if (holder !== null) {\n // Busy to the idle watch for the whole restore: a box it hibernated mid-download would refuse the swap.\n held = refKey({ owner: ref.owner, name: holder });\n holding.set(held, (holding.get(held) ?? 0) + 1);\n const box = await readBox({ owner: ref.owner, name: holder }, p);\n if (!vmAlive(box) && existsSync(p.machine(box.owner, box.name).hibernateVmstate)) {\n throw new KvboxError(`volume ${shown(ref)} is attached to box ${shown(box)}, which is hibernated; its memory belongs to the disks it has: kvbox wake ${shown(box)} or kvbox stop ${shown(box)} first`);\n }\n }\n // A backup of an earlier, bigger volume of the name would not fit in this one.\n if (req.sizeBytes > meta.sizeGib * 1024 ** 3) {\n const gib = Math.ceil(req.sizeBytes / 1024 ** 3);\n throw new KvboxError(`this backup's volume was ${gib} GB and volume ${shown(ref)} is ${meta.sizeGib} GB: kvbox volume grow ${shown(ref)} ${gib} first`);\n }\n await assertRoom(v.dir, req.chunks.length * CHUNK_SIZE, `a restore of volume ${shown(ref)}`, p);\n await downloadDisk(file, req, p);\n return await replaceVolumeDisk(ref, file, p);\n } finally {\n restoring.delete(k);\n if (held !== null) {\n const n = (holding.get(held) ?? 1) - 1;\n if (n > 0) holding.set(held, n);\n else holding.delete(held);\n }\n await rm(file, { force: true });\n }\n}\n\n/** Run `fn` over `items`, PARALLEL at a time; the first failure stops new work and is thrown. */\nasync function pool<T>(items: readonly T[], fn: (item: T) => Promise<void>): Promise<void> {\n let next = 0;\n let failed: unknown;\n const worker = async () => {\n while (failed === undefined && next < items.length) {\n const item = items[next++]!;\n try {\n await fn(item);\n } catch (err) {\n failed ??= err;\n }\n }\n };\n await Promise.all(Array.from({ length: Math.min(PARALLEL, items.length) }, worker));\n if (failed !== undefined) throw failed;\n}\n\nasync function withTries<T>(what: string, fn: () => Promise<T>, signal?: AbortSignal): Promise<T> {\n let last: unknown;\n for (let i = 0; i < TRIES; i++) {\n if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);\n try {\n return await fn();\n } catch (err) {\n if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);\n last = err;\n await sleep(250 * 2 ** i);\n }\n }\n throw new KvboxError(`${what} failed ${TRIES} times: ${(last as Error).message}`);\n}\n","/**\n * Box backups (decision \"Backups: encrypted 4 MiB chunks in object storage\"): the format both ends\n * agree on. A box's disk is cut into fixed CHUNK_SIZE slots; a slot of zeros is not stored, every\n * other one is named by a keyed hash of its contents and stored once per slug, so a backup only sends\n * the slots that changed since any earlier backup of the same slug.\n *\n * Keys: each slug has one random data key (the control plane keeps it sealed). Two keys come out of\n * it: one names chunks (HMAC-SHA256 of the plaintext, so equal data in two slugs never shares a name\n * and a name says nothing about the data), one encrypts them. The host gets the data key for the one\n * backup or restore it runs; the bucket only ever sees ciphertext.\n *\n * A stored chunk: [flag][12-byte nonce][AES-256-GCM ciphertext][16-byte tag]. `flag` says whether the\n * plaintext was deflated (data that does not shrink is stored raw); it and the chunk's name are the\n * GCM associated data, so a chunk swapped for another, or its flag flipped, fails to open.\n *\n * Pure node:crypto and node:zlib: the host encrypts and decrypts, the control plane only signs URLs.\n */\nimport { createCipheriv, createDecipheriv, createHmac, randomBytes } from \"node:crypto\";\nimport { promisify } from \"node:util\";\nimport { deflateRaw as deflateRawCb, inflateRaw as inflateRawCb, constants as zlib } from \"node:zlib\";\n\nconst deflateRaw = promisify(deflateRawCb);\nconst inflateRaw = promisify(inflateRawCb);\n\n/** One slot of a box's disk: 4 MiB. A disk writes blocks in place, so unchanged slots keep their hash. */\nexport const CHUNK_SIZE = 4 * 1024 * 1024;\n\n/** What a backup's `id` looks like (`bk_` and 12 characters): checked by the host before it names a directory with it. */\nexport const BACKUP_ID_RE = /^bk_[A-Za-z0-9_-]{12}$/;\n\n/** A chunk's name: 64 hex characters. */\nexport const CHUNK_HASH_RE = /^[0-9a-f]{64}$/;\n\nconst FLAG_RAW = 0x01;\nconst FLAG_DEFLATE = 0x02;\nconst NONCE = 12;\nconst TAG = 16;\n\nexport interface BackupKeys {\n /** Names chunks: HMAC-SHA256 of the plaintext. */\n name: Buffer;\n /** Encrypts chunks and the box's variables. */\n seal: Buffer;\n}\n\n/** The two working keys of a slug's 32-byte data key (base64 on the wire). */\nexport function backupKeys(dataKeyB64: string): BackupKeys {\n const dk = Buffer.from(dataKeyB64, \"base64\");\n if (dk.length !== 32) throw new Error(\"backup key: expected 32 bytes\");\n return {\n name: createHmac(\"sha256\", dk).update(\"kvbox-backup chunk-name v1\").digest(),\n seal: createHmac(\"sha256\", dk).update(\"kvbox-backup chunk-seal v1\").digest(),\n };\n}\n\n/** A new slug data key, base64. */\nexport function newBackupKey(): string {\n return randomBytes(32).toString(\"base64\");\n}\n\n/** Whether a slot holds nothing but zeros (never stored: it is a hole when restored). */\nexport function isZero(buf: Buffer): boolean {\n return buf.equals(zeros(buf.length));\n}\n\nlet zeroBuf = Buffer.alloc(0);\nfunction zeros(n: number): Buffer {\n if (zeroBuf.length < n) zeroBuf = Buffer.alloc(n);\n return zeroBuf.subarray(0, n);\n}\n\n/** A chunk's name: the keyed hash of its plaintext, hex. */\nexport function chunkName(keys: BackupKeys, plain: Buffer): string {\n return createHmac(\"sha256\", keys.name).update(plain).digest(\"hex\");\n}\n\n/** The stored form of a chunk named `name`: deflated when that helps, then sealed. */\nexport async function sealChunk(keys: BackupKeys, name: string, plain: Buffer): Promise<Buffer> {\n const packed = await deflateRaw(plain, { level: zlib.Z_BEST_SPEED });\n const [flag, body] = packed.length < plain.length ? [FLAG_DEFLATE, packed] : [FLAG_RAW, plain];\n return seal(keys.seal, Buffer.from([flag]), body, `${name}:${flag}`);\n}\n\n/**\n * The plaintext of a stored chunk, checked: it must open under the slug's key with its own name, and\n * hash back to that name. Anything else (another slug's chunk, a corrupted object) throws.\n */\nexport async function openChunk(keys: BackupKeys, name: string, stored: Buffer): Promise<Buffer> {\n if (stored.length < 1 + NONCE + TAG) throw new Error(`chunk ${name.slice(0, 12)}: too short to be one`);\n const flag = stored[0]!;\n if (flag !== FLAG_RAW && flag !== FLAG_DEFLATE) throw new Error(`chunk ${name.slice(0, 12)}: unknown format ${flag}`);\n const body = unseal(keys.seal, stored.subarray(1), `${name}:${flag}`, `chunk ${name.slice(0, 12)}`);\n const plain = flag === FLAG_DEFLATE ? await inflateRaw(body, { maxOutputLength: CHUNK_SIZE }) : body;\n if (chunkName(keys, plain) !== name) throw new Error(`chunk ${name.slice(0, 12)}: contents do not match its name`);\n return plain;\n}\n\n/** A box's own variables file (env.json), sealed for the backup row: base64. */\nexport function sealText(keys: BackupKeys, text: string, label: string): string {\n return seal(keys.seal, Buffer.alloc(0), Buffer.from(text, \"utf8\"), label).toString(\"base64\");\n}\n\nexport function openText(keys: BackupKeys, sealedB64: string, label: string): string {\n return unseal(keys.seal, Buffer.from(sealedB64, \"base64\"), label, label).toString(\"utf8\");\n}\n\nfunction seal(key: Buffer, prefix: Buffer, plain: Buffer, aad: string): Buffer {\n const nonce = randomBytes(NONCE);\n const cipher = createCipheriv(\"aes-256-gcm\", key, nonce);\n cipher.setAAD(Buffer.from(aad));\n const data = Buffer.concat([cipher.update(plain), cipher.final()]);\n return Buffer.concat([prefix, nonce, data, cipher.getAuthTag()]);\n}\n\nfunction unseal(key: Buffer, sealed: Buffer, aad: string, what: string): Buffer {\n if (sealed.length < NONCE + TAG) throw new Error(`${what}: too short`);\n const nonce = sealed.subarray(0, NONCE);\n const tag = sealed.subarray(sealed.length - TAG);\n const data = sealed.subarray(NONCE, sealed.length - TAG);\n try {\n const decipher = createDecipheriv(\"aes-256-gcm\", key, nonce);\n decipher.setAAD(Buffer.from(aad));\n decipher.setAuthTag(tag);\n return Buffer.concat([decipher.update(data), decipher.final()]);\n } catch {\n throw new Error(`${what}: does not open with this slug's backup key (changed or not this slug's)`);\n }\n}\n\n/** How many slots a disk of `bytes` has. */\nexport function chunkCount(bytes: number): number {\n return Math.ceil(bytes / CHUNK_SIZE);\n}\n","/**\n * The copy a backup is taken from (decision \"A backup's disk copy is a reflink clone or nothing…\"): a\n * clone, which the host's filesystem (XFS) makes in an instant and which takes no room until the\n * original changes. Where the filesystem cannot clone there is no backup: a full copy would freeze a\n * running box for as long as it takes (#157) and need the disk's whole size free.\n */\nimport { rm } from \"node:fs/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { run } from \"./exec.js\";\n\n/**\n * How long a clone may take: an instant, but a heavily fragmented disk of terabytes on XFS takes a while,\n * and the box stays paused for all of it. The full copy this replaced had the same bound.\n */\nexport const CLONE_TIMEOUT_MS = 600_000;\n\nexport async function cloneDisk(from: string, to: string, timeoutMs = CLONE_TIMEOUT_MS): Promise<void> {\n const started = Date.now();\n try {\n await run([\"cp\", \"--reflink=always\", from, to], { timeoutMs });\n } catch (err) {\n await rm(to, { force: true });\n if (Date.now() - started >= timeoutMs) {\n throw new KvboxError(`the instant copy of the disk took more than ${Math.round(timeoutMs / 1000)} s and was stopped; the box was paused for that long. Try again; if it keeps happening, the host's operator should look at its disk`);\n }\n const why = (err as Error).message;\n if (/failed to clone|not supported|cross-device|Invalid cross/i.test(why)) {\n throw new KvboxError(\"this host cannot take backups: its disk cannot make an instant copy of a box's disk (kvbox hosts keep their boxes on XFS); the host's operator has to move it to XFS\");\n }\n throw err;\n }\n}\n","/**\n * How a host reaches a backup store for a chunk (core/backups.ts). A store is another host's HTTPS\n * listener, whose certificate is self-signed: the control plane hands over that certificate's sha256\n * fingerprint (`pin`) with the signed URLs, and a connection is kept only when the peer presents it.\n * When the store is this very host, the connection goes to localhost instead of out to its public\n * address and back (through a relay, that is the whole uplink twice); the URL, and so the `Host` the\n * signature covers, stay as they were. Without a pin (a store with a public certificate) it is a plain fetch.\n */\nimport type { TLSSocket } from \"node:tls\";\nimport { Agent, buildConnector, fetch as pinnedFetch, type Dispatcher } from \"undici\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { loadConfig } from \"./config.js\";\n\nexport interface ChunkResponse {\n ok: boolean;\n status: number;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n}\nexport type ChunkFetch = (url: string, init: { method?: \"PUT\"; body?: Buffer; signal: AbortSignal }) => Promise<ChunkResponse>;\n\nconst dispatchers = new Map<string, Dispatcher>();\n\n/** One dispatcher per fingerprint (and per \"it is this host\"): full handshakes only, a resumed session has no certificate to check. */\nexport function storeDispatcher(pin: string, local: boolean): Dispatcher {\n const id = `${pin}|${local}`;\n const have = dispatchers.get(id);\n if (have) return have;\n const plain = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0, timeout: 10_000 });\n const connect: buildConnector.connector = (opts, cb) => {\n plain(local ? { ...opts, hostname: \"127.0.0.1\" } : opts, (err, socket) => {\n if (err || !socket) return cb(err ?? new Error(\"no socket\"), null);\n const tls = socket as TLSSocket;\n const got = typeof tls.getPeerCertificate === \"function\" ? tls.getPeerCertificate().fingerprint256 : undefined;\n if (got !== pin) {\n socket.destroy();\n return cb(new Error(\"the backup store's certificate is not the one the control plane knows (fingerprint mismatch)\"), null);\n }\n cb(null, socket);\n });\n };\n const agent = new Agent({ connect });\n dispatchers.set(id, agent);\n return agent;\n}\n\n/** The fetch for one backup's or one restore's URLs. */\nexport async function chunkFetcher(pin: string | undefined, sampleUrl: string | undefined, p: Paths = paths()): Promise<ChunkFetch> {\n if (pin === undefined) return (url, init) => fetch(url, init);\n const cfg = await loadConfig(p);\n const cp = cfg.controlPlane;\n let local = false;\n if (cfg.backupStore && cp && sampleUrl !== undefined) {\n const target = new URL(sampleUrl);\n local = target.hostname === cp.advertise && Number(target.port || 443) === cp.port;\n }\n const dispatcher = storeDispatcher(pin, local);\n return (url, init) => pinnedFetch(url, { ...init, dispatcher }) as Promise<ChunkResponse>;\n}\n","/**\n * The host's side of a relay (#50). A home host behind a router has no public address of its own;\n * a relay (a small public VM, set up with install-relay.sh) owns one for it and forwards it down a\n * WireGuard tunnel the host dials out. `kvbox-relay add` on the relay prints a join string; here it\n * becomes a wg-quick conf under relay/, which net-setup.sh installs as /etc/wireguard/kvbox.conf\n * and enables (root). config.json keeps what the rest of the server needs: the public IP `join`\n * advertises by default, the tunnel address, the endpoint. The private key stays in the conf.\n */\nimport { access, chmod, mkdir, rm, writeFile } from \"node:fs/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { decodeRelayJoin, RELAY_TUNNEL_GATEWAY, type RelayJoin } from \"@kvbox/shared/relay\";\nimport { loadConfig, saveConfig, type Relay } from \"./config.js\";\nimport { DEFAULT_HTTPS_PORT } from \"./controlPlane.js\";\nimport { netSetup } from \"./network.js\";\n\n/** The wg-quick conf for the host's end of the tunnel. */\nexport function relayConf(join: RelayJoin): string {\n return [\n \"# kvbox relay tunnel: made by `kvbox-server relay`, installed by net-setup.sh. Do not edit.\",\n \"[Interface]\",\n `PrivateKey = ${join.privateKey}`,\n `Address = ${join.tunnelIp}/32`,\n \"\",\n \"[Peer]\",\n `PublicKey = ${join.relayKey}`,\n `Endpoint = ${join.relay}`,\n // Only the relay's own tunnel address goes through the tunnel: the host keeps its normal internet\n // route, and the relay SNATs forwarded connections so their replies come back this way.\n `AllowedIPs = ${RELAY_TUNNEL_GATEWAY}/32`,\n // The router forgets an idle outbound mapping; a packet every 25 s keeps the relay able to reach us.\n \"PersistentKeepalive = 25\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Decode the join string, write the conf, bring the tunnel up (root via net-setup.sh), remember the relay. */\nexport async function useRelay(joinString: string, p: Paths = paths()): Promise<Relay> {\n const join = decodeRelayJoin(joinString);\n if (!join) throw new KvboxError(\"that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay\");\n const cfg = await loadConfig(p);\n if (cfg.relay && cfg.relay.name !== join.name) {\n throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox-server relay off first`);\n }\n // A re-issued string may carry another public IP; the control plane would keep calling the old one.\n if (cfg.relay && cfg.relay.publicIp !== join.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {\n throw new KvboxError(\n `${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join.publicIp}; run kvbox-server leave first, then join again`,\n );\n }\n await mkdir(p.relay, { recursive: true, mode: 0o700 });\n await writeFile(p.relayConf, relayConf(join), { mode: 0o600 });\n await chmod(p.relayConf, 0o600);\n // The root helper also lets the control plane's port in on the tunnel interface (a host firewall would drop it).\n await netSetup(cfg, [\"relay\", \"up\", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);\n const relay: Relay = { name: join.name, publicIp: join.publicIp, tunnelIp: join.tunnelIp, endpoint: join.relay };\n await saveConfig({ ...cfg, relay }, p);\n return relay;\n}\n\n/**\n * Put the tunnel's firewall rule back after a host reboot (#114). wg-quick@kvbox is enabled, so the\n * tunnel itself comes back on its own, but iptables rules are not persisted (and ufw rebuilds the tables\n * at boot): the INPUT rule letting the control plane's port in on the tunnel interface was gone, and\n * every box showed `unknown`. `relay up` is idempotent: the installed conf and an existing rule are\n * skipped, a live tunnel is only reloaded. Returns the relay, or null when the host has none.\n */\nexport async function restoreRelay(p: Paths = paths()): Promise<Relay | null> {\n const cfg = await loadConfig(p);\n if (!cfg.relay) return null;\n // The conf is what `relay up` installs; without it (removed by hand) there is nothing to re-apply.\n await access(p.relayConf);\n await netSetup(cfg, [\"relay\", \"up\", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);\n return cfg.relay;\n}\n\n/** Take the tunnel down and forget the relay. Refused while a control plane still reaches this host through it. */\nexport async function dropRelay(p: Paths = paths()): Promise<Relay> {\n const cfg = await loadConfig(p);\n const relay = cfg.relay;\n if (!relay) throw new KvboxError(\"this host does not go through a relay\");\n if (cfg.controlPlane?.advertise === relay.publicIp) {\n throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);\n }\n await netSetup(cfg, [\"relay\", \"down\"]);\n await rm(p.relayConf, { force: true });\n const { relay: _gone, ...rest } = cfg;\n await saveConfig(rest, p);\n return relay;\n}\n","/**\n * The relay join string (#50). A home host behind a router gets a public address through a relay:\n * a small public VM with one extra IPv4 per host and a WireGuard tunnel the host dials out. The\n * relay's `kvbox-relay add <name> --ip <public-ip>` (kvbox-relay.sh at the repo root, bash: it builds\n * the same base64url token) makes the host's keypair and prints this string once; the host's\n * `kvbox-server relay <string>` turns it into its tunnel. It carries the host's\n * private key, so it is a secret. The control plane never sees any of it: the host just advertises\n * the public IP.\n */\nimport { z } from \"zod\";\n\n/** Where WireGuard listens on the relay's primary address. */\nexport const RELAY_WG_PORT = 51820;\n/** The tunnel network: the relay is .1, hosts are .2 onwards. */\nexport const RELAY_TUNNEL_SUBNET = \"10.77.0.0/24\";\nexport const RELAY_TUNNEL_GATEWAY = \"10.77.0.1\";\n\nconst IPV4_RE = /^(\\d{1,3})(\\.\\d{1,3}){3}$/;\nconst WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;\n\nexport const RelayJoinSchema = z.object({\n v: z.literal(1),\n /** How the relay lists this host. */\n name: z.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),\n /** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */\n relay: z.string().regex(/^(\\d{1,3})(\\.\\d{1,3}){3}:\\d{1,5}$/),\n /** The relay's WireGuard public key. */\n relayKey: z.string().regex(WG_KEY_RE),\n /** This host's address inside the tunnel. */\n tunnelIp: z.string().regex(IPV4_RE),\n /** This host's WireGuard private key, generated on the relay, kept nowhere else. */\n privateKey: z.string().regex(WG_KEY_RE),\n /** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */\n publicIp: z.string().regex(IPV4_RE),\n});\nexport type RelayJoin = z.infer<typeof RelayJoinSchema>;\n\n/** The string the relay prints: base64url of the JSON, one token the owner can paste. */\nexport function encodeRelayJoin(join: RelayJoin): string {\n return Buffer.from(JSON.stringify(RelayJoinSchema.parse(join)), \"utf8\").toString(\"base64url\");\n}\n\n/** The string back into its fields, or null when it is not a relay join string. */\nexport function decodeRelayJoin(text: string): RelayJoin | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(text.trim(), \"base64url\").toString(\"utf8\"));\n } catch {\n return null;\n }\n const res = RelayJoinSchema.safeParse(parsed);\n return res.success ? res.data : null;\n}\n","/**\n * The host's side of the control plane (#18, design in the brain's multi-host doc). A host joins\n * exactly one control plane with a one-time token an admin minted there; it gets back a secret the\n * control plane will present on every call, and from its next start it also serves the API over\n * HTTPS. The control plane trusts the host by the fingerprint of the self-signed certificate made\n * here (no CA), so the certificate is generated once and kept for the host's life.\n */\nimport { X509Certificate } from \"node:crypto\";\nimport { chmod, mkdir, readFile } from \"node:fs/promises\";\nimport { hostname as osHostname } from \"node:os\";\nimport { request } from \"undici\";\nimport { parseCountry } from \"@kvbox/shared/country\";\nimport { HostJoinResponseSchema, HostSshCaResponseSchema, type CloudCa, type HostJoinRequest } from \"@kvbox/shared/api\";\nimport { parseSshPublicKey, sshKeyFingerprint } from \"@kvbox/shared/ssh\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { loadConfig, saveConfig } from \"./config.js\";\nimport { run } from \"./exec.js\";\nimport { REALM_RE } from \"./refs.js\";\n\nexport const DEFAULT_HTTPS_PORT = 7777;\n\n/** The certificate's sha256 fingerprint, `AA:BB:…`, the form the control plane pins. */\nexport interface TlsIdentity {\n fingerprint: string;\n}\n\n/** Generate `tls/key.pem` + `tls/cert.pem` on first use (openssl, EC P-256, 10 years); return the fingerprint either way. */\nexport async function ensureTlsCert(p: Paths = paths()): Promise<TlsIdentity> {\n const have = await readFile(p.tlsCert, \"utf8\").catch(() => null);\n const haveKey = await readFile(p.tlsKey).then(() => true, () => false);\n if (have === null || !haveKey) {\n await mkdir(p.tls, { recursive: true, mode: 0o700 });\n try {\n await run([\n \"openssl\", \"req\", \"-x509\", \"-newkey\", \"ec\", \"-pkeyopt\", \"ec_paramgen_curve:prime256v1\", \"-nodes\",\n \"-keyout\", p.tlsKey, \"-out\", p.tlsCert, \"-subj\", \"/CN=kvbox-host\", \"-days\", \"3650\",\n ]);\n } catch (err) {\n throw new KvboxError(`could not make the host's certificate (is openssl installed?): ${(err as Error).message}`);\n }\n await chmod(p.tlsKey, 0o600);\n }\n const pem = await readFile(p.tlsCert, \"utf8\");\n return { fingerprint: new X509Certificate(pem).fingerprint256 };\n}\n\nexport interface JoinOptions {\n /** The control plane, e.g. https://api.kvbox.sh. */\n url: string;\n /** One-time token an admin minted there. */\n token: string;\n /** Host or IP the control plane reaches this host at; default: the address of this host's default route. */\n advertise?: string;\n /** How the control plane lists this host; default: the hostname. */\n name?: string;\n /** Where this host is (`romania`, `RO`): `kvbox new --country` places boxes by it. */\n country?: string;\n port?: number;\n}\n\nexport interface Joined {\n hostName: string;\n controlPlane: string;\n /** Where the control plane will call this host: https://<advertise>:<port>. */\n hostUrl: string;\n}\n\n/** RFC 1918, loopback, link-local and carrier-grade NAT: addresses a control plane on the internet cannot reach. */\nexport function isPrivateAddress(ip: string): boolean {\n const m = /^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(ip);\n if (!m) return false;\n const [a, b] = [Number(m[1]), Number(m[2])];\n return a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);\n}\n\n/** The IPv4 this host would use to reach the internet: the `src` of the default route. */\nexport async function defaultAdvertise(): Promise<string> {\n const { stdout } = await run([\"ip\", \"-4\", \"route\", \"get\", \"1.1.1.1\"]).catch((err: Error) => {\n throw new KvboxError(`cannot tell this host's address (${err.message}); pass --advertise <host-or-ip>`);\n });\n const m = /\\bsrc\\s+(\\S+)/.exec(stdout);\n if (!m) throw new KvboxError(\"cannot tell this host's address from its routes; pass --advertise <host-or-ip>\");\n return m[1]!;\n}\n\n/**\n * Register this host with a control plane: make sure it has a certificate, send the join, keep the\n * secret in config.json. The server picks the HTTPS listener up at its next start.\n */\nexport async function joinControlPlane(opts: JoinOptions, p: Paths = paths(), guessAddress: () => Promise<string> = defaultAdvertise): Promise<Joined> {\n const url = opts.url.replace(/\\/+$/, \"\");\n const port = opts.port ?? DEFAULT_HTTPS_PORT;\n const cfg = await loadConfig(p);\n if (cfg.controlPlane) throw new KvboxError(`this host has already joined ${cfg.controlPlane.name} (${cfg.controlPlane.url}); run kvbox-server leave first`);\n let advertise = opts.advertise;\n if (advertise === undefined && cfg.relay) {\n // Behind a relay the host's own addresses are beside the point: the relay's public IP is where it is reached.\n advertise = cfg.relay.publicIp;\n } else if (advertise === undefined) {\n advertise = await guessAddress();\n if (isPrivateAddress(advertise)) {\n throw new KvboxError(\n `${advertise} is a private address: a control plane on the internet cannot reach this host there.\\n` +\n ` Pass --advertise <public host or ip>, or --advertise ${advertise} if the control plane is on the same network.`,\n );\n }\n }\n const name = opts.name ?? osHostname();\n const country = opts.country === undefined ? undefined : parseCountry(opts.country); // a typo fails here, before the token is spent\n const { fingerprint } = await ensureTlsCert(p);\n const hostUrl = `https://${advertise}:${port}`;\n const body: HostJoinRequest = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...(country !== undefined ? { country } : {}) };\n\n const res = await request(`${url}/hosts/join`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n headersTimeout: 10_000,\n bodyTimeout: 10_000,\n }).catch((err: Error) => {\n throw new KvboxError(`cannot reach ${url} (${err.message})`);\n });\n const text = await res.body.text();\n if (res.statusCode < 200 || res.statusCode >= 300) {\n throw new KvboxError(errorIn(text) ?? `control plane answered ${res.statusCode}`);\n }\n const parsed = HostJoinResponseSchema.safeParse(jsonOrNull(text));\n if (!parsed.success) throw new KvboxError(`${url} did not answer like a kvbox control plane`);\n if (!REALM_RE.test(parsed.data.controlPlane.name)) {\n throw new KvboxError(`${url} calls itself \"${parsed.data.controlPlane.name}\", which cannot name a realm (letters, digits, '.', '-')`);\n }\n\n await saveConfig({ ...cfg, controlPlane: { url, name: parsed.data.controlPlane.name, secret: parsed.data.hostSecret, advertise, port } }, p);\n return { hostName: name, controlPlane: parsed.data.controlPlane.name, hostUrl };\n}\n\n/**\n * Ask the joined control plane which SSH CA boxes should trust (`GET /hosts/self/ssh-ca`, by the\n * host secret), with its fingerprint, for `kvbox-server trust-ca --from-cloud` to show before\n * anything changes (#55).\n */\nexport async function fetchCloudCa(p: Paths = paths()): Promise<CloudCa> {\n const cfg = await loadConfig(p);\n const cp = cfg.controlPlane;\n if (!cp) throw new KvboxError(\"this host has not joined a control plane, so there is no CA to fetch; paste the key instead: kvbox-server trust-ca <public-key>\");\n const res = await request(`${cp.url}/hosts/self/ssh-ca`, {\n headers: { authorization: `Bearer ${cp.secret}` },\n headersTimeout: 10_000,\n bodyTimeout: 10_000,\n }).catch((err: Error) => {\n throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);\n });\n const text = await res.body.text();\n if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not answer /hosts/self/ssh-ca: it is older than this host; paste the key instead`);\n if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(errorIn(text) ?? `${cp.name} answered ${res.statusCode}`);\n const parsed = HostSshCaResponseSchema.safeParse(jsonOrNull(text));\n if (!parsed.success) throw new KvboxError(`${cp.name} did not answer with a CA key`);\n const publicKey = parseSshPublicKey(parsed.data.publicKey);\n return { controlPlane: cp.name, publicKey, fingerprint: sshKeyFingerprint(publicKey) };\n}\n\n/**\n * What the joined control plane calls itself now (`GET /health`, its `name`): the realm\n * `kvbox-server rename-realm` moves this host's cloud boxes to when no name is given.\n */\nexport async function fetchCloudName(p: Paths = paths()): Promise<string> {\n const cfg = await loadConfig(p);\n const cp = cfg.controlPlane;\n if (!cp) throw new KvboxError(\"this host has not joined a control plane, so there is no name to ask for; give it: kvbox-server rename-realm <name>\");\n const res = await request(`${cp.url}/health`, { headersTimeout: 10_000, bodyTimeout: 10_000 }).catch((err: Error) => {\n throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);\n });\n const text = await res.body.text();\n if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(`${cp.url} answered ${res.statusCode}`);\n const name = (jsonOrNull(text) as { name?: unknown } | null)?.name;\n if (typeof name !== \"string\" || !REALM_RE.test(name)) throw new KvboxError(`${cp.url} did not say its name; give it: kvbox-server rename-realm <name>`);\n return name;\n}\n\nexport interface Left {\n controlPlane: string;\n /** Whether the control plane acknowledged; false means an admin has to remove the host there. */\n told: boolean;\n}\n\n/** Forget the control plane (the HTTPS listener stops at the next start) and tell it so, best effort. */\nexport async function leaveControlPlane(p: Paths = paths()): Promise<Left> {\n const cfg = await loadConfig(p);\n const cp = cfg.controlPlane;\n if (!cp) throw new KvboxError(\"this host has not joined a control plane\");\n const told = await request(`${cp.url}/hosts/self`, {\n method: \"DELETE\",\n headers: { authorization: `Bearer ${cp.secret}` },\n headersTimeout: 3000,\n bodyTimeout: 3000,\n })\n .then(async (res) => {\n await res.body.dump();\n return res.statusCode >= 200 && res.statusCode < 300;\n })\n .catch(() => false);\n const { controlPlane: _gone, ...rest } = cfg;\n // A backup store stays set up, but the control plane no longer knows it: `backup setup` registers it again after a join.\n await saveConfig({ ...rest, ...(rest.backupStore ? { backupStore: { ...rest.backupStore, registered: false } } : {}) }, p);\n return { controlPlane: cp.name, told };\n}\n\nfunction jsonOrNull(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n\n/** The `{ error }` of a kvbox JSON answer, if that is what the text is. */\nfunction errorIn(text: string): string | undefined {\n const v = jsonOrNull(text);\n if (v && typeof v === \"object\" && typeof (v as { error?: unknown }).error === \"string\") return (v as { error: string }).error;\n return undefined;\n}\n","/**\n * Where a host is: an ISO 3166-1 alpha-2 code (`RO`, `US`). People type a code or an English name\n * (`romania`, `United States`, `usa`); Node's own ICU (`Intl.DisplayNames`) maps between the two, so\n * there is no table to keep.\n */\nimport { KvboxError } from \"./errors.js\";\n\nconst names = new Intl.DisplayNames([\"en\"], { type: \"region\", fallback: \"none\" });\n\n/** Region codes ICU knows that are not a country a host can be in. */\nconst NOT_COUNTRIES = new Set([\"EU\", \"EZ\", \"UN\", \"QO\", \"XA\", \"XB\", \"ZZ\"]);\n\n/** Common short names ICU's English names do not cover. */\nconst ALIASES: Record<string, string> = { usa: \"US\", america: \"US\", uk: \"GB\", britain: \"GB\", england: \"GB\", holland: \"NL\" };\n\nconst fold = (s: string) =>\n s\n .normalize(\"NFD\")\n .replace(/[̀-ͯ]/g, \"\")\n .toLowerCase()\n .replace(/[^a-z]/g, \"\");\n\nlet byName: Map<string, string> | undefined;\nfunction nameIndex(): Map<string, string> {\n if (byName) return byName;\n byName = new Map(Object.entries(ALIASES));\n for (let a = 65; a <= 90; a++) {\n for (let b = 65; b <= 90; b++) {\n const code = String.fromCharCode(a, b);\n const name = countryName(code);\n // a retired code (DD, UK, YU) shares or outlived its country's name: only current codes name one\n if (name !== undefined && canonical(code) === code) byName.set(fold(name), code);\n }\n }\n return byName;\n}\n\n/** ICU's current code for a retired one (UK -> GB, DD -> DE); the code itself otherwise. */\nfunction canonical(code: string): string {\n return /-([A-Z]{2})$/.exec(Intl.getCanonicalLocales(`und-${code}`)[0] ?? \"\")?.[1] ?? code;\n}\n\n/** The English name of a country code, or undefined when it is not one. */\nexport function countryName(code: string): string | undefined {\n if (!/^[A-Z]{2}$/.test(code) || NOT_COUNTRIES.has(code)) return undefined;\n return names.of(code);\n}\n\n/** `ro`, `RO`, `Romania`, `usa` -> the country code; a KvboxError for anything else. */\nexport function parseCountry(input: string): string {\n const t = input.trim();\n const upper = t.toUpperCase();\n const code = countryName(upper) !== undefined ? canonical(upper) : nameIndex().get(fold(t));\n if (code !== undefined) return code;\n throw new KvboxError(`unknown country \"${input}\": give its name or its two-letter code, e.g. RO or US`);\n}\n","/**\n * Auto-hibernate (#47): a box with `autoHibernateSec` whose tap has carried no traffic, either way, for\n * that long is hibernated, so the host gets its RAM back and the meter moves to the cheaper state.\n * `connect` and `exec` already wake a hibernated box, and their ssh sends a keepalive every minute, so a\n * quiet open session counts as traffic. Any byte counts as activity; CPU-only work with nobody connected\n * looks idle (the guest's own view comes with #67). Only running boxes are watched: one in standby was\n * paused on purpose, for an instant resume. When a box was last active is kept in memory only, so a\n * server restart gives every box its full timeout again.\n *\n * A box may decide itself (#102): one with an `idleCheck` (its image's `idle` by default, or `kvbox vm set\n * --idle-check`) is asked through kvbox-agent instead, and its answer alone counts (a GitHub runner's open\n * connection never goes quiet). An error, a timeout or an agent too old to know the request is a busy answer.\n */\nimport { readFile } from \"node:fs/promises\";\nimport type { Machine } from \"@kvbox/shared/api\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { idle as agentIdle } from \"./agent.js\";\nimport { restoreRunning } from \"./backups.js\";\nimport { boxBusy, withBoxLock } from \"./locks.js\";\nimport { getMachine, hibernateMachine, listMachines } from \"./machines.js\";\nimport { tapName } from \"./network.js\";\nimport { log as daemonLog } from \"./log.js\";\n\n/** Hibernations at once: each one dumps a box's whole memory to disk. */\nconst HIBERNATE_CONCURRENCY = 2;\n\nexport interface IdleWatchOptions {\n intervalMs?: number;\n /** Every box on the host. */\n list?: () => Promise<Machine[]>;\n /** rx + tx bytes of a box's tap; null when it cannot be read (no tap). */\n traffic?: (id: string) => Promise<number | null>;\n /** For a box with an idle check (#102): whether it says idle. null: no check, watch the traffic. A rejection is a busy answer. */\n guestIdle?: (box: Machine) => Promise<boolean | null>;\n /** Hibernate the box if it still runs; false when it no longer did. */\n hibernate?: (box: Machine) => Promise<boolean>;\n /** Whether a caller's operation holds the box right now. */\n busy?: (box: Machine) => boolean;\n now?: () => number;\n log?: (line: string) => void;\n p?: Paths;\n}\n\n/** Bytes the box's tap has moved in both directions since it was created. */\nexport async function tapTraffic(id: string): Promise<number | null> {\n const dir = `/sys/class/net/${tapName(id)}/statistics`;\n try {\n const [rx, tx] = await Promise.all([readFile(`${dir}/rx_bytes`, \"utf8\"), readFile(`${dir}/tx_bytes`, \"utf8\")]);\n return Number(rx) + Number(tx);\n } catch {\n return null;\n }\n}\n\n/** The box's idle check (#102), if it has one: asked through kvbox-agent. Rejects when the check could not answer. */\nasync function boxIdle(box: Machine, p: Paths): Promise<boolean | null> {\n if (box.idleCheck === undefined) return null;\n return agentIdle(p.machine(box.owner, box.name).vsock, box.idleCheck);\n}\n\n/** Under the box's lock: hibernate it unless something paused, stopped or hibernated it since the listing. */\nasync function hibernateIfRunning(box: Machine, p: Paths): Promise<boolean> {\n const ref = { owner: box.owner, name: box.name };\n return withBoxLock(ref, async () => {\n if ((await getMachine(ref, p)).status !== \"running\" || restoreRunning(ref)) return false;\n await hibernateMachine(ref, p, \"auto-hibernate\");\n return true;\n });\n}\n\n/**\n * Start watching; returns a stop function. Also returns `round` so tests can drive it without timers:\n * one check plus the hibernations it started. The timer runs only the check, so a long dump does not\n * hold back the next minute's check of every other box.\n */\nexport function startIdleWatch(opts: IdleWatchOptions = {}): { stop: () => void; round: () => Promise<void> } {\n const intervalMs = opts.intervalMs ?? 60_000;\n const p = opts.p ?? paths();\n const list = opts.list ?? (() => listMachines(null, p));\n const traffic = opts.traffic ?? tapTraffic;\n const guestIdle = opts.guestIdle ?? ((box: Machine) => boxIdle(box, p));\n const hibernate = opts.hibernate ?? ((box: Machine) => hibernateIfRunning(box, p));\n // A restore downloads outside the box's lock and refuses a hibernated box at the swap: busy too.\n const busy = opts.busy ?? ((box: Machine) => boxBusy(box) || restoreRunning(box));\n const now = opts.now ?? Date.now;\n const log = opts.log ?? ((line: string) => daemonLog.info(line));\n // box id -> the tap's byte count when it last changed (-1 for a box its own check watches), and when that was\n const seen = new Map<string, { bytes: number; since: number }>();\n // box id -> why its idle check last failed, so the log says it once rather than every minute\n const checkErrors = new Map<string, string>();\n let timer: NodeJS.Timeout | undefined;\n let stopped = false;\n\n // boxes being hibernated right now\n const inflight = new Set<string>();\n\n const hibernateOne = async (box: Machine, quiet: number, bytes: number, t: number) => {\n inflight.add(box.id);\n const byImage = bytes < 0;\n try {\n if (await hibernate(box)) log(`box ${box.owner}/${box.name}: ${byImage ? \"idle by its own check\" : \"no network traffic\"} for ${quiet} min; hibernated it (kvbox connect wakes it)`);\n seen.delete(box.id);\n } catch (err) {\n // Try again after another full timeout rather than every round.\n log(`warning: box ${box.owner}/${box.name}: could not hibernate it after ${quiet} min ${byImage ? \"idle\" : \"without traffic\"}: ${(err as Error).message}`);\n seen.set(box.id, { bytes, since: t });\n } finally {\n inflight.delete(box.id);\n }\n };\n\n /** The box's idle check answer; a failure is busy, logged once per reason. */\n const askIdle = (box: Machine): Promise<boolean | null> =>\n guestIdle(box).then(\n (v) => (checkErrors.delete(box.id), v),\n (err: Error) => {\n if (checkErrors.get(box.id) !== err.message) log(`warning: box ${box.owner}/${box.name}: its idle check ${box.idleCheck ?? \"\"} failed, so it counts as busy and does not hibernate: ${err.message}`);\n checkErrors.set(box.id, err.message);\n return false;\n },\n );\n\n const check = async (): Promise<Promise<void>[]> => {\n const started: Promise<void>[] = [];\n const watched = new Set<string>();\n const due: Machine[] = [];\n for (const box of await list()) {\n // A box other boxes link to waits for their TCP, which does not wake it (#98): it stays up.\n if (!box.autoHibernateSec || box.status !== \"running\" || box.links?.length) continue;\n if (inflight.has(box.id)) watched.add(box.id);\n else due.push(box);\n }\n // Every box's idle check at once: each may take up to 15 s, and one slow guest must not hold up the round.\n const verdicts = await Promise.all(due.map(askIdle));\n for (const [i, box] of due.entries()) {\n const verdict = verdicts[i] ?? null;\n const bytes = verdict === null ? await traffic(box.id) : -1;\n if (bytes === null) continue;\n watched.add(box.id);\n const t = now();\n const last = seen.get(box.id);\n // A caller working on the box (a snapshot, a resize) is activity too.\n if (!last || last.bytes !== bytes || verdict === false || busy(box)) {\n seen.set(box.id, { bytes, since: t });\n continue;\n }\n if (t - last.since < box.autoHibernateSec! * 1000) continue;\n if (inflight.size >= HIBERNATE_CONCURRENCY) continue; // next round: it stays due\n started.push(hibernateOne(box, Math.round((t - last.since) / 60_000), bytes, t));\n }\n // A box that slept, stopped or lost its timeout starts over when it is watched again.\n for (const id of seen.keys()) if (!watched.has(id)) seen.delete(id);\n for (const id of checkErrors.keys()) if (!watched.has(id)) checkErrors.delete(id);\n return started;\n };\n\n const round = async () => {\n await Promise.all(await check());\n };\n\n const schedule = () => {\n if (stopped) return;\n timer = setTimeout(() => void check().catch((err: Error) => log(`warning: idle watch: ${err.message}`)).finally(schedule), intervalMs);\n timer.unref();\n };\n schedule();\n return {\n stop: () => {\n stopped = true;\n clearTimeout(timer);\n },\n round,\n };\n}\n","/**\n * Keeps a relay tunnel (#50) carrying traffic. After the relay VM reboots, the home router can keep a\n * stale mapping for the tunnel's UDP flow: the relay still gets our handshakes, but nothing it sends\n * reaches us, and wg-quick never notices (seen 2026-10-26, every box went `unknown`). Restarting the\n * tunnel makes WireGuard dial from a new port, which the router maps afresh. So while the host uses\n * a relay, the server pings the relay's tunnel address and restarts the tunnel after a few misses.\n */\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { RELAY_TUNNEL_GATEWAY } from \"@kvbox/shared/relay\";\nimport { loadConfig } from \"./config.js\";\nimport { run } from \"./exec.js\";\nimport { netSetup } from \"./network.js\";\nimport { log as daemonLog } from \"./log.js\";\n\n/** What `/health` reports: restarts since this server started. */\nexport interface RelayWatchReport {\n restarts: number;\n lastRestartAt: string | null;\n}\n\nexport interface RelayWatchOptions {\n intervalMs?: number;\n /** Misses in a row before a restart. */\n misses?: number;\n /** Does the relay answer through the tunnel? */\n probe?: () => Promise<boolean>;\n restart?: () => Promise<void>;\n log?: (line: string) => void;\n p?: Paths;\n}\n\nlet report: RelayWatchReport = { restarts: 0, lastRestartAt: null };\n\nexport function relayWatchReport(): RelayWatchReport {\n return report;\n}\n\n/** One ICMP echo to the relay's end of the tunnel. */\nexport async function pingRelay(): Promise<boolean> {\n try {\n await run([\"ping\", \"-c\", \"1\", \"-W\", \"3\", RELAY_TUNNEL_GATEWAY], { timeoutMs: 5000 });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Start watching; returns a stop function. The config is read on every round, so `kvbox-server relay`\n * (no daemon restart) starts or ends the watching without telling us. While the relay itself is down\n * the tunnel is restarted every `misses` rounds; that costs nothing and only the first is logged.\n */\nexport function startRelayWatch(opts: RelayWatchOptions = {}): () => void {\n const intervalMs = opts.intervalMs ?? 30_000;\n const misses = opts.misses ?? 3;\n const probe = opts.probe ?? pingRelay;\n const p = opts.p ?? paths();\n const log = opts.log ?? ((line: string) => daemonLog.info(line));\n const restart = opts.restart ?? (async () => netSetup(await loadConfig(p), [\"relay\", \"restart\"]));\n report = { restarts: 0, lastRestartAt: null };\n let missed = 0;\n let stuck = false; // restarted, and the relay has not answered since\n let timer: NodeJS.Timeout | undefined;\n let stopped = false;\n\n const round = async () => {\n const cfg = await loadConfig(p).catch(() => null);\n if (!cfg?.relay) {\n missed = 0;\n return;\n }\n if (await probe()) {\n if (stuck) log(`relay ${cfg.relay.name}: the tunnel carries traffic again`);\n missed = 0;\n stuck = false;\n return;\n }\n if (++missed < misses) return;\n missed = 0;\n if (!stuck) log(`relay ${cfg.relay.name}: no answer through the tunnel for ${(misses * intervalMs) / 1000} s; restarting it`);\n try {\n await restart();\n report = { restarts: report.restarts + 1, lastRestartAt: new Date().toISOString() };\n } catch (err) {\n if (!stuck) daemonLog.warn(`relay ${cfg.relay.name}: could not restart the tunnel: ${(err as Error).message}`);\n }\n stuck = true;\n };\n\n const schedule = () => {\n if (stopped) return;\n timer = setTimeout(() => void round().catch((err: Error) => daemonLog.warn(`relay watch: ${err.message}`)).finally(schedule), intervalMs);\n timer.unref();\n };\n schedule();\n return () => {\n stopped = true;\n clearTimeout(timer);\n };\n}\n","/**\n * The daemon as a process, for the operator subcommands (`kvbox-server status|stop|start -d`, and the\n * restart after `join` / `leave`): is it running, stop it, start it in the background. Where\n * install-server.sh set up the systemd unit for this home (#29), the start goes through systemd, so the\n * server running is the one it keeps and brings back at boot; otherwise this binary spawns itself\n * detached with its output in server.log. Boxes are Firecracker processes of their own: none of this\n * touches them.\n */\nimport { spawn } from \"node:child_process\";\nimport { accessSync, constants, openSync, readFileSync, statSync } from \"node:fs\";\nimport { mkdir, readFile, stat } from \"node:fs/promises\";\nimport { userInfo } from \"node:os\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { hasUnitFor, startUnitProcess, UNIT, unitActive, unitPid } from \"@kvbox/shared/systemd\";\nimport { KVM_DEVICE } from \"./core/kvm.js\";\nimport { SocketClient } from \"./socketClient.js\";\n\n/** The pid in server.pid when that process exists, else null. */\nexport async function runningPid(p: Paths = paths()): Promise<number | null> {\n let pid: number;\n try {\n pid = Number.parseInt(await readFile(p.serverPid, \"utf8\"), 10);\n } catch {\n return null;\n }\n return Number.isInteger(pid) && alive(pid) ? pid : null;\n}\n\n/**\n * The daemon's pid: server.pid's when that process lives, else the systemd unit's when it serves this home\n * (a daemon whose pid file was deleted under it, #159, is still found, so status and stop can reach it).\n */\nexport async function daemonPid(p: Paths = paths()): Promise<number | null> {\n return (await runningPid(p)) ?? (hasUnitFor(p) ? unitPid() : null);\n}\n\n/**\n * Throws when another kvbox-server already serves this home (#159). A second daemon must never start: it\n * clears the staged backups, then takes the socket and pid file from the first, or, failing its HTTPS bind,\n * deletes them and leaves the first running but unreachable. Checked by every foreground start, before it\n * touches anything. This process's own pid does not count (a stale pid file from before a reboot may\n * name it, and under systemd the unit's pid is this process).\n */\nexport async function refuseSecondDaemon(p: Paths = paths()): Promise<void> {\n const live = await answering(p);\n if (live) throw new KvboxError(`kvbox-server is already running (pid ${live.pid}); kvbox-server status shows it`);\n const pid = await daemonPid(p);\n if (pid !== null && pid !== process.pid && isKvboxServer(pid)) {\n throw new KvboxError(`kvbox-server is already running (pid ${pid}) but its socket is gone, so nothing can reach it; restart it: kvbox-server stop, then kvbox-server start -d`);\n }\n}\n\n/**\n * A pid file outlives its process, and the pid may be reused by something else by now. argv[0] is left\n * out: it is the interpreter (node), whose own path may well contain \"kvbox\" (a runner on a kvbox box).\n */\nfunction isKvboxServer(pid: number): boolean {\n try {\n return readFileSync(`/proc/${pid}/cmdline`, \"utf8\").split(\"\\0\").slice(1).some((arg) => arg.includes(\"kvbox\"));\n } catch (err) {\n return (err as NodeJS.ErrnoException).code !== \"ENOENT\";\n }\n}\n\nfunction alive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** SIGTERM the daemon and resolve once the process is gone (boxes keep running; systemd does not restart a clean stop). */\nexport async function stopDaemon(pid: number, timeoutMs = 10_000): Promise<void> {\n process.kill(pid, \"SIGTERM\");\n const deadline = Date.now() + timeoutMs;\n while (alive(pid)) {\n if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1000}s`);\n await sleep(100);\n }\n}\n\nexport interface Started {\n pid: number;\n socketPath: string;\n /** The group `sg` switched to so the daemon can open /dev/kvm (#61); undefined for a plain start. */\n viaGroup: string | undefined;\n /** True when systemd started it (the unit install-server.sh wrote serves this home). */\n viaUnit: boolean;\n /** Set when a daemon already answered on the socket: nothing was started, this is its version. */\n alreadyRunning?: string;\n}\n\n/**\n * The daemon answering on this home's socket, else null. A second daemon must never start beside it:\n * before listening it clears the staged backups (a backup running in the first is lost), then takes the\n * socket and pid file, or, failing its HTTPS bind, deletes them and leaves the first unreachable.\n */\nexport async function answering(p: Paths = paths()): Promise<{ pid: number; version: string } | null> {\n if (!(await stat(p.serverSock).then(() => true, () => false))) return null;\n const probe = new SocketClient(p.serverSock);\n try {\n const health = await probe.health();\n return { pid: health.pid, version: health.version };\n } catch {\n return null;\n } finally {\n await probe.close();\n }\n}\n\n/**\n * Start the daemon in the background and resolve once its socket answers /health (or reject after\n * `timeoutMs`, or as soon as it exits); when one already answers, start nothing and return it. With the systemd unit for this home, `systemctl start` does it.\n * Without, this binary spawns itself (`start`), detached, stdout and stderr appended to server.log; through\n * `sg <group>` when this shell cannot open /dev/kvm but the user is in its group (#61).\n */\nexport async function startDetached(p: Paths = paths(), timeoutMs = 5000): Promise<Started> {\n await mkdir(p.home, { recursive: true });\n const running = await answering(p);\n if (running) return { pid: running.pid, socketPath: p.serverSock, viaGroup: undefined, viaUnit: false, alreadyRunning: running.version };\n if (hasUnitFor(p)) return startUnit(p, timeoutMs);\n const log = openSync(p.serverLog, \"a\");\n const launcher = selfLauncher();\n const child = spawn(launcher.cmd, launcher.args, { detached: true, stdio: [\"ignore\", log, log], env: { ...process.env, KVBOX_HOME: p.home } });\n\n const failed = new Promise<never>((_, reject) => {\n child.once(\"error\", (err: Error) => reject(new KvboxError(`could not start kvbox-server: ${err.message}`)));\n child.once(\"exit\", (code) => {\n void lastErrorLine(p.serverLog).then((why) => {\n reject(new KvboxError(why === undefined ? `kvbox-server exited with code ${String(code)} before listening; see ${p.serverLog}` : `kvbox-server could not start: ${why}`));\n });\n });\n });\n\n await Promise.race([serving(p, timeoutMs), failed]);\n child.removeAllListeners(\"exit\");\n child.unref();\n return { pid: await pidFile(p, child.pid ?? -1), socketPath: p.serverSock, viaGroup: launcher.viaGroup, viaUnit: false };\n}\n\n/** Stop the daemon when it runs, then start it: how a join or a leave takes effect. */\nexport async function restartDaemon(p: Paths = paths()): Promise<Started> {\n const pid = await runningPid(p);\n if (pid !== null) await stopDaemon(pid);\n return startDetached(p);\n}\n\nasync function startUnit(p: Paths, timeoutMs: number): Promise<Started> {\n const logFrom = await stat(p.serverLog).then((s) => s.size, () => 0);\n const res = startUnitProcess();\n if (!res.ok) {\n const why = res.out || (await lastErrorLine(p.serverLog, logFrom)) || \"systemctl start failed\";\n throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT}; rerun install-server.sh if sudo asked for a password)`);\n }\n await serving(p, timeoutMs, async () => {\n if (unitActive()) return;\n const why = (await lastErrorLine(p.serverLog, logFrom)) ?? \"it exited right after starting\";\n throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT})`);\n });\n return { pid: await pidFile(p, -1), socketPath: p.serverSock, viaGroup: undefined, viaUnit: true };\n}\n\n/** The pid the daemon wrote itself (the child here may be sg or systemd's), else `fallback`. */\nasync function pidFile(p: Paths, fallback: number): Promise<number> {\n const pid = Number.parseInt(await readFile(p.serverPid, \"utf8\").catch(() => \"\"), 10);\n return Number.isNaN(pid) ? fallback : pid;\n}\n\n/** Resolve once the socket answers /health; reject after `timeoutMs`, or when `check` throws (polled while waiting). */\nasync function serving(p: Paths, timeoutMs: number, check?: () => Promise<void>): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n await check?.();\n if (await stat(p.serverSock).then(() => true, () => false)) {\n const probe = new SocketClient(p.serverSock);\n try {\n await probe.health();\n return;\n } catch {\n // socket exists but not serving yet\n } finally {\n await probe.close();\n }\n }\n await sleep(100);\n }\n throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1000}s; see ${p.serverLog}`);\n}\n\n/**\n * The last error line of server.log, which is why a daemon that just died did not come up: a\n * `[time][error]: …` line (core/log.ts), or a plain `error: …` from an older server. `from`: only\n * what was written past that byte offset (this start's lines, not an earlier run's).\n */\nexport async function lastErrorLine(logPath: string, from = 0): Promise<string | undefined> {\n const text = (await readFile(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString(\"utf8\");\n for (const line of text.trimEnd().split(\"\\n\").slice(-20).reverse()) {\n const m = /^(?:\\[[^\\]]*\\])?\\[?error\\]?: (.*)$/.exec(line);\n if (m?.[1] !== undefined) return m[1];\n }\n return undefined;\n}\n\ninterface Launcher {\n cmd: string;\n args: string[];\n viaGroup?: string;\n}\n\n/**\n * The argv that runs this very binary's `start`: plain, or through `sg <group>` when this process cannot\n * open /dev/kvm but /etc/group says the user is in the device's group (#61: a shell from before the user\n * was added to the group hands its stale group list to everything it spawns). Anything else (no device,\n * user not in the group) is left to the daemon's own check, which explains it in plain words.\n */\nexport function selfLauncher(opts: { device?: string; groupFile?: string; user?: string } = {}): Launcher {\n const device = opts.device ?? KVM_DEVICE;\n const argv = [process.execPath, ...process.execArgv, process.argv[1] ?? \"kvbox-server\", \"start\"];\n const plain: Launcher = { cmd: argv[0]!, args: argv.slice(1) };\n try {\n accessSync(device, constants.R_OK | constants.W_OK);\n return plain;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"EACCES\" && code !== \"EPERM\") return plain;\n }\n let gid: number;\n try {\n gid = statSync(device).gid;\n } catch {\n return plain;\n }\n const group = groupWithMember(gid, opts.user ?? userInfo().username, opts.groupFile ?? \"/etc/group\");\n if (group === undefined) return plain;\n // sg runs a shell string: every word is single-quoted, so a path with a space or a quote survives.\n return { cmd: \"sg\", args: [group, \"-c\", argv.map(shellQuote).join(\" \")], viaGroup: group };\n}\n\nfunction shellQuote(word: string): string {\n return `'${word.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/** The name of the group with this gid when the group file lists `user` among its members, else undefined. */\nexport function groupWithMember(gid: number, user: string, groupFile: string): string | undefined {\n let text: string;\n try {\n text = readFileSync(groupFile, \"utf8\");\n } catch {\n return undefined;\n }\n for (const line of text.split(\"\\n\")) {\n const [name, , id, members = \"\"] = line.split(\":\");\n if (name === undefined || id === undefined || Number.parseInt(id, 10) !== gid) continue;\n return members.split(\",\").includes(user) ? name : undefined;\n }\n return undefined;\n}\n","/**\n * The systemd unit install-server.sh writes so kvbox-server starts at boot (#29): a system unit that\n * runs the server as the installing user. When it serves this KVBOX_HOME, the CLI starts the daemon\n * through it (`sudo -n`, the sudoers rule allows exactly that) instead of spawning one beside it.\n */\nimport { spawnSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { Paths } from \"./paths.js\";\n\nexport const UNIT = \"kvbox-server\";\nexport const UNIT_FILE = `/etc/systemd/system/${UNIT}.service`;\n\n/** True when the unit exists and runs the server on `p.home` (a dev or test KVBOX_HOME has none). */\nexport function hasUnitFor(p: Paths, file = UNIT_FILE): boolean {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch {\n return false;\n }\n const home = /^Environment=\"?KVBOX_HOME=([^\"\\n]+)\"?$/m.exec(text)?.[1];\n return home !== undefined && resolve(home) === resolve(p.home);\n}\n\n/** `sudo -n systemctl start kvbox-server`; what it said when it failed. */\nexport function startUnitProcess(): { ok: boolean; out: string } {\n const res = spawnSync(\"sudo\", [\"-n\", \"systemctl\", \"start\", UNIT], { encoding: \"utf8\" });\n return { ok: res.status === 0, out: `${res.stdout ?? \"\"}${res.stderr ?? \"\"}`.trim() };\n}\n\n/**\n * False once the unit's server has exited: systemd then shows it waiting to restart (\"activating\")\n * or given up (\"failed\"). `systemctl start` returns as soon as a Type=simple unit forks, so this is\n * how a server that dies right away is told apart from one still coming up.\n */\nexport function unitActive(): boolean {\n const res = spawnSync(\"systemctl\", [\"is-active\", UNIT], { encoding: \"utf8\" });\n return (res.stdout ?? \"\").trim() === \"active\";\n}\n\n/** The unit's running process, or null (no systemd, or the unit is not running). */\nexport function unitPid(): number | null {\n const res = spawnSync(\"systemctl\", [\"show\", UNIT, \"-p\", \"MainPID\", \"--value\"], { encoding: \"utf8\" });\n const pid = Number.parseInt((res.stdout ?? \"\").trim(), 10);\n return Number.isInteger(pid) && pid > 0 ? pid : null;\n}\n\n/** Whether the server comes back by itself after a reboot: the unit serves this home and is enabled. */\nexport function startsAtBoot(p: Paths): boolean {\n return hasUnitFor(p) && spawnSync(\"systemctl\", [\"is-enabled\", \"--quiet\", UNIT]).status === 0;\n}\n","/**\n * The operator subcommands' way to the running daemon: plain HTTP over its Unix socket, the API the CLI\n * speaks. `status` reads /health here; `trust-ca` goes through the socket rather than core because a box's\n * lock (core/locks.ts) is in-process, so only the daemon may change a box.\n */\nimport { Agent, request } from \"undici\";\nimport type { z } from \"zod\";\nimport { ApiErrorSchema, BackupStoreStatusSchema, CloudCaSchema, HealthSchema, TrustCaReportSchema, type BackupStoreSetupRequest, type TrustCaRequest } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\n\nexport class SocketClient {\n private readonly agent: Agent;\n\n constructor(socketPath: string) {\n this.agent = new Agent({ connect: { socketPath } });\n }\n\n health() {\n return this.call(\"GET\", \"/health\", HealthSchema);\n }\n\n cloudCa() {\n return this.call(\"GET\", \"/ssh/cloud-ca\", CloudCaSchema);\n }\n\n trustCa(req: TrustCaRequest) {\n return this.call(\"POST\", \"/ssh/trust-ca\", TrustCaReportSchema, req);\n }\n\n backupStore() {\n return this.call(\"GET\", \"/backup-store\", BackupStoreStatusSchema);\n }\n /** Downloads Garage the first time, so it may take minutes. */\n setupBackupStore(req: BackupStoreSetupRequest) {\n return this.call(\"POST\", \"/backup-store\", BackupStoreStatusSchema, req, 15 * 60_000);\n }\n async close(): Promise<void> {\n await this.agent.close();\n }\n\n private async call<T>(method: \"GET\" | \"POST\", path: string, schema: z.ZodType<T>, body?: unknown, timeoutMs?: number): Promise<T> {\n let res: Awaited<ReturnType<typeof request>>;\n try {\n res = await request(`http://kvbox-server${path}`, {\n method,\n dispatcher: this.agent,\n ...(timeoutMs === undefined ? {} : { headersTimeout: timeoutMs, bodyTimeout: timeoutMs }),\n ...(body === undefined ? {} : { headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(body) }),\n });\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code ?? \"\";\n if (code === \"ENOENT\" || code === \"ECONNREFUSED\") throw new KvboxError(\"kvbox-server is not running; start it with: kvbox-server start -d\");\n throw new KvboxError(`cannot reach kvbox-server: ${(err as Error).message}`);\n }\n const text = await res.body.text();\n if (res.statusCode >= 300) {\n const parsed = ApiErrorSchema.safeParse(safeJson(text) ?? {});\n if (!parsed.success) throw new KvboxError(`kvbox-server answered ${res.statusCode}`);\n throw new KvboxError(parsed.data.error, res.statusCode === 501 ? 2 : 1);\n }\n const json = safeJson(text);\n if (json === undefined) throw new KvboxError(`kvbox-server answered ${res.statusCode} with something that is not JSON`);\n return schema.parse(json);\n }\n}\n\nfunction safeJson(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n","/**\n * Bind the app to the local Unix socket and write the pid file. A host that joined a control plane\n * (`kvbox-server join`) also serves a second instance of the app over HTTPS with its own\n * certificate; that instance demands the host secret on every call (caller.ts).\n */\nimport { readFile, rm, writeFile } from \"node:fs/promises\";\nimport { createServer as createHttpsServer } from \"node:https\";\nimport type { IncomingMessage, Server, ServerResponse } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { createAdaptorServer, type ServerType } from \"@hono/node-server\";\nimport { ensureLayout } from \"./core/state.js\";\nimport { loadConfig } from \"./core/config.js\";\nimport { stopRecovery } from \"./core/machines.js\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { REQUEST_TIMEOUT_MS } from \"@kvbox/shared/names\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { createApp } from \"./app.js\";\nimport { refuseSecondDaemon } from \"./daemon.js\";\nimport { edgeCheck, secretCheck } from \"./caller.js\";\nimport { boxUpgradeHandler } from \"./routes/boxHttp.js\";\nimport { forStore, storeProxy } from \"./core/backupStore.js\";\n\nexport interface ListenOptions {\n socketPath?: string;\n /** Overrides the joined control plane's port (tests: 0 picks a free one). */\n httpsPort?: number;\n}\n\nexport interface Listening {\n socketPath: string;\n server: ServerType;\n /** Present when the host has joined a control plane. */\n https?: { port: number; url: string };\n close: () => Promise<void>;\n}\n\nexport async function listen(opts: ListenOptions = {}): Promise<Listening> {\n const p = await ensureLayout(paths());\n const cfg = await loadConfig(p);\n const socketPath = opts.socketPath ?? p.serverSock;\n // Linux limits a Unix socket path (sun_path) to 108 bytes; bind() fails with EINVAL past it.\n if (Buffer.byteLength(socketPath) > 100) {\n throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);\n }\n\n // Never beside a running daemon (#159): the rm below would take its socket from it.\n if (socketPath === p.serverSock) await refuseSecondDaemon(p);\n // A stale socket file from a crashed server blocks bind(); the pid file tells\n // `kvbox-server status` whether anything is actually alive.\n await rm(socketPath, { force: true });\n\n const server = createAdaptorServer({ fetch: createApp().fetch });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(socketPath, () => resolve());\n });\n await writeFile(p.serverPid, `${process.pid}\\n`);\n\n let https: Listening[\"https\"];\n let httpsServer: ServerType | undefined;\n const cp = cfg.controlPlane;\n if (cp) {\n const [key, cert] = await Promise.all([readFile(p.tlsKey), readFile(p.tlsCert)]).catch((err: Error) => {\n throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);\n });\n httpsServer = createAdaptorServer({\n fetch: createApp({ controlPlane: { name: cp.name, secret: cp.secret } }).fetch,\n createServer: createHttpsServer,\n // A body forwarded to a box may take long to arrive (a large upload through the edge, #182).\n serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS },\n });\n // A backup store's chunks (core/backupStore.ts) come in on this listener too and never reach the app:\n // a path under the bucket's name is Garage's, which checks the signed URL itself.\n const appListeners = httpsServer.listeners(\"request\") as ((req: IncomingMessage, res: ServerResponse) => void)[];\n httpsServer.removeAllListeners(\"request\");\n httpsServer.on(\"request\", (req: IncomingMessage, res: ServerResponse) => {\n if (forStore(req.url, p)) return storeProxy(req, res);\n for (const l of appListeners) l.call(httpsServer, req, res);\n });\n const secret = secretCheck(cp);\n const edge = edgeCheck(cp);\n limitUntrusted(httpsServer as Server, (req) => secret(req.headers.authorization) || edge(req.headers.authorization));\n // WebSockets to a box's web server (#31) never reach the app: the server hands them over raw.\n httpsServer.on(\"upgrade\", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));\n const port = opts.httpsPort ?? cp.port;\n await new Promise<void>((resolve, reject) => {\n httpsServer!.once(\"error\", reject);\n httpsServer!.listen(port, \"0.0.0.0\", () => resolve());\n }).catch(async (err: Error) => {\n server.close();\n await rm(socketPath, { force: true });\n await rm(p.serverPid, { force: true });\n throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);\n });\n const bound = (httpsServer.address() as AddressInfo).port;\n https = { port: bound, url: `https://${cp.advertise}:${bound}` };\n }\n\n /** Tests: wait for both listeners to let go. */\n const close = async () => {\n await Promise.all([\n new Promise<void>((resolve) => server.close(() => resolve())),\n httpsServer ? new Promise<void>((resolve) => httpsServer!.close(() => resolve())) : undefined,\n ]);\n await rm(socketPath, { force: true });\n await rm(p.serverPid, { force: true });\n };\n // A signal must end the process even mid-request (a box creation can take a while and\n // `kvbox-server stop` sends one SIGTERM): stop accepting, drop the files, exit. Only boxes being\n // brought back after a reboot are waited for, so none is left running unrecorded (#29).\n const shutdown = async () => {\n server.close();\n httpsServer?.close();\n await stopRecovery();\n await rm(socketPath, { force: true });\n await rm(p.serverPid, { force: true });\n process.exit(0);\n };\n process.once(\"SIGINT\", () => void shutdown());\n process.once(\"SIGTERM\", () => void shutdown());\n\n return https ? { socketPath, server, https, close } : { socketPath, server, close };\n}\n\n/** Node's own limit on receiving a request, which a caller without credentials keeps. */\nexport const UNTRUSTED_REQUEST_MS = 300_000;\n\n/**\n * The HTTPS server gives a request `REQUEST_TIMEOUT_MS` (an hour) to arrive, for uploads forwarded\n * from the edge; a caller with neither the host secret nor the edge's credential still gets Node's\n * five minutes, so a body dripped by anyone on the internet does not hold a socket for an hour.\n */\nexport function limitUntrusted(server: Server, trusted: (req: IncomingMessage) => boolean, ms = UNTRUSTED_REQUEST_MS): void {\n server.on(\"request\", (req: IncomingMessage) => {\n if (trusted(req)) return;\n const timer = setTimeout(() => req.socket.destroy(), ms);\n timer.unref();\n const done = () => clearTimeout(timer);\n req.once(\"end\", done);\n req.once(\"close\", done);\n });\n}\n","/**\n * HTTPS names for boxes (#31, decision \"A box claims one subdomain\"): a box claims one subdomain\n * `<sub>.kvbox.app` with a default port, and named ports nest under it as `<name>.<sub>.kvbox.app`.\n * Both are single DNS labels. The CLI checks them before calling; the control plane checks again.\n */\nimport { createHmac } from \"node:crypto\";\nimport { KvboxError } from \"./errors.js\";\n\n/** Where box URLs live (decision d2cb4d88's domain); the control plane and the edge can be told otherwise. */\nexport const DEFAULT_PROXY_DOMAIN = \"kvbox.app\";\n/**\n * Names kvbox gives out itself (#182): `s3-<slug>` is a slug's object storage address, so a box never\n * claims a name starting like one.\n */\nexport const STORAGE_SUBDOMAIN_PREFIX = \"s3-\";\n\n/** Subdomains one box may claim (`<sub>.kvbox.app`); every one is covered by the `*.kvbox.app` certificate. */\nexport const MAX_BOX_SUBDOMAINS = 5;\n\n/** A domain box names may live under (`kvbox.app`): the control plane's and the edge's must match. */\nexport function assertProxyDomain(text: string, key: string): string {\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(text)) throw new KvboxError(`${key} must be a domain like ${DEFAULT_PROXY_DOMAIN}: ${text}`);\n return text;\n}\n\n/** One DNS label: lowercase letters, digits and `-`, never at either end. */\nconst LABEL_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n\n/** Subdomains nobody may claim: the platform's own names, and ones that would read as ours. */\nexport const RESERVED_SUBDOMAINS: ReadonlySet<string> = new Set([\n \"admin\",\n \"api\",\n \"app\",\n \"assets\",\n \"auth\",\n \"billing\",\n \"blog\",\n \"cdn\",\n \"dashboard\",\n \"dev\",\n \"docs\",\n \"edge\",\n \"help\",\n \"install\",\n \"kvbox\",\n \"login\",\n \"mail\",\n \"relay\",\n \"root\",\n \"smtp\",\n \"static\",\n \"status\",\n \"support\",\n \"www\",\n]);\n\n/** Why `text` cannot be a claimed subdomain, or null when it can. */\nexport function subdomainProblem(text: string): string | null {\n if (text.length < 3 || text.length > 63) return `\"${text}\" must be 3 to 63 characters`;\n if (!LABEL_RE.test(text)) return `\"${text}\" may hold only lowercase letters, digits and '-', not at either end`;\n if (RESERVED_SUBDOMAINS.has(text)) return `\"${text}\" is reserved; pick another name`;\n return null;\n}\n\n/** Why `text` cannot be a name under a subdomain (`<name>.<sub>`), or null when it can. */\nexport function routeNameProblem(text: string): string | null {\n if (text.length < 1 || text.length > 63) return `\"${text}\" must be 1 to 63 characters`;\n if (!LABEL_RE.test(text)) return `\"${text}\" may hold only lowercase letters, digits and '-', not at either end`;\n return null;\n}\n\nexport function assertSubdomain(text: string): string {\n const problem = subdomainProblem(text);\n if (problem) throw new KvboxError(`subdomain ${problem}`);\n return text;\n}\n\nexport function assertRouteName(text: string): string {\n const problem = routeNameProblem(text);\n if (problem) throw new KvboxError(`name ${problem}`);\n return text;\n}\n\n/** `https://<sub>.<domain>`, or `https://<name>.<sub>.<domain>` for a named port. */\nexport function subdomainUrl(domain: string, sub: string, name?: string): string {\n return `https://${name === undefined ? \"\" : `${name}.`}${sub}.${domain}`;\n}\n\n/** Domains a user may not bring (#89): the platform's own, and everything under them. */\nexport const PLATFORM_DOMAINS: readonly string[] = [\"kvbox.sh\", DEFAULT_PROXY_DOMAIN];\n\n/**\n * Why `text` cannot be a custom domain (#89), or null when it can: a lowercase host name of at least\n * two labels ending in a letters-only top-level label, not the platform's own nor under it.\n * `proxyDomain` is the control plane's, when it is not kvbox.app.\n */\nexport function domainProblem(text: string, proxyDomain?: string): string | null {\n if (text.length > 253) return `\"${text}\" is longer than a domain may be`;\n const labels = text.split(\".\");\n if (labels.length < 2 || labels.some((l) => l.length > 63 || !LABEL_RE.test(l))) return `\"${text}\" is not a domain like example.com or www.example.com (lowercase, no \"*\", no \"https://\")`;\n if (!/^[a-z]{2,}$/.test(labels.at(-1)!) && !labels.at(-1)!.startsWith(\"xn--\")) return `\"${text}\" does not end in a top-level domain`;\n const ours = [...PLATFORM_DOMAINS, ...(proxyDomain ? [proxyDomain] : [])];\n if (ours.some((d) => text === d || text.endsWith(`.${d}`))) return `\"${text}\" belongs to kvbox; bring a domain of your own`;\n return null;\n}\n\nexport function assertDomain(text: string, proxyDomain?: string): string {\n const problem = domainProblem(text, proxyDomain);\n if (problem) throw new KvboxError(`domain ${problem}`);\n return text;\n}\n\n/** A visitor's `Host` as a domain row is keyed: lowercase, no port, no trailing dot. */\nexport function bareHost(host: string): string {\n return host.toLowerCase().replace(/:\\d+$/, \"\").replace(/\\.$/, \"\");\n}\n\n/**\n * What a request's `Host` names under `domain`: the subdomain and, for `<name>.<sub>`, the name.\n * Null for anything else (the bare domain, deeper names, another domain).\n */\nexport function parseProxyHost(host: string, domain: string): { sub: string; name?: string } | null {\n const bare = bareHost(host);\n const suffix = `.${domain}`;\n if (!bare.endsWith(suffix)) return null;\n const labels = bare.slice(0, -suffix.length).split(\".\");\n if (labels.some((l) => !LABEL_RE.test(l))) return null;\n if (labels.length === 1) return { sub: labels[0]! };\n if (labels.length === 2) return { sub: labels[1]!, name: labels[0]! };\n return null;\n}\n\n/**\n * How the edge and a host carry a visitor's request to a box (#31). The host's answers of its own\n * (no such box, box not running, nothing listening) carry `PROXY_ERROR_HEADER`, and the box's carry\n * `PROXIED_HEADER`, so the edge can tell the box's own 404 or 401 from the host's and show its page\n * for the latter. The edge strips every `x-kvbox-*` header before a visitor sees the answer.\n */\nexport const PROXY_ERROR_HEADER = \"x-kvbox-proxy-error\";\n/**\n * `hibernated`, `standby` and `stopped` say why a box is not running (#80): the edge may ask for the\n * first two to be woken, never the last. `waking`: a wake asked for is still under way. `wake-failed`:\n * it did not work. `not-running` is what a host from before #80 says for all three.\n */\nexport type ProxyError = \"not-found\" | \"hibernated\" | \"standby\" | \"stopped\" | \"not-running\" | \"waking\" | \"wake-failed\" | \"unreachable\" | \"timeout\";\n/** Set by the host on every answer that came from the box: anything without it is the host's own (a refusal, a host too old for #31). */\nexport const PROXIED_HEADER = \"x-kvbox-proxied\";\n/**\n * The visitor's path and query. It never goes into the URL the edge calls on the host: a URL resolves\n * `..`, and `/machines/<box>/http/<port>/../../..` would reach any route on the host with the host\n * secret. The host URL is always exactly `/machines/<box>/http/<port>`.\n */\nexport const VISITOR_PATH_HEADER = \"x-kvbox-path\";\n/**\n * Sent by the edge when the box may be woken for this request (#80): its slug is not suspended and\n * the edge has not had it woken in the last minute. A host then wakes a hibernated box (resumes one in\n * standby) before forwarding, and stamps its answer with WOKE_HEADER when it did.\n */\nexport const WAKE_HEADER = \"x-kvbox-wake\";\n/**\n * The longest a host holds a request on a wake before answering `waking` (the wake itself goes on).\n * The edge adds it to its own wait for the host's answer when it sends WAKE_HEADER.\n */\nexport const WAKE_WAIT_MS = 30_000;\n/**\n * How long a visitor may take to send one request, body included, at the edge and at the host's HTTPS\n * server (#182). Node's own limit is five minutes, which cut a large upload to a box (an object put in\n * a bucket) in the middle; the headers alone keep Node's one-minute limit. Traefik, in front of the\n * edge, has a limit of its own (its entry point's `readTimeout`, 60 s by default in v3): the\n * deployment must raise it to match (packages/edge/docker-compose.yml), or this one is never reached.\n */\nexport const REQUEST_TIMEOUT_MS = 3_600_000;\n/**\n * On a host's answer: this request woke the box, so the edge counts it against the box's wake limit.\n * Also on the host's own `unreachable` or `timeout` after a wake: the box was woken all the same.\n */\nexport const WOKE_HEADER = \"x-kvbox-woke\";\n/** The visitor's own `Authorization`, carried past the host secret that takes its place between edge and host. */\nexport const VISITOR_AUTH_HEADER = \"x-kvbox-authorization\";\n\n/**\n * Request headers neither hop passes on although they are not hop-by-hop: undici refuses to send\n * `expect` at all, so `Expect: 100-continue` (curl on a large upload) would fail every forward.\n * Node's server already answers the `100 Continue` itself.\n */\nexport const NOT_FORWARDED: ReadonlySet<string> = new Set([\"expect\"]);\n\n/** Headers that describe one connection, never passed along by a proxy (RFC 9110 §7.6.1). */\nexport const HOP_BY_HOP: ReadonlySet<string> = new Set([\"connection\", \"keep-alive\", \"proxy-authenticate\", \"proxy-authorization\", \"proxy-connection\", \"te\", \"trailer\", \"transfer-encoding\", \"upgrade\"]);\n\n/** The one host path the edge calls: a box's port, `/machines/<box>/http/<port>`. */\nexport const BOX_HTTP_PATH_RE = /^\\/machines\\/([^/]+)\\/http\\/(\\d{1,5})\\/?$/;\n\n/**\n * The edge's bearer for a host, derived from the host secret so neither side stores anything new.\n * A host takes it on `BOX_HTTP_PATH_RE` alone, so the internet-facing edge never holds a key to the\n * rest of a host's API; the control plane keeps it in `hosts.edge_secret` for the edge to read.\n */\nexport function edgeCredential(hostSecret: string): string {\n return createHmac(\"sha256\", hostSecret).update(\"kvbox-edge-v1\").digest(\"base64url\");\n}\n","/**\n * The hono app behind `kvbox-server`. Served over `~/.kvbox/server.sock` to the host owner, and,\n * once the host joined a control plane, a second instance over HTTPS that demands the host secret\n * (see caller.ts).\n */\nimport { Hono } from \"hono\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { VERSION } from \"./version.js\";\nimport { resolveCaller, type CallerOptions, type Env } from \"./caller.js\";\nimport { loadConfig } from \"./core/config.js\";\nimport { currentBaseVersion, lastRecovery } from \"./core/machines.js\";\nimport { relayWatchReport } from \"./core/relayWatch.js\";\nimport { readUpdateState, startUpdate } from \"./core/update.js\";\nimport { backupMachineRoutes, backupRoutes, backupVolumeRoutes } from \"./routes/backups.js\";\nimport { backupStoreRoutes } from \"./routes/backupStore.js\";\nimport { boxHttpRoutes } from \"./routes/boxHttp.js\";\nimport { capacityRoutes } from \"./routes/capacity.js\";\nimport { envRoutes } from \"./routes/env.js\";\nimport { machineRoutes } from \"./routes/machines.js\";\nimport { snapshotRoutes } from \"./routes/snapshots.js\";\nimport { sshRoutes } from \"./routes/ssh.js\";\nimport { usageRoutes } from \"./routes/usage.js\";\nimport { volumeRoutes } from \"./routes/volumes.js\";\nimport { log } from \"./core/log.js\";\n\nexport function createApp(opts: CallerOptions = {}) {\n const app = new Hono<Env>();\n app.use(resolveCaller(opts));\n\n app.get(\"/health\", async (c) => {\n const cfg = await loadConfig();\n const cp = cfg.controlPlane;\n return c.json({\n ok: true as const,\n version: VERSION,\n pid: process.pid,\n base: await currentBaseVersion().catch(() => null),\n owner: cfg.owner,\n controlPlane: cp ? { name: cp.name, url: cp.url, hostUrl: `https://${cp.advertise}:${cp.port}` } : null,\n relay: cfg.relay ? { name: cfg.relay.name, publicIp: cfg.relay.publicIp, endpoint: cfg.relay.endpoint, ...relayWatchReport() } : null,\n recovery: lastRecovery(),\n update: await readUpdateState(),\n });\n });\n // The admin's host update (core/update.ts): the control plane's door only, the operator runs the installer.\n if (opts.controlPlane) app.post(\"/update\", async (c) => c.json(await startUpdate(VERSION), 202));\n // A box's web servers for the edge (#31): only what came from the control plane's side.\n if (opts.controlPlane) app.route(\"/machines\", boxHttpRoutes());\n // Backups: the control plane holds the keys and the bucket, so the socket has no such routes.\n if (opts.controlPlane) {\n app.route(\"/machines\", backupMachineRoutes());\n app.route(\"/volumes\", backupVolumeRoutes());\n app.route(\"/backups\", backupRoutes());\n }\n app.route(\"/machines\", machineRoutes());\n app.route(\"/snapshots\", snapshotRoutes());\n app.route(\"/volumes\", volumeRoutes());\n app.route(\"/capacity\", capacityRoutes());\n app.route(\"/env\", envRoutes());\n app.route(\"/ssh\", sshRoutes(opts));\n app.route(\"/backup-store\", backupStoreRoutes(opts));\n app.route(\"/usage\", usageRoutes(opts));\n\n app.notFound((c) => c.json({ error: `no route: ${c.req.method} ${c.req.path}` }, 404));\n app.onError((err, c) => {\n if (err instanceof NotFoundError) return c.json({ error: err.message }, 404);\n if (err instanceof KvboxError) {\n return c.json({ error: err.message }, err.exitCode === 2 ? 501 : 400);\n }\n log.error(`${c.req.method} ${c.req.path}: ${err.stack ?? err.message}`);\n return c.json({ error: err.message }, 500);\n });\n\n return app;\n}\n\nexport type App = ReturnType<typeof createApp>;\n","/**\n * Each binary's version comes from its own package.json: tsup injects\n * `__KVBOX_VERSION__` at build time; the dev path (tsx) reads the file.\n * Usage in a package: `versionOf(import.meta.url)` from its `src/version.ts`.\n */\nimport { createRequire } from \"node:module\";\n\nexport function versionOf(srcFileUrl: string, injected?: string): string {\n if (typeof injected === \"string\") return injected;\n try {\n const require = createRequire(srcFileUrl);\n return (require(\"../package.json\") as { version: string }).version;\n } catch {\n return \"0.0.0-dev\";\n }\n}\n","import { versionOf } from \"@kvbox/shared/version\";\n\ndeclare const __KVBOX_VERSION__: string | undefined;\n\nexport const VERSION: string = versionOf(import.meta.url, typeof __KVBOX_VERSION__ === \"string\" ? __KVBOX_VERSION__ : undefined);\n","/**\n * Who is calling. Every request carries an `owner` the routes file boxes under and scope listings\n * to. Two callers exist:\n * - the host owner over the local Unix socket: no credential (the socket's permissions are the\n * auth), owner = the server's configured `owner` (the Unix user running it);\n * - the control plane this host joined (#18), over HTTPS: it presents the host secret from `join`\n * as a bearer on every call and names the user it acts for in `X-Kvbox-Owner`, qualified here\n * and nowhere else to `<user>@<control plane name>` (decision \"Owner realms\"). `/health` and\n * `/capacity` need no owner; box, snapshot, volume and env routes do, except the listings: without the\n * header `GET /machines`, `GET /snapshots`, `GET /volumes` and `GET /env` cover every owner of the realm (the\n * control plane reconciling its index, #20). The host owner's local boxes are never in that answer.\n * The edge (#31) presents `edgeCredential(secret)` instead, which opens a box's port\n * (`BOX_HTTP_PATH_RE`) and nothing else.\n */\nimport { createHash, timingSafeEqual } from \"node:crypto\";\nimport type { MiddlewareHandler } from \"hono\";\nimport { BOX_HTTP_PATH_RE, edgeCredential } from \"@kvbox/shared/names\";\nimport { loadConfig } from \"./core/config.js\";\nimport { LOCAL_OWNER_RE, type ListScope } from \"./core/refs.js\";\n\nexport type Env = { Variables: { owner: string; listScope: ListScope } };\n\nexport interface ControlPlaneCaller {\n /** The realm name owners are qualified with. */\n name: string;\n /** The host secret minted at join. */\n secret: string;\n}\n\nexport interface CallerOptions {\n /** Set on the HTTPS app only; the socket app trusts its caller. */\n controlPlane?: ControlPlaneCaller;\n}\n\nexport const OWNER_HEADER = \"x-kvbox-owner\";\n\nexport function resolveCaller(opts: CallerOptions = {}): MiddlewareHandler<Env> {\n const cp = opts.controlPlane;\n if (!cp) {\n return async (c, next) => {\n const cfg = await loadConfig();\n c.set(\"owner\", cfg.owner);\n c.set(\"listScope\", cfg.owner);\n await next();\n };\n }\n const authorized = secretCheck(cp);\n const edge = edgeCheck(cp);\n return async (c, next) => {\n const auth = c.req.header(\"authorization\");\n if (!authorized(auth) && !(edge(auth) && BOX_HTTP_PATH_RE.test(c.req.path))) return c.json({ error: \"not authorized\" }, 401);\n const user = c.req.header(OWNER_HEADER);\n if (user === undefined) {\n const path = c.req.path.replace(/\\/$/, \"\");\n const realmListing = c.req.method === \"GET\" && (path === \"/machines\" || path === \"/snapshots\" || path === \"/volumes\" || path === \"/env\");\n if (!realmListing && /^\\/(machines|snapshots|volumes|env)(\\/|$)/.test(c.req.path)) {\n return c.json({ error: \"X-Kvbox-Owner header required\" }, 400);\n }\n c.set(\"owner\", \"\");\n c.set(\"listScope\", { realm: cp.name });\n } else {\n if (!LOCAL_OWNER_RE.test(user)) return c.json({ error: \"X-Kvbox-Owner: letters, digits, '.', '_', '-'\" }, 400);\n const owner = `${user}@${cp.name}`;\n c.set(\"owner\", owner);\n c.set(\"listScope\", owner);\n }\n await next();\n };\n}\n\n/** Whether an `Authorization` header carries the host secret (constant time). */\nexport function secretCheck(cp: ControlPlaneCaller): (authorization: string | undefined) => boolean {\n return bearerCheck(cp.secret);\n}\n\n/** Whether it carries the edge's credential, good for a box's port only. */\nexport function edgeCheck(cp: ControlPlaneCaller): (authorization: string | undefined) => boolean {\n return bearerCheck(edgeCredential(cp.secret));\n}\n\nfunction bearerCheck(token: string): (authorization: string | undefined) => boolean {\n const expected = digest(token);\n return (authorization) => {\n const m = /^Bearer\\s+(\\S+)$/i.exec(authorization ?? \"\");\n return m !== null && timingSafeEqual(digest(m[1]!), expected);\n };\n}\n\n/** Fixed-length form of a secret so the compare is constant time whatever the caller sent. */\nfunction digest(secret: string): Buffer {\n return createHash(\"sha256\").update(secret).digest();\n}\n","/**\n * The host updating itself, at the control plane's request (`POST /update`, the HTTPS app only; the admin's\n * `POST /admin/hosts/:name/update`). It downloads install-server.sh from kvbox.sh and runs it with\n * `--update`: new packages, images and kernel, then a daemon restart, never sudo (decision \"Hosts update\n * over the API with install-server.sh --update\"). The script runs detached, since it stops this very\n * process; it writes `update.json` at its start and end, which `/health` reports. Where the script comes\n * from is the host's own setting (`KVBOX_INSTALL_SERVER_URL`), never the caller's.\n */\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { HostUpdateSchema, type HostUpdate } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { spawnDetached } from \"./exec.js\";\nimport { log } from \"./log.js\";\n\nexport const INSTALL_SERVER_URL = \"https://kvbox.sh/install-server.sh\";\n\n/** An update still `running` after this long never finished (the host rebooted, the script was killed). */\nexport const UPDATE_STALE_MS = 60 * 60_000;\n\n/** The last update as update.json says, a stale `running` one turned into `failed`; null when none ran or the file is unreadable. */\nexport async function readUpdateState(p: Paths = paths(), now = Date.now()): Promise<HostUpdate | null> {\n let raw: unknown;\n try {\n raw = JSON.parse(await readFile(p.updateState, \"utf8\"));\n } catch {\n return null;\n }\n const parsed = HostUpdateSchema.safeParse(raw);\n if (!parsed.success) return null;\n const u = parsed.data;\n if (u.state === \"running\" && now - Date.parse(u.startedAt) > UPDATE_STALE_MS) {\n return { ...u, state: \"failed\", error: `never finished; see ${p.updateLog}` };\n }\n return u;\n}\n\nexport interface UpdateDeps {\n fetch?: typeof fetch;\n spawn?: (argv: readonly string[], logFile: string, env: NodeJS.ProcessEnv) => Promise<number>;\n url?: string;\n}\n\n/** Start the update and answer at once with its `running` state; refuses while one is already running. */\nexport async function startUpdate(version: string, p: Paths = paths(), deps: UpdateDeps = {}): Promise<HostUpdate> {\n const current = await readUpdateState(p);\n if (current?.state === \"running\") throw new KvboxError(`an update is already running since ${current.startedAt}`);\n const url = deps.url ?? process.env[\"KVBOX_INSTALL_SERVER_URL\"] ?? INSTALL_SERVER_URL;\n const res = await (deps.fetch ?? fetch)(url, { signal: AbortSignal.timeout(20_000) });\n if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);\n const script = await res.text();\n if (!script.startsWith(\"#!\") || !script.includes(\"--update\")) throw new KvboxError(`${url} is not an install-server.sh that knows --update`);\n\n await mkdir(p.updateDir, { recursive: true });\n await writeFile(p.updateScript, script, { mode: 0o700 });\n const state: HostUpdate = { state: \"running\", startedAt: new Date().toISOString(), finishedAt: null, from: version, to: null, error: null, needsManual: [] };\n await writeFile(p.updateState, `${JSON.stringify(state, null, 2)}\\n`);\n await writeFile(p.updateLog, `--- ${state.startedAt} update from ${version}, ${url}\\n`, { flag: \"a\" });\n const env = { ...process.env, KVBOX_HOME: p.home, KVBOX_YES: \"1\" };\n try {\n await (deps.spawn ?? spawnDetached)([\"bash\", p.updateScript, \"--update\"], p.updateLog, env);\n } catch (err) {\n const failed: HostUpdate = { ...state, state: \"failed\", finishedAt: new Date().toISOString(), error: (err as Error).message };\n await writeFile(p.updateState, `${JSON.stringify(failed, null, 2)}\\n`);\n throw err;\n }\n log.info(`update started from ${version}: install-server.sh --update, log in ${p.updateLog}`);\n return state;\n}\n","/**\n * Backups (decision \"Backups: encrypted 4 MiB chunks in object storage\"): the control plane's only, so\n * served on the HTTPS app alone (app.ts), never on the socket. core/backups.ts does the work; the\n * control plane calls these in order: `POST /machines/:name/backup`, then `POST /backups/:id/upload`\n * (or `DELETE /backups/:id` when it gives up); `POST /machines/:name/restore` on its own. A volume's\n * (#168) are the same two under `/volumes/:name`, sharing the upload and the drop.\n */\nimport { Hono } from \"hono\";\nimport { HostBackupRequest, HostRestoreRequest, HostUploadRequest, HostVolumeRestoreRequest } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { dropBackup, restoreBackup, restoreVolumeBackup, stageBackup, stageVolumeBackup, uploadBackup } from \"../core/backups.js\";\nimport { parseRef } from \"../core/refs.js\";\nimport type { Env } from \"../caller.js\";\n\nexport function backupMachineRoutes() {\n const r = new Hono<Env>();\n r.post(\"/:name/backup\", async (c) => {\n const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"backup: expected {id, key}\");\n return c.json(await stageBackup(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data));\n });\n r.post(\"/:name/restore\", async (c) => {\n const body = HostRestoreRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"restore: expected {id, key, sizeBytes, base, env, chunks}\");\n return c.json(await restoreBackup(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data));\n });\n return r;\n}\n\n/** A volume's (#168): `POST /volumes/:name/backup`, then the same upload or drop as a box's; `POST /volumes/:name/restore`. */\nexport function backupVolumeRoutes() {\n const r = new Hono<Env>();\n r.post(\"/:name/backup\", async (c) => {\n const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"backup: expected {id, key}\");\n return c.json(await stageVolumeBackup(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data));\n });\n r.post(\"/:name/restore\", async (c) => {\n const body = HostVolumeRestoreRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"restore: expected {id, key, sizeBytes, chunks}\");\n return c.json(await restoreVolumeBackup(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data));\n });\n return r;\n}\n\nexport function backupRoutes() {\n const r = new Hono<Env>();\n r.post(\"/:id/upload\", async (c) => {\n const body = HostUploadRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"upload: expected {key, urls}\");\n return c.json(await uploadBackup(c.req.param(\"id\"), body.data));\n });\n r.delete(\"/:id\", async (c) => {\n await dropBackup(c.req.param(\"id\"));\n return c.body(null, 204);\n });\n return r;\n}\n","/**\n * This host as a backup store (core/backupStore.ts): `POST /backup-store` sets it up, `GET` says how it\n * is. On the Unix socket only: which disk a host gives to backups is decided by someone on the host\n * (`kvbox-server backup`), never by the control plane.\n */\nimport { Hono } from \"hono\";\nimport { BackupStoreSetupRequest } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { CallerOptions, Env } from \"../caller.js\";\nimport { backupStoreStatus, setupBackupStore } from \"../core/backupStore.js\";\n\nexport function backupStoreRoutes(opts: CallerOptions = {}) {\n const r = new Hono<Env>();\n if (opts.controlPlane) {\n r.all(\"/*\", (c) => c.json({ error: \"a backup store is set up on the host itself (kvbox-server backup setup there)\" }, 403));\n return r;\n }\n r.get(\"/\", async (c) => c.json(await backupStoreStatus()));\n r.post(\"/\", async (c) => {\n const body = BackupStoreSetupRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"backup setup: expected the directory as path\");\n return c.json(await setupBackupStore(body.data));\n });\n return r;\n}\n","/**\n * A box's web servers for the edge (#31): `ANY /machines/:name/http/:port` on the HTTPS app only\n * (never the socket) is passed to `<box ip>:<port><x-kvbox-path>` with its body streamed both ways,\n * and the same call as a WebSocket upgrade (listen.ts) is piped. The visitor's path comes in a\n * header, never in the URL (see VISITOR_PATH_HEADER). The control plane already decided\n * the name is the box's; this only forwards to a box of the caller's realm that is running.\n *\n * The edge sends the visitor's `Authorization` as `x-kvbox-authorization` (the host secret holds the\n * real header between edge and host) and the visitor's host name as `x-forwarded-host`; the box\n * gets them back as `authorization` and `host`, and never sees the secret or `x-kvbox-owner`.\n * Answers the host gives itself carry `x-kvbox-proxy-error`; the box's carry `x-kvbox-proxied`,\n * and any `x-kvbox-*` the box sent itself is dropped, so a box cannot pass for the host.\n * The caller is the control plane (host secret) or the edge (its credential, caller.ts).\n *\n * Wake on request (#80): with WAKE_HEADER, a hibernated box is woken (one in standby resumed) before\n * the forward, one wake per box however many requests wait on it; the edge decides whether a box\n * may be woken (credit, its rate limit), the host only how. A stopped box is never started.\n */\nimport type { IncomingHttpHeaders, IncomingMessage } from \"node:http\";\nimport { connect, type Socket } from \"node:net\";\nimport { Readable } from \"node:stream\";\nimport { Hono } from \"hono\";\nimport { request } from \"undici\";\nimport type { BoxStatus } from \"@kvbox/shared/api\";\nimport { NotFoundError } from \"@kvbox/shared/errors\";\nimport { HeadTimeoutError, readHead, rewriteHead } from \"@kvbox/shared/httpHead\";\nimport {\n BOX_HTTP_PATH_RE,\n HOP_BY_HOP,\n NOT_FORWARDED,\n PROXIED_HEADER,\n PROXY_ERROR_HEADER,\n VISITOR_AUTH_HEADER,\n VISITOR_PATH_HEADER,\n WAKE_HEADER,\n WAKE_WAIT_MS,\n WOKE_HEADER,\n type ProxyError,\n} from \"@kvbox/shared/names\";\nimport { edgeCheck, OWNER_HEADER, secretCheck, type ControlPlaneCaller, type Env } from \"../caller.js\";\nimport { getMachine, resumeMachine, wakeMachine } from \"../core/machines.js\";\nimport { LOCAL_OWNER_RE, parseRef, type BoxRef } from \"../core/refs.js\";\n\n/**\n * How long the box may take to start answering; a stream (SSE, a long download) then has no limit.\n * Shorter than the edge's wait for the host (edge proxy.ts), so the host's `timeout` answer gets there first.\n */\nconst HEADERS_TIMEOUT_MS = 55_000;\n/** The most a box's answer to a WebSocket handshake may hold before its blank line. */\nconst MAX_HANDSHAKE_BYTES = 16 * 1024;\n/** Connecting to the box: it is on the host's own bridge, so anything slower means nothing is there. */\nconst CONNECT_TIMEOUT_MS = 5_000;\n/** Headers that never reach the box: the edge-to-host credentials and what the forward rewrites. */\nconst DROPPED = new Set([...HOP_BY_HOP, ...NOT_FORWARDED, \"host\", \"authorization\", OWNER_HEADER, VISITOR_AUTH_HEADER, VISITOR_PATH_HEADER, WAKE_HEADER]);\n\nclass ProxyFailure extends Error {\n constructor(\n readonly status: number,\n readonly code: ProxyError,\n message: string,\n ) {\n super(message);\n }\n}\n\ninterface Target {\n ip: string;\n port: number;\n /** The path and query on the box. */\n path: string;\n /** This request woke the box (WOKE_HEADER on the answer). */\n woke: boolean;\n}\n\n/** Brings a hibernated or standby box back. Resolves once it runs; tests pass their own. */\nexport type Waker = (ref: BoxRef, status: \"hibernated\" | \"standby\") => Promise<void>;\n\n/**\n * A Waker that runs one wake per box at a time, the requests that arrive meanwhile waiting on the\n * same one, and gives up waiting (not waking) after `capMs` with a `waking` failure.\n */\nexport function sharedWaker(bring: Waker = defaultBring, capMs = WAKE_WAIT_MS): Waker {\n const inFlight = new Map<string, Promise<void>>();\n return async (ref, status) => {\n const key = `${ref.owner}/${ref.name}`;\n let wake = inFlight.get(key);\n if (!wake) {\n wake = bring(ref, status).finally(() => inFlight.delete(key));\n inFlight.set(key, wake);\n // a wake nobody waits on any more (they all hit the cap) must not be an unhandled rejection\n wake.catch(() => {});\n }\n let timer: NodeJS.Timeout | undefined;\n const cap = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new ProxyFailure(503, \"waking\", `box ${ref.name} is waking up`)), capMs);\n });\n try {\n await Promise.race([wake, cap]);\n } finally {\n clearTimeout(timer);\n }\n };\n}\n\nconst defaultBring: Waker = async (ref, status) => {\n await (status === \"hibernated\" ? wakeMachine(ref) : resumeMachine(ref));\n};\n\n/** Shared by the plain route and the upgrade handler, so a page and its WebSocket wake the box once. */\nconst wakeBox = sharedWaker();\n\n/** The answer code for a box that is not running. */\nconst notRunning = (status: BoxStatus): ProxyError => (status === \"hibernated\" || status === \"standby\" ? status : \"stopped\");\n\n/** The path on the box: the edge's header, a plain origin-form path; anything else is the box's `/`. */\nfunction visitorPath(value: string | string[] | null | undefined): string {\n const path = Array.isArray(value) ? value[0] : value;\n return path !== undefined && path !== null && path.startsWith(\"/\") && !/[\\s]/.test(path) ? path : \"/\";\n}\n\n/**\n * The running box a forward path names, or a ProxyFailure saying why not. With `wake`, a hibernated\n * or standby box is brought back first.\n */\nasync function targetOf(url: URL, owner: string, path: string, wake?: Waker): Promise<Target> {\n const m = BOX_HTTP_PATH_RE.exec(url.pathname);\n const port = Number(m?.[2]);\n if (!m || port < 1 || port > 65535) throw new ProxyFailure(404, \"not-found\", `no route: ${url.pathname}`);\n const name = decodeURIComponent(m[1]!);\n const ref = parseRef(name, owner);\n let box;\n try {\n box = await getMachine(ref);\n } catch (err) {\n if (err instanceof NotFoundError) throw new ProxyFailure(404, \"not-found\", err.message);\n throw err;\n }\n let woke = false;\n if (box.status !== \"running\" && wake && (box.status === \"hibernated\" || box.status === \"standby\")) {\n try {\n await wake(ref, box.status);\n woke = true;\n } catch (err) {\n if (err instanceof ProxyFailure) throw err;\n // another wake may have finished between our look and our call: then the box is up all the same\n box = await getMachine(ref);\n if (box.status !== \"running\") throw new ProxyFailure(502, \"wake-failed\", `box ${name} did not wake: ${(err as Error).message}`);\n }\n if (woke) box = await getMachine(ref);\n }\n if (box.status !== \"running\") throw new ProxyFailure(409, notRunning(box.status), `box ${name} is ${box.status}`);\n return { ip: box.ip, port, path, woke };\n}\n\n/** The request headers as the box gets them. `upgrade` keeps the two headers a WebSocket handshake needs. */\nfunction boxHeaders(incoming: Iterable<[string, string]>, target: Target, upgrade = false): [string, string][] {\n const out: [string, string][] = [];\n let host = `${target.ip}:${target.port}`;\n for (const [name, value] of incoming) {\n const key = name.toLowerCase();\n if (key === \"x-forwarded-host\") host = value;\n if (key === VISITOR_AUTH_HEADER) out.push([\"authorization\", value]);\n if (upgrade && (key === \"upgrade\" || key === \"connection\")) out.push([name, value]);\n else if (!DROPPED.has(key)) out.push([name, value]);\n }\n out.push([\"host\", host]);\n return out;\n}\n\n/** `woke`: this request woke the box before failing, so the edge still counts the wake (WOKE_HEADER). */\nconst failure = (err: ProxyFailure, woke = false) =>\n new Response(JSON.stringify({ error: err.message }), { status: err.status, headers: { \"content-type\": \"application/json\", [PROXY_ERROR_HEADER]: err.code, ...(woke ? { [WOKE_HEADER]: \"1\" } : {}) } });\n\n/** Whether the caller asked for the box to be woken (WAKE_HEADER). */\nconst wants = (value: string | string[] | null | undefined) => value === \"1\";\n\nexport function boxHttpRoutes(wake: Waker = wakeBox) {\n const r = new Hono<Env>();\n r.all(\"/:name/http/:port\", (c) => forward(c, wake));\n return r;\n}\n\nasync function forward(c: import(\"hono\").Context<Env>, wake: Waker): Promise<Response> {\n let target: Target;\n try {\n target = await targetOf(new URL(c.req.url), c.get(\"owner\"), visitorPath(c.req.header(VISITOR_PATH_HEADER)), wants(c.req.header(WAKE_HEADER)) ? wake : undefined);\n } catch (err) {\n if (err instanceof ProxyFailure) return failure(err);\n throw err;\n }\n const raw = c.req.raw;\n const pairs: [string, string][] = [];\n raw.headers.forEach((value, name) => pairs.push([name, value]));\n let res;\n try {\n res = await request(`http://${target.ip}:${target.port}${target.path}`, {\n method: raw.method as \"GET\",\n headers: boxHeaders(pairs, target).flat(),\n body: raw.body === null ? null : Readable.fromWeb(raw.body as import(\"node:stream/web\").ReadableStream),\n headersTimeout: HEADERS_TIMEOUT_MS,\n bodyTimeout: 0,\n signal: raw.signal,\n });\n } catch (err) {\n const e = err as Error & { code?: string };\n if (e.code === \"UND_ERR_HEADERS_TIMEOUT\") return failure(new ProxyFailure(504, \"timeout\", `box took over ${HEADERS_TIMEOUT_MS / 1000} s to answer on port ${target.port}`), target.woke);\n return failure(new ProxyFailure(502, \"unreachable\", `box answered nothing on port ${target.port} (${e.code ?? e.message})`), target.woke);\n }\n const headers = new Headers();\n for (const [name, value] of Object.entries(res.headers)) {\n if (value === undefined || HOP_BY_HOP.has(name) || name.startsWith(\"x-kvbox-\")) continue;\n for (const v of Array.isArray(value) ? value : [value]) headers.append(name, v);\n }\n headers.set(PROXIED_HEADER, \"1\");\n if (target.woke) headers.set(WOKE_HEADER, \"1\");\n const empty = res.statusCode === 204 || res.statusCode === 304 || raw.method === \"HEAD\";\n if (empty) res.body.resume();\n return new Response(empty ? null : (Readable.toWeb(res.body) as ReadableStream), { status: res.statusCode, headers });\n}\n\n/**\n * An answer written straight on a socket, for an upgrade that cannot go ahead. It always carries\n * PROXY_ERROR_HEADER (`refused` when no box reason applies) and never PROXIED_HEADER, which only a\n * box's own answer gets.\n */\nfunction refuse(socket: Socket, status: number, text: string, code: ProxyError | \"refused\" = \"refused\", woke = false): void {\n const body = JSON.stringify({ error: text });\n socket.end(`HTTP/1.1 ${status} ${status === 401 ? \"Unauthorized\" : \"Error\"}\\r\\ncontent-type: application/json\\r\\ncontent-length: ${Buffer.byteLength(body)}\\r\\n${PROXY_ERROR_HEADER}: ${code}\\r\\n${woke ? `${WOKE_HEADER}: 1\\r\\n` : \"\"}connection: close\\r\\n\\r\\n${body}`);\n}\n\nfunction headerPairs(raw: readonly string[]): [string, string][] {\n const out: [string, string][] = [];\n for (let i = 0; i + 1 < raw.length; i += 2) out.push([raw[i]!, raw[i + 1]!]);\n return out;\n}\n\n/**\n * The HTTPS server's `upgrade` handler: a WebSocket to a box. Checked like any call from the control\n * plane's side (host secret or the edge's credential, owner), then the handshake is written to the\n * box as it came, rewritten the same way as a plain forward. The box's answer is read up to its\n * blank line (a box that says nothing in `headersTimeoutMs` is our `timeout`), stamped like a plain\n * forward's, and from then on the two sockets are piped.\n */\nexport function boxUpgradeHandler(cp: ControlPlaneCaller, headersTimeoutMs = HEADERS_TIMEOUT_MS, wake: Waker = wakeBox) {\n const full = secretCheck(cp);\n const edge = edgeCheck(cp);\n const authorized = (auth: string | undefined) => full(auth) || edge(auth);\n return (req: IncomingMessage, socket: Socket, head: Buffer): void => {\n // Node drops its own error listener on an upgraded socket: without this one, a visitor resetting\n // the connection while we look the box up (or write a refusal) would crash the daemon.\n socket.on(\"error\", () => socket.destroy());\n void (async () => {\n const headers: IncomingHttpHeaders = req.headers;\n if (!authorized(headers.authorization)) return refuse(socket, 401, \"not authorized\");\n const user = headers[OWNER_HEADER];\n if (typeof user !== \"string\" || !LOCAL_OWNER_RE.test(user)) return refuse(socket, 400, \"X-Kvbox-Owner header required\");\n let target: Target;\n try {\n target = await targetOf(new URL(req.url ?? \"/\", \"https://host\"), `${user}@${cp.name}`, visitorPath(headers[VISITOR_PATH_HEADER]), wants(headers[WAKE_HEADER]) ? wake : undefined);\n } catch (err) {\n if (err instanceof ProxyFailure) return refuse(socket, err.status, err.message, err.code);\n return refuse(socket, 500, (err as Error).message);\n }\n // the visitor may have left while we looked: then there is nobody to open the box for\n if (socket.destroyed) return;\n const box = connect({ host: target.ip, port: target.port, timeout: CONNECT_TIMEOUT_MS });\n let connected = false;\n let piped = false;\n box.once(\"timeout\", () => box.destroy(new Error(\"timed out\")));\n box.once(\"error\", (err: Error & { code?: string }) => {\n if (!connected && !socket.destroyed) refuse(socket, 502, `box answered nothing on port ${target.port} (${err.code ?? err.message})`, \"unreachable\", target.woke);\n else if (piped) socket.destroy();\n });\n socket.once(\"close\", () => box.destroy());\n box.once(\"close\", () => {\n if (piped) socket.destroy();\n });\n box.once(\"connect\", () => {\n connected = true;\n box.setTimeout(0);\n const lines = boxHeaders(headerPairs(req.rawHeaders), target, true).map(([k, v]) => `${k}: ${v}\\r\\n`);\n box.write(`${req.method ?? \"GET\"} ${target.path} HTTP/1.1\\r\\n${lines.join(\"\")}\\r\\n`);\n if (head.length > 0) box.write(head);\n readHead(box, { maxBytes: MAX_HANDSHAKE_BYTES, timeoutMs: headersTimeoutMs }).then(\n (answer) => {\n if (socket.destroyed) return void box.destroy();\n socket.write(rewriteHead(answer.head, (name) => name.startsWith(\"x-kvbox-\"), { [PROXIED_HEADER]: \"1\", ...(target.woke ? { [WOKE_HEADER]: \"1\" } : {}) }));\n if (answer.rest.length > 0) socket.write(answer.rest);\n piped = true;\n box.pipe(socket);\n socket.pipe(box);\n },\n (err: Error) => {\n box.destroy();\n if (socket.destroyed) return;\n if (err instanceof HeadTimeoutError) refuse(socket, 504, `box took over ${headersTimeoutMs / 1000} s to answer on port ${target.port}`, \"timeout\", target.woke);\n else refuse(socket, 502, `box gave no answer on port ${target.port} (${err.message})`, \"unreachable\", target.woke);\n },\n );\n });\n })();\n };\n}\n","/**\n * The head of an HTTP/1.1 answer read off a raw socket (#31). A WebSocket goes edge → host → box as\n * piped bytes, so both hops read the answer to the handshake themselves: the host to stamp the box's\n * answer as the box's and drop any `x-kvbox-*` it sent, the edge to tell that from the host's refusal.\n */\nimport type { Duplex } from \"node:stream\";\n\nconst END = \"\\r\\n\\r\\n\";\n\n/** Nothing came before `timeoutMs`: the box (or host) took the connection and said nothing. */\nexport class HeadTimeoutError extends Error {}\n\n/**\n * What `socket` answers, up to its blank line: the head (status line and headers, no blank line) and\n * whatever came after it in the same reads. The socket is left paused with nothing more consumed.\n */\nexport function readHead(socket: Duplex, opts: { maxBytes: number; timeoutMs: number }): Promise<{ head: string; rest: Buffer }> {\n return new Promise((resolve, reject) => {\n let bytes = Buffer.alloc(0);\n const done = (err?: Error) => {\n clearTimeout(timer);\n socket.off(\"data\", onData);\n socket.off(\"close\", onClose);\n socket.pause();\n if (err) return reject(err);\n const end = bytes.indexOf(END);\n resolve({ head: bytes.subarray(0, end).toString(\"latin1\"), rest: bytes.subarray(end + END.length) });\n };\n const onData = (chunk: Buffer) => {\n bytes = Buffer.concat([bytes, chunk]);\n if (bytes.includes(END)) done();\n else if (bytes.length > opts.maxBytes) done(new Error(\"answer head too large\"));\n };\n const onClose = () => done(new Error(\"closed before answering\"));\n const timer = setTimeout(() => done(new HeadTimeoutError(`no answer within ${opts.timeoutMs / 1000} s`)), opts.timeoutMs);\n socket.on(\"data\", onData);\n socket.once(\"close\", onClose);\n });\n}\n\n/** The value of header `name` (lowercase) in a head, or undefined. */\nexport function headHeader(head: string, name: string): string | undefined {\n const line = head.split(\"\\r\\n\").slice(1).find((l) => l.slice(0, l.indexOf(\":\")).trim().toLowerCase() === name);\n return line?.slice(line.indexOf(\":\") + 1).trim();\n}\n\n/** The head again with the headers `drop` names left out and `add` appended, blank line included. */\nexport function rewriteHead(head: string, drop: (name: string) => boolean, add: Record<string, string> = {}): Buffer {\n const [status, ...lines] = head.split(\"\\r\\n\");\n const kept = lines.filter((l) => !drop(l.slice(0, l.indexOf(\":\")).trim().toLowerCase()));\n const extra = Object.entries(add).map(([k, v]) => `${k}: ${v}`);\n return Buffer.from(`${[status, ...kept, ...extra].join(\"\\r\\n\")}${END}`, \"latin1\");\n}\n","import { Hono } from \"hono\";\nimport { capacity } from \"../core/capacity.js\";\nimport { VERSION } from \"../version.js\";\n\nexport function capacityRoutes() {\n const r = new Hono();\n // The version rides along so the control plane's poller keeps it on the host row (`GET /admin/hosts`).\n r.get(\"/\", async (c) => c.json({ ...(await capacity()), version: VERSION }));\n return r;\n}\n","/**\n * Environment variables (#88). `POST /env` is the control plane handing this host an owner's whole\n * list (the caller's: `X-Kvbox-Owner`); `GET /env` says which version is held per owner, the realm's\n * without the header, for the control plane's sweep. Values are never sent back.\n */\nimport { Hono } from \"hono\";\nimport { HostEnvRequest } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { listEnvVersions, setOwnerEnv } from \"../core/env.js\";\nimport type { Env } from \"../caller.js\";\n\nexport function envRoutes() {\n const r = new Hono<Env>();\n r.get(\"/\", async (c) => c.json(await listEnvVersions(c.get(\"listScope\"))));\n r.post(\"/\", async (c) => {\n const body = HostEnvRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"env: expected {version, vars: [{name, value}]}\");\n return c.json(await setOwnerEnv(c.get(\"owner\"), body.data));\n });\n return r;\n}\n","import { Hono } from \"hono\";\nimport {\n CreateMachineRequest,\n ForkMachineRequest,\n LinkRequest,\n PortsRequest,\n RescaleMachineRequest,\n RunScriptRequest,\n StartMachineRequest,\n SetEnvRequest,\n SetMachineRequest,\n SetSshKeysRequest,\n type BoxEnv,\n type BoxEnvChange,\n} from \"@kvbox/shared/api\";\nimport { envNameProblem } from \"@kvbox/shared/env\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport {\n addLink,\n addPorts,\n createMachine,\n destroyMachine,\n forkMachine,\n getMachine,\n hibernateMachine,\n listMachines,\n pauseMachine,\n removeLink,\n removePorts,\n rescaleMachine,\n resumeMachine,\n setMachine,\n setSshKeys,\n startMachine,\n stopMachine,\n updateMachine,\n wakeMachine,\n} from \"../core/machines.js\";\nimport { readBoxEnv, rmBoxVar, setBoxVar, shownBoxEnv } from \"../core/env.js\";\nimport { ownerFor, parseRef } from \"../core/refs.js\";\nimport { machineStats } from \"../core/stats.js\";\nimport { runBoxScript } from \"../core/scripts.js\";\nimport { machineUsage } from \"../core/usage.js\";\nimport type { Env } from \"../caller.js\";\n\nexport function machineRoutes() {\n const r = new Hono<Env>();\n r.get(\"/\", async (c) => c.json(await listMachines(c.get(\"listScope\"))));\n r.post(\"/\", async (c) => {\n const body = CreateMachineRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await createMachine(body, c.get(\"owner\")), 201);\n });\n // The source is the caller's (X-Kvbox-Owner), like every box route; the copy goes to `owner` (#79).\n r.post(\"/:name/fork\", async (c) => {\n const body = ForkMachineRequest.parse(await c.req.json().catch(() => ({})));\n const caller = c.get(\"owner\");\n const into = body.owner === undefined ? caller : ownerFor(body.owner, caller);\n return c.json(await forkMachine(parseRef(c.req.param(\"name\"), caller), into, body), 201);\n });\n r.post(\"/:name/stop\", async (c) => c.json(await stopMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.post(\"/:name/start\", async (c) => {\n const body = StartMachineRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await startMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")), undefined, body.force ?? false));\n });\n r.post(\"/:name/pause\", async (c) => c.json(await pauseMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.post(\"/:name/resume\", async (c) => c.json(await resumeMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.post(\"/:name/hibernate\", async (c) => c.json(await hibernateMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.post(\"/:name/wake\", async (c) => {\n const body = StartMachineRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await wakeMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")), undefined, body.force ?? false));\n });\n r.post(\"/:name/update\", async (c) => c.json(await updateMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.post(\"/:name/rescale\", async (c) => {\n const body = RescaleMachineRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await rescaleMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body));\n });\n r.post(\"/:name/set\", async (c) => {\n const body = SetMachineRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await setMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body));\n });\n r.post(\"/:name/ssh-keys\", async (c) => {\n const body = SetSshKeysRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"sshKeys: expected a list of authorized_keys lines\");\n const { machine, applied } = await setSshKeys(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data.sshKeys);\n return c.json({ ...machine, sshKeysApplied: applied });\n });\n // Published box ports (#30): both answer with the box, its `ports` as they are now.\n r.post(\"/:name/ports\", async (c) => {\n const body = PortsRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"ports: expected a list of box ports\");\n return c.json(await addPorts(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data), 201);\n });\n r.delete(\"/:name/ports\", async (c) => {\n const body = PortsRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"ports: expected a list of box ports\");\n return c.json(await removePorts(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data));\n });\n // Links into a box (#98): both answer with the box, its `links` as they are now.\n const linkBody = async (c: { req: { json: () => Promise<unknown> } }) => {\n const body = LinkRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"links: expected {from, port}\");\n return body.data;\n };\n r.post(\"/:name/links\", async (c) => c.json(await addLink(parseRef(c.req.param(\"name\"), c.get(\"owner\")), await linkBody(c), c.get(\"owner\")), 201));\n r.delete(\"/:name/links\", async (c) => c.json(await removeLink(parseRef(c.req.param(\"name\"), c.get(\"owner\")), await linkBody(c), c.get(\"owner\"))));\n r.get(\"/:name/usage\", async (c) => {\n const since = c.req.query(\"since\");\n let from: string | undefined;\n if (since !== undefined) {\n const t = Date.parse(since);\n if (Number.isNaN(t)) throw new KvboxError(`since: \"${since}\" is not a date; write it like 2026-10-19 or 2026-10-19T08:00:00Z`);\n from = new Date(t).toISOString();\n }\n return c.json(await machineUsage(parseRef(c.req.param(\"name\"), c.get(\"owner\")), from));\n });\n // A box's own variables (#87): kept beside its meta.json, over its owner's at its next start.\n r.get(\"/:name/env\", async (c) => {\n const ref = parseRef(c.req.param(\"name\"), c.get(\"owner\"));\n await getMachine(ref);\n return c.json({ box: ref.name, vars: shownBoxEnv(await readBoxEnv(ref)) } satisfies BoxEnv);\n });\n r.post(\"/:name/env/:var\", async (c) => {\n const ref = parseRef(c.req.param(\"name\"), c.get(\"owner\"));\n const name = c.req.param(\"var\");\n const problem = envNameProblem(name);\n if (problem !== null) throw new KvboxError(problem);\n const body = SetEnvRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"expected {value, secret?}\");\n await setBoxVar(ref, name, body.data.value, body.data.secret ?? false);\n const box = await getMachine(ref);\n return c.json({ box: ref.name, name, running: box.status !== \"stopped\" } satisfies BoxEnvChange);\n });\n r.delete(\"/:name/env/:var\", async (c) => {\n const ref = parseRef(c.req.param(\"name\"), c.get(\"owner\"));\n const name = c.req.param(\"var\");\n await rmBoxVar(ref, name);\n const box = await getMachine(ref);\n return c.json({ box: ref.name, name, running: box.status !== \"stopped\" } satisfies BoxEnvChange);\n });\n // A script the box's image names (#173); the answer is `{output}`, whatever the script printed.\n r.post(\"/:name/scripts/:script\", async (c) => {\n const body = RunScriptRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await runBoxScript(parseRef(c.req.param(\"name\"), c.get(\"owner\")), c.req.param(\"script\"), body.input));\n });\n r.get(\"/:name/stats\", async (c) => c.json(await machineStats(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.delete(\"/:name\", async (c) => {\n await destroyMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")));\n return c.body(null, 204);\n });\n return r;\n}\n","/**\n * `kvbox vm top` (#67): a running box's own load, memory and disk, asked of kvbox-agent over vsock,\n * so it answers whatever the box did to its network. Read-only and unlocked: a box that stops\n * mid-question just fails this one answer.\n */\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { MachineStats } from \"@kvbox/shared/api\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { isGuestBooting, isNoAgent, isUnknownOp, stats } from \"./agent.js\";\nimport { getMachine, stateMessage } from \"./machines.js\";\nimport type { BoxRef } from \"./refs.js\";\n\n/** The guest is asked live; a busy one gets this long before the caller hears it did not answer. */\nconst STATS_REPLY_MS = 3_000;\n\nexport async function machineStats(ref: BoxRef, p: Paths = paths(), replyMs = STATS_REPLY_MS): Promise<MachineStats> {\n const m = await getMachine(ref, p);\n if (m.status !== \"running\") throw new KvboxError(`${stateMessage(ref, m.status)}; only a running box can say how it is doing`);\n try {\n return { name: m.name, owner: m.owner, stats: await stats(p.machine(m.owner, m.name).vsock, replyMs) };\n } catch (err) {\n // An image older than base v0.7.0 (an agent without \"stats\", or no agent at all): no numbers, not an\n // error. A guest that is still booting is neither: the caller hears it did not answer, like a busy one.\n if (isUnknownOp(err) || (isNoAgent(err) && !isGuestBooting(err))) return { name: m.name, owner: m.owner, stats: null };\n throw err;\n }\n}\n","/**\n * Image scripts (#173): an image names scripts in its image.json (`scripts`: `status`, `password`, …)\n * and the host runs one by name inside a running box, through kvbox-agent over vsock. The host knows\n * nothing about what a script does: its input and its answer are the image's and the caller's (the\n * control plane's managed services). Unlocked, like `machineStats`: a box that stops mid-question just\n * fails this one answer.\n */\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport type { ScriptOutput } from \"@kvbox/shared/api\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { isNoAgent, isUnknownOp, runScript } from \"./agent.js\";\nimport { imageFileFor, imageLabel, imageManifest } from \"./images.js\";\nimport { stateMessage, statusOf } from \"./machines.js\";\nimport { shown, type BoxRef } from \"./refs.js\";\nimport { readMachineMeta } from \"./state.js\";\n\nexport async function runBoxScript(ref: BoxRef, script: string, input: unknown, p: Paths = paths()): Promise<ScriptOutput> {\n const meta = await readMachineMeta(ref, p).catch((err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") throw new NotFoundError(`box ${shown(ref)}`);\n throw err;\n });\n const manifest = await imageManifest(imageFileFor(meta, p));\n const path = Object.hasOwn(manifest.scripts ?? {}, script) ? manifest.scripts![script] : undefined;\n if (path === undefined) throw new KvboxError(`box ${shown(ref)} runs on ${imageLabel(meta.image)} ${meta.base}, which has no \"${script}\" script`);\n const status = statusOf(meta, p);\n if (status !== \"running\") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be asked`);\n try {\n return { output: await runScript(p.machine(meta.owner, meta.name).vsock, path, input) };\n } catch (err) {\n if (isUnknownOp(err) || isNoAgent(err)) {\n throw new KvboxError(`box ${shown(ref)} did not take the request: its image's kvbox-agent is too old or still starting (${(err as Error).message})`);\n }\n throw err;\n }\n}\n","/**\n * What the usage_events ledger (db.ts) adds up to: one box (`kvbox vm usage <box>`) or every box of\n * an owner (`kvbox usage`, #41). The arithmetic is `computeUsage` in @kvbox/shared/usage, shared with\n * the control plane, which sums the same rows after pulling them (#42).\n */\nimport type { MachineUsage, UsageReport } from \"@kvbox/shared/api\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { computeUsage, groupUsage, groupVolumeUsage, reportTotals } from \"@kvbox/shared/usage\";\nimport { loadConfig } from \"./config.js\";\nimport { usageEventsFor, usageEventsInScope, volumeEventsInScope } from \"./db.js\";\nimport { getMachine, listMachines } from \"./machines.js\";\nimport type { BoxRef, ListScope } from \"./refs.js\";\n\nexport { computeUsage, type UsageEvent, type UsageState, type UsageTotals, type UsageWindow } from \"@kvbox/shared/usage\";\n\n/**\n * Usage of one box from its creation (or `since`, already an ISO string) until now. Reading the box\n * (getMachine) also closes the run of a box whose Firecracker died, so the ledger is current before\n * it is summed.\n */\nexport async function machineUsage(ref: BoxRef, since: string | undefined, p: Paths = paths()): Promise<MachineUsage> {\n const box = await getMachine(ref, p);\n const cfg = await loadConfig(p);\n const now = new Date().toISOString();\n const events = usageEventsFor(box.id, box.createdAt, p);\n const window = { from: since ?? box.createdAt, to: now };\n return { name: box.name, owner: box.owner, status: box.status, window, ...computeUsage(events, { ...window, pricing: cfg.pricing }) };\n}\n\n/**\n * Every box of the owners in `scope` over the window, removed ones included: the ledger keeps their\n * rows, and a name removed and made again is two boxes (two ids). Listing the live boxes first closes\n * any run whose Firecracker died, so the ledger is current. A box with no row inside the window is\n * left out: it did not exist then. Volumes (#91) the same way from their own ledger.\n */\nexport async function usageReport(scope: ListScope, window: { from: string; to: string }, p: Paths = paths()): Promise<UsageReport> {\n const cfg = await loadConfig(p);\n const live = new Map((await listMachines(scope, p)).map((m) => [m.id, m.status]));\n const boxes = groupUsage(usageEventsInScope(scope, window, p), window, cfg.pricing, live);\n const volumes = groupVolumeUsage(volumeEventsInScope(scope, window, p), window, cfg.pricing);\n return { window, boxes, volumes, totals: reportTotals(boxes, volumes, cfg.pricing) };\n}\n","import { Hono } from \"hono\";\nimport { CreateSnapshotRequest } from \"@kvbox/shared/api\";\nimport { deleteSnapshot, listSnapshots, saveSnapshot } from \"../core/snapshots.js\";\nimport { parseRef } from \"../core/refs.js\";\nimport type { Env } from \"../caller.js\";\n\nexport function snapshotRoutes() {\n const r = new Hono<Env>();\n r.get(\"/\", async (c) => c.json(await listSnapshots(c.get(\"listScope\"))));\n r.post(\"/\", async (c) => {\n const body = CreateSnapshotRequest.parse(await c.req.json());\n return c.json(await saveSnapshot(body, c.get(\"owner\")), 201);\n });\n r.delete(\"/:name\", async (c) => {\n await deleteSnapshot(parseRef(c.req.param(\"name\"), c.get(\"owner\")));\n return c.body(null, 204);\n });\n return r;\n}\n","/**\n * The SSH CA on a host (#55). `POST /ssh/trust-ca` makes every cloud box trust a new CA, `GET\n * /ssh/cloud-ca` asks the joined control plane which CA that should be. Both exist on the Unix\n * socket only: adding a trusted CA to every box is the most powerful thing a host can do, so it\n * takes someone on the host itself, never the control plane (or whoever holds its token).\n */\nimport { Hono } from \"hono\";\nimport { TrustCaRequestSchema } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { CallerOptions, Env } from \"../caller.js\";\nimport { fetchCloudCa } from \"../core/controlPlane.js\";\nimport { trustCa } from \"../core/machines.js\";\n\nexport function sshRoutes(opts: CallerOptions = {}) {\n const r = new Hono<Env>();\n if (opts.controlPlane) {\n r.all(\"/*\", (c) => c.json({ error: \"trusting a CA is done on the host itself (kvbox-server trust-ca there); the control plane cannot ask a host to\" }, 403));\n return r;\n }\n r.get(\"/cloud-ca\", async (c) => c.json(await fetchCloudCa()));\n r.post(\"/trust-ca\", async (c) => {\n const body = TrustCaRequestSchema.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"trust-ca: expected the CA public key as publicKey\");\n return c.json(await trustCa(body.data.publicKey));\n });\n return r;\n}\n","/**\n * The usage ledger over HTTP. `GET /usage?since=&until=` is the host-wide report (#41) for the\n * caller's boxes. `GET /usage/events?after=&limit=` hands out raw ledger rows by id for a control\n * plane to pull (#42): over HTTPS only the caller's realm (or, with `X-Kvbox-Owner`, that one\n * owner) comes back, so the host owner's local boxes never leave the host; over the socket the\n * host owner gets every row.\n */\nimport { Hono } from \"hono\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { usageWindow } from \"@kvbox/shared/usage\";\nimport type { CallerOptions, Env } from \"../caller.js\";\nimport { ledgerId, usageEventsAfter, volumeEventsAfter } from \"../core/db.js\";\nimport { usageReport } from \"../core/usage.js\";\n\n/** Rows per pull; the control plane keeps pulling while a page comes back full. */\nexport const PULL_LIMIT = 1000;\n\nexport function usageRoutes(opts: CallerOptions = {}) {\n const r = new Hono<Env>();\n r.get(\"/\", async (c) => {\n let window;\n try {\n window = usageWindow(c.req.query(\"since\"), c.req.query(\"until\"));\n } catch (err) {\n throw new KvboxError((err as Error).message);\n }\n return c.json(await usageReport(c.get(\"listScope\"), window));\n });\n r.get(\"/events\", async (c) => {\n const after = whole(c.req.query(\"after\") ?? \"0\", \"after\");\n const limit = Math.min(whole(c.req.query(\"limit\") ?? String(PULL_LIMIT), \"limit\") || PULL_LIMIT, PULL_LIMIT);\n // The socket app trusts its caller: the whole ledger. The HTTPS app's scope is its realm or the named owner.\n const scope = opts.controlPlane === undefined ? null : c.get(\"listScope\");\n const events = usageEventsAfter(after, limit, scope);\n return c.json({ ledger: ledgerId(), events, next: events.length === 0 ? after : events[events.length - 1]!.id });\n });\n // The volume ledger (#91), pulled the same way: same ledger id, its own row ids and cursor.\n r.get(\"/volume-events\", async (c) => {\n const after = whole(c.req.query(\"after\") ?? \"0\", \"after\");\n const limit = Math.min(whole(c.req.query(\"limit\") ?? String(PULL_LIMIT), \"limit\") || PULL_LIMIT, PULL_LIMIT);\n const scope = opts.controlPlane === undefined ? null : c.get(\"listScope\");\n const events = volumeEventsAfter(after, limit, scope);\n return c.json({ ledger: ledgerId(), events, next: events.length === 0 ? after : events[events.length - 1]!.id });\n });\n return r;\n}\n\nfunction whole(value: string, name: string): number {\n const n = Number(value);\n if (!Number.isInteger(n) || n < 0) throw new KvboxError(`${name}: expected a whole number, got \"${value}\"`);\n return n;\n}\n","/**\n * Volumes (#52). A volume is the caller's (`X-Kvbox-Owner` over HTTPS, the host owner over the socket),\n * named bare or as owner/name like a box. Attach and detach answer with the box, as it is after the\n * change (running again if it was running: Firecracker takes drives at boot only).\n */\nimport { Hono } from \"hono\";\nimport { AttachVolumeRequest, CreateVolumeRequest, ResizeVolumeRequest } from \"@kvbox/shared/api\";\nimport { attachVolume, detachVolume, resizeVolume } from \"../core/machines.js\";\nimport { parseRef } from \"../core/refs.js\";\nimport { createVolume, deleteVolume, getVolume, listVolumes } from \"../core/volumes.js\";\nimport type { Env } from \"../caller.js\";\n\nexport function volumeRoutes() {\n const r = new Hono<Env>();\n r.get(\"/\", async (c) => c.json(await listVolumes(c.get(\"listScope\"))));\n r.post(\"/\", async (c) => {\n const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await createVolume(body, c.get(\"owner\")), 201);\n });\n r.get(\"/:name\", async (c) => c.json(await getVolume(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.delete(\"/:name\", async (c) => {\n await deleteVolume(parseRef(c.req.param(\"name\"), c.get(\"owner\")));\n return c.body(null, 204);\n });\n r.post(\"/:name/attach\", async (c) => {\n const body = AttachVolumeRequest.parse(await c.req.json().catch(() => ({})));\n const owner = c.get(\"owner\");\n return c.json(await attachVolume(parseRef(body.box, owner), parseRef(c.req.param(\"name\"), owner)));\n });\n r.post(\"/:name/detach\", async (c) => {\n const body = AttachVolumeRequest.parse(await c.req.json().catch(() => ({})));\n const owner = c.get(\"owner\");\n return c.json(await detachVolume(parseRef(body.box, owner), parseRef(c.req.param(\"name\"), owner)));\n });\n // #147: answers the volume at its new size; the box holding it, if it was running, is running again.\n r.post(\"/:name/resize\", async (c) => {\n const body = ResizeVolumeRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await resizeVolume(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.sizeGib));\n });\n return r;\n}\n","/**\n * Builds the kvbox-server commander tree, one file per command under commands/. Importable without side\n * effects (tests); src/index.ts runs it. `start` is the daemon (the systemd unit runs `kvbox-server start`);\n * everything else manages it from the host's terminal. A bare `kvbox-server` prints help, like `kvbox`.\n */\nimport { Command } from \"commander\";\nimport { backupCommand } from \"./commands/backup/index.js\";\nimport { joinCommand } from \"./commands/join.js\";\nimport { leaveCommand } from \"./commands/leave.js\";\nimport { logsCommand } from \"./commands/logs.js\";\nimport { netCommand } from \"./commands/net.js\";\nimport { relayCommand } from \"./commands/relay.js\";\nimport { renameRealmCommand } from \"./commands/rename-realm.js\";\nimport { startCommand } from \"./commands/start.js\";\nimport { statusCommand } from \"./commands/status.js\";\nimport { stopCommand } from \"./commands/stop.js\";\nimport { trustCaCommand } from \"./commands/trust-ca.js\";\nimport { VERSION } from \"./version.js\";\n\nexport function buildProgram(): Command {\n return new Command(\"kvbox-server\")\n .description(\"kvbox host daemon: owns Firecracker and $KVBOX_HOME (~/.kvbox), serves the kvbox API\")\n .version(VERSION, \"-v, --version\")\n .showHelpAfterError()\n .addCommand(startCommand)\n .addCommand(stopCommand)\n .addCommand(statusCommand)\n .addCommand(logsCommand)\n .addCommand(joinCommand)\n .addCommand(leaveCommand)\n .addCommand(relayCommand)\n .addCommand(trustCaCommand)\n .addCommand(renameRealmCommand)\n .addCommand(backupCommand)\n .addCommand(netCommand);\n}\n","import { Command } from \"commander\";\nimport { setupCommand } from \"./setup.js\";\nimport { statusCommand } from \"./status.js\";\n\nexport const backupCommand = new Command(\"backup\")\n .description(\"make this host a backup store: box backups are kept on a disk of its own, in Garage\")\n .addCommand(setupCommand)\n .addCommand(statusCommand);\n","/**\n * kvbox-server backup setup --path <dir> [--force] [--new-store] [--json] — make this host a backup store: Garage is\n * installed and keeps its data in <dir> (a directory on the disk bought for backups, already mounted),\n * one key is made, and the control plane this host joined is told. Run again with the same path, it\n * finishes a setup that stopped half way and registers the store again; a path that does not hold the\n * store (its disk not mounted, or a new disk) is refused unless --new-store says the old disk is gone. Through the running daemon's\n * socket: the daemon is what keeps Garage up afterwards.\n * --json output: BackupStoreStatus {path, bucket, accessKey, running, totalBytes, freeBytes, objects?, storedBytes?, registered}\n */\nimport { resolve } from \"node:path\";\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { SocketClient } from \"../../socketClient.js\";\nimport { printStore } from \"./output.js\";\n\nexport const setupCommand = new Command(\"setup\")\n .description(\"keep box backups on this host: run Garage with its data in a directory on the backup disk, and tell the control plane\")\n .requiredOption(\"--path <dir>\", \"a directory on the disk for backups (mounted already)\")\n .option(\"--force\", \"use the path even when it is on the same disk as this host's boxes\")\n .option(\"--new-store\", \"the store's disk is gone for good: start a new store at the path (the old backups are lost)\")\n .option(\"--json\", \"print the store as JSON\")\n .action(async (opts: { path: string; force?: boolean; newStore?: boolean; json?: boolean }) => {\n const client = new SocketClient(paths().serverSock);\n try {\n if (!opts.json) console.log(\"setting up the backup store (the first time downloads Garage, which can take a minute)\");\n const store = await client.setupBackupStore({ path: resolve(opts.path), ...(opts.force ? { force: true } : {}), ...(opts.newStore ? { newStore: true } : {}) });\n if (opts.json) return console.log(JSON.stringify(store, null, 2));\n console.log(\"this host is now a backup store; new backups can be kept here\");\n printStore(store);\n } finally {\n await client.close();\n }\n });\n","/** How `backup setup` and `backup status` print a store: one aligned `label value` row per fact. */\nimport type { BackupStoreStatus } from \"@kvbox/shared/api\";\n\nfunction size(bytes: number): string {\n const gib = bytes / 1024 ** 3;\n return gib >= 1024 ? `${(gib / 1024).toFixed(1)} TB` : `${gib.toFixed(1)} GB`;\n}\n\nexport function printStore(s: BackupStoreStatus): void {\n const rows: [string, string][] = [\n [\"path\", s.path],\n [\"storage\", s.running ? \"running\" : \"not running (the daemon starts it again within a minute; kvbox-server logs says why if it does not)\"],\n [\"disk\", `${size(s.totalBytes - s.freeBytes)} used of ${size(s.totalBytes)}, ${size(s.freeBytes)} free`],\n ];\n if (s.storedBytes !== undefined) rows.push([\"backups\", `${size(s.storedBytes)} in ${s.objects ?? 0} chunks`]);\n rows.push([\"key\", s.accessKey]);\n rows.push([\"control plane\", s.registered ? \"knows this store\" : \"does not know this store yet: run kvbox-server backup setup again with the same path\"]);\n const width = Math.max(...rows.map(([label]) => label.length));\n for (const [label, value] of rows) console.log(`${label.padEnd(width)} ${value}`);\n}\n","/**\n * kvbox-server backup status [--json] — this host's backup store: where its data is, whether Garage\n * runs, how full the disk is, what the backups take, and whether the control plane knows it.\n * --json output: BackupStoreStatus {path, bucket, accessKey, running, totalBytes, freeBytes, objects?, storedBytes?, registered}\n */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { SocketClient } from \"../../socketClient.js\";\nimport { printStore } from \"./output.js\";\n\nexport const statusCommand = new Command(\"status\")\n .description(\"show this host's backup store: its disk, whether it runs and what it holds\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }) => {\n const client = new SocketClient(paths().serverSock);\n try {\n const store = await client.backupStore();\n if (opts.json) console.log(JSON.stringify(store, null, 2));\n else printStore(store);\n } finally {\n await client.close();\n }\n });\n","/**\n * kvbox-server join <url> --token <t> — register this host with a control plane (M2), then restart a\n * running daemon so it answers that control plane over HTTPS now.\n */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { joinControlPlane } from \"../core/controlPlane.js\";\nimport { restartDaemon, runningPid } from \"../daemon.js\";\n\nexport const joinCommand = new Command(\"join\")\n .description(\"put this host behind a control plane (needs a one-time token minted there) and restart the daemon\")\n .argument(\"<control-plane-url>\", \"the control plane, e.g. https://api.kvbox.sh\")\n .requiredOption(\"--token <token>\", \"one-time join token from the control plane\")\n .option(\"--advertise <host-or-ip>\", \"address the control plane reaches this host at (default: this host's default-route address)\")\n .option(\"--name <name>\", \"how the control plane lists this host (default: hostname)\")\n .option(\"--country <country>\", \"where this host is, a name or a code (romania, US); kvbox new --country places boxes by it\")\n .action(async (url: string, opts: { token: string; advertise?: string; name?: string; country?: string }) => {\n const p = paths();\n const joined = await joinControlPlane({ url, ...opts }, p);\n console.log(`joined ${joined.controlPlane} as host ${joined.hostName}`);\n console.log(`make sure port ${new URL(joined.hostUrl).port} is reachable from the control plane`);\n if ((await runningPid(p)) === null) {\n console.log(`it answers the control plane on ${joined.hostUrl} once the daemon starts (kvbox-server start -d)`);\n return;\n }\n const started = await restartDaemon(p);\n console.log(`kvbox-server restarted (pid ${started.pid}); it answers the control plane on ${joined.hostUrl} now`);\n });\n","/** kvbox-server leave — forget the control plane this host joined, then restart a running daemon so the HTTPS port closes now. */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { leaveControlPlane } from \"../core/controlPlane.js\";\nimport { restartDaemon, runningPid } from \"../daemon.js\";\n\nexport const leaveCommand = new Command(\"leave\")\n .description(\"take this host out from behind its control plane and restart the daemon\")\n .action(async () => {\n const p = paths();\n const left = await leaveControlPlane(p);\n console.log(`left ${left.controlPlane}`);\n if (!left.told) console.log(`(the control plane could not be told; remove this host there)`);\n if ((await runningPid(p)) === null) {\n console.log(\"the HTTPS port stays closed from the daemon's next start\");\n return;\n }\n const started = await restartDaemon(p);\n console.log(`kvbox-server restarted (pid ${started.pid}); only this machine talks to it now`);\n });\n","/**\n * kvbox-server logs [-n <lines>] [-f] — the daemon's log, $KVBOX_HOME/server.log: its own lines\n * (core/log.ts, `[time][level]: message`) and, under the systemd unit, everything else it printed.\n * The last `-n` lines (50), then with `-f` every line as it is written, until Ctrl-C.\n */\nimport { open, readFile, stat } from \"node:fs/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\n\nexport const logsCommand = new Command(\"logs\")\n .description(\"show the daemon's log ($KVBOX_HOME/server.log); -f keeps printing as it grows\")\n .option(\"-n, --lines <n>\", \"how many lines to show from the end\", \"50\")\n .option(\"-f, --follow\", \"keep printing new lines until Ctrl-C\")\n .action(async (opts: { lines: string; follow?: boolean }) => {\n const n = Number.parseInt(opts.lines, 10);\n if (!Number.isInteger(n) || n < 0) throw new KvboxError(`--lines: expected a number, got ${opts.lines}`);\n const p = paths();\n const text = await readFile(p.serverLog, \"utf8\").catch((err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") throw new KvboxError(`no log yet at ${p.serverLog} (the daemon writes it once it has run)`);\n throw err;\n });\n const tail = tailLines(text, n);\n if (tail !== \"\") process.stdout.write(`${tail}\\n`);\n if (!opts.follow) return;\n const ac = new AbortController();\n process.once(\"SIGINT\", () => ac.abort());\n process.once(\"SIGTERM\", () => ac.abort());\n await follow(p.serverLog, (chunk) => process.stdout.write(chunk), { from: Buffer.byteLength(text), signal: ac.signal });\n });\n\n/** The last `n` lines of `text` (a trailing newline is not a line); \"\" for n = 0. */\nexport function tailLines(text: string, n: number): string {\n if (n === 0) return \"\";\n const lines = text.endsWith(\"\\n\") ? text.slice(0, -1).split(\"\\n\") : text.split(\"\\n\");\n return lines.slice(-n).join(\"\\n\");\n}\n\nexport interface FollowOptions {\n /** The byte offset to start from (what was already shown); default: the end of the file now. */\n from?: number;\n /** How often to look for new bytes. */\n intervalMs?: number;\n signal?: AbortSignal;\n}\n\n/**\n * Hand every byte appended to `path` to `write`, polling, until `signal` aborts. A file that shrinks\n * (truncated, or replaced by a rotation) is read again from its start. Polling rather than fs.watch: it\n * works the same on every filesystem and the file may not exist yet.\n */\nexport async function follow(path: string, write: (chunk: string) => void, opts: FollowOptions = {}): Promise<void> {\n const intervalMs = opts.intervalMs ?? 250;\n let offset = opts.from ?? (await stat(path).then((s) => s.size, () => 0));\n while (!opts.signal?.aborted) {\n const size = await stat(path).then((s) => s.size, () => 0);\n if (size < offset) offset = 0;\n if (size > offset) {\n const fh = await open(path, \"r\");\n try {\n const buf = Buffer.alloc(size - offset);\n const { bytesRead } = await fh.read(buf, 0, buf.length, offset);\n write(buf.subarray(0, bytesRead).toString(\"utf8\"));\n offset += bytesRead;\n } finally {\n await fh.close();\n }\n }\n await sleep(intervalMs, undefined, { signal: opts.signal }).catch(() => undefined);\n }\n}\n","/** kvbox-server net up|down|status — the host network (bridge, forwarding, NAT) through the root helper net-setup.sh. */\nimport { spawnSync } from \"node:child_process\";\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { loadConfig } from \"../core/config.js\";\nimport { netSetupScript } from \"../core/network.js\";\n\nexport const netCommand = new Command(\"net\")\n .description(\"host network: up | down | status (bridge, forwarding, NAT; uses sudo)\")\n .argument(\"<action>\", \"up, down or status\")\n .action(async (action: string) => {\n if (![\"up\", \"down\", \"status\"].includes(action)) throw new KvboxError(\"net: expected up, down or status\");\n const cfg = await loadConfig(paths());\n const res = spawnSync(netSetupScript(), [action], {\n stdio: \"inherit\",\n env: { ...process.env, KVBOX_BRIDGE: cfg.bridge, KVBOX_SUBNET: cfg.subnet, KVBOX_GATEWAY: cfg.gateway },\n });\n process.exit(res.status ?? 1);\n });\n","/**\n * kvbox-server relay <join-string> | off — dial the tunnel to a relay that lends this host a public IP\n * (what `kvbox-relay add` printed there, #50), or take it down. No daemon restart: the HTTPS listener\n * already answers on every address.\n */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { dropRelay, useRelay } from \"../core/relay.js\";\n\nexport const relayCommand = new Command(\"relay\")\n .description(\"reach the internet through a relay (paste what `kvbox-relay add` printed on the relay VM); `off` takes the tunnel down\")\n .argument(\"<join-string>\", \"the line `kvbox-relay add` printed, or `off`\")\n .action(async (joinString: string) => {\n if (joinString === \"off\") {\n const relay = await dropRelay(paths());\n console.log(`tunnel to relay ${relay.name} is down; this host no longer answers at ${relay.publicIp}`);\n return;\n }\n const relay = await useRelay(joinString, paths());\n console.log(`tunnel to relay ${relay.name} (${relay.endpoint}) is up`);\n console.log(`this host is reachable at ${relay.publicIp}; kvbox-server join advertises it by default`);\n });\n","/**\n * kvbox-server rename-realm [name] [--from <old>] [-y] [--json] — the control plane this host joined\n * changed its name (`KVBOX_CLOUD_NAME`): move every cloud box, snapshot and volume on this host from\n * `<user>@<old>` to `<user>@<new>`. Without a name, the control plane is asked what it calls itself now.\n * The daemon is stopped for the few seconds it takes and started again; boxes keep running.\n * --json output: RealmRename {from, to, boxes, snapshots, volumes, keysUpdated: [\"owner/name\"], keysPending: [{box, when, why?}]}\n */\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { loadConfig } from \"../core/config.js\";\nimport { fetchCloudName } from \"../core/controlPlane.js\";\nimport { countRealm, renameRealm, type RealmRename } from \"../core/realm.js\";\nimport { daemonPid, startDetached, stopDaemon } from \"../daemon.js\";\nimport { confirm } from \"./trust-ca.js\";\n\nexport const renameRealmCommand = new Command(\"rename-realm\")\n .description(\"move this host's cloud boxes to the control plane's new name (after KVBOX_CLOUD_NAME changed there)\")\n .argument(\"[name]\", \"the new name; without it the control plane is asked\")\n .option(\"--from <old>\", \"the name the boxes are under now (default: the one this host joined under)\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .option(\"--json\", \"print the report as JSON\")\n .action(async (name: string | undefined, opts: { from?: string; yes?: boolean; json?: boolean }) => {\n const p = paths();\n const cp = (await loadConfig(p)).controlPlane;\n const from = opts.from ?? cp?.name;\n if (from === undefined) throw new KvboxError(\"this host has not joined a control plane; say which name the boxes are under: --from <old>\");\n const to = name ?? (await fetchCloudName(p));\n if (from === to) {\n if (!opts.json) console.log(`nothing to do: the control plane is called ${to} and this host's boxes are already under that name`);\n else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [] } satisfies RealmRename, null, 2));\n return;\n }\n const count = await countRealm(from, to, p);\n if (!opts.json) {\n console.log(`${name === undefined ? `the control plane is now called ${to}; ` : \"\"}this host has ${count.boxes} box(es), ${count.snapshots} snapshot(s) and ${count.volumes} volume(s) under ${from}`);\n }\n if (!(await confirm(`move them to ${to}? (kvbox-server restarts; boxes keep running, a backup in progress is lost)`, opts.yes ?? false))) {\n throw new KvboxError(\"cancelled\", 130);\n }\n\n const pid = await daemonPid(p);\n if (pid !== null) await stopDaemon(pid);\n let report: RealmRename;\n try {\n report = await renameRealm(from, to, p);\n } finally {\n // Whatever happened, a host whose daemon ran is not left without one.\n if (pid !== null) await startDetached(p);\n }\n if (opts.json) console.log(JSON.stringify(report, null, 2));\n else describe(report, pid !== null);\n });\n\nconst WHEN: Record<RealmRename[\"keysPending\"][number][\"when\"], string> = {\n start: \"is stopped: it accepts them from its next start\",\n wake: \"is hibernated: it accepts them from its next wake\",\n resume: \"is in standby: it accepts them from its next resume\",\n later: \"is running but could not take the change now; it accepts them from its next stop and start\",\n};\n\nfunction describe(report: RealmRename, restarted: boolean): void {\n console.log(`moved ${report.boxes} box(es), ${report.snapshots} snapshot(s) and ${report.volumes} volume(s) from ${report.from} to ${report.to}`);\n for (const box of report.keysUpdated) console.log(`box ${box} accepts SSH certificates for ${report.to} now`);\n for (const k of report.keysPending) console.log(`box ${k.box} ${WHEN[k.when]}${k.why ? ` (${k.why})` : \"\"}`);\n console.log(restarted ? \"kvbox-server restarted\" : \"kvbox-server was not running; start it with kvbox-server start -d\");\n}\n","/**\n * `kvbox-server rename-realm`: the control plane this host joined changed its name, so every owner\n * `<slug>@<old>` on this host becomes `<slug>@<new>`. The realm is written in many places (decision\n * \"Owner realms\"): the owner folders under machines/, snapshots/ and volumes/, each meta.json (owner,\n * sources, links, the SSH CA line's principals), env/<owner>.json, the usage ledgers and config.json.\n *\n * Done with the daemon stopped (the command sees to that): its locks, DNS and idle watchers are keyed\n * by owner. Boxes keep running: Firecracker has the box folder as its working directory and every\n * drive by a relative name, and a socket bound in a folder is still reached after the folder moves.\n *\n * Everything is read and checked before anything is written, and config.json is written last, so a\n * run that was cut short is finished by running the command again.\n */\nimport { lstat, readFile, readdir, readlink, rename, rm, symlink, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport type { SshKeysApplied } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { isCaLine } from \"@kvbox/shared/ssh\";\nimport { loadConfig, saveConfig } from \"./config.js\";\nimport { closeDb, renameLedgerRealm } from \"./db.js\";\nimport { pushAuthorizedKeys, statusOf } from \"./machines.js\";\nimport { REALM_RE } from \"./refs.js\";\nimport { MachineMetaSchema, SnapshotMetaSchema, VolumeMetaSchema, type MachineMeta } from \"./state.js\";\n\nexport interface RealmRename {\n from: string;\n to: string;\n boxes: number;\n snapshots: number;\n volumes: number;\n /** Boxes whose guest took the new SSH CA line now, as `owner/name`. */\n keysUpdated: string[];\n /** Boxes whose guest takes it later: at its next start, wake or resume, or (`later`) its next stop and start. */\n keysPending: { box: string; when: Exclude<SshKeysApplied, \"now\">; why?: string }[];\n}\n\n/** What a rename would touch, for the command to show before it asks. */\nexport interface RealmCount {\n boxes: number;\n snapshots: number;\n volumes: number;\n}\n\ninterface Entry<T> {\n oldOwner: string;\n name: string;\n /** The meta.json as it will be written. */\n meta: T;\n}\n\ninterface Plan {\n boxes: (Entry<MachineMeta> & { status: ReturnType<typeof statusOf> })[];\n snapshots: Entry<unknown>[];\n volumes: Entry<unknown>[];\n envOwners: string[];\n}\n\nconst esc = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/** Folders (or `<owner>.json` files) of `root` that name an owner of realm `from`. */\nasync function ownersIn(root: string, from: string, suffix = \"\"): Promise<string[]> {\n const entries = await readdir(root).catch((err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") return [] as string[];\n throw err;\n });\n const tail = `@${from}${suffix}`;\n return entries.filter((e) => e.endsWith(tail)).map((e) => e.slice(0, e.length - suffix.length));\n}\n\nasync function namesIn(dir: string): Promise<string[]> {\n return (await readdir(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);\n}\n\nasync function plan(from: string, to: string, p: Paths): Promise<Plan> {\n if (!REALM_RE.test(to)) throw new KvboxError(`\"${to}\" cannot name a realm (letters, digits, '.', '-')`);\n if (from === to) throw new KvboxError(`this host's cloud boxes are already under ${to}`);\n const tail = new RegExp(`@${esc(from)}$`);\n const owner = (o: string) => o.replace(tail, `@${to}`);\n // `alice@old/lab1`, `snapshot:alice@old/warm`, `fork:alice@old/lab1`\n const source = (s: string) => s.replace(new RegExp(`^((?:[a-z]+:)?[^/@]+)@${esc(from)}/`), `$1@${to}/`);\n const caLine = (line: string) =>\n isCaLine(line) ? line.replace(/principals=\"([^\"]*)\"/, (_, list: string) => `principals=\"${list.split(\",\").map(owner).join(\",\")}\"`) : line;\n\n const out: Plan = { boxes: [], snapshots: [], volumes: [], envOwners: await ownersIn(p.env, from, \".json\") };\n const clash = async (path: string, what: string) => {\n if (await lstat(path).then(() => true, () => false)) throw new KvboxError(`${what} already exists under ${to} (${path}); nothing was changed`);\n };\n const read = async <T>(file: string, schema: z.ZodType<T>, what: string): Promise<T> => {\n try {\n return schema.parse(JSON.parse(await readFile(file, \"utf8\")));\n } catch (err) {\n throw new KvboxError(`${what} cannot be read (${file}: ${(err as Error).message}); nothing was changed`);\n }\n };\n\n for (const oldOwner of await ownersIn(p.machines, from)) {\n await clash(p.ownerMachines(owner(oldOwner)), `boxes of ${owner(oldOwner)}`);\n for (const name of await namesIn(p.ownerMachines(oldOwner))) {\n const meta = await read(p.machine(oldOwner, name).meta, MachineMetaSchema, `box ${oldOwner}/${name}`);\n const status = statusOf({ ...meta, owner: oldOwner, name }, p);\n const sshKeys = meta.sshKeys?.map(caLine);\n const keysChanged = sshKeys !== undefined && sshKeys.some((l, i) => l !== meta.sshKeys![i]);\n out.boxes.push({\n oldOwner,\n name,\n status,\n meta: {\n ...meta,\n owner: owner(meta.owner),\n source: source(meta.source),\n ...(sshKeys !== undefined ? { sshKeys } : {}),\n // A stopped box reads its lines at boot; any other guest still holds the old ones.\n ...(keysChanged ? { sshKeysStale: status === \"stopped\" ? undefined : true } : {}),\n ...(meta.links !== undefined ? { links: meta.links.map((l) => ({ ...l, owner: owner(l.owner) })) } : {}),\n },\n });\n }\n }\n for (const oldOwner of await ownersIn(p.snapshots, from)) {\n await clash(p.ownerSnapshots(owner(oldOwner)), `snapshots of ${owner(oldOwner)}`);\n // The dot folders a replace works in (#83) hold no finished snapshot: they move with the owner folder.\n for (const name of (await namesIn(p.ownerSnapshots(oldOwner))).filter((n) => !n.startsWith(\".\"))) {\n const meta = await read(p.snapshot(oldOwner, name).meta, SnapshotMetaSchema, `snapshot ${oldOwner}/${name}`);\n out.snapshots.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner), source: source(meta.source) } });\n }\n }\n for (const oldOwner of await ownersIn(p.volumes, from)) {\n await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);\n for (const name of await namesIn(p.ownerVolumes(oldOwner))) {\n // A volume from before #91 has no id yet; the daemon gives it one when it next reads it.\n const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z.string().optional() }), `volume ${oldOwner}/${name}`);\n out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });\n }\n }\n for (const oldOwner of out.envOwners) await clash(p.ownerEnv(owner(oldOwner)), `the variables of ${owner(oldOwner)}`);\n return out;\n}\n\n/** How many boxes, snapshots and volumes are under realm `from`; throws what `renameRealm` would refuse. */\nexport async function countRealm(from: string, to: string, p: Paths = paths()): Promise<RealmCount> {\n const planned = await plan(from, to, p);\n return { boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length };\n}\n\nasync function writeJson(file: string, value: unknown): Promise<void> {\n const tmp = `${file}.tmp`;\n await writeFile(tmp, JSON.stringify(value, null, 2) + \"\\n\");\n await rename(tmp, file);\n}\n\n/** Write each entry's meta.json where it is now, then move every owner folder of the root. */\nasync function move(entries: Entry<unknown>[], metaOf: (owner: string, name: string) => string, ownerDir: (owner: string) => string, owners: string[], to: (o: string) => string) {\n for (const e of entries) await writeJson(metaOf(e.oldOwner, e.name), e.meta);\n for (const o of owners) await rename(ownerDir(o), ownerDir(to(o)));\n}\n\n/**\n * Move every owner of realm `from` on this host to realm `to`. The daemon must not be running. `from`\n * is usually config.json's control plane name, which then becomes `to`; a host that already joined\n * under the new name while its boxes stayed under the old one passes the old name.\n */\nexport async function renameRealm(from: string, to: string, p: Paths = paths()): Promise<RealmRename> {\n const planned = await plan(from, to, p);\n const tail = new RegExp(`@${esc(from)}$`);\n const owner = (o: string) => o.replace(tail, `@${to}`);\n\n await move(planned.volumes, (o, n) => p.volume(o, n).meta, p.ownerVolumes, await ownersIn(p.volumes, from), owner);\n await move(planned.snapshots, (o, n) => p.snapshot(o, n).meta, p.ownerSnapshots, await ownersIn(p.snapshots, from), owner);\n await move(planned.boxes, (o, n) => p.machine(o, n).meta, p.ownerMachines, await ownersIn(p.machines, from), owner);\n\n // A volume's drive is a link in the box folder to the volume's disk by its full path, which just moved.\n // A running Firecracker has the disk open already; a wake or the next boot follows the link.\n for (const box of planned.boxes) {\n const m = p.machine(box.meta.owner, box.name);\n for (const volume of box.meta.volumes ?? []) {\n const link = m.volumeDrive(volume);\n const target = await readlink(link).catch(() => null); // a restore's placeholder is a plain file\n if (target !== p.volume(box.oldOwner, volume).disk) continue;\n await rm(link, { force: true });\n await symlink(p.volume(box.meta.owner, volume).disk, link);\n }\n }\n for (const o of planned.envOwners) await rename(p.ownerEnv(o), p.ownerEnv(owner(o)));\n\n renameLedgerRealm(from, to, p);\n closeDb(p);\n\n const cfg = await loadConfig(p);\n if (cfg.controlPlane?.name === from) await saveConfig({ ...cfg, controlPlane: { ...cfg.controlPlane, name: to } }, p);\n\n const report: RealmRename = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [] };\n for (const box of planned.boxes) {\n const { meta, status } = box;\n if (!(meta.sshKeys ?? []).some(isCaLine)) continue; // a managed service's box: no certificate opens it\n const key = `${meta.owner}/${meta.name}`;\n if (status === \"stopped\") report.keysPending.push({ box: key, when: \"start\" });\n else if (status === \"hibernated\") report.keysPending.push({ box: key, when: \"wake\" });\n else if (status === \"standby\") report.keysPending.push({ box: key, when: \"resume\" });\n else if (!meta.sshKeysStale) report.keysUpdated.push(key); // a run cut short already gave it the line\n else {\n const why = await pushAuthorizedKeys(meta, p.machine(meta.owner, meta.name).vsock, p);\n if (why === undefined) {\n await writeJson(p.machine(meta.owner, meta.name).meta, { ...meta, sshKeysStale: undefined });\n report.keysUpdated.push(key);\n } else report.keysPending.push({ box: key, when: \"later\", why });\n }\n }\n return report;\n}\n","/**\n * kvbox-server trust-ca [public-key] [--from-cloud] [-y] [--json] — every cloud box on this host trusts\n * a new SSH CA (#55), the step after `ca rotate` on the control plane. Through the running daemon's socket\n * (its box locks are in-process): the control plane cannot ask a host to trust a CA, someone on the host does.\n * --json output: TrustCaReport {publicKey, fingerprint, updated: [\"owner/name\"], pending: [{box, when, why?}], failed: [{box, error}], local, skipped: [\"owner/name\"]}\n */\nimport { Command } from \"commander\";\nimport type { SshKeysApplied, TrustCaReport } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { SocketClient } from \"../socketClient.js\";\n\nexport const trustCaCommand = new Command(\"trust-ca\")\n .description(\"make every cloud box on this host trust a new SSH CA (after `ca rotate` on the control plane)\")\n .argument(\"[public-key]\", \"the CA public key (or its cert-authority line); or --from-cloud\")\n .option(\"--from-cloud\", \"ask the control plane this host joined for its current CA, show the fingerprint, then ask\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .option(\"--json\", \"print the report as JSON\")\n .action(async (publicKey: string | undefined, opts: { fromCloud?: boolean; yes?: boolean; json?: boolean }) => {\n if (publicKey === undefined && !opts.fromCloud) throw new KvboxError(\"give the CA public key, or --from-cloud to fetch it from the control plane this host joined\");\n if (publicKey !== undefined && opts.fromCloud) throw new KvboxError(\"either a public key or --from-cloud, not both\");\n const client = new SocketClient(paths().serverSock);\n try {\n let key = publicKey;\n if (key === undefined) {\n const ca = await client.cloudCa();\n console.log(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);\n if (!(await confirm(\"make every cloud box on this host trust it (in place of the CA it trusts now)?\", opts.yes ?? false))) {\n throw new KvboxError(\"cancelled\", 130);\n }\n key = ca.publicKey;\n }\n const report = await client.trustCa({ publicKey: key });\n if (opts.json) console.log(JSON.stringify(report, null, 2));\n else describeReport(report);\n } finally {\n await client.close();\n }\n });\n\n/** y/N on a terminal; without one it refuses unless `yes`, the way a script must say -y. */\nexport async function confirm(question: string, yes: boolean): Promise<boolean> {\n if (yes) return true;\n if (!process.stdin.isTTY) {\n console.error(\"refusing without -y when stdin is not a terminal\");\n return false;\n }\n const { createInterface } = await import(\"node:readline/promises\");\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();\n return answer === \"y\" || answer === \"yes\";\n } finally {\n rl.close();\n }\n}\n\nconst WHEN: Record<Exclude<SshKeysApplied, \"now\">, string> = {\n start: \"is stopped: it trusts the CA from its next start\",\n wake: \"is hibernated: it trusts the CA from its next wake\",\n resume: \"is in standby: it trusts the CA from its next resume\",\n later: \"is running but could not take it now; it trusts the CA from its next stop and start\",\n};\n\nexport function describeReport(report: TrustCaReport): void {\n console.log(`CA ${report.fingerprint}`);\n for (const box of report.updated) console.log(`box ${box} now trusts the CA`);\n for (const p of report.pending) console.log(`box ${p.box} ${WHEN[p.when as Exclude<SshKeysApplied, \"now\">]}${p.why ? ` (${p.why})` : \"\"}`);\n for (const f of report.failed) console.error(`box ${f.box}: ${f.error}`);\n const parts = [`${report.updated.length} box(es) updated now`, `${report.pending.length} pending`, `${report.failed.length} failed`];\n const skipped = report.skipped ?? [];\n if (skipped.length > 0) parts.push(`${skipped.length} cloud box(es) without a CA line untouched (managed services: no certificate opens them)`);\n if (report.local > 0) parts.push(`${report.local} local box(es) untouched (they trust this host's key only)`);\n console.log(parts.join(\", \"));\n}\n","/**\n * kvbox-server status [--json] — is the daemon running, and what it knows: its version and pid, the\n * control plane it answers, its relay, the base image new boxes get, what it brought back at its last\n * start, and whether systemd starts it at boot (#29). Exit 1 when it is not running.\n * --json output: Health (shared/api) plus `running: true` and `startsAtBoot`; `{running: false, startsAtBoot}` when stopped;\n * `{running: true, reachable: false, pid, startsAtBoot}` when the process lives but its socket is gone (#159).\n */\nimport { homedir } from \"node:os\";\nimport { styleText } from \"node:util\";\nimport { Command } from \"commander\";\nimport type { Health } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { startsAtBoot } from \"@kvbox/shared/systemd\";\nimport { answering, daemonPid } from \"../daemon.js\";\nimport { SocketClient } from \"../socketClient.js\";\n\nexport const statusCommand = new Command(\"status\")\n .description(\"show whether the daemon is running, its control plane and which base image new boxes get\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }) => {\n const p = paths();\n const atBoot = startsAtBoot(p);\n const pid = await daemonPid(p);\n if (pid === null) {\n if (opts.json) {\n console.log(JSON.stringify({ running: false, startsAtBoot: atBoot }, null, 2));\n process.exitCode = 1;\n return;\n }\n throw new KvboxError(`kvbox-server is not running (start it with: kvbox-server start -d)${atBoot ? \"; it starts at boot\" : \"\"}`);\n }\n if (!(await answering(p))) {\n if (opts.json) {\n console.log(JSON.stringify({ running: true, reachable: false, pid, startsAtBoot: atBoot }, null, 2));\n process.exitCode = 1;\n return;\n }\n throw new KvboxError(`kvbox-server is running (pid ${pid}) but its socket is gone, so nothing can reach it; restart it: kvbox-server stop, then kvbox-server start -d`);\n }\n const client = new SocketClient(p.serverSock);\n try {\n const health = await client.health();\n if (opts.json) {\n console.log(JSON.stringify({ running: true, ...health, startsAtBoot: atBoot }, null, 2));\n return;\n }\n printStatus(health, atBoot, p.serverLog);\n } finally {\n await client.close();\n }\n });\n\n/**\n * A header line, then one aligned `label value` row per fact, and what the last restart brought back as\n * its own block. Colour only on a terminal (styleText checks stdout and NO_COLOR).\n */\nfunction printStatus(health: Health, atBoot: boolean, logPath: string): void {\n const dim = (t: string) => styleText(\"dim\", t, { stream: process.stdout });\n const rows: [string, string][] = [];\n rows.push([\"starts at boot\", atBoot ? \"yes, and brings back the boxes that were running\" : `no ${dim(\"(install-server.sh sets that up)\")}`]);\n if (health.controlPlane) {\n rows.push([\"control plane\", `${health.controlPlane.name} ${dim(`(${health.controlPlane.url})`)}`]);\n rows.push([\"answers it on\", health.controlPlane.hostUrl]);\n } else {\n rows.push([\"control plane\", `none ${dim(\"(kvbox-server join <url> --token <token>)\")}`]);\n }\n if (health.relay) {\n rows.push([\"relay\", `${health.relay.name} lends this host ${health.relay.publicIp} ${dim(`(tunnel to ${health.relay.endpoint})`)}`]);\n if (health.relay.restarts && health.relay.lastRestartAt) {\n rows.push([\"tunnel redialed\", `${health.relay.restarts} time(s) since the server started, last at ${health.relay.lastRestartAt}`]);\n }\n }\n rows.push([\"base image\", health.base === null ? \"none usable yet (run install-server.sh)\" : `${health.base} ${dim(\"(what kvbox new uses)\")}`]);\n const home = homedir();\n rows.push([\"log\", `${logPath.startsWith(`${home}/`) ? `~${logPath.slice(home.length)}` : logPath} ${dim(\"(kvbox-server logs -f)\")}`]);\n\n const r = health.recovery;\n const after: [string, string][] = [];\n if (r) {\n if (r.booted.length > 0) after.push([\"booted again\", r.booted.join(\", \")]);\n if (r.leftStopped.length > 0) after.push([\"left stopped\", `${r.leftStopped.join(\", \")} ${dim(\"(were in standby, their memory was lost)\")}`]);\n for (const f of r.failed) after.push([\"did not come back\", `${f.box} ${dim(`(${f.error})`)}`]);\n }\n\n const width = Math.max(...rows.map(([k]) => k.length));\n const line = ([k, v]: [string, string]) => console.log(` ${dim(k.padEnd(width))} ${v}`);\n console.log(`${styleText(\"bold\", `kvbox-server ${health.version}`, { stream: process.stdout })} ${styleText(\"green\", \"● running\", { stream: process.stdout })} ${dim(`(pid ${health.pid})`)}`);\n console.log();\n rows.forEach(line);\n if (after.length > 0) {\n console.log();\n console.log(\" after the last restart\");\n const w = Math.max(...after.map(([k]) => k.length));\n for (const [k, v] of after) console.log(` ${dim(k.padEnd(w))} ${v}`);\n }\n}\n","/** kvbox-server stop — SIGTERM the daemon (server.pid, else the systemd unit's, #159) and wait for it to go. Boxes keep running. */\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { daemonPid, stopDaemon } from \"../daemon.js\";\n\nexport const stopCommand = new Command(\"stop\")\n .description(\"stop the daemon (running boxes are not affected)\")\n .action(async () => {\n const pid = await daemonPid(paths());\n if (pid === null) throw new KvboxError(\"kvbox-server is not running\");\n await stopDaemon(pid);\n console.log(`kvbox-server stopped (pid ${pid}); boxes keep running`);\n });\n","/**\n * kvbox-server entry point: parse argv, map KvboxError to an exit code. The foreground daemon\n * (`kvbox-server` / `kvbox-server start`) reports its errors as server.log lines; the operator\n * subcommands (status, logs, stop, join, …) print a plain `error: …` for the terminal.\n */\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { isDaemon } from \"./commands/start.js\";\nimport { log } from \"./core/log.js\";\nimport { buildProgram } from \"./program.js\";\n\ntry {\n await buildProgram().parseAsync(process.argv);\n} catch (err) {\n if (err instanceof KvboxError) {\n if (isDaemon()) log.error(err.message);\n else console.error(`error: ${err.message}`);\n process.exit(err.exitCode);\n }\n if (isDaemon()) {\n log.error((err as Error).stack ?? String(err));\n process.exit(1);\n }\n throw err;\n}\n"],"mappings":";;;AACO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YACE,SACgB,WAAmB,GACnC;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;AAUO,IAAM,gBAAN,cAA4B,WAAW;AAAA,EAC5C,YAAY,MAAc;AACxB,UAAM,GAAG,IAAI,eAAe,CAAC;AAC7B,SAAK,OAAO;AAAA,EACd;AACF;;;ACjBA,SAAS,eAAe;;;ACAxB,SAAS,eAAe;AACxB,SAAS,YA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AAE,MAAM,CAAC;AAClD,eAAW,CAAC,GAAG,CAAC,KAAK,MAAO,SAAQ,IAAI,OAAO,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE;AAAA,EACzE;AACF;;;AC/FA,SAAS,WAAAC,iBAAe;AAKjB,IAAM,cAAc,IAAIC,UAAQ,MAAM,EAC1C,YAAY,kDAAkD,EAC9D,OAAO,YAAY;AAClB,QAAM,MAAM,MAAM,UAAU,MAAM,CAAC;AACnC,MAAI,QAAQ,KAAM,OAAM,IAAI,WAAW,6BAA6B;AACpE,QAAM,WAAW,GAAG;AACpB,UAAQ,IAAI,6BAA6B,GAAG,uBAAuB;AACrE,CAAC;;;AdMI,SAAS,eAAwB;AACtC,SAAO,IAAIC,UAAQ,cAAc,EAC9B,YAAY,sFAAsF,EAClG,QAAQ,SAAS,eAAe,EAChC,mBAAmB,EACnB,WAAW,YAAY,EACvB,WAAW,WAAW,EACtB,WAAWC,cAAa,EACxB,WAAW,WAAW,EACtB,WAAW,WAAW,EACtB,WAAW,YAAY,EACvB,WAAW,YAAY,EACvB,WAAW,cAAc,EACzB,WAAW,kBAAkB,EAC7B,WAAW,aAAa,EACxB,WAAW,UAAU;AAC1B;;;AezBA,IAAI;AACF,QAAM,aAAa,EAAE,WAAW,QAAQ,IAAI;AAC9C,SAAS,KAAK;AACZ,MAAI,eAAe,YAAY;AAC7B,QAAI,SAAS,EAAG,KAAI,MAAM,IAAI,OAAO;AAAA,QAChC,SAAQ,MAAM,UAAU,IAAI,OAAO,EAAE;AAC1C,YAAQ,KAAK,IAAI,QAAQ;AAAA,EAC3B;AACA,MAAI,SAAS,GAAG;AACd,QAAI,MAAO,IAAc,SAAS,OAAO,GAAG,CAAC;AAC7C,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,QAAM;AACR;","names":["z","z","readFile","readFile","readFile","rename","writeFile","z","z","z","readFile","writeFile","rename","resolve","spawn","closeSync","existsSync","openSync","statSync","link","mkdir","readFile","rename","rm","truncate","writeFile","sleep","z","z","z","z","z","resolve","mkdir","readFile","readdir","rename","writeFile","z","resolve","z","readFile","writeFile","rename","names","mkdir","readdir","randomBytes","existsSync","readdir","z","openSync","openSync","resolve","existsSync","link","names","readdir","z","randomBytes","connect","shown","existsSync","mkdir","readdir","writeFile","usedBytes","existsSync","mkdir","writeFile","readdir","link","createHash","randomBytes","existsSync","chmod","mkdir","readFile","rename","rm","stat","statfs","writeFile","userInfo","join","stat","existsSync","readFile","createHash","mkdir","writeFile","chmod","rename","join","rm","randomBytes","userInfo","statfs","pid","closeSync","openSync","existsSync","mkdir","readdir","rename","rm","stat","request","request","bootArgs","readdir","stat","existsSync","rm","mkdir","rename","failure","existsSync","existsSync","link","NAME_RE","link","statSync","existsSync","alive","writeFile","truncate","sleep","readFile","rm","openSync","spawn","closeSync","existsSync","size","mkdir","link","forkMachine","statSync","failure","stopMachine","startMachine","setSshKeys","report","pauseMachine","resumeMachine","hibernateMachine","wakeMachine","updateMachine","rescaleMachine","replaceDisk","rename","attachVolume","detachVolume","setMachine","addPorts","open","removePorts","addLink","removeLink","destroyBox","run","randomBytes","existsSync","mkdir","readdir","readFile","rm","stat","statfs","writeFile","basename","join","sleep","randomBytes","promisify","randomBytes","rm","rm","Agent","connect","Agent","statfs","readBox","size","stat","rm","mkdir","meta","envText","existsSync","readFile","writeFile","basename","readdir","join","gb","randomBytes","held","sleep","access","chmod","mkdir","rm","writeFile","z","z","chmod","mkdir","readFile","request","readFile","mkdir","chmod","request","join","mkdir","writeFile","chmod","access","rm","readFile","readFile","log","round","log","round","spawn","constants","openSync","readFileSync","statSync","mkdir","readFile","stat","userInfo","sleep","readFileSync","Agent","request","Agent","request","readFile","readFileSync","sleep","stat","mkdir","log","openSync","spawn","constants","statSync","userInfo","readFile","rm","writeFile","createHmac","createHmac","Hono","require","createHash","createHash","mkdir","readFile","writeFile","readFile","mkdir","writeFile","Hono","Hono","connect","Hono","request","resolve","Hono","request","connect","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","rm","resolve","writeFile","readFile","shutdown","recovery","Command","Command","resolve","Command","Command","resolve","Command","Command","Command","Command","Command","Command","Command","open","readFile","stat","sleep","Command","Command","readFile","stat","size","open","sleep","spawnSync","Command","Command","spawnSync","Command","Command","relay","Command","lstat","readFile","readdir","rename","rm","symlink","writeFile","z","readdir","namesIn","lstat","readFile","z","writeFile","rename","link","rm","symlink","report","Command","Command","report","Command","report","WHEN","homedir","Command","statusCommand","Command","homedir","Command","Command","Command","statusCommand"]}
1
+ {"version":3,"sources":["../../shared/src/errors.ts","../src/commands/start.ts","../../shared/src/paths.ts","../src/core/config.ts","../../shared/src/sizes.ts","../../shared/src/usage.ts","../src/core/refs.ts","../src/core/kvm.ts","../src/core/dns.ts","../src/core/state.ts","../src/core/db.ts","../src/core/machines.ts","../../shared/src/duration.ts","../../shared/src/api.ts","../../shared/src/ssh.ts","../src/core/agent.ts","../src/core/env.ts","../../shared/src/env.ts","../src/core/locks.ts","../src/core/log.ts","../src/core/images.ts","../src/core/exec.ts","../src/core/volumes.ts","../../shared/src/capacity.ts","../src/core/capacity.ts","../src/core/backupStore.ts","../src/core/ext4.ts","../src/core/snapshots.ts","../src/core/firecracker.ts","../src/core/network.ts","../src/core/backups.ts","../../shared/src/backup.ts","../src/core/clone.ts","../src/core/storeFetch.ts","../src/core/relay.ts","../../shared/src/relay.ts","../src/core/controlPlane.ts","../../shared/src/country.ts","../src/core/idle.ts","../src/core/runs.ts","../src/core/relayWatch.ts","../src/daemon.ts","../../shared/src/systemd.ts","../src/socketClient.ts","../src/listen.ts","../../shared/src/names.ts","../src/app.ts","../../shared/src/version.ts","../src/version.ts","../src/caller.ts","../src/core/update.ts","../src/routes/backups.ts","../src/routes/backupStore.ts","../src/routes/boxHttp.ts","../../shared/src/httpHead.ts","../src/routes/capacity.ts","../src/routes/env.ts","../src/routes/machines.ts","../src/core/stats.ts","../src/core/scripts.ts","../src/core/usage.ts","../src/routes/runs.ts","../src/routes/snapshots.ts","../src/routes/ssh.ts","../src/routes/usage.ts","../src/routes/volumes.ts","../src/program.ts","../src/commands/backup/index.ts","../src/commands/backup/setup.ts","../src/commands/backup/output.ts","../src/commands/backup/status.ts","../src/commands/join.ts","../src/commands/leave.ts","../src/commands/logs.ts","../src/commands/net.ts","../src/commands/relay.ts","../src/commands/rename-realm.ts","../src/core/realm.ts","../src/commands/trust-ca.ts","../src/commands/status.ts","../src/commands/stop.ts","../src/index.ts"],"sourcesContent":["/** Errors with an exit code; the entry point prints `message` and exits with `exitCode`. */\nexport class KvboxError extends Error {\n constructor(\n message: string,\n public readonly exitCode: number = 1,\n ) {\n super(message);\n this.name = \"KvboxError\";\n }\n}\n\nexport class NotImplementedError extends KvboxError {\n constructor(what: string) {\n super(`${what}: not implemented yet`, 2);\n this.name = \"NotImplementedError\";\n }\n}\n\n/** The named box/snapshot/host does not exist: HTTP 404, exit 1. */\nexport class NotFoundError extends KvboxError {\n constructor(what: string) {\n super(`${what}: not found`, 1);\n this.name = \"NotFoundError\";\n }\n}\n\n/** The caller is known but the rule says no (an org member outside their role): HTTP 403, exit 1. */\nexport class ForbiddenError extends KvboxError {\n constructor(message: string) {\n super(message, 1);\n this.name = \"ForbiddenError\";\n }\n}\n\n/** A bare name that is in more than one of the caller's orgs (#68); the CLI and the control plane say it the same way. */\nexport class AmbiguousRefError extends KvboxError {\n /** `orgFlag` false: `--org` names something else on this command (a fork's target), so only `slug/name` is offered. */\n constructor(kind: string, name: string, slugs: readonly string[], orgFlag = true) {\n const way = orgFlag ? `--org ${slugs[0]} or ${slugs[0]}/${name}` : `${slugs[0]}/${name}`;\n super(`${kind} ${name} exists in ${slugs.slice(0, -1).join(\", \")} and ${slugs.at(-1)}; say which with ${way}`, 1);\n this.name = \"AmbiguousRefError\";\n }\n}\n","/**\n * kvbox-server start [-d] [--socket <path>] — the daemon. In the foreground (what\n * the systemd unit runs) it serves the kvbox API on $KVBOX_HOME/server.sock and, once joined, answers its\n * control plane over HTTPS; every message is a server.log line (core/log.ts). With `-d` it starts that\n * daemon in the background instead (through systemd where install-server.sh set the unit up) and returns\n * once the socket answers.\n */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { loadConfig } from \"../core/config.js\";\nimport { requireKvm } from \"../core/kvm.js\";\nimport { DNS_RETRY_MS, startDns } from \"../core/dns.js\";\nimport { bootRecovered, pinRunningTaps, settleDeadBoxes } from \"../core/machines.js\";\nimport { clearStagedBackups } from \"../core/backups.js\";\nimport { startBackupStoreWatch } from \"../core/backupStore.js\";\nimport { ensureHostNetwork } from \"../core/network.js\";\nimport { restoreRelay } from \"../core/relay.js\";\nimport { startIdleWatch } from \"../core/idle.js\";\nimport { startRelayWatch } from \"../core/relayWatch.js\";\nimport { log } from \"../core/log.js\";\nimport { refuseSecondDaemon, startDetached } from \"../daemon.js\";\nimport { listen } from \"../listen.js\";\nimport { VERSION } from \"../version.js\";\n\n// Set once the foreground daemon is on its way: its errors are then log lines (server.log), where a\n// subcommand's (start -d included) are plain `error: …` for the terminal.\nlet daemon = false;\nexport const isDaemon = (): boolean => daemon;\n\nexport const startCommand = new Command(\"start\")\n .description(\"run the daemon in the foreground; -d starts it in the background and returns\")\n .option(\"-d, --detach\", \"start the daemon in the background (through systemd when install-server.sh set it up) and return once it answers\")\n .option(\"--socket <path>\", \"socket to listen on (default: $KVBOX_HOME/server.sock)\")\n .action(async (opts: { detach?: boolean; socket?: string }) => {\n if (opts.detach) {\n const started = await startDetached(paths());\n if (started.alreadyRunning !== undefined) {\n console.log(`kvbox-server ${started.alreadyRunning} is already running (pid ${started.pid})`);\n return;\n }\n console.log(`kvbox-server started (pid ${started.pid}), listening on ${started.socketPath}${started.viaUnit ? \" (through systemd)\" : \"\"}`);\n if (started.viaGroup !== undefined) console.log(`started through the ${started.viaGroup} group, which this shell does not have yet (log out and back in to get it)`);\n return;\n }\n // Before anything is touched: settling boxes and clearing staged backups belong to the running one (#159).\n if (opts.socket === undefined) await refuseSecondDaemon(paths());\n daemon = true;\n await requireKvm(); // a daemon without /dev/kvm would only fail at the first kvbox new (#61)\n // Before listening: boxes whose Firecracker died with the host (#29), so a listing cannot get to them first.\n const settled = await settleDeadBoxes(paths());\n // A backup or restore cut short by the restart never finishes: the control plane marks a backup failed.\n await clearStagedBackups(paths()).catch((err: unknown) => log.warn(`staged backups not cleared: ${(err as Error).message}`));\n const { socketPath, https } = await listen(opts.socket ? { socketPath: opts.socket } : {});\n log.info(`kvbox-server ${VERSION} listening on ${socketPath} (pid ${process.pid})`);\n if (https) {\n const cfg = await loadConfig(paths());\n log.info(`control plane ${cfg.controlPlane?.name}: answering on ${https.url}`);\n }\n // The bridge vanishes on host reboot; recreate it. Not fatal: ls/status must still work.\n try {\n const cfg = await loadConfig(paths());\n const state = await ensureHostNetwork(cfg);\n log.info(`host network: bridge ${cfg.bridge} ${state}`);\n await pinRunningTaps(paths());\n } catch (err) {\n log.warn(`host network not ready (${(err as Error).message}); run: kvbox-server net up`);\n }\n // The tunnel's firewall rule goes with the reboot too (#114); the box rules above are re-pinned the same way.\n try {\n const relay = await restoreRelay(paths());\n if (relay) log.info(`relay ${relay.name}: the control plane may reach this host through the tunnel again`);\n } catch (err) {\n log.warn(`the control plane may not reach this host through its relay (${(err as Error).message}); run: kvbox-server relay <join string>`);\n }\n // Box names inside boxes (#97), on the bridge address, so it needs the bridge. Not fatal either: a box\n // whose resolver gets no answer here asks the next one, only <name>.kvbox stops resolving. Without the\n // bridge yet (a box boot recreates it), the bind is tried again until it holds.\n let dnsWarned = false;\n const bindDns = (): void => {\n loadConfig(paths())\n .then(async (cfg) => {\n await startDns({ host: cfg.gateway });\n log.info(`box names: <name>.kvbox answered on ${cfg.gateway}`);\n })\n .catch((err: Error) => {\n if (!dnsWarned) log.warn(`box names (<name>.kvbox) do not resolve yet (${err.message}); retrying`);\n dnsWarned = true;\n setTimeout(bindDns, DNS_RETRY_MS).unref();\n });\n };\n bindDns();\n // A relay tunnel that stops carrying traffic is redialed (#50); idle when the host has no relay.\n startRelayWatch();\n // Boxes with an idle timeout are hibernated once their network goes quiet (#47).\n startIdleWatch();\n // A backup store's Garage is started again after a reboot or a crash; idle when the host is not a store.\n startBackupStoreWatch();\n const recovery = await bootRecovered(settled, paths());\n if (recovery) {\n for (const box of recovery.booted) log.info(`box ${box} was running when it went down; booted it again`);\n for (const box of recovery.leftStopped) log.info(`box ${box} was in standby when it went down; its memory is gone, left stopped`);\n for (const f of recovery.failed) log.warn(`box ${f.box} was running when it went down and did not come back: ${f.error}`);\n }\n });\n","/**\n * Host state layout. The filesystem is the database and `~/.kvbox` is its root.\n * This module is dependency-free so both the CLI (socket path, cli.json)\n * and core (everything else) can use it without crossing the layer boundary.\n *\n * `KVBOX_HOME` overrides the root, mainly for tests.\n */\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport function kvboxHome(): string {\n return process.env[\"KVBOX_HOME\"] ?? join(homedir(), \".kvbox\");\n}\n\nexport function paths(home: string = kvboxHome()) {\n return {\n home,\n config: join(home, \"config.json\"),\n /** The host's ledgers (SQLite via node:sqlite): usage events today. Boxes and snapshots stay files; see server core/db.ts. */\n db: join(home, \"kvbox.db\"),\n serverSock: join(home, \"server.sock\"),\n serverPid: join(home, \"server.pid\"),\n serverLog: join(home, \"server.log\"),\n /**\n * The host's self-update (`POST /update`, the control plane's admin): `update.json` is its state\n * (install-server.sh --update writes it), `update/` holds the downloaded script and its log.\n */\n updateState: join(home, \"update.json\"),\n updateDir: join(home, \"update\"),\n updateScript: join(home, \"update\", \"install-server.sh\"),\n updateLog: join(home, \"update\", \"update.log\"),\n /** The CLI's login to the control plane (`kvbox login`): url, bearer token, user. Mode 600. */\n cli: join(home, \"cli.json\"),\n /** The CLI's last look at npm for a newer @kvbox/cli: `{checkedAt, latest}`, at most once a day (cli update.ts). */\n updateCheck: join(home, \"update-check.json\"),\n ssh: join(home, \"ssh\"),\n sshKey: join(home, \"ssh\", \"id_ed25519\"),\n /** The device key signed by the control plane's CA (#51); ssh loads it by itself next to `-i id_ed25519`. */\n sshCert: join(home, \"ssh\", \"id_ed25519-cert.pub\"),\n /** Host keys of the cloud boxes this laptop connected to, one entry per box (`connect`, #21). */\n sshKnownHosts: join(home, \"ssh\", \"known_hosts\"),\n /** The host's self-signed TLS identity for the control plane (`kvbox-server join`): pinned there by fingerprint. */\n tls: join(home, \"tls\"),\n tlsKey: join(home, \"tls\", \"key.pem\"),\n tlsCert: join(home, \"tls\", \"cert.pem\"),\n /** The host's WireGuard tunnel to its relay (`kvbox-server relay`, #50): the conf net-setup.sh installs for wg-quick. Mode 600. */\n relay: join(home, \"relay\"),\n relayConf: join(home, \"relay\", \"kvbox.conf\"),\n bin: join(home, \"bin\"),\n firecracker: join(home, \"bin\", \"firecracker\"),\n /** Firecracker's snapshot-editor, from the same release: merges a diff snapshot onto a full memory image. */\n snapshotEditor: join(home, \"bin\", \"snapshot-editor\"),\n /** Garage, on a host that is a backup store (`kvbox-server backup setup` downloads it). */\n garage: join(home, \"bin\", \"garage\"),\n /** The store's Garage as this host runs it: its configuration, pid and log. The data is on the disk the operator named. */\n backupStore: {\n dir: join(home, \"backup-store\"),\n conf: join(home, \"backup-store\", \"garage.toml\"),\n pid: join(home, \"backup-store\", \"garage.pid\"),\n log: join(home, \"backup-store\", \"garage.log\"),\n },\n assets: join(home, \"assets\"),\n kernel: join(home, \"assets\", \"vmlinux\"),\n /** Symlink to the current base image, assets/rootfs-<version>.ext4; boxes keep using the version they were made from. */\n rootfs: join(home, \"assets\", \"rootfs.ext4\"),\n baseImage: (version: string) => join(home, \"assets\", `rootfs-${version}.ext4`),\n /**\n * Every other image (#87), one dir each so nothing collides with the base's `rootfs-*.ext4`:\n * assets/images/<image>/rootfs-<version>.ext4, and rootfs.ext4 there the symlink to its current one.\n */\n images: join(home, \"assets\", \"images\"),\n image: (image: string) => ({\n dir: join(home, \"assets\", \"images\", image),\n rootfs: join(home, \"assets\", \"images\", image, \"rootfs.ext4\"),\n version: (version: string) => join(home, \"assets\", \"images\", image, `rootfs-${version}.ext4`),\n }),\n machines: join(home, \"machines\"),\n snapshots: join(home, \"snapshots\"),\n /** Boxes and snapshots are filed by owner: machines/<owner>/<name>. The owner is part of a box's identity. */\n ownerMachines: (owner: string) => join(home, \"machines\", owner),\n ownerSnapshots: (owner: string) => join(home, \"snapshots\", owner),\n machine: (owner: string, name: string) => {\n const dir = join(home, \"machines\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n /** The box's own environment variables (#87), merged over its owner's at boot. Mode 600: values in the clear. */\n env: join(dir, \"env.json\"),\n /** The box's writable layer, stacked on the read-only base image inside the guest. */\n overlay: join(dir, \"overlay.ext4\"),\n /** A restore's disk while it downloads (a backup's chunks), renamed over `overlay` once complete. */\n restoring: join(dir, \"overlay.ext4.restore\"),\n /**\n * The box's memory as of its last snapshot (a hard link to that snapshot's `mem`, never modified).\n * The next snapshot is a diff of the pages dirtied since, merged onto this. Absent after a boot.\n */\n memBase: join(dir, \"mem.base\"),\n /** `kvbox vm fork` (#79): the source's VM state, captured here and gone once the box runs. Its memory is `memBase`. */\n forkVmstate: join(dir, \"fork.vmstate\"),\n /** `kvbox hibernate`: the box's memory image and VM state while it is hibernated; gone again after `wake` or `stop`. */\n hibernateDir: join(dir, \"hibernate\"),\n hibernateVmstate: join(dir, \"hibernate\", \"vmstate\"),\n hibernateMem: join(dir, \"hibernate\", \"mem\"),\n sock: join(dir, \"fc.sock\"),\n /** Firecracker's vsock endpoint: the host connects here to reach kvbox-agent inside the box (core/agent.ts). */\n vsock: join(dir, \"vsock.sock\"),\n log: join(dir, \"fc.log\"),\n /**\n * An attached volume's drive as Firecracker sees it (#52): a symlink in the box dir to the volume's\n * disk, given to Firecracker by its relative name (`volumeDriveRel`), so a snapshot's vmstate names\n * it relative to whichever box dir it is restored into. There it is a same-size empty placeholder.\n */\n volumeDrive: (volume: string) => join(dir, volumeDriveRel(volume)),\n };\n },\n /** Volumes are filed like boxes, by owner: volumes/<owner>/<name> (#52). */\n volumes: join(home, \"volumes\"),\n ownerVolumes: (owner: string) => join(home, \"volumes\", owner),\n volume: (owner: string, name: string) => {\n const dir = join(home, \"volumes\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n /** The volume itself: a sparse ext4 the guest sees as a whole disk. */\n disk: join(dir, \"disk.ext4\"),\n /** A restore's disk while it downloads (a backup's chunks), renamed over `disk` once complete. */\n restoring: join(dir, \"disk.ext4.restore\"),\n };\n },\n /** Each owner's environment variables as the control plane last sent them (#88): env/<owner>.json, mode 600. */\n env: join(home, \"env\"),\n ownerEnv: (owner: string) => join(home, \"env\", `${owner}.json`),\n /**\n * Backups in progress (decision \"Backups: encrypted 4 MiB chunks in object storage\"): backups/<id>/ holds the\n * copy of the box's disk being uploaded and its chunk list, gone once the upload ends. Nothing here outlives\n * a daemon restart.\n */\n backups: join(home, \"backups\"),\n backup: (id: string) => {\n const dir = join(home, \"backups\", id);\n return { dir, disk: join(dir, \"disk.ext4\"), chunks: join(dir, \"chunks.json\") };\n },\n snapshot: (owner: string, name: string) => {\n const dir = join(home, \"snapshots\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n vmstate: join(dir, \"vmstate\"),\n mem: join(dir, \"mem\"),\n /** The box's own environment variables when it was taken (#87); a restore starts with them. */\n env: join(dir, \"env.json\"),\n /** Copy of the box's overlay at the moment of the snapshot; the base image is referenced by version in meta.json. */\n overlay: join(dir, \"overlay.ext4\"),\n };\n },\n } as const;\n}\n\nexport type Paths = ReturnType<typeof paths>;\n\n/** The file name of a volume's drive inside a box dir (relative: how Firecracker is given it). */\nexport function volumeDriveRel(volume: string): string {\n return `volume-${volume}.ext4`;\n}\n\n/** Where a volume is mounted inside the box (the image's kvbox-volumes.service, by label). */\nexport function volumeMountPath(volume: string): string {\n return `/mnt/${volume}`;\n}\n","/** `~/.kvbox/config.json`: asset paths, subnet, default size, owner. Written with defaults on first run. */\nimport { chmod, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { DEFAULT_SIZE, SIZE_NAMES } from \"@kvbox/shared/sizes\";\nimport { PricingSchema } from \"@kvbox/shared/usage\";\nimport { LOCAL_OWNER_RE, REALM_RE, localOwner } from \"./refs.js\";\n\n/** What an hour of each resource costs, for `kvbox vm usage`'s estimated cost. Absent by default: no cost row. */\nexport { PricingSchema, type Pricing } from \"@kvbox/shared/usage\";\n\n/** The control plane this host joined (`kvbox-server join`, #18): where it is, what it calls itself, and the secret it presents. */\nexport const ControlPlaneSchema = z.object({\n url: z.string().url(),\n /** The realm name: boxes the control plane creates are owned by `<user>@<name>`, a directory name on disk. */\n name: z.string().regex(REALM_RE),\n /** Minted at join; every HTTPS call from the control plane carries it as a bearer. */\n secret: z.string().min(1),\n /** The address the control plane reaches this host at. */\n advertise: z.string().min(1),\n port: z.number().int().positive().default(7777),\n});\nexport type ControlPlane = z.infer<typeof ControlPlaneSchema>;\n\n/**\n * The relay this host reaches the internet through (`kvbox-server relay`, #50): a public VM that owns\n * `publicIp` and forwards it down a WireGuard tunnel to `tunnelIp`. The tunnel's private key is not\n * here: it lives in the wg-quick conf under relay/. `join` advertises `publicIp` by default.\n */\nexport const RelaySchema = z.object({\n name: z.string().min(1),\n publicIp: z.string().min(1),\n tunnelIp: z.string().min(1),\n /** `<relay-ip>:<port>` the tunnel dials. */\n endpoint: z.string().min(1),\n});\nexport type Relay = z.infer<typeof RelaySchema>;\n\n/**\n * This host as a backup store (`kvbox-server backup setup`, core/backupStore.ts): where Garage keeps its\n * data, and the one S3 key of its bucket, which the control plane holds too and signs chunk URLs with.\n */\nexport const BackupStoreSchema = z.object({\n /** A directory on the disk bought for backups. */\n path: z.string().min(1),\n bucket: z.string().min(1),\n region: z.string().min(1),\n accessKey: z.string().min(1),\n secretKey: z.string().min(1),\n /** Whether the control plane took the store; false after a setup that could not reach it. */\n registered: z.boolean().default(false),\n});\nexport type BackupStore = z.infer<typeof BackupStoreSchema>;\n\nexport const ConfigSchema = z.object({\n kernel: z.string(),\n rootfs: z.string(),\n firecracker: z.string(),\n snapshotEditor: z.string().optional(), // default: bin/snapshot-editor next to firecracker\n bridge: z.string().default(\"kvbox0\"),\n subnet: z.string().default(\"172.30.0.0/24\"),\n gateway: z.string().default(\"172.30.0.1\"),\n defaultSize: z.enum(SIZE_NAMES as [string, ...string[]]).default(DEFAULT_SIZE),\n /** Who boxes made over the local socket belong to: the Unix user running the server unless set here. No `@`, no `/`. */\n owner: z.string().regex(LOCAL_OWNER_RE, \"owner: letters, digits, '.', '_', '-'; no '@' or '/'\").default(localOwner),\n pricing: PricingSchema.optional(),\n /** What a new box gets when `new` does not say (#47): seconds without network traffic before it is hibernated; 0: never. */\n autoHibernateSec: z.number().int().min(0).default(0),\n /**\n * GiB of disk `kvbox volume create` leaves free for the boxes' overlays and snapshots (#52): a volume is\n * refused when it could not fill up with that much still free. 0 only on a host whose disk is for tests.\n */\n volumeHeadroomGib: z.number().int().min(0).default(20),\n /** Absent until the host joins a control plane; then the server also listens on HTTPS. */\n controlPlane: ControlPlaneSchema.optional(),\n /** Absent unless the host sits behind a relay. */\n relay: RelaySchema.optional(),\n /** Absent unless the host is a backup store. */\n backupStore: BackupStoreSchema.optional(),\n});\nexport type Config = z.infer<typeof ConfigSchema>;\n\n/** Write config.json back, whole or not at all. Mode 600: once joined it holds the host's secret. */\nexport async function saveConfig(cfg: Config, p: Paths = paths()): Promise<void> {\n const parsed = ConfigSchema.parse(cfg);\n const tmp = `${p.config}.tmp`;\n await writeFile(tmp, JSON.stringify(parsed, null, 2) + \"\\n\", { mode: 0o600 });\n await chmod(tmp, 0o600); // writeFile's mode applies to a new file only\n await rename(tmp, p.config);\n}\n\nexport function defaultConfig(p: Paths = paths()): Config {\n return ConfigSchema.parse({\n kernel: p.kernel,\n rootfs: p.rootfs,\n firecracker: p.firecracker,\n snapshotEditor: p.snapshotEditor,\n owner: localOwner(),\n });\n}\n\nexport async function loadConfig(p: Paths = paths()): Promise<Config> {\n try {\n const raw = await readFile(p.config, \"utf8\");\n return ConfigSchema.parse(JSON.parse(raw));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n const cfg = defaultConfig(p);\n await writeFile(p.config, JSON.stringify(cfg, null, 2) + \"\\n\");\n return cfg;\n }\n throw err;\n }\n}\n","/**\n * Fixed box sizes. Firecracker backs guest memory lazily and the disk is a sparse overlay on the\n * shared base image, so a box only costs what the guest actually touches.\n */\nexport const SIZES = {\n xs: { vcpu: 1, memMib: 2048, diskGib: 8 },\n s: { vcpu: 2, memMib: 4096, diskGib: 8 },\n m: { vcpu: 4, memMib: 8192, diskGib: 16 },\n l: { vcpu: 8, memMib: 16384, diskGib: 32 },\n} as const;\n\nexport type SizeName = keyof typeof SIZES;\nexport const SIZE_NAMES = Object.keys(SIZES) as SizeName[];\nexport const DEFAULT_SIZE: SizeName = \"s\";\n\nexport function isSizeName(value: string): value is SizeName {\n return value in SIZES;\n}\n\n/**\n * \"16GB\", \"16G\", \"16\", \"4096MB\", \"4096M\", \"0.5GB\" -> MiB. A bare number is GB: that is how\n * people say it (\"16gb\", \"4 vcpu 16gb\"). Returns undefined when it is not a size.\n */\nexport function parseMib(text: string): number | undefined {\n const m = /^\\s*(\\d+(?:\\.\\d+)?)\\s*([gm]i?b?)?\\s*$/i.exec(text);\n if (!m) return undefined;\n const n = Number(m[1]);\n const unit = (m[2] ?? \"g\").toLowerCase();\n const mib = unit.startsWith(\"m\") ? n : n * 1024;\n return Number.isInteger(mib) && mib > 0 ? mib : undefined;\n}\n","/**\n * Summing a box's usage ledger: one pure function over its state-change rows, used by the host\n * (`kvbox vm usage`, `GET /usage`) and by the control plane over the rows it pulled (#42). A row\n * opens an interval that lasts until the next row; the sizes ride on every row so a rescale\n * changes the rate from that moment on. Pricing is per resource-hour (decision \"Usage is priced\n * per resource-hour\").\n */\nimport { z } from \"zod\";\nimport type { BoxStatus, BoxUsage, CronUsage, UsageDay, UsageDayItem, VolumeUsage } from \"./api.js\";\n\nexport type UsageState = \"running\" | \"standby\" | \"hibernated\" | \"stopped\";\n\n/** One state change of a box. */\nexport interface UsageEvent {\n at: string;\n state: UsageState;\n vcpu: number;\n memMib: number;\n diskGib: number;\n /** What made it: new, start, stop, pause, resume, hibernate, wake, rescale, update, rm, server (a stop the server did not see). */\n by: string;\n}\n\n/**\n * What an hour of each resource costs. A volume (#91) is an hour of its existence plus an hour of each\n * GiB of its size; a price list from before volumes charges nothing for them. A box's own disk is billed\n * only beyond `diskIncludedGib` (decision \"8 GB of box disk included\"): `diskGibHours` counts what is above it.\n */\nexport const PricingSchema = z.object({\n currency: z.string().min(1),\n vcpuHour: z.number().nonnegative(),\n ramGibHour: z.number().nonnegative(),\n diskGibHour: z.number().nonnegative(),\n volumeHour: z.number().nonnegative().default(0),\n volumeGibHour: z.number().nonnegative().default(0),\n diskIncludedGib: z.number().int().nonnegative().default(0),\n /**\n * Object storage (#182): an hour of a slug's storage existing, whatever it holds, which covers its\n * hidden box and the first `storageIncludedGib` of its size; each GiB above that is `storageGibHour`.\n * A price list from before object storage charges nothing for it.\n */\n storageHour: z.number().nonnegative().default(0),\n storageGibHour: z.number().nonnegative().default(0),\n storageIncludedGib: z.number().int().nonnegative().default(0),\n /** The cron service (#190): an hour of one cron service existing, whatever it holds or fires. A price list from before it charges nothing. */\n cronHour: z.number().nonnegative().default(0),\n});\nexport type Pricing = z.infer<typeof PricingSchema>;\n\n/**\n * `GET /pricing` on the control plane: the price list, and the credit a user's first saved card adds\n * (`KVBOX_CLOUD_WELCOME_CREDIT`, 0 for none), which the web app's activation page shows.\n */\nexport const PriceListSchema = PricingSchema.extend({ welcomeCredit: z.number().nonnegative() });\nexport type PriceList = z.infer<typeof PriceListSchema>;\n\nexport interface UsageWindow {\n from: string;\n to: string;\n pricing?: Pricing | undefined;\n}\n\nexport interface UsageTotals {\n seconds: Record<UsageState, number>;\n vcpuHours: number;\n ramGibHours: number;\n diskGibHours: number;\n cost?: { amount: number; currency: string };\n /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */\n estimatedStops: number;\n /** The first recorded moment, null when nothing is recorded. */\n historyFrom: string | null;\n}\n\nconst HOUR_MS = 3_600_000;\n\nexport const round = (n: number, places: number) => Math.round(n * 10 ** places) / 10 ** places;\n\n/**\n * Each event opens an interval that lasts until the next one (or `to`); intervals are clipped to the\n * window, so the event before `from` supplies the state the window starts in. Time before the first\n * event belongs to no state: it was never recorded. Running hours earn vCPU and RAM; standby hours\n * earn RAM (the memory is still held) but no vCPU; every hour the box exists earns disk (its overlay\n * is there while it is hibernated or stopped too), the GiB above the price list's `diskIncludedGib`\n * only, interval by interval (a rescale moves it). A repeated state continues it.\n */\nexport function computeUsage(events: readonly UsageEvent[], w: UsageWindow): UsageTotals {\n const sorted = [...events].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const from = Date.parse(w.from);\n const to = Date.parse(w.to);\n const ms: Record<UsageState, number> = { running: 0, standby: 0, hibernated: 0, stopped: 0 };\n let vcpuHours = 0;\n let ramGibHours = 0;\n let diskGibHours = 0;\n const included = w.pricing?.diskIncludedGib ?? 0;\n sorted.forEach((e, i) => {\n const start = Math.max(Date.parse(e.at), from);\n const next = sorted[i + 1];\n const end = Math.min(next === undefined ? to : Date.parse(next.at), to);\n if (end <= start) return;\n const h = (end - start) / HOUR_MS;\n ms[e.state] += end - start;\n if (e.state === \"running\") vcpuHours += h * e.vcpu;\n if (e.state === \"running\" || e.state === \"standby\") ramGibHours += (h * e.memMib) / 1024;\n diskGibHours += h * Math.max(0, e.diskGib - included);\n });\n const totals: UsageTotals = {\n seconds: {\n running: Math.round(ms.running / 1000),\n standby: Math.round(ms.standby / 1000),\n hibernated: Math.round(ms.hibernated / 1000),\n stopped: Math.round(ms.stopped / 1000),\n },\n vcpuHours: round(vcpuHours, 3),\n ramGibHours: round(ramGibHours, 3),\n diskGibHours: round(diskGibHours, 3),\n // Inside the window only: rows may be dated after `to` (a ledger counted up to its last pull, #172).\n estimatedStops: sorted.filter((e) => e.state === \"stopped\" && e.by === \"server\" && e.at >= w.from && e.at < w.to).length,\n historyFrom: sorted[0]?.at ?? null,\n };\n if (w.pricing !== undefined) totals.cost = { amount: round(costOf(totals, w.pricing), 4), currency: w.pricing.currency };\n return totals;\n}\n\n/** The price of a set of resource-hours; totals over several boxes are summed the same way. */\nexport function costOf(t: Pick<UsageTotals, \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">, pricing: Pricing): number {\n return t.vcpuHours * pricing.vcpuHour + t.ramGibHours * pricing.ramGibHour + t.diskGibHours * pricing.diskGibHour;\n}\n\n/** Add up several boxes' totals (hours and seconds; the cost is recomputed from the hours when priced). */\nexport function sumUsage(items: readonly Pick<UsageTotals, \"seconds\" | \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">[], pricing?: Pricing): Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> {\n const sum: Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> = {\n seconds: { running: 0, standby: 0, hibernated: 0, stopped: 0 },\n vcpuHours: 0,\n ramGibHours: 0,\n diskGibHours: 0,\n };\n for (const t of items) {\n for (const s of Object.keys(sum.seconds) as UsageState[]) sum.seconds[s] += t.seconds[s];\n sum.vcpuHours += t.vcpuHours;\n sum.ramGibHours += t.ramGibHours;\n sum.diskGibHours += t.diskGibHours;\n }\n sum.vcpuHours = round(sum.vcpuHours, 3);\n sum.ramGibHours = round(sum.ramGibHours, 3);\n sum.diskGibHours = round(sum.diskGibHours, 3);\n if (pricing !== undefined) sum.cost = { amount: round(costOf(sum, pricing), 4), currency: pricing.currency };\n return sum;\n}\n\n/**\n * The window a `GET /usage` call asks for: `since` and `until` as the user wrote them (any Date.parse\n * form), defaulting to the start of the current calendar month (UTC, what a bill covers) and now.\n */\nexport function usageWindow(since: string | undefined, until: string | undefined, now = new Date()): { from: string; to: string } {\n const parse = (name: string, value: string): string => {\n const t = Date.parse(value);\n if (Number.isNaN(t)) throw new Error(`${name}: \"${value}\" is not a date; write it like 2026-10-19 or 2026-10-19T08:00:00Z`);\n return new Date(t).toISOString();\n };\n const from = since === undefined ? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString() : parse(\"since\", since);\n const to = until === undefined ? now.toISOString() : parse(\"until\", until);\n return { from, to };\n}\n\n/** A ledger row as the host stores it: the event plus whose box it is. */\nexport interface LedgerRow extends UsageEvent {\n /** The host ledger the row came from, when rows of several hosts are mixed: box ids are only unique within one. */\n ledger?: string;\n boxId: string;\n owner: string;\n name: string;\n}\n\n/**\n * Rows of many boxes → one `BoxUsage` per box id, in owner/name order: the report both the host\n * (`GET /usage`) and the control plane build. A box's `rm` row ends its time: nothing accrues after\n * it, and a box gone before the window opened (or made after it closed) is left out. `live` says what\n * a box that still exists is doing now; one not in it reads its state off its last row, `removed`\n * when that row is the `rm`. A name removed and made again is two boxes (two ids); rows carrying a\n * `ledger` are grouped by ledger and box id, so two hosts' boxes never merge.\n */\nexport function groupUsage(\n rows: readonly LedgerRow[],\n window: { from: string; to: string },\n pricing: Pricing | undefined,\n live: ReadonlyMap<string, BoxStatus> = new Map(),\n): BoxUsage[] {\n const byBox = new Map<string, LedgerRow[]>();\n for (const r of rows) {\n const key = r.ledger === undefined ? r.boxId : `${r.ledger}:${r.boxId}`;\n const list = byBox.get(key);\n if (list === undefined) byBox.set(key, [r]);\n else list.push(r);\n }\n const out: BoxUsage[] = [];\n for (const events of byBox.values()) {\n events.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const first = events[0]!;\n const last = events[events.length - 1]!;\n const id = last.boxId;\n const removed = last.by === \"rm\" && !live.has(id);\n const to = removed && last.at < window.to ? last.at : window.to;\n if (first.at >= to || (removed && last.at <= window.from)) continue;\n const totals = computeUsage(events, { from: window.from, to, pricing });\n const status: BoxUsage[\"status\"] = live.get(id) ?? (removed ? \"removed\" : last.state);\n out.push({ id, name: last.name, owner: last.owner, status, ...totals });\n }\n return out.sort(usageOrder);\n}\n\n/** The order `groupUsage` returns boxes in: owner, name, then the older of a name made twice first. */\nexport const usageOrder = (a: Pick<BoxUsage, \"owner\" | \"name\" | \"historyFrom\">, b: Pick<BoxUsage, \"owner\" | \"name\" | \"historyFrom\">): number =>\n a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name) || (a.historyFrom ?? \"\").localeCompare(b.historyFrom ?? \"\");\n\n// ---- volumes (#91) -------------------------------------------------------------------------------\n\n/** One change of a volume: made, resized, or removed. The size rides on every row like a box's. */\nexport interface VolumeEvent {\n at: string;\n sizeGib: number;\n by: \"create\" | \"resize\" | \"rm\";\n}\n\n/** A volume ledger row as the host stores it: the event plus whose volume it is. */\nexport interface VolumeLedgerRow extends VolumeEvent {\n /** The host ledger the row came from, when rows of several hosts are mixed: volume ids are only unique within one. */\n ledger?: string;\n volumeId: string;\n owner: string;\n name: string;\n}\n\nexport interface VolumeTotals {\n volumeHours: number;\n volumeGibHours: number;\n cost?: { amount: number; currency: string };\n}\n\n/**\n * A volume costs for every hour it exists, whatever it holds and whether a box has it: each row opens\n * an interval that lasts until the next one (or `to`), the `rm` row ends the time, intervals are clipped\n * to the window. The GiB-hours are of the size, a reservation on the host's disk.\n */\nexport function computeVolumeUsage(events: readonly VolumeEvent[], w: UsageWindow): VolumeTotals {\n const sorted = [...events].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const from = Date.parse(w.from);\n const to = Date.parse(w.to);\n let hours = 0;\n let gibHours = 0;\n sorted.forEach((e, i) => {\n if (e.by === \"rm\") return;\n const start = Math.max(Date.parse(e.at), from);\n const next = sorted[i + 1];\n const end = Math.min(next === undefined ? to : Date.parse(next.at), to);\n if (end <= start) return;\n const h = (end - start) / HOUR_MS;\n hours += h;\n gibHours += h * e.sizeGib;\n });\n const totals: VolumeTotals = { volumeHours: round(hours, 3), volumeGibHours: round(gibHours, 3) };\n if (w.pricing !== undefined) totals.cost = { amount: round(volumeCostOf(totals, w.pricing), 4), currency: w.pricing.currency };\n return totals;\n}\n\nexport function volumeCostOf(t: Pick<VolumeTotals, \"volumeHours\" | \"volumeGibHours\">, pricing: Pricing): number {\n return t.volumeHours * pricing.volumeHour + t.volumeGibHours * pricing.volumeGibHour;\n}\n\n/**\n * Rows of many volumes → one `VolumeUsage` per volume id, like `groupUsage`: a volume whose `rm` row is\n * before the window, or whose first row is after it, is left out; a name removed and made again is two.\n */\nexport function groupVolumeUsage(rows: readonly VolumeLedgerRow[], window: { from: string; to: string }, pricing: Pricing | undefined): VolumeUsage[] {\n const byVolume = new Map<string, VolumeLedgerRow[]>();\n for (const r of rows) {\n const key = r.ledger === undefined ? r.volumeId : `${r.ledger}:${r.volumeId}`;\n const list = byVolume.get(key);\n if (list === undefined) byVolume.set(key, [r]);\n else list.push(r);\n }\n const out: VolumeUsage[] = [];\n for (const events of byVolume.values()) {\n events.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const first = events[0]!;\n const last = events[events.length - 1]!;\n const removed = last.by === \"rm\";\n const to = removed && last.at < window.to ? last.at : window.to;\n if (first.at >= to || (removed && last.at <= window.from)) continue;\n const totals = computeVolumeUsage(events, { from: window.from, to, pricing });\n out.push({ id: last.volumeId, name: last.name, owner: last.owner, sizeGib: last.sizeGib, status: removed ? \"removed\" : \"present\", ...totals, historyFrom: first.at });\n }\n return out.sort(usageOrder);\n}\n\n/**\n * Object storage's volume rows as `computeVolumeUsage` prices them (#182): the storage prices in the\n * volume prices' place, and each row's size cut to what is billed beyond the included GiB. The hours\n * that come out are the storage's, the GiB-hours those of the billed GiB only.\n */\nexport function storagePricing(pricing: Pricing): Pricing {\n return { ...pricing, volumeHour: pricing.storageHour, volumeGibHour: pricing.storageGibHour };\n}\nexport function billedStorageRows<R extends VolumeEvent>(rows: readonly R[], pricing: Pricing): R[] {\n return rows.map((r) => ({ ...r, sizeGib: Math.max(0, r.sizeGib - pricing.storageIncludedGib) }));\n}\n\n// ---- cron services ------------------------------------------------------------------------------\n\n/** One cron service's life (#190): made at `from`, removed at `to` (null: it is still there). It has no ledger: its own row says both. */\nexport interface CronLife {\n id: string;\n owner: string;\n name: string;\n from: string;\n to: string | null;\n}\n\n/** The hours of `window` a cron service existed in. */\nfunction cronHours(life: CronLife, window: { from: string; to: string }): number {\n const from = Math.max(Date.parse(life.from), Date.parse(window.from));\n const to = Math.min(life.to === null ? Infinity : Date.parse(life.to), Date.parse(window.to));\n return to > from ? (to - from) / HOUR_MS : 0;\n}\n\n/** One `CronUsage` per service that existed inside the window, priced by the hour it existed. */\nexport function groupCronUsage(lives: readonly CronLife[], window: { from: string; to: string }, pricing: Pricing | undefined): CronUsage[] {\n const out: CronUsage[] = [];\n for (const life of lives) {\n const hours = cronHours(life, window);\n if (hours <= 0) continue;\n const removed = life.to !== null && life.to <= window.to;\n out.push({\n id: life.id,\n name: life.name,\n owner: life.owner,\n status: removed ? \"removed\" : \"present\",\n hours: round(hours, 3),\n ...(pricing === undefined ? {} : { cost: { amount: round(hours * pricing.cronHour, 4), currency: pricing.currency } }),\n historyFrom: life.from,\n });\n }\n return out.sort(usageOrder);\n}\n\n/** The same services cut into the window's UTC days: one list per day of `windowDays`, most expensive first. */\nexport function dailyCronUsage(lives: readonly CronLife[], window: { from: string; to: string }, pricing: Pricing): UsageDayItem[][] {\n return windowDays(window).map((day) =>\n lives\n .flatMap((life) => {\n const hours = cronHours(life, day);\n return hours <= 0 ? [] : [{ id: life.id, name: life.name, owner: life.owner, removed: life.to !== null && life.to <= window.to, cost: round(hours * pricing.cronHour, 4) }];\n })\n .sort((a, b) => b.cost - a.cost || a.name.localeCompare(b.name)),\n );\n}\n\n/** Totals of a report: the boxes' sums plus the volumes', one cost for both when priced. */\nexport function reportTotals(\n boxes: readonly Pick<UsageTotals, \"seconds\" | \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">[],\n volumes: readonly Pick<VolumeTotals, \"volumeHours\" | \"volumeGibHours\">[],\n pricing?: Pricing,\n): Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> & Pick<VolumeTotals, \"volumeHours\" | \"volumeGibHours\"> {\n const { cost: _boxes, ...sum } = sumUsage(boxes);\n const vol = { volumeHours: round(volumes.reduce((n, v) => n + v.volumeHours, 0), 3), volumeGibHours: round(volumes.reduce((n, v) => n + v.volumeGibHours, 0), 3) };\n const out = { ...sum, ...vol };\n if (pricing !== undefined) return { ...out, cost: { amount: round(costOf(sum, pricing) + volumeCostOf(vol, pricing), 4), currency: pricing.currency } };\n return out;\n}\n\n// ---- per day -------------------------------------------------------------------------------------\n\nconst DAY_MS = 24 * HOUR_MS;\n\n/** The UTC days a window touches, each clipped to it: `[date, from, to]`. */\nexport function windowDays(window: { from: string; to: string }): { date: string; from: string; to: string }[] {\n const from = Date.parse(window.from);\n const to = Date.parse(window.to);\n const out: { date: string; from: string; to: string }[] = [];\n for (let day = Math.floor(from / DAY_MS) * DAY_MS; day < to; day += DAY_MS) {\n const start = Math.max(day, from);\n const end = Math.min(day + DAY_MS, to);\n if (end > start) out.push({ date: new Date(day).toISOString().slice(0, 10), from: new Date(start).toISOString(), to: new Date(end).toISOString() });\n }\n return out;\n}\n\n/** Rows grouped per ledger and id, each group sorted by time: what the day loop walks. */\nfunction sortedGroups<R extends { at: string; ledger?: string }>(rows: readonly R[], idOf: (r: R) => string): R[][] {\n const groups = new Map<string, R[]>();\n for (const r of rows) {\n const key = r.ledger === undefined ? idOf(r) : `${r.ledger}:${idOf(r)}`;\n const list = groups.get(key);\n if (list === undefined) groups.set(key, [r]);\n else list.push(r);\n }\n return [...groups.values()].map((list) => list.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0)));\n}\n\n/**\n * One box's or volume's cost on each day, as `groupUsage` / `groupVolumeUsage` would price it over that\n * day alone: its `rm` row ends its time, it is absent before its first row and after an `rm` before the\n * day. Only the rows that matter to a day are handed to `price` (the one the day opens in, those inside\n * it), found with a pointer that moves forward with the days: the work is the rows plus the days, not\n * their product.\n */\nfunction costPerDay<R extends { at: string; by: string }>(\n events: readonly R[],\n days: readonly { from: string; to: string }[],\n price: (events: readonly R[], w: { from: string; to: string }) => number,\n ledgerEnd?: string,\n): (number | null)[] {\n const first = events[0]!;\n const last = events[events.length - 1]!;\n const removed = last.by === \"rm\";\n let open = 0;\n return days.map((day) => {\n let to = removed && last.at < day.to ? last.at : day.to;\n if (ledgerEnd !== undefined && ledgerEnd < to) to = ledgerEnd;\n if (to <= day.from) return null;\n if (first.at >= to || (removed && last.at <= day.from)) return null;\n while (open + 1 < events.length && events[open + 1]!.at <= day.from) open++;\n let end = open;\n while (end < events.length && events[end]!.at < to) end++;\n return price(events.slice(open, Math.max(end, open + 1)), { from: day.from, to });\n });\n}\n\n/**\n * The same rows as a report, cut into UTC days: each day's boxes and volumes priced over that day\n * alone, the way `groupUsage` / `groupVolumeUsage` price a window (a removed box stops at its `rm`, a\n * box made later is absent before its first row). Rows must cover the whole window, the row before it\n * included, as `usageReport` reads them. Rows are grouped and sorted once, not once per day. `ends`\n * (ledger → time) is where a ledger's rows stop counting: nothing of it accrues after, as when the\n * window given to `groupUsage` is cut there.\n */\nexport function dailyUsage(\n boxRows: readonly LedgerRow[],\n volumeRows: readonly VolumeLedgerRow[],\n window: { from: string; to: string },\n pricing: Pricing,\n ends: ReadonlyMap<string, string> = new Map(),\n): UsageDay[] {\n const days = windowDays(window);\n const perDay: { boxes: UsageDayItem[]; volumes: UsageDayItem[] }[] = days.map(() => ({ boxes: [], volumes: [] }));\n for (const events of sortedGroups(boxRows, (r) => r.boxId)) {\n const last = events[events.length - 1]!;\n costPerDay(events, days, (e, w) => computeUsage(e, { ...w, pricing }).cost?.amount ?? 0, ends.get(last.ledger ?? \"\")).forEach((cost, i) => {\n if (cost !== null) perDay[i]!.boxes.push({ id: last.boxId, name: last.name, owner: last.owner, removed: last.by === \"rm\", cost });\n });\n }\n for (const events of sortedGroups(volumeRows, (r) => r.volumeId)) {\n const last = events[events.length - 1]!;\n costPerDay(events, days, (e, w) => computeVolumeUsage(e, { ...w, pricing }).cost?.amount ?? 0, ends.get(last.ledger ?? \"\")).forEach((cost, i) => {\n if (cost !== null) perDay[i]!.volumes.push({ id: last.volumeId, name: last.name, owner: last.owner, removed: last.by === \"rm\", cost });\n });\n }\n const byCost = (a: UsageDayItem, b: UsageDayItem) => b.cost - a.cost || a.name.localeCompare(b.name);\n return days.map((day, i) => {\n const { boxes, volumes } = perDay[i]!;\n const cost = round([...boxes, ...volumes].reduce((n, item) => n + item.cost, 0), 4);\n return { ...day, cost, currency: pricing.currency, boxes: boxes.sort(byCost), volumes: volumes.sort(byCost) };\n });\n}\n","/**\n * Who a box belongs to. Names are unique per owner, not per host, so a box is addressed as\n * `owner/name`; a bare `name` means the caller's own. The owner is part of the box's identity and\n * lives with it on disk (machines/<owner>/<name>, `owner` in meta.json), never in a database.\n * Decision \"Owner realms\": a bare owner is local to this host (the Unix user running kvbox-server);\n * a control plane's users arrive as `user@<control plane>` later (#18), so the two never collide.\n */\nimport { userInfo } from \"node:os\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\n\nexport interface BoxRef {\n owner: string;\n name: string;\n /** How the caller wrote it: `lab1` for their own, `user2/lab1` for someone else's. Set by parseRef, used in messages. */\n display?: string;\n}\n\n/** The ref as the caller knows it (see BoxRef.display); bare name when nothing else is known. */\nexport function shown(ref: BoxRef): string {\n return ref.display ?? ref.name;\n}\n\n/** A local owner is a Unix user name: no `@` (that marks a control-plane realm) and no `/`. */\nexport const LOCAL_OWNER_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}$/;\n/** A realm: a control plane's name as hosts qualify owners with it (`kvbox.sh`). A path segment later, so nothing but a host name. */\nexport const REALM_RE = /^[A-Za-z0-9.-]{1,128}$/;\n/** Any owner, local or `user@realm`. */\nexport const OWNER_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}(@[A-Za-z0-9.-]{1,128})?$/;\n\n/** The Unix user running this server: what boxes made over the local socket belong to. */\nexport function localOwner(): string {\n try {\n const name = userInfo().username;\n if (LOCAL_OWNER_RE.test(name)) return name;\n } catch {\n /* no passwd entry */\n }\n const env = process.env[\"USER\"];\n return env !== undefined && LOCAL_OWNER_RE.test(env) ? env : \"kvbox\";\n}\n\n/**\n * Who a listing is for: one owner, every owner of a realm (`{ realm }`: the control plane reconciling\n * its index, #20), or everyone (`null`: the host owner's own accounting).\n */\nexport type ListScope = string | { realm: string } | null;\n\nexport function inScope(owner: string, scope: ListScope): boolean {\n if (scope === null) return true;\n if (typeof scope === \"string\") return owner === scope;\n return realmOf(owner) === scope.realm;\n}\n\n/** The control plane an owner belongs to (`alice@kvbox.sh` → `kvbox.sh`); null for a local owner. */\nexport function realmOf(owner: string): string | null {\n const at = owner.indexOf(\"@\");\n return at === -1 ? null : owner.slice(at + 1);\n}\n\n/**\n * `lab1` → the caller's box; `user2/lab1` → that owner's. A caller from a control plane (`user@realm`)\n * can only name owners of that realm: the control plane never sees the host owner's local boxes or\n * another control plane's. The host owner over the socket is not restricted.\n */\nexport function parseRef(text: string, caller: string): BoxRef {\n const slash = text.indexOf(\"/\");\n if (slash === -1) return { owner: caller, name: text, display: text };\n const owner = text.slice(0, slash);\n const name = text.slice(slash + 1);\n if (!OWNER_RE.test(owner) || name.length === 0 || name.includes(\"/\")) {\n throw new KvboxError(`invalid box reference \"${text}\": use <name> or <owner>/<name>`);\n }\n const realm = realmOf(caller);\n if (realm !== null && realmOf(owner) !== realm) {\n throw new KvboxError(`invalid box reference \"${text}\": ${owner} is not in your realm`);\n }\n return { owner, name, display: owner === caller ? name : text };\n}\n\n/**\n * The owner a caller names for a new box (`kvbox vm fork --org`, #79): a bare slug, kept inside the\n * caller's realm (`acme` from `alice@kvbox.sh` is `acme@kvbox.sh`). The host owner over the socket\n * names a local owner as it is.\n */\nexport function ownerFor(slug: string, caller: string): string {\n if (!LOCAL_OWNER_RE.test(slug)) throw new KvboxError(`invalid owner \"${slug}\": a bare slug, without '@' or '/'`);\n const realm = realmOf(caller);\n return realm === null ? slug : `${slug}@${realm}`;\n}\n\n/** `owner/name`: how a ref is written down (snapshot sources, box sources, admin listings). */\nexport function refKey(ref: BoxRef): string {\n return `${ref.owner}/${ref.name}`;\n}\n","/**\n * Firecracker needs /dev/kvm. A daemon that cannot open it starts fine and only fails at the first\n * `kvbox new`, with an opaque firecracker 400 (#61): the usual cause is a shell that logged in\n * before the user was added to the kvm group, so the daemon it spawned runs without that group.\n * Checked once at `kvbox-server start`, before the socket is bound, and told in plain words.\n */\nimport { access, constants, readFile, stat } from \"node:fs/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\n\nexport const KVM_DEVICE = \"/dev/kvm\";\n\n/** The group's name for a gid from /etc/group, `kvm` when the file does not say. */\nexport async function groupName(gid: number, groupFile = \"/etc/group\"): Promise<string> {\n const text = await readFile(groupFile, \"utf8\").catch(() => \"\");\n for (const line of text.split(\"\\n\")) {\n const [name, , id] = line.split(\":\");\n if (id !== undefined && Number.parseInt(id, 10) === gid && name) return name;\n }\n return \"kvm\";\n}\n\n/** Resolves when this process can open the device for reading and writing; a KvboxError saying what to do otherwise. */\nexport async function requireKvm(device = KVM_DEVICE, groupFile = \"/etc/group\"): Promise<void> {\n try {\n await access(device, constants.R_OK | constants.W_OK);\n return;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n throw new KvboxError(`${device} is missing: this machine has no KVM, so boxes cannot run here (enable virtualization in the BIOS, then install-server.sh checks the rest)`);\n }\n if (code !== \"EACCES\" && code !== \"EPERM\") throw new KvboxError(`cannot open ${device}: ${(err as Error).message}`);\n }\n const owner = await stat(device).then((s) => groupName(s.gid, groupFile), () => \"kvm\");\n throw new KvboxError(\n `cannot start: this process is not allowed to open ${device}, so no box could run. ` +\n `It was started from a shell without the ${owner} group (a login from before you were added to it). ` +\n `Log out and back in, or start it from a shell that has the group: sg ${owner} -c \"kvbox-server start -d\"`,\n );\n}\n","/**\n * Box names inside boxes (#97): `<name>.kvbox` resolves to the box of that name with the asker's owner.\n * A small DNS server on the bridge address, reached on port 53 through net-setup.sh's redirect to\n * DNS_PORT (the daemon is not root). The image lists it first and 1.1.1.1 second, so it answers only\n * `.kvbox` names and REFUSED to everything else, which sends the guest's resolver straight to the next\n * server: internet lookups never depend on this daemon. The asker is known by its source address.\n * Only A records; a name is not an access grant (boxes stay isolated from each other).\n */\nimport { createSocket, type Socket } from \"node:dgram\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { boxListVersionNow, listMachineRefs, readMachineMeta } from \"./state.js\";\n\n/** Where the listener binds on the bridge address; net-setup.sh redirects port 53 there (keep both in step). */\nexport const DNS_PORT = 10053;\nexport const DNS_SUFFIX = \".kvbox\";\n/** How often the daemon tries the bind again while the bridge address does not exist. */\nexport const DNS_RETRY_MS = 10_000;\nconst TTL_SEC = 5;\n/**\n * How long one scan of the boxes answers every lookup when nothing changed. Every create and rm goes\n * through this daemon and moves the box list's version, which re-reads at once (a removed box's IP goes\n * to the next box, of any owner); this is only the backstop for a change made behind its back.\n */\nconst BOXES_FRESH_MS = 60_000;\n\nconst TYPE_A = 1;\nconst CLASS_IN = 1;\nconst RCODE = { ok: 0, nxDomain: 3, refused: 5 } as const;\n\nexport interface Query {\n id: number;\n /** Recursion desired, echoed back. */\n rd: boolean;\n name: string;\n type: number;\n class: number;\n /** The question section as received, echoed in the answer. */\n question: Buffer;\n}\n\n/** The first question of a standard query, or null when the packet is not one we can answer. */\nexport function parseQuery(msg: Buffer): Query | null {\n if (msg.length < 12) return null;\n const flags = msg.readUInt16BE(2);\n const isResponse = flags & 0x8000;\n const opcode = (flags >> 11) & 0xf;\n if (isResponse || opcode !== 0 || msg.readUInt16BE(4) < 1) return null;\n const labels: string[] = [];\n let at = 12;\n for (;;) {\n if (at >= msg.length) return null;\n const len = msg[at]!;\n at += 1;\n if (len === 0) break;\n if (len > 63 || at + len > msg.length) return null; // compression pointers never appear in a question\n labels.push(msg.subarray(at, at + len).toString(\"latin1\"));\n at += len;\n }\n if (at + 4 > msg.length) return null;\n return {\n id: msg.readUInt16BE(0),\n rd: Boolean(flags & 0x0100),\n name: labels.join(\".\").toLowerCase(),\n type: msg.readUInt16BE(at),\n class: msg.readUInt16BE(at + 2),\n question: msg.subarray(12, at + 4),\n };\n}\n\n/** A response to `q`: the question echoed, plus one A record when `ip` is given. */\nexport function buildAnswer(q: Query, rcode: number, ip?: string): Buffer {\n const header = Buffer.alloc(12);\n header.writeUInt16BE(q.id, 0);\n // QR, AA (we own .kvbox), RD echoed; RA off: we never recurse.\n header.writeUInt16BE(0x8000 | 0x0400 | (q.rd ? 0x0100 : 0) | rcode, 2);\n header.writeUInt16BE(1, 4);\n header.writeUInt16BE(ip ? 1 : 0, 6);\n if (!ip) return Buffer.concat([header, q.question]);\n const rr = Buffer.alloc(16);\n rr.writeUInt16BE(0xc00c, 0); // the name: a pointer to the question's\n rr.writeUInt16BE(TYPE_A, 2);\n rr.writeUInt16BE(CLASS_IN, 4);\n rr.writeUInt32BE(TTL_SEC, 6);\n rr.writeUInt16BE(4, 10);\n ip.split(\".\").forEach((o, i) => rr.writeUInt8(Number(o), 12 + i));\n return Buffer.concat([header, q.question, rr]);\n}\n\nexport interface BoxAddress {\n name: string;\n owner: string;\n ip: string;\n /** The IPs of the boxes linked into this one (#98): they see its name across slugs. */\n linkedFrom?: readonly string[];\n}\n\n/** `alice@kvbox.sh` → `alice`: the slug a name's second label spells. */\nconst slugOf = (owner: string) => owner.split(\"@\")[0]!.toLowerCase();\n\n/** A `.kvbox` name in class IN: the only questions worth looking at the boxes for. */\nexport const isOurs = (q: Query) => q.class === CLASS_IN && q.name.endsWith(DNS_SUFFIX);\n\n/**\n * What to answer `asker` (a source address) about `q`. `db.kvbox` is the asker's owner's box `db`;\n * `db.acme.kvbox` is slug `acme`'s: the asker's own slug (an org's boxes asking about each other), or\n * another slug's box the asker is linked into (#98, the link is the grant). Not ours:\n * REFUSED. Ours but the asker is no box, or no such box it may see: NXDOMAIN, the same for a name\n * another owner uses, so names cannot be probed across owners. A name that exists but a type other\n * than A: no records.\n */\nexport function answerFor(q: Query, asker: string, boxes: readonly BoxAddress[]): { rcode: number; ip?: string } {\n if (!isOurs(q)) return { rcode: RCODE.refused };\n const [name, slug, ...rest] = q.name.slice(0, -DNS_SUFFIX.length).split(\".\");\n const from = boxes.find((b) => b.ip === asker);\n let box: BoxAddress | undefined;\n if (from && rest.length === 0) {\n box =\n slug === undefined || slug === slugOf(from.owner)\n ? boxes.find((b) => b.owner === from.owner && b.name === name)\n : boxes.find((b) => slugOf(b.owner) === slug && b.name === name && b.linkedFrom?.includes(asker));\n }\n if (!box) return { rcode: RCODE.nxDomain };\n return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };\n}\n\nasync function boxAddresses(p: Paths): Promise<BoxAddress[]> {\n const out: BoxAddress[] = [];\n for (const ref of await listMachineRefs(p)) {\n const meta = await readMachineMeta(ref, p).catch(() => null); // a half-written box is not an answer\n if (meta) out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...(meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {}) });\n }\n return out;\n}\n\n/**\n * `load` again only when the box list's `version` moved or `freshMs` passed, its result shared by every\n * lookup meanwhile, the ones waiting on a scan in flight included. A failed scan is not kept: the next\n * lookup tries again.\n */\nexport function sharedBoxes(\n load: () => Promise<BoxAddress[]>,\n freshMs = BOXES_FRESH_MS,\n version: () => number = boxListVersionNow,\n): () => Promise<BoxAddress[]> {\n let last: { at: number; version: number; list: Promise<BoxAddress[]> } | null = null;\n return () => {\n if (!last || last.version !== version() || Date.now() - last.at > freshMs) {\n // The version is taken before the scan: a change during it makes the next lookup scan again.\n const entry = { at: Date.now(), version: version(), list: load() };\n last = entry;\n entry.list.catch(() => {\n if (last === entry) last = null;\n });\n }\n return last.list;\n };\n}\n\nexport interface DnsOptions {\n /** The bridge address. */\n host: string;\n port?: number;\n boxes?: () => Promise<BoxAddress[]>;\n p?: Paths;\n}\n\n/** Bind and answer until closed. Rejects when the address cannot be bound (no bridge yet, port taken). */\nexport async function startDns(opts: DnsOptions): Promise<{ socket: Socket; close: () => Promise<void> }> {\n const p = opts.p ?? paths();\n const boxes = sharedBoxes(opts.boxes ?? (() => boxAddresses(p)));\n const socket = createSocket(\"udp4\");\n socket.on(\"message\", (msg, rinfo) => {\n const q = parseQuery(msg);\n if (!q) return; // nothing a resolver sends us; it moves on after its timeout\n const reply = (a: { rcode: number; ip?: string }) => socket.send(buildAnswer(q, a.rcode, a.ip), rinfo.port, rinfo.address);\n // Every internet lookup of every box comes here first: refused at once, without touching the boxes.\n if (!isOurs(q)) return reply({ rcode: RCODE.refused });\n void boxes()\n .then((list) => answerFor(q, rinfo.address, list))\n .catch((): { rcode: number; ip?: string } => ({ rcode: RCODE.refused }))\n .then(reply);\n });\n await new Promise<void>((resolve, reject) => {\n socket.once(\"error\", (err) => {\n socket.close(); // a caller that retries must not pile up dead sockets\n reject(err);\n });\n socket.bind(opts.port ?? DNS_PORT, opts.host, () => {\n socket.removeAllListeners(\"error\");\n socket.on(\"error\", () => {}); // a send to a box that went away must not crash the daemon\n resolve();\n });\n });\n return { socket, close: () => new Promise<void>((resolve) => socket.close(() => resolve())) };\n}\n","/**\n * The `~/.kvbox` layout and the per-box / per-snapshot `meta.json` files.\n * The server is the only writer; every read is validated with zod.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { mkdir, readFile, readdir, rename, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { insertVolumeEvent } from \"./db.js\";\nimport type { BoxRef } from \"./refs.js\";\n\nexport const MachineMetaSchema = z.object({\n /** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */\n id: z.string(),\n name: z.string(),\n /** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */\n owner: z.string(),\n ip: z.string(),\n mac: z.string(),\n pid: z.number().int().nullable(), // null: stopped on purpose, disk kept\n /**\n * The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot\n * the number can name some other process; a pid from another boot is dead whatever `kill -0` says.\n * Absent (boxes launched before #29): the pid alone decides.\n */\n bootId: z.string().optional(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n createdAt: z.string(),\n source: z.string(),\n /** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */\n base: z.string(),\n /** The image (#87), when not the base one: assets/images/<image>/rootfs-<base>.ext4. `vm update` keeps it. */\n image: z.string().optional(),\n /** The image's connect line with its secrets masked and `${BOX}` unfilled (#87, `maskedUrl`). Absent: the image declares none. */\n url: z.string().optional(),\n /**\n * Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at\n * each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file\n * is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.\n */\n memSnapshots: z.number().int().optional(),\n /** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */\n paused: z.boolean().optional(),\n /**\n * authorized_keys lines the box gets on top of the host's own key, as the control plane sent them\n * at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so\n * `start` has to send the same lines again. Absent: host key only.\n */\n sshKeys: z.array(z.string()).optional(),\n /**\n * The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,\n * or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.\n */\n sshKeysStale: z.boolean().optional(),\n /** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */\n sshPort: z.number().int().optional(),\n /**\n * Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,\n * each host port the box's for its life. DNATed while the box runs, rebuilt from here with its\n * current IP every time it comes up. Absent: none.\n */\n ports: z.array(z.object({ guestPort: z.number().int(), hostPort: z.number().int(), proto: z.enum([\"tcp\", \"udp\"]), closed: z.literal(true).optional() })).optional(),\n /** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */\n autoHibernateSec: z.number().int().positive().optional(),\n /**\n * A script inside the box auto-hibernate asks instead of watching the tap (#102, core/idle.ts): run by\n * kvbox-agent, exit 0 = idle. A new box gets its image's `idle` (image.json); `kvbox vm set --idle-check`\n * changes it. The one place the host looks. Absent: the traffic rule.\n */\n idleCheck: z.string().optional(),\n /**\n * Names of the owner's volumes attached to the box (#52), in the order they were attached, which is\n * their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a\n * volume's meta.json does not say. Absent: none.\n */\n volumes: z.array(z.string()).optional(),\n /**\n * Links into this box (#98, `kvbox vm link`): box `owner/name`, at `ip`, may open TCP connections to\n * `port`. The rule is open while this box runs, rebuilt from here at every boot; `ip` is the other\n * box's, fixed for its life, and checked against its meta.json before a rule opens. `stale`: that box\n * was removed but the rule would not close; kept only so this box's next stop closes it, never opened\n * again, never listed (a new box of the same name may get the same IP). Absent: none.\n */\n links: z.array(z.object({ owner: z.string(), name: z.string(), ip: z.string(), port: z.number().int(), stale: z.literal(true).optional() })).optional(),\n});\nexport type MachineMeta = z.infer<typeof MachineMetaSchema>;\n\n/** A volume (#52): its own meta.json next to its disk under volumes/<owner>/<name>. Which box has it is the box's meta.json. */\nexport const VolumeMetaSchema = z.object({\n /** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n sizeGib: z.number().int(),\n createdAt: z.string(),\n});\nexport type VolumeMeta = z.infer<typeof VolumeMetaSchema>;\n\n/** 6 lowercase hex chars: 16M values per host, 9 chars as a tap name, well inside Linux's 15-char limit. */\nexport const BOX_ID_RE = /^[0-9a-f]{6}$/;\n\n/** A fresh id no box on the host has (`taken`: every id in use, so a draw can be retried). */\nexport function newBoxId(taken: ReadonlySet<string>): string {\n for (;;) {\n const id = randomBytes(3).toString(\"hex\");\n if (!taken.has(id)) return id;\n }\n}\n\nexport const SnapshotMetaSchema = z.object({\n name: z.string(),\n owner: z.string(),\n /** The box it was taken from, as owner/name. */\n source: z.string(),\n base: z.string(),\n /** As in a box's meta.json (#87). */\n image: z.string().optional(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n sizeBytes: z.number().int(),\n createdAt: z.string(),\n /**\n * The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate\n * and their mounts in the memory image, but their data is not here. A box restored from the snapshot\n * gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.\n */\n volumes: z.array(z.object({ name: z.string(), sizeGib: z.number().int() })).optional(),\n});\nexport type SnapshotMeta = z.infer<typeof SnapshotMetaSchema>;\n\n/** Create every directory of the layout. Idempotent; called by `kvbox-server start`. */\nexport async function ensureLayout(p: Paths = paths()): Promise<Paths> {\n for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n }\n return p;\n}\n\nasync function readJson<T>(file: string, schema: z.ZodType<T>): Promise<T> {\n return schema.parse(JSON.parse(await readFile(file, \"utf8\")));\n}\n\nasync function listDirs(dir: string): Promise<string[]> {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n}\n\nexport async function readMachineMeta(ref: BoxRef, p: Paths = paths()) {\n return readJson(p.machine(ref.owner, ref.name).meta, MachineMetaSchema);\n}\n\nlet boxListVersion = 0;\n/** Moves whenever a box's meta.json is written or its dir removed: a cache of the box list (core/dns.ts) re-reads when it has. */\nexport const boxListVersionNow = () => boxListVersion;\nexport const boxListChanged = () => void (boxListVersion += 1);\n\n/** Whole or not at all: a listing reading the box at the same moment sees the old meta or the new, never a cut one. */\nexport async function writeMachineMeta(meta: MachineMeta, p: Paths = paths()) {\n const m = p.machine(meta.owner, meta.name);\n await mkdir(m.dir, { recursive: true });\n const tmp = `${m.meta}.tmp`;\n await writeFile(tmp, JSON.stringify(meta, null, 2) + \"\\n\");\n await rename(tmp, m.meta);\n boxListChanged();\n}\n\n/** Every box on the host, all owners: machines/<owner>/<name>. */\nexport async function listMachineRefs(p: Paths = paths()) {\n return listRefs(p.machines);\n}\n\nexport async function readSnapshotMeta(ref: BoxRef, p: Paths = paths()) {\n return readJson(p.snapshot(ref.owner, ref.name).meta, SnapshotMetaSchema);\n}\n\n/** `s` is where the snapshot's files are: its own dir, or the temp dir a replace captures into (#83). */\nexport async function writeSnapshotMeta(meta: SnapshotMeta, p: Paths = paths(), s = p.snapshot(meta.owner, meta.name)) {\n await mkdir(s.dir, { recursive: true });\n await writeFile(s.meta, JSON.stringify(meta, null, 2) + \"\\n\");\n}\n\n/** Skips the dot dirs a replace works in (`.<name>.new-<box id>`, `.<name>.old-<box id>`, #83): no snapshot name starts with a dot. */\nexport async function listSnapshotRefs(p: Paths = paths()) {\n return (await listRefs(p.snapshots)).filter((ref) => !ref.name.startsWith(\".\"));\n}\n\n/**\n * A volume made before #91 has no `id`: it gets one here, written back, and the `create` ledger row it\n * never had, dated when the volume was made, so it is listed, billed and bootable like any other.\n */\nexport async function readVolumeMeta(ref: BoxRef, p: Paths = paths()): Promise<VolumeMeta> {\n const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z.string().optional() }));\n if (raw.id !== undefined) return { ...raw, id: raw.id };\n const taken = new Set<string>();\n for (const other of await listVolumeRefs(p)) {\n try {\n const j = JSON.parse(await readFile(p.volume(other.owner, other.name).meta, \"utf8\")) as { id?: unknown };\n if (typeof j.id === \"string\") taken.add(j.id);\n } catch {\n /* an unreadable volume holds no id to avoid */\n }\n }\n const meta: VolumeMeta = { ...raw, id: newBoxId(taken) };\n await writeVolumeMeta(meta, p);\n insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: meta.createdAt, sizeGib: meta.sizeGib, by: \"create\" }, p);\n return meta;\n}\n\nexport async function writeVolumeMeta(meta: VolumeMeta, p: Paths = paths()) {\n const v = p.volume(meta.owner, meta.name);\n await mkdir(v.dir, { recursive: true, mode: 0o700 });\n await writeFile(v.meta, JSON.stringify(meta, null, 2) + \"\\n\");\n}\n\nexport async function listVolumeRefs(p: Paths = paths()) {\n return listRefs(p.volumes);\n}\n\n/** Two levels: <root>/<owner>/<name>. */\nasync function listRefs(root: string): Promise<BoxRef[]> {\n const out: BoxRef[] = [];\n for (const owner of await listDirs(root)) {\n for (const name of await listDirs(`${root}/${owner}`)) {\n out.push({ owner, name });\n }\n }\n return out;\n}\n\n/** True when a pid is alive (signal 0). */\nexport function pidAlive(pid: number | null): boolean {\n if (pid === null || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nlet bootId: { id: string | undefined } | undefined;\n\n/** This boot's id (undefined where the kernel does not expose one). Read once: it cannot change under a running process. */\nexport function currentBootId(): string | undefined {\n if (bootId === undefined) {\n try {\n bootId = { id: readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\").trim() };\n } catch {\n bootId = { id: undefined };\n }\n }\n return bootId.id;\n}\n\n/** True when the box's Firecracker is still there: its pid is alive and was launched in this boot. */\nexport function vmAlive(meta: Pick<MachineMeta, \"pid\" | \"bootId\">): boolean {\n if (meta.bootId !== undefined && meta.bootId !== currentBootId()) return false;\n return pidAlive(meta.pid);\n}\n\n/** When the host booted, from /proc/stat's btime (null where there is none). */\nexport function hostBootTime(): Date | null {\n try {\n const m = /^btime (\\d+)$/m.exec(readFileSync(\"/proc/stat\", \"utf8\"));\n return m ? new Date(Number(m[1]) * 1000) : null;\n } catch {\n return null;\n }\n}\n","/**\n * `~/.kvbox/kvbox.db`: the host's ledgers, through Node's built-in SQLite (node:sqlite, Node >= 22.13;\n * no dependency). Decision \"Hosts keep boxes as files + SQLite ledgers\": a box is still its directory\n * and meta.json, the database only holds what has to be appended to over time and summed later.\n * First table: `usage_events`, one row per state change of a box, the source of `kvbox vm usage`.\n *\n * One handle per database file for the life of the process; WAL so readers never block the writer.\n * The file is created 0600 before SQLite opens it, so the -wal and -shm files it makes next to it\n * inherit the mode.\n */\nimport { chmodSync, closeSync, mkdirSync, openSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport type { UsageEvent, UsageState, VolumeLedgerRow } from \"@kvbox/shared/usage\";\nimport { inScope, type ListScope } from \"./refs.js\";\n\n/** Each entry upgrades the schema one version; `schema_version` records how far a file has come. */\nconst MIGRATIONS: string[] = [\n `create table usage_events (\n id integer primary key,\n box_id text not null,\n owner text not null,\n name text not null,\n at text not null,\n state text not null,\n vcpu integer not null,\n mem_mib integer not null,\n disk_gib integer not null,\n by text not null\n );\n create index usage_events_box_at on usage_events (box_id, at);`,\n // The ledger's identity (#42): a control plane keys pulled rows by it, so a re-join is recognised\n // and a fresh ledger (KVBOX_HOME wiped) restarts its cursor instead of waiting for ids it already saw.\n `create table ledger (id text not null);\n insert into ledger (id) values (lower(hex(randomblob(16))));\n create index usage_events_at on usage_events (at);`,\n // Volumes (#91): a row per create, resize and rm, the size from that moment on. Its own table and\n // ids, pulled by the control plane like usage_events, in the same ledger.\n `create table volume_events (\n id integer primary key,\n volume_id text not null,\n owner text not null,\n name text not null,\n at text not null,\n size_gib integer not null,\n by text not null\n );\n create index volume_events_volume_at on volume_events (volume_id, at);`,\n];\n\nconst handles = new Map<string, DatabaseSync>();\n\nexport function openDb(p: Paths = paths()): DatabaseSync {\n const have = handles.get(p.db);\n if (have !== undefined) return have;\n mkdirSync(dirname(p.db), { recursive: true, mode: 0o700 });\n closeSync(openSync(p.db, \"a\", 0o600));\n chmodSync(p.db, 0o600);\n const db = new DatabaseSync(p.db);\n db.exec(\"pragma journal_mode = wal\");\n db.exec(\"pragma busy_timeout = 5000\");\n migrate(db);\n handles.set(p.db, db);\n return db;\n}\n\n/** Close the handle for this home (tests; the daemon keeps its open until exit). */\nexport function closeDb(p: Paths = paths()): void {\n const db = handles.get(p.db);\n if (db === undefined) return;\n db.close();\n handles.delete(p.db);\n}\n\nfunction migrate(db: DatabaseSync): void {\n db.exec(\"create table if not exists schema_version (version integer not null)\");\n const row = db.prepare(\"select version from schema_version\").get() as { version: number } | undefined;\n let version = row?.version ?? 0;\n if (row === undefined) db.prepare(\"insert into schema_version (version) values (0)\").run();\n while (version < MIGRATIONS.length) {\n db.exec(\"begin\");\n try {\n db.exec(MIGRATIONS[version]!);\n version += 1;\n db.prepare(\"update schema_version set version = ?\").run(version);\n db.exec(\"commit\");\n } catch (err) {\n db.exec(\"rollback\");\n throw err;\n }\n }\n}\n\n/**\n * `kvbox-server rename-realm`: every ledger row of an owner in realm `from` now names the same slug in `to`.\n * Ids do not move, so the control plane's pull cursors stay right. Returns how many rows changed.\n */\nexport function renameLedgerRealm(from: string, to: string, p: Paths = paths()): number {\n const db = openDb(p);\n let rows = 0;\n db.exec(\"begin\");\n try {\n for (const table of [\"usage_events\", \"volume_events\"]) {\n const res = db\n .prepare(`update ${table} set owner = substr(owner, 1, length(owner) - length(?)) || ? where substr(owner, -length(?)) = ?`)\n .run(`@${from}`, `@${to}`, `@${from}`, `@${from}`);\n rows += Number(res.changes);\n }\n db.exec(\"commit\");\n } catch (err) {\n db.exec(\"rollback\");\n throw err;\n }\n return rows;\n}\n\n// ---- usage_events --------------------------------------------------------------------------------\n\nexport type { UsageEvent, UsageState };\n\n/** States in which a Firecracker process exists: a run that `closeOpenRun` has to close if that process died. */\nconst LIVE_STATES: readonly UsageState[] = [\"running\", \"standby\"];\n\nexport interface UsageEventRow extends UsageEvent {\n /** The box's id. Owner and name ride along so the ledger reads alone after a box is gone. */\n boxId: string;\n owner: string;\n name: string;\n}\n\ninterface Raw {\n id: number;\n box_id: string;\n owner: string;\n name: string;\n at: string;\n state: string;\n vcpu: number;\n mem_mib: number;\n disk_gib: number;\n by: string;\n}\n\nfunction fromRaw(r: Raw): UsageEventRow {\n return { boxId: r.box_id, owner: r.owner, name: r.name, at: r.at, state: r.state as UsageState, vcpu: r.vcpu, memMib: r.mem_mib, diskGib: r.disk_gib, by: r.by };\n}\n\nfunction lastEvent(boxId: string, db: DatabaseSync): UsageEventRow | undefined {\n const raw = db.prepare(\"select * from usage_events where box_id = ? order by at desc, id desc limit 1\").get(boxId) as Raw | undefined;\n return raw === undefined ? undefined : fromRaw(raw);\n}\n\nfunction insertRaw(e: UsageEventRow, db: DatabaseSync): void {\n db.prepare(\n \"insert into usage_events (box_id, owner, name, at, state, vcpu, mem_mib, disk_gib, by) values (?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n ).run(e.boxId, e.owner, e.name, e.at, e.state, e.vcpu, e.memMib, e.diskGib, e.by);\n}\n\n/**\n * Append a state change. A `running` on top of an open run (running or standby) means the box stopped\n * without the server knowing (Firecracker died, host rebooted): that run is closed first, dated now, by\n * `server`. The one exception is a resume, the legitimate way from standby back to running.\n */\nexport function insertUsageEvent(e: UsageEventRow, p: Paths = paths()): void {\n const db = openDb(p);\n if (e.state === \"running\" && e.by !== \"resume\") closeOpenRun(e.boxId, e.at, p);\n insertRaw(e, db);\n}\n\n/** If the box's last event has a live process (running or standby), add the `stopped` the server never saw, at `at`. True when one was added. */\nexport function closeOpenRun(boxId: string, at: string, p: Paths = paths()): boolean {\n const db = openDb(p);\n const last = lastEvent(boxId, db);\n if (last === undefined || !LIVE_STATES.includes(last.state)) return false;\n insertRaw({ ...last, at, state: \"stopped\", by: \"server\" }, db);\n return true;\n}\n\n/**\n * The run a host shutdown cut (#29): a run that began before the host booted cannot have outlived the\n * boot, so it ends at `bootAt`; one that began after it (Firecracker crashed since) ends `now`.\n */\nexport function closeRunCutByBoot(boxId: string, bootAt: string, now: string, p: Paths = paths()): boolean {\n const last = lastEvent(boxId, openDb(p));\n return closeOpenRun(boxId, last !== undefined && last.at < bootAt ? bootAt : now, p);\n}\n\n/** The box's events from `since` on, oldest first. */\nexport function usageEventsFor(boxId: string, since: string, p: Paths = paths()): UsageEventRow[] {\n const rows = openDb(p).prepare(\"select * from usage_events where box_id = ? and at >= ? order by at, id\").all(boxId, since) as unknown as Raw[];\n return rows.map(fromRaw);\n}\n\n/** A ledger row with its id: the cursor a control plane pulls by (#42). */\nexport type UsageEventWithId = UsageEventRow & { id: number };\n\nconst withId = (r: Raw): UsageEventWithId => ({ ...fromRaw(r), id: r.id });\n\n/** This home's ledger id, made with the database; it changes only when the database is recreated. */\nexport function ledgerId(p: Paths = paths()): string {\n return (openDb(p).prepare(\"select id from ledger\").get() as { id: string }).id;\n}\n\n/**\n * Rows after `after` by id (the order they were written in, so a puller never misses one), at\n * most `limit`, of the owners in `scope`. The id is monotonic: a pull is resumable and a repeat\n * is a no-op on the other side.\n */\nexport function usageEventsAfter(after: number, limit: number, scope: ListScope, p: Paths = paths()): UsageEventWithId[] {\n const db = openDb(p);\n const rows = (scope === null\n ? db.prepare(\"select * from usage_events where id > ? order by id limit ?\").all(after, limit)\n : typeof scope === \"string\"\n ? db.prepare(\"select * from usage_events where id > ? and owner = ? order by id limit ?\").all(after, scope, limit)\n : db.prepare(\"select * from usage_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?\").all(after, `@${scope.realm}`, `@${scope.realm}`, limit)) as unknown as Raw[];\n return rows.map(withId);\n}\n\n/**\n * The rows of the owners in `scope` that a report over the window needs, in time order: those inside\n * it plus each box's last row before it (the state the window opens in). The host-wide report (#41).\n */\nexport function usageEventsInScope(scope: ListScope, window: { from: string; to: string }, p: Paths = paths()): UsageEventWithId[] {\n const rows = openDb(p)\n .prepare(\n `select * from usage_events where at < ? and (at >= ? or id in (select max(id) from usage_events where at < ? group by box_id))\n order by at, id`,\n )\n .all(window.to, window.from, window.from) as unknown as Raw[];\n return rows.filter((r) => inScope(r.owner, scope)).map(withId);\n}\n\n// ---- volume_events (#91) -------------------------------------------------------------------------\n\nexport type VolumeEventWithId = VolumeLedgerRow & { id: number };\n\ninterface RawVolume {\n id: number;\n volume_id: string;\n owner: string;\n name: string;\n at: string;\n size_gib: number;\n by: string;\n}\n\nconst volumeWithId = (r: RawVolume): VolumeEventWithId => ({ id: r.id, volumeId: r.volume_id, owner: r.owner, name: r.name, at: r.at, sizeGib: r.size_gib, by: r.by as VolumeLedgerRow[\"by\"] });\n\nexport function insertVolumeEvent(e: VolumeLedgerRow, p: Paths = paths()): void {\n openDb(p)\n .prepare(\"insert into volume_events (volume_id, owner, name, at, size_gib, by) values (?, ?, ?, ?, ?, ?)\")\n .run(e.volumeId, e.owner, e.name, e.at, e.sizeGib, e.by);\n}\n\n/** Rows after `after` by id, at most `limit`, of the owners in `scope`: the control plane's pull, like `usageEventsAfter`. */\nexport function volumeEventsAfter(after: number, limit: number, scope: ListScope, p: Paths = paths()): VolumeEventWithId[] {\n const db = openDb(p);\n const rows = (scope === null\n ? db.prepare(\"select * from volume_events where id > ? order by id limit ?\").all(after, limit)\n : typeof scope === \"string\"\n ? db.prepare(\"select * from volume_events where id > ? and owner = ? order by id limit ?\").all(after, scope, limit)\n : db.prepare(\"select * from volume_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?\").all(after, `@${scope.realm}`, `@${scope.realm}`, limit)) as unknown as RawVolume[];\n return rows.map(volumeWithId);\n}\n\n/** The volume rows a report over the window needs: those inside it plus each volume's last row before it. */\nexport function volumeEventsInScope(scope: ListScope, window: { from: string; to: string }, p: Paths = paths()): VolumeEventWithId[] {\n const rows = openDb(p)\n .prepare(\n `select * from volume_events where at < ? and (at >= ? or id in (select max(id) from volume_events where at < ? group by volume_id))\n order by at, id`,\n )\n .all(window.to, window.from, window.from) as unknown as RawVolume[];\n return rows.filter((r) => inScope(r.owner, scope)).map(volumeWithId);\n}\n\n","/**\n * Create, list and destroy boxes: what spikes #4 and #6 did by hand.\n * See architecture \"Process model\". The server is the only writer of ~/.kvbox/machines.\n */\nimport { spawn } from \"node:child_process\";\nimport { closeSync, existsSync, openSync, statSync } from \"node:fs\";\nimport { link, mkdir, readFile, rename, rm, truncate, writeFile } from \"node:fs/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { parseDuration } from \"@kvbox/shared/duration\";\nimport { MAX_BOX_LINKS, MAX_BOX_PORTS, type BoxStatus, type CreateMachineRequest, type ForkMachineRequest, type LinkRequest, type Machine, type PortsRequest, type RecoveryReport, type RescaleMachineRequest, type SetMachineRequest, type SshKeysApplied, type TrustCaReport, type Volume } from \"@kvbox/shared/api\";\nimport { paths, volumeDriveRel, type Paths } from \"@kvbox/shared/paths\";\nimport { SIZES, isSizeName } from \"@kvbox/shared/sizes\";\nimport { caLineFor, isCaLine, parseSshPublicKey, sshKeyFingerprint } from \"@kvbox/shared/ssh\";\nimport { dropVolumes, isNoAgent, isUnknownOp, setAuthorizedKeys, setEnv, setIdentity } from \"./agent.js\";\nimport { copyBoxEnv, envForBoot, mergeBoxEnv, readBoxEnvFile, readOwnerEnv, writeBoxEnv } from \"./env.js\";\nimport { assertOverlayCapable, baseVersionOf, currentImage, imageEnv, imageFile, imageFileFor, imageKey, imageLabel, imageManifest, maskedUrl, urlFor, type ImageManifest } from \"./images.js\";\nimport { assertCanGrow, attachedBox, getVolume, growVolume, captureDrivesOf, placeholderDrives, placeVolumeDrives, readVolume, volumeDriveId, volumeSummaries, type VolumeDrive } from \"./volumes.js\";\nimport { assertRoomFor } from \"./capacity.js\";\nimport { closeOpenRun, closeRunCutByBoot, insertUsageEvent, type UsageState } from \"./db.js\";\nimport { inScope, ownerFor, parseRef, realmOf, refKey, shown, type BoxRef, type ListScope } from \"./refs.js\";\nimport { loadConfig, type Config } from \"./config.js\";\nimport { locked, withBoxLock, withHostLock, withSnapshotLock } from \"./locks.js\";\nimport { run } from \"./exec.js\";\nimport { ext4Usage } from \"./ext4.js\";\nimport { captureBox } from \"./snapshots.js\";\nimport { FirecrackerClient } from \"./firecracker.js\";\nimport { attachTap, bridgeExists, closeLink, closeProxy, createTap, deleteTap, ensureHostNetwork, listeningPorts, macFor, nextFreeIp, openLink, openProxy, pickSshPort, pinTap, tapName, type Link, type Proxy } from \"./network.js\";\nimport {\n boxListChanged,\n listMachineRefs,\n newBoxId,\n currentBootId,\n hostBootTime,\n pidAlive,\n readMachineMeta,\n readSnapshotMeta,\n vmAlive,\n writeMachineMeta,\n type MachineMeta,\n type SnapshotMeta,\n} from \"./state.js\";\nimport { log } from \"./log.js\";\n\n/** Box names double as guest hostnames; short and plain on purpose. */\nconst NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;\nconst AUTO_PREFIX = \"box\";\n/** Every box's vsock address. Firecracker's vsock is per process, so the number need not be unique on the host. */\nconst GUEST_CID = 3;\n/** The overlay drive's path as Firecracker sees it: relative to the box dir, see spawnFirecracker. */\nconst OVERLAY_REL = \"overlay.ext4\";\n\n/** Every id in use on the host, so a new draw can avoid them. */\nconst idsInUse = (metas: MachineMeta[]) => new Set(metas.map((m) => m.id));\n/** Every public port a box on the host holds, running or not (its SSH port and the ones it published): a port stays the box's for its life. */\nconst publicPortsInUse = (metas: MachineMeta[]) => metas.flatMap((m) => [...(m.sshPort === undefined ? [] : [m.sshPort]), ...(m.ports ?? []).map((f) => f.hostPort)]);\n\n/**\n * A box made through a control plane (its owner is `user@realm`) is reached from the internet:\n * it gets the control plane's authorized_keys lines and a public SSH port on the host (#49).\n * A box the host owner makes over the socket keeps the host key only and no public port.\n */\nconst isCloudBox = (owner: string) => realmOf(owner) !== null;\n\ntype Forwarded = Pick<MachineMeta, \"id\" | \"ip\" | \"sshPort\" | \"ports\" | \"links\">;\n\n/** Every forward the box has on the host: its public SSH port (#49) and the ports it published (#30). */\nfunction boxProxies(meta: Forwarded): Proxy[] {\n const ssh: Proxy[] = meta.sshPort === undefined ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];\n // a closed port (#173) keeps its host port and has no rule\n return [...ssh, ...(meta.ports ?? []).filter((f) => !f.closed).map((f) => ({ box: meta.id, boxIp: meta.ip, hostPort: f.hostPort, guestPort: f.guestPort, proto: f.proto }))];\n}\n\n/** The links into the box (#98) as host rules, with its current IP. */\nfunction boxLinks(meta: Forwarded): Link[] {\n return (meta.links ?? []).map((l) => ({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }));\n}\n\n/**\n * The links into the box that may open now. A linked box's IP goes to the next box when it is removed:\n * a link opens only while that box still has it.\n */\nexport async function standingLinks(meta: Forwarded, p: Paths): Promise<Link[]> {\n const links = boxLinks(meta);\n const stands = await Promise.all(\n (meta.links ?? []).map(async (l) => !l.stale && (await readMachineMeta({ owner: l.owner, name: l.name }, p).catch(() => null))?.ip === l.ip),\n );\n return links.filter((_, i) => stands[i]);\n}\n\n/**\n * Open the box's public ports and the links into it (after Firecracker is up), always with its current\n * IP; nothing to do for a box without any.\n */\nasync function openPorts(meta: Forwarded, cfg: Config, p: Paths): Promise<void> {\n for (const proxy of boxProxies(meta)) await openProxy(proxy, cfg);\n for (const link of await standingLinks(meta, p)) {\n // a link that cannot open (a host network from before #98) costs that link, never the box's boot\n await openLink(link, cfg).catch((err: Error) => log.warn(`could not open the link from ${link.fromIp}: ${err.message}`));\n }\n}\n\n/** Close them (the box is going down); a failure here is logged, the box's own state change goes on. */\nasync function closePorts(meta: Forwarded, cfg: Config): Promise<void> {\n for (const proxy of boxProxies(meta)) {\n await closeProxy(proxy, cfg).catch((err: Error) => log.warn(`could not close port ${proxy.hostPort}: ${err.message}`));\n }\n for (const link of boxLinks(meta)) {\n await closeLink(link, cfg).catch((err: Error) => log.warn(`could not close the link from ${link.fromIp}: ${err.message}`));\n }\n}\n\n/** Public ports drawn but not in any meta.json yet: the next draw must see them too. */\nconst reservedPorts = new Set<number>();\n\n/**\n * `count` fresh public ports: random, never 22, not another box's, not something the host listens\n * on (#49, #30). Drawn under the host's `ports` lock and held in `reservedPorts` until the caller has\n * written them to meta.json and calls `release`, so two boxes drawing at once never get the same one.\n */\nasync function drawPorts(count: number, p: Paths): Promise<{ ports: number[]; release: () => void }> {\n return withHostLock(\"ports\", async () => {\n // Reservations first: one released while the metas are read was written before its release, but\n // that write may be the half-written meta.json the read skipped.\n const reserved = [...reservedPorts];\n const taken = new Set([...reserved, ...publicPortsInUse(await readAllMeta(p)), ...(await listeningPorts())]);\n const ports: number[] = [];\n for (let i = 0; i < count; i++) {\n const port = pickSshPort(taken);\n taken.add(port);\n ports.push(port);\n }\n for (const port of ports) reservedPorts.add(port);\n return { ports, release: () => ports.forEach((port) => reservedPorts.delete(port)) };\n });\n}\n\n/**\n * The disk's size, what the box uses of it and what its sparse file occupies on the host (#115).\n * The usage is the filesystem's own count, read from the file (core/ext4.ts): what the guest's `df`\n * says, give or take a journal commit. Host allocation is a different number: Firecracker's block\n * device has no discard, so it only grows while the box runs, and `kvbox stop` trims it back\n * (compactDisk). It stands in for the usage only when the file cannot be read as ext4.\n */\nfunction diskStats(disk: string): { diskBytes: number; diskUsedBytes: number; diskHostBytes: number } {\n try {\n const st = statSync(disk);\n const diskHostBytes = st.blocks * 512;\n const fs = ext4Usage(disk);\n return { diskBytes: st.size, diskUsedBytes: fs ? Math.min(fs.usedBytes, st.size) : diskHostBytes, diskHostBytes };\n } catch {\n return { diskBytes: 0, diskUsedBytes: 0, diskHostBytes: 0 };\n }\n}\n\n/**\n * Give the host back what the guest freed. Firecracker's block device has no discard, so a box's\n * sparse disk file only grows while it runs; on the unmounted disk, e2fsck's discard punches a hole\n * for every free block. `-f`: without it a clean filesystem is skipped, discard included. `-p`: only\n * the fixes that need nobody's say, a journal replay after a power cut among them (what the guest\n * kernel would do at its next mount). Exit 1 and 2 are \"fixed\"; anything else throws.\n */\nexport async function compactDisk(file: string): Promise<void> {\n await run([\"e2fsck\", \"-f\", \"-p\", \"-E\", \"discard\", file], { okExitCodes: [1, 2], timeoutMs: 10 * 60_000 });\n}\n\n/** Whole GiB of the box's overlay (its size as the guest sees it, not what it occupies). */\nfunction diskGibOf(meta: MachineMeta, p: Paths): number {\n try {\n return Math.round(statSync(p.machine(meta.owner, meta.name).overlay).size / 1024 ** 3);\n } catch {\n return 0;\n }\n}\n\n/**\n * Append the box's state change to the usage ledger (core/db.ts). Bookkeeping never fails the\n * operation it records: a ledger problem is logged and the box carries on.\n */\nexport function recordState(meta: MachineMeta, state: UsageState, by: string, p: Paths, at = new Date().toISOString()): void {\n try {\n insertUsageEvent({ boxId: meta.id, owner: meta.owner, name: meta.name, at, state, by, vcpu: meta.vcpu, memMib: meta.memMib, diskGib: diskGibOf(meta, p) }, p);\n } catch (err) {\n log.warn(`usage ledger: ${(err as Error).message}`);\n }\n}\n\n/** No process, but a memory dump in the box dir: `kvbox hibernate` left it, `wake` continues from it. */\nfunction isHibernated(meta: MachineMeta, p: Paths): boolean {\n return !vmAlive(meta) && existsSync(p.machine(meta.owner, meta.name).hibernateVmstate);\n}\n\nexport function statusOf(meta: MachineMeta, p: Paths = paths()): BoxStatus {\n if (vmAlive(meta)) return meta.paused ? \"standby\" : \"running\";\n return isHibernated(meta, p) ? \"hibernated\" : \"stopped\";\n}\n\n/** \"box lab1 is stopped\" / \"is in standby\" / \"is hibernated\", for refusals. */\nexport function stateMessage(ref: BoxRef, status: BoxStatus): string {\n return `box ${shown(ref)} is ${status === \"standby\" ? \"in standby\" : status}`;\n}\n\nfunction toMachine(meta: MachineMeta, p: Paths = paths()): Machine {\n const alive = vmAlive(meta);\n // A pid the server set that is no longer alive: Firecracker died on its own (crash, host reboot,\n // kill). The ledger's open run is closed now, by `server`: the box's stop time is estimated, and\n // `usage` says so. Nothing is written to meta.json here (listing stays read-only on the state dir).\n if (!alive && meta.pid !== null) {\n try {\n closeOpenRun(meta.id, new Date().toISOString(), p);\n } catch (err) {\n log.warn(`usage ledger: ${(err as Error).message}`);\n }\n }\n return {\n id: meta.id,\n name: meta.name,\n owner: meta.owner,\n ip: meta.ip,\n mac: meta.mac,\n pid: alive ? meta.pid : null,\n vcpu: meta.vcpu,\n memMib: meta.memMib,\n ...diskStats(p.machine(meta.owner, meta.name).overlay),\n base: meta.base,\n ...(meta.image !== undefined ? { image: meta.image } : {}),\n ...(meta.url !== undefined ? { url: urlFor(meta.url, meta.name) } : {}),\n createdAt: meta.createdAt,\n source: meta.source,\n status: statusOf(meta, p),\n ...(meta.sshPort === undefined ? {} : { sshPort: meta.sshPort }),\n ...(meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {}),\n ...(meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {}),\n ...(meta.idleCheck !== undefined ? { idleCheck: meta.idleCheck } : {}),\n ...(meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {}),\n ...(meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}),\n };\n}\n\n/** A linked box as its target's owner names it: `api`, or `<slug>/api` for another slug's (#98). */\nconst linkFrom = (l: { owner: string; name: string }, owner: string) => (l.owner === owner ? l.name : `${l.owner.split(\"@\")[0]}/${l.name}`);\n\n/**\n * The idle timeout a new box gets (#47): the request's, else the host's default; 0 is stored as absent.\n * An image whose manifest says `autoHibernate: false` (#87) skips the host's default: nothing wakes it;\n * one that gives a duration (`\"10m\"`, #102) has it instead of the host's default.\n */\nfunction autoHibernateFor(req: CreateMachineRequest, cfg: Config, manifest: ImageManifest = {}): number | undefined {\n if (req.autoHibernateSec !== undefined) return req.autoHibernateSec || undefined;\n if (manifest.autoHibernate === false) return undefined;\n if (typeof manifest.autoHibernate === \"string\") return parseDuration(manifest.autoHibernate) || undefined;\n return cfg.autoHibernateSec || undefined;\n}\n\nasync function readAllMeta(p: Paths): Promise<MachineMeta[]> {\n const metas: MachineMeta[] = [];\n for (const ref of await listMachineRefs(p)) {\n try {\n metas.push(await readMachineMeta(ref, p));\n } catch (err) {\n log.warn(`skipping machines/${refKey(ref)}: ${(err as Error).message}`);\n }\n }\n return metas;\n}\n\n/** The boxes of one owner, or every box on the host when `owner` is null (the host operator's view). */\nexport async function listMachines(scope: ListScope, p: Paths = paths()): Promise<Machine[]> {\n return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));\n}\n\nexport async function getMachine(ref: BoxRef, p: Paths = paths()): Promise<Machine> {\n return toMachine(await readMeta(ref, p), p);\n}\n\nfunction pickName(requested: string | undefined, taken: Set<string>): string {\n if (requested !== undefined) {\n if (!NAME_RE.test(requested)) {\n throw new KvboxError(`invalid box name \"${requested}\": 1-12 chars, lowercase letters, digits and '-', starting with a letter or digit`);\n }\n if (taken.has(requested)) throw new KvboxError(`box ${requested} already exists`);\n return requested;\n }\n for (let i = 1; ; i++) {\n const candidate = `${AUTO_PREFIX}${i}`;\n if (!taken.has(candidate)) return candidate;\n }\n}\n\n/** Lines a box's authorized_keys may hold: the host's key plus what the control plane sends. */\nexport const MAX_SSH_KEY_LINES = 8;\n/** The kernel command line is 2 KB on x86; the rest of ours is ~200 bytes, so the key blob gets this much. */\nconst MAX_SSH_KEYS_B64 = 1500;\n\n/** The authorized_keys lines a box holds: the host's own key first, then what the control plane gave it. Checked, never written unchecked. */\nexport function authorizedKeysLines(hostKey: string, extra: readonly string[]): string[] {\n const lines = [hostKey.trim(), ...extra.map((l) => l.trim())];\n if (lines.some((l) => l === \"\" || /[\\r\\n]/.test(l))) throw new KvboxError(\"sshKeys: every entry must be one non-empty authorized_keys line\");\n if (lines.length > MAX_SSH_KEY_LINES) {\n throw new KvboxError(`a box takes at most ${MAX_SSH_KEY_LINES - 1} SSH keys on top of the host's own; ${extra.length} were given`);\n }\n return lines;\n}\n\n/**\n * The `kvbox.sshkey=` value: the host's own public key and every extra authorized_keys line, as\n * base64 of the whole file (one line each, trailing newline). kvbox-init in the image decodes it\n * verbatim into the kvbox user's authorized_keys at every boot, so `cert-authority …` lines work\n * without an image change. Checked before Firecracker starts.\n */\nexport function authorizedKeysB64(hostKey: string, extra: readonly string[]): string {\n const lines = authorizedKeysLines(hostKey, extra);\n const b64 = Buffer.from(lines.join(\"\\n\") + \"\\n\").toString(\"base64\");\n if (b64.length > MAX_SSH_KEYS_B64) {\n throw new KvboxError(`the SSH keys for this box do not fit the kernel command line (${b64.length} bytes encoded, ${MAX_SSH_KEYS_B64} at most); use fewer or shorter keys`);\n }\n return b64;\n}\n\nexport function bootArgs(name: string, ip: string, cfg: Config, pubkeyB64: string): string {\n // Firecracker appends `pci=off root=/dev/vda ro` itself. ip= is read by the guest kernel,\n // kvbox.name= / kvbox.sshkey= by kvbox-init on first boot (the kvbox-images contract).\n // /sbin/overlay-init in the image stacks the box's disk (/dev/vdb) on the read-only base before\n // systemd starts.\n const args = `console=ttyS0 reboot=k panic=1 init=/sbin/overlay-init kvbox.overlay=/dev/vdb ip=${ip}::${cfg.gateway}:255.255.255.0:${name}:eth0:off kvbox.name=${name} kvbox.sshkey=${pubkeyB64}`;\n return process.arch === \"arm64\" ? `keep_bootcon ${args}` : args;\n}\n\nexport { baseVersionOf };\n\n/** The box's writable disk: a sparse ext4 of `gib` GiB, ready in milliseconds and occupying a few MB until written to. */\nexport async function createOverlay(file: string, gib: number): Promise<void> {\n await writeFile(file, \"\", { mode: 0o600 });\n await truncate(file, gib * 1024 ** 3);\n // -F: it is a file, not a block device. -m 0: no blocks held back for root, the whole disk is the box's.\n // Lazy init: the inode tables are zeroed by the guest kernel as it goes, so mkfs writes almost nothing.\n await run([\"mkfs.ext4\", \"-q\", \"-F\", \"-m\", \"0\", \"-L\", \"kvbox-box\", \"-E\", \"lazy_itable_init=1,lazy_journal_init=1\", file]);\n}\n\nasync function waitFor(pred: () => boolean, timeoutMs: number, stepMs = 50): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (pred()) return true;\n await sleep(stepMs);\n }\n return pred();\n}\n\nasync function tailOf(file: string, lines = 5): Promise<string> {\n try {\n return (await readFile(file, \"utf8\")).trim().split(\"\\n\").slice(-lines).join(\"\\n\");\n } catch {\n return \"\";\n }\n}\n\ninterface LaunchSpec {\n id: string;\n name: string;\n owner: string;\n ip: string;\n mac: string;\n vcpu: number;\n memMib: number;\n base: string;\n /** The image when not the base one (#87); `base` is its version. */\n image?: string | undefined;\n /** See MachineMetaSchema (#49). */\n sshKeys?: string[] | undefined;\n sshPort?: number | undefined;\n /** Attached volumes, in drive order (#52); a cold boot gives Firecracker one drive each. */\n volumes?: string[] | undefined;\n}\n\n/**\n * Spawn Firecracker detached for box `name` and wait for its API socket. Returns the pid; the\n * caller kills it on any later failure. Its working directory is the box dir and the overlay drive\n * is given as a relative path (OVERLAY_REL): a snapshot's vmstate stores drive paths verbatim, so a\n * relative one resolves to whichever box dir the snapshot is restored into.\n */\nasync function spawnFirecracker(ref: BoxRef, cfg: Config, p: Paths): Promise<number> {\n const m = p.machine(ref.owner, ref.name);\n await rm(m.sock, { force: true });\n await rm(m.vsock, { force: true });\n const logFd = openSync(m.log, \"a\");\n let child;\n try {\n child = spawn(cfg.firecracker, [\"--api-sock\", m.sock, \"--id\", ref.name, \"--level\", \"Error\"], {\n cwd: m.dir,\n detached: true,\n stdio: [\"ignore\", logFd, logFd],\n });\n } finally {\n closeSync(logFd);\n }\n child.unref();\n const pid = child.pid;\n if (pid === undefined) throw new KvboxError(\"could not start firecracker\");\n if (!(await waitFor(() => existsSync(m.sock), 3000))) {\n killQuietly(pid);\n throw new KvboxError(`firecracker did not open its API socket; last log lines:\\n${await tailOf(m.log)}`);\n }\n return pid;\n}\n\nfunction killQuietly(pid: number): void {\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n /* already gone */\n }\n}\n\n/** Spawn Firecracker, configure it over its socket, InstanceStart. Returns the pid. Caller rolls back on throw. */\nasync function launch(spec: LaunchSpec, tap: string, cfg: Config, pubkeyB64: string, p: Paths): Promise<number> {\n const m = p.machine(spec.owner, spec.name);\n const baseFile = imageFileFor(spec, p);\n // Before the process: a volume that is gone is a plain refusal, nothing to clean up.\n const volumes = await placeVolumeDrives(spec, p);\n const pid = await spawnFirecracker(spec, cfg, p);\n try {\n const fc = new FirecrackerClient(m.sock);\n try {\n await fc.bootSource(cfg.kernel, bootArgs(spec.name, spec.ip, cfg, pubkeyB64));\n await fc.rootDrive(baseFile);\n await fc.overlayDrive(OVERLAY_REL);\n // /dev/vdc and up, in attachment order; the image mounts each at /mnt/<name> by its label.\n for (const v of volumes) await fc.volumeDrive(volumeDriveId(v.name), volumeDriveRel(v.name));\n await fc.machineConfig(spec.vcpu, spec.memMib);\n await fc.networkInterface(\"eth0\", tap, spec.mac);\n await fc.vsock(GUEST_CID, m.vsock);\n await fc.start();\n } finally {\n await fc.close();\n }\n return pid;\n } catch (err) {\n killQuietly(pid);\n throw err;\n }\n}\n\n/** A frozen VM on disk: a snapshot's files, or a hibernated box's own dump. `label` names it in errors. */\ninterface MemoryImage {\n vmstate: string;\n mem: string;\n label: string;\n /** Volumes the image was frozen with (#52): placeholders are in place, the guest's mounts of them are dropped after the restore. */\n volumes?: readonly VolumeDrive[] | undefined;\n}\n\n/**\n * Spawn Firecracker and restore the image into it, still paused, with this box's tap and vsock\n * in place of the source box's. Drive paths cannot be overridden at load, and need not be: the\n * vmstate names the overlay relative to the box dir, so it already resolves to this box's copy.\n * Returns the pid; the caller resumes and rolls back on throw.\n */\nasync function loadSnapshot(spec: LaunchSpec, image: MemoryImage, tap: string, cfg: Config, p: Paths): Promise<number> {\n const m = p.machine(spec.owner, spec.name);\n const pid = await spawnFirecracker(spec, cfg, p);\n try {\n const fc = new FirecrackerClient(m.sock);\n try {\n await fc.snapshotLoad({\n snapshotPath: image.vmstate,\n memFilePath: image.mem,\n tap: { ifaceId: \"eth0\", hostDevName: tap },\n vsockPath: m.vsock,\n trackDirtyPages: true,\n resume: false,\n });\n } finally {\n await fc.close();\n }\n return pid;\n } catch (err) {\n killQuietly(pid);\n throw err;\n }\n}\n\n/** The base image version `kvbox new` uses right now (what `assets/rootfs.ext4` points at). */\nexport async function currentBaseVersion(p: Paths = paths()): Promise<string> {\n return (await currentImage(undefined, await loadConfig(p), p)).version;\n}\n\n/** The host's own public key line: every box on the host trusts it (that is how local `connect` works). */\nasync function readHostPubkey(p: Paths): Promise<string> {\n try {\n return (await readFile(`${p.sshKey}.pub`, \"utf8\")).trim();\n } catch {\n throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);\n }\n}\n\nfunction assertAssets(cfg: Config): void {\n for (const [what, file] of [[\"kernel\", cfg.kernel], [\"base image\", cfg.rootfs], [\"firecracker\", cfg.firecracker]] as const) {\n if (!existsSync(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);\n }\n}\n\n/**\n * `owner` is who the box belongs to: the caller, as the route resolved it (the host owner over the\n * local socket). `req.owner` is not read here on purpose: a caller does not get to pick.\n */\nexport async function createMachine(req: CreateMachineRequest, owner: string, p: Paths = paths()): Promise<Machine> {\n const cfg = await loadConfig(p);\n if (req.from !== undefined) return restoreMachine(req.from, owner, req, cfg, p);\n const sizeName = req.size ?? cfg.defaultSize;\n if (!isSizeName(sizeName)) throw new KvboxError(`unknown size \"${sizeName}\"; use one of ${Object.keys(SIZES).join(\", \")}`);\n const size = SIZES[sizeName];\n assertAssets(cfg);\n await assertRoomFor(size.vcpu, size.memMib, req.force ?? false, { owner }, \"new\", p);\n const sshKeys = isCloudBox(owner) && req.sshKeys !== undefined && req.sshKeys.length > 0 ? req.sshKeys : undefined;\n authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []); // refuse bad lines before anything exists\n\n const existing = await readAllMeta(p);\n // names are per owner; IPs, taps and public ports are per host\n const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));\n const id = newBoxId(idsInUse(existing));\n const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);\n\n const image = imageKey(req.image);\n const base = await currentImage(image, cfg, p);\n await assertOverlayCapable(base.file, image, base.version);\n // The image's manifest (#87): its variables' defaults and generated secrets join the caller's -e ones.\n const manifest = await imageManifest(base.file);\n // A name the owner's list already has stays the owner's (it would lose to the box's own at boot).\n const env = imageEnv(manifest, name, req.env ?? [], (await readOwnerEnv(owner, p).catch(() => null))?.vars ?? []);\n const now = new Date().toISOString();\n const autoHibernateSec = autoHibernateFor(req, cfg, manifest);\n const vars = env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now }));\n const machine = await bootInto(\n { id, name, owner, ip, mac: macFor(ip), vcpu: size.vcpu, memMib: size.memMib, base: base.version, image, sshKeys },\n // The image is shared read-only by every box; only the box's own writes land in its overlay.\n async (m) => {\n await createOverlay(m.overlay, size.diskGib);\n // A secret the host made up (or a default made from one) is kept as one: `connect` hands it over this once.\n if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);\n },\n { source: \"base\", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },\n cfg,\n p,\n );\n return env.connect === undefined ? machine : { ...machine, connect: env.connect };\n}\n\n/** A box about to exist: everything but the public SSH port, which is drawn when its dir is made. */\ntype NewBox = Omit<LaunchSpec, \"sshPort\">;\ntype BoxDir = ReturnType<Paths[\"machine\"]>;\n/** What a new box's meta.json says about where it came from. */\ntype Origin = Pick<MachineMeta, \"source\" | \"autoHibernateSec\" | \"idleCheck\" | \"url\">;\n\n/**\n * Boot `box` fresh (`new`, a cold fork): `prepare` puts its overlay in its new dir. On any failure\n * nothing of it is left: no process, tap, forwards or dir.\n */\nasync function bootInto(box: NewBox, prepare: (m: BoxDir) => Promise<void>, origin: Origin, cfg: Config, p: Paths): Promise<Machine> {\n const { id, ip, owner, name } = box;\n const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);\n const m = p.machine(owner, name);\n await ensureHostNetwork(cfg);\n await mkdir(m.dir, { recursive: true, mode: 0o700 });\n let tapCreated = false;\n let pid: number | undefined;\n let sshPort: number | undefined;\n let drawn: Awaited<ReturnType<typeof drawPorts>> | undefined;\n try {\n drawn = isCloudBox(owner) ? await drawPorts(1, p) : undefined;\n sshPort = drawn?.ports[0];\n await prepare(m);\n const tap = await createTap(box, cfg);\n tapCreated = true;\n const spec: LaunchSpec = { ...box, sshPort };\n pid = await launch(spec, tap, cfg, keysB64, p);\n await openPorts(spec, cfg, p);\n void pushEnvAfterBoot(spec, pid, m.vsock, p);\n const meta: MachineMeta = { ...spec, pid, bootId: currentBootId(), createdAt: new Date().toISOString(), ...origin };\n await writeMachineMeta(meta, p);\n recordState(meta, \"running\", \"new\", p, meta.createdAt);\n return toMachine(meta, p);\n } catch (err) {\n // leave nothing half-made behind\n if (pid !== undefined) killQuietly(pid);\n await closePorts({ id, ip, sshPort }, cfg);\n if (tapCreated) await deleteTap(id, cfg).catch(() => undefined);\n await rm(m.dir, { recursive: true, force: true });\n boxListChanged();\n throw err;\n } finally {\n drawn?.release();\n }\n}\n\nasync function readSnap(ref: BoxRef, p: Paths): Promise<SnapshotMeta> {\n // A dot dir is a replace's work in progress (#83), never a snapshot.\n if (ref.name.startsWith(\".\")) throw new NotFoundError(`snapshot ${shown(ref)}`);\n try {\n return await readSnapshotMeta(ref, p);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") throw new NotFoundError(`snapshot ${shown(ref)}`);\n throw err;\n }\n}\n\n/** a.b.c.d/len -> len */\nfunction prefixLenOf(subnet: string): number {\n return Number(subnet.split(\"/\")[1]);\n}\n\n/**\n * `kvbox new --from <snapshot>`: a warm box. The snapshot's memory and overlay come back exactly as\n * frozen, processes included, under a new name, IP and MAC. The guest itself still remembers the\n * source box's identity, so its tap stays off the bridge until kvbox-agent (reached over vsock, not\n * the network) has applied the new one and set the clock. Sub-second: the memory file is mapped,\n * not read, and the overlay copy is sparse.\n */\nasync function restoreMachine(fromText: string, owner: string, req: CreateMachineRequest, cfg: Config, p: Paths): Promise<Machine> {\n const from = parseRef(fromText, owner);\n // A `snapshots new --replace` of this snapshot waits until its files are copied and loaded (#83).\n return withSnapshotLock(from, () => restoreFrom(from, owner, req, cfg, p));\n}\n\nasync function restoreFrom(from: BoxRef, owner: string, req: CreateMachineRequest, cfg: Config, p: Paths): Promise<Machine> {\n const snap = await readSnap(from, p);\n if (req.size !== undefined) {\n throw new KvboxError(`--size cannot be combined with --from: a restored box has the snapshot's size (${shown(from)}: ${snap.vcpu} vCPU, ${snap.memMib} MiB)`);\n }\n assertAssets(cfg);\n if (!existsSync(imageFile(snap.image, snap.base, p))) {\n throw new KvboxError(`snapshot ${shown(from)} stacks on ${imageLabel(snap.image)} ${snap.base}, which is gone from ${p.assets}`);\n }\n // A restored database box stays awake like a new one of its image.\n const manifest = await imageManifest(imageFile(snap.image, snap.base, p));\n if (req.image !== undefined && imageKey(req.image) !== snap.image) {\n throw new KvboxError(`--base cannot be combined with --from: a restored box has the snapshot's image (${shown(from)}: ${imageLabel(snap.image)})`);\n }\n await assertRoomFor(snap.vcpu, snap.memMib, req.force ?? false, { owner }, \"new\", p);\n // The lines are kept so a later cold boot (`stop`, `start`) writes them like a fresh box; the\n // restored guest gets them through kvbox-agent (#63).\n const sshKeys = isCloudBox(owner) && req.sshKeys !== undefined && req.sshKeys.length > 0 ? req.sshKeys : undefined;\n authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);\n\n const existing = await readAllMeta(p);\n const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));\n // A restored box is a new box: its own id, never the source box's (a snapshot carries none).\n const id = newBoxId(idsInUse(existing));\n const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);\n const s = p.snapshot(from.owner, from.name);\n // The variables the box will have: the snapshot's, `-e` ones over them (as `mergeBoxEnv` writes them).\n const given = new Set((req.env ?? []).map((v) => v.name));\n const vars = [...(await readBoxEnvFile(s.env)).filter((v) => !given.has(v.name)), ...(req.env ?? []).map((v) => ({ ...v, secret: false }))];\n return restoreInto(\n { id, name, owner, ip, mac: macFor(ip), vcpu: snap.vcpu, memMib: snap.memMib, base: snap.base, image: snap.image, sshKeys },\n async (m) => {\n await run([\"cp\", \"--sparse=always\", \"--reflink=auto\", s.overlay, m.overlay]);\n // The snapshot's own variables (#87), with `-e` ones over them.\n await copyBoxEnv(s.env, m.env);\n if (req.env?.length) await mergeBoxEnv({ owner, name }, req.env, p);\n // The box's memory lineage starts at the snapshot's image: its first snapshot is a diff merged onto it.\n await link(s.mem, m.memBase);\n // The vmstate names the source's volume drives; a new box never comes with a volume (decision\n // \"A snapshot captures the box, never its volume\"), so each gets an empty file of the same size.\n await placeholderDrives(m.dir, snap.volumes ?? []);\n return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };\n },\n { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },\n cfg,\n p,\n );\n}\n\n/**\n * Bring `box` up from a frozen image under its own identity (`new --from`, a warm fork). `prepare`\n * fills its new dir (overlay and `mem.base`) and names the image to load. On any failure nothing of\n * it is left: no process, tap, forwards or dir. With `keysOrFail`, a guest that keeps the authorized_keys\n * it was frozen with is such a failure, and the string leads its message.\n */\nasync function restoreInto(box: NewBox, prepare: (m: BoxDir) => Promise<MemoryImage>, origin: Origin, cfg: Config, p: Paths, keysOrFail?: string): Promise<Machine> {\n const { id, ip, owner, name } = box;\n const m = p.machine(owner, name);\n await ensureHostNetwork(cfg);\n await mkdir(m.dir, { recursive: true, mode: 0o700 });\n let tapCreated = false;\n let pid: number | undefined;\n let sshPort: number | undefined;\n let drawn: Awaited<ReturnType<typeof drawPorts>> | undefined;\n try {\n drawn = isCloudBox(owner) ? await drawPorts(1, p) : undefined;\n sshPort = drawn?.ports[0];\n const image = await prepare(m);\n const tap = await createTap(box, cfg, { detached: true });\n tapCreated = true;\n const spec: LaunchSpec = { ...box, sshPort };\n pid = await loadSnapshot(spec, image, tap, cfg, p);\n await resumeVm(m.sock);\n await introduce(spec, m.vsock, cfg, {\n silent: `nothing answered on the restored box's control channel for 3 s; the restored box was discarded, try again`,\n noAnswer: \"the restored box was discarded. kvbox-agent inside it took the request but gave no answer; try again, and if it keeps happening look at the box's journal (kvbox exec <box> -- sudo journalctl -u kvbox-agent) on a box started from the same snapshot.\",\n });\n // The guest woke up with the authorized_keys the image froze; give it the current ones (#63).\n const stale = await pushAuthorizedKeys(box, m.vsock, p);\n if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);\n // And with the source's volumes mounted, over placeholders now: drop those mounts (#52).\n if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);\n // And with the variables of the moment it was frozen: give it its owner's list of today (#88).\n await pushEnv(box, m.vsock, p);\n await attachTap(box, cfg);\n await openPorts(spec, cfg, p);\n const meta: MachineMeta = { ...spec, pid, bootId: currentBootId(), createdAt: new Date().toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : undefined };\n await writeMachineMeta(meta, p);\n recordState(meta, \"running\", \"new\", p, meta.createdAt);\n return toMachine(meta, p);\n } catch (err) {\n if (pid !== undefined) killQuietly(pid);\n await closePorts({ id, ip, sshPort }, cfg);\n if (tapCreated) await deleteTap(id, cfg).catch(() => undefined);\n await rm(m.dir, { recursive: true, force: true });\n boxListChanged();\n throw err;\n } finally {\n drawn?.release();\n }\n}\n\n/**\n * `kvbox vm fork <box> [name]` (#79): a new box, `owner`'s, from `ref` as it is right now, on this\n * host, and no snapshot left behind. A running or paused source is copied warm, straight into the new\n * box's dir: the copy carries on from the same instant, processes included, under its own name, IP\n * and MAC like `new --from`, and the source is frozen only as long as a snapshot freezes it. A stopped\n * source is copied cold: its overlay, then a fresh boot. A hibernated one is refused (decision\n * c6d662d8). Under the source's lock, so it cannot change state halfway.\n */\nexport const forkMachine = locked(async function forkMachine(ref: BoxRef, owner: string, req: ForkMachineRequest, p: Paths = paths()): Promise<Machine> {\n const src = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const status = statusOf(src, p);\n if (status === \"hibernated\") throw new KvboxError(`${stateMessage(ref, status)}; a fork copies a running or a stopped box (kvbox wake ${shown(ref)} first)`);\n const warm = status !== \"stopped\";\n const srcDisk = p.machine(src.owner, src.name).overlay;\n let shape = { vcpu: src.vcpu, memMib: src.memMib };\n let growTo: number | undefined;\n if (req.size !== undefined) {\n if (warm) {\n throw new KvboxError(`--size cannot be combined with forking a running box: the copy keeps its memory, so its size (${shown(ref)}: ${src.vcpu} vCPU, ${src.memMib} MiB); kvbox vm rescale the copy afterwards`);\n }\n if (!isSizeName(req.size)) throw new KvboxError(`unknown size \"${req.size}\"; use one of ${Object.keys(SIZES).join(\", \")}`);\n const preset = SIZES[req.size];\n const diskGib = Math.round(statSync(srcDisk).size / 1024 ** 3);\n if (preset.diskGib < diskGib) throw new KvboxError(`box ${shown(ref)} has a ${diskGib} GB disk and a disk cannot shrink; size ${req.size} has ${preset.diskGib} GB`);\n shape = { vcpu: preset.vcpu, memMib: preset.memMib };\n growTo = preset.diskGib > diskGib ? preset.diskGib : undefined;\n }\n assertAssets(cfg);\n imageFileFor(src, p);\n await assertRoomFor(shape.vcpu, shape.memMib, req.force ?? false, { owner }, \"new\", p);\n const sshKeys = isCloudBox(owner) && req.sshKeys !== undefined && req.sshKeys.length > 0 ? req.sshKeys : undefined;\n authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);\n\n const existing = await readAllMeta(p);\n const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));\n const id = newBoxId(idsInUse(existing));\n const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);\n const box: NewBox = { id, name, owner, ip, mac: macFor(ip), ...shape, base: src.base, image: src.image, sshKeys };\n const srcEnv = p.machine(src.owner, src.name).env;\n // Ports and subdomains are not copied: each is one box's alone.\n const origin: Origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || undefined, idleCheck: src.idleCheck, url: src.url };\n\n if (!warm) {\n return bootInto(\n box,\n async (m) => {\n await run([\"cp\", \"--sparse=always\", \"--reflink=auto\", srcDisk, m.overlay]);\n if (growTo !== undefined) await growDisk(m.overlay, growTo);\n await copyBoxEnv(srcEnv, m.env);\n },\n origin,\n cfg,\n p,\n );\n }\n // The capture lands in the new box's dir: its memory image is the new box's mem.base (and, hard-linked,\n // the source's), so a fork costs what a snapshot costs and leaves nothing to clean up but the VM state.\n const srcVolumes = await captureDrivesOf(src, p);\n const machine = await restoreInto(\n box,\n async (m) => {\n await captureBox(src, { vmstate: m.forkVmstate, mem: m.memBase, overlay: m.overlay }, cfg, p);\n await copyBoxEnv(srcEnv, m.env);\n // The source's volume drives are in the captured state; the copy gets placeholders, not the data (#52).\n await placeholderDrives(m.dir, srcVolumes);\n return { vmstate: m.forkVmstate, mem: m.memBase, label: `box ${shown(ref)}`, volumes: srcVolumes };\n },\n origin,\n cfg,\n p,\n // The copy froze the source slug's CA line; left in place, that slug's members could open a box of\n // another slug. Such a fork is discarded rather than kept stale; a cold fork boots with the new line.\n owner === src.owner ? undefined : `box ${shown(ref)} was not forked into ${owner}: the copy would still let ${src.owner} in (stop the box and fork it cold, which boots with ${owner}'s keys)`,\n );\n await rm(p.machine(owner, name).forkVmstate, { force: true });\n return machine;\n});\n\n/**\n * Hand the restored guest its identity through kvbox-agent. The agent is already running (it was\n * in memory at the snapshot), but the vsock path to it comes up with the VM, so refused connections\n * are retried for a moment. Once it has accepted, it gets a generous wait: the guest's memory is\n * paged in from the snapshot file on first touch, which on a cold, busy disk can take seconds\n * (seen on the dev host right after install-server.sh had written a new base image).\n */\nconst AGENT_REPLY_MS = 20_000;\n\nasync function introduce(spec: LaunchSpec, vsock: string, cfg: Config, failure: { silent: string; noAnswer: string }): Promise<void> {\n const id = { name: spec.name, ip: spec.ip, prefixLen: prefixLenOf(cfg.subnet), gateway: cfg.gateway, mac: spec.mac, time: Math.floor(Date.now() / 1000) };\n const deadline = Date.now() + 3000;\n for (;;) {\n try {\n await setIdentity(vsock, id, AGENT_REPLY_MS);\n return;\n } catch (err) {\n const msg = (err as Error).message;\n const transient = /unreachable|refused|before the guest accepted/.test(msg);\n if (transient && Date.now() < deadline) {\n await sleep(100);\n continue;\n }\n if (transient) throw new KvboxError(`${msg}\\n ${failure.silent}`);\n throw new KvboxError(`${msg}\\n ${failure.noAnswer}`);\n }\n }\n}\n\n/**\n * Hand a live guest its current authorized_keys through kvbox-agent (base v0.6.0 and later): a\n * restored or woken box has the file it was frozen with, which may predate a CA change (#63, #55).\n * Never fails the caller. The reason is returned (and logged) when the guest keeps its old file: an\n * image whose agent does not know the request, or one that did not answer; a boot fixes both.\n */\nexport async function pushAuthorizedKeys(box: Pick<MachineMeta, \"owner\" | \"name\" | \"sshKeys\">, vsock: string, p: Paths): Promise<string | undefined> {\n try {\n await setAuthorizedKeys(vsock, authorizedKeysLines(await readHostPubkey(p), box.sshKeys ?? []), AGENT_REPLY_MS);\n return undefined;\n } catch (err) {\n const why = isUnknownOp(err)\n ? `its image predates base v0.6.0, whose kvbox-agent can replace authorized_keys (kvbox vm update ${shown(box)} moves it onto the current base)`\n : (err as Error).message;\n log.warn(`box ${shown(box)} keeps the authorized_keys it was frozen with: ${why}`);\n return why;\n }\n}\n\n/**\n * A box restored from an image frozen with volumes attached (#52) still has them mounted, over empty\n * placeholder disks now: ask kvbox-agent (base v0.9.0 and later) to drop those mounts, so a program\n * touching the path gets an error instead of a dead filesystem. Never fails the restore: an older\n * image keeps the dead mounts until the box's next cold boot, and the warning says so.\n */\nasync function dropGuestVolumes(box: Pick<MachineMeta, \"owner\" | \"name\">, vsock: string): Promise<void> {\n try {\n await dropVolumes(vsock, AGENT_REPLY_MS);\n } catch (err) {\n const why = isUnknownOp(err)\n ? `its image predates base v0.9.0, whose kvbox-agent can unmount them (kvbox vm update ${shown(box)} moves it onto the current base)`\n : (err as Error).message;\n log.warn(`box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);\n }\n}\n\n/**\n * Hand a live guest its owner's environment variables (#88, base v0.10.0 and later). Never fails the\n * caller: a local owner has no list and nothing is sent; a cloud owner's box always gets one, empty\n * when the slug never set a variable, so a box forked from another slug's box loses that slug's\n * files. A guest that cannot take it keeps the files it has until its next boot, which the warning says.\n */\nasync function pushEnv(box: Pick<MachineMeta, \"owner\" | \"name\">, vsock: string, p: Paths): Promise<void> {\n const vars = await envForBoot(box, p);\n if (vars === null) return;\n try {\n await setEnv(vsock, vars, AGENT_REPLY_MS);\n } catch (err) {\n warnEnv(box, vars, err);\n }\n}\n\n/** An image older than the request is only worth a warning when there was something to hand over. */\nfunction warnEnv(box: Pick<MachineMeta, \"owner\" | \"name\">, vars: readonly unknown[], err: unknown): void {\n if (isUnknownOp(err)) {\n if (vars.length === 0) return;\n log.warn(`box ${shown(box)} did not get its environment variables: its image predates base v0.10.0, whose kvbox-agent takes them (kvbox vm update ${shown(box)} moves it onto the current base)`);\n return;\n }\n log.warn(`box ${shown(box)} did not get its environment variables: ${(err as Error).message}`);\n}\n\n/** How long a cold boot may take before kvbox-agent listens: the box boots in seconds, a busy host is slower. */\nconst ENV_BOOT_WAIT_MS = 120_000;\n\n/**\n * After a cold boot (`new`, `start`) the guest's kvbox-agent listens a few seconds after the VM starts:\n * wait for it in the background and hand it the owner's list then. `new` and `start` do not wait for\n * it; the app service comes up with last boot's /etc/kvbox/env and the agent restarts it if the list\n * changed (decision \"Env vars belong to a slug…\"). The list is read again at every attempt, so a change\n * made while the guest boots is what it gets; the loop ends when `pid`, the Firecracker process it was\n * started for, is gone: the box was stopped, or restarted and a new loop owns the new boot (the vsock\n * path is the same for every boot of a box, so it tells the two apart no better than the list does).\n * Exported for its test; `timing` is the test's shortcut.\n */\nexport function pushEnvAfterBoot(box: Pick<MachineMeta, \"owner\" | \"name\">, pid: number, vsock: string, p: Paths, timing = { replyMs: AGENT_REPLY_MS, waitMs: ENV_BOOT_WAIT_MS }): Promise<void> {\n return (async () => {\n const deadline = Date.now() + timing.waitMs;\n for (;;) {\n if (!pidAlive(pid)) return;\n const vars = await envForBoot(box, p);\n if (vars === null) return;\n try {\n await setEnv(vsock, vars, timing.replyMs);\n return;\n } catch (err) {\n if (!pidAlive(pid)) return;\n if (isNoAgent(err) && Date.now() < deadline) {\n await sleep(500);\n continue;\n }\n warnEnv(box, vars, err);\n return;\n }\n }\n })();\n}\n\nasync function resumeVm(sock: string): Promise<void> {\n const fc = new FirecrackerClient(sock);\n try {\n await fc.resume();\n } finally {\n await fc.close();\n }\n}\n\n/**\n * Clean guest shutdown (Ctrl+Alt+Del), SIGKILL after `graceMs`; tap removed; disk and meta kept.\n * A box in standby is unfrozen first, so the guest can actually act on the key.\n */\nasync function shutdown(meta: MachineMeta, cfg: Config, p: Paths, graceMs: number): Promise<void> {\n const pid = meta.pid;\n if (vmAlive(meta)) {\n const fc = new FirecrackerClient(p.machine(meta.owner, meta.name).sock);\n try {\n if (meta.paused) await fc.resume();\n await fc.sendCtrlAltDel();\n } catch {\n process.kill(pid!, \"SIGTERM\");\n } finally {\n await fc.close();\n }\n await waitDead(pid!, graceMs);\n }\n await cleanupProcess(meta, cfg, p);\n}\n\n/** Wait `graceMs` for the process to go, then SIGKILL it. */\nasync function waitDead(pid: number, graceMs: number): Promise<void> {\n if (!(await waitFor(() => !pidAlive(pid), graceMs, 100))) {\n killQuietly(pid);\n await waitFor(() => !pidAlive(pid), 1000, 50);\n }\n}\n\n/** After Firecracker is gone: the public port, the tap and the sockets it left behind. */\nasync function cleanupProcess(meta: MachineMeta, cfg: Config, p: Paths): Promise<void> {\n await closePorts(meta, cfg);\n await deleteTap(meta.id, cfg);\n const m = p.machine(meta.owner, meta.name);\n await rm(m.sock, { force: true });\n await rm(m.vsock, { force: true });\n}\n\n/**\n * `kvbox stop`: clean shutdown, disk kept. A hibernated box has no process to shut down; its memory\n * dump is discarded instead, which for the guest is a power cut (files intact, what was in memory gone).\n */\nexport const stopMachine = locked(async function stopMachine(ref: BoxRef, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const m = p.machine(ref.owner, ref.name);\n if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);\n await shutdown(meta, cfg, p, 10_000);\n // Best effort, and only here: the restarts (rescale, update, volume attach) shut down and boot\n // again at once, a stop is when the box has the time. A problem is logged and the stop stands.\n await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${(err as Error).message}`));\n await rm(m.hibernateDir, { recursive: true, force: true });\n // A stopped box boots from scratch next time, so its memory lineage (see state.ts memSnapshots) starts over.\n await rm(m.memBase, { force: true });\n const stopped: MachineMeta = { ...meta, pid: null, memSnapshots: undefined, paused: undefined };\n await writeMachineMeta(stopped, p);\n recordState(stopped, \"stopped\", \"stop\", p);\n return toMachine(stopped, p);\n});\n\n/**\n * `kvbox start`: boot a stopped box. Its size counts against the host like a new box's (#37);\n * `force` skips that, and the restarts that only give a running box back its own room (rescale,\n * update, volume attach, recovery after a host reboot) pass it.\n */\nexport const startMachine = locked(async function startMachine(ref: BoxRef, p: Paths = paths(), force: boolean = false): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n if (vmAlive(meta)) throw new KvboxError(`box ${shown(ref)} is already ${meta.paused ? \"up, in standby (kvbox resume \" + shown(ref) + \")\" : \"running\"}`);\n if (isHibernated(meta, p)) {\n throw new KvboxError(`${stateMessage(ref, \"hibernated\")}: kvbox wake ${shown(ref)} continues where it left off; to boot fresh instead, kvbox stop ${shown(ref)} first (discards its memory)`);\n }\n assertAssets(cfg);\n await assertRoomFor(meta.vcpu, meta.memMib, force, meta, \"start\", p);\n const keysB64 = authorizedKeysB64(await readHostPubkey(p), meta.sshKeys ?? []);\n await ensureHostNetwork(cfg);\n const tap = await createTap(meta, cfg);\n let pid: number | undefined;\n try {\n pid = await launch(meta, tap, cfg, keysB64, p);\n await openPorts(meta, cfg, p);\n void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);\n // kvbox-init writes the file from the command line; a VM just launched is never paused\n const started: MachineMeta = { ...meta, pid, bootId: currentBootId(), sshKeysStale: undefined, paused: undefined };\n await writeMachineMeta(started, p);\n recordState(started, \"running\", \"start\", p);\n return toMachine(started, p);\n } catch (err) {\n if (pid !== undefined) killQuietly(pid);\n await closePorts(meta, cfg);\n await deleteTap(meta.id, cfg).catch(() => undefined);\n throw err;\n }\n});\n\n/**\n * Replace the authorized_keys lines the box gets on top of the host's key (the control plane's\n * `rewrite-boxes`: a new CA line for the box's owner). Checked like at `new`, before anything is\n * written. A running box gets them through kvbox-agent right away; any other state gets them when\n * it next runs (`applied` says when).\n */\nexport const setSshKeys = locked(async function setSshKeys(ref: BoxRef, sshKeys: readonly string[], p: Paths = paths()): Promise<{ machine: Machine; applied: SshKeysApplied }> {\n const meta = await readMeta(ref, p);\n // Like `new`: a local box trusts this host's key and nothing else; only a cloud box carries lines.\n if (!isCloudBox(meta.owner)) throw new KvboxError(`box ${shown(ref)} is local: it trusts this host's key, there are no authorized_keys lines to replace`);\n // A cloud box with the host's key alone would be open to nobody who logs in: one bad call must not do that fleet-wide.\n if (sshKeys.length === 0) throw new KvboxError(\"sshKeys: at least one authorized_keys line (the box would keep only the host's own key)\");\n authorizedKeysB64(await readHostPubkey(p), sshKeys);\n const { meta: updated, applied } = await applySshKeys(meta, sshKeys, p);\n return { machine: toMachine(updated, p), applied };\n});\n\n/**\n * Write new `sshKeys` into meta.json and get them to the guest: through kvbox-agent when the box\n * runs, else at its next start (kvbox-init), wake or resume (the `sshKeysStale` flag makes those\n * push). A running box whose agent could not take them is `later`: its next stop and start.\n */\nasync function applySshKeys(meta: MachineMeta, sshKeys: readonly string[], p: Paths): Promise<{ meta: MachineMeta; applied: SshKeysApplied; why?: string }> {\n const status = statusOf(meta, p);\n let updated: MachineMeta = { ...meta, sshKeys: [...sshKeys], sshKeysStale: status === \"stopped\" ? undefined : true };\n let applied: SshKeysApplied = status === \"stopped\" ? \"start\" : status === \"standby\" ? \"resume\" : status === \"hibernated\" ? \"wake\" : \"later\";\n let why: string | undefined;\n if (status === \"running\") {\n why = await pushAuthorizedKeys(updated, p.machine(meta.owner, meta.name).vsock, p);\n if (why === undefined) {\n updated = { ...updated, sshKeysStale: undefined };\n applied = \"now\";\n }\n }\n await writeMachineMeta(updated, p);\n return why === undefined ? { meta: updated, applied } : { meta: updated, applied, why };\n}\n\n/**\n * `kvbox-server trust-ca` (#55): every cloud box on this host trusts `publicKey` as the CA for its\n * owner, in place of the CA line it had (one CA per box, as at `new`; the old CA is out, which is\n * the point after a leak, and a laptop renews its certificate at the next refused connect). Local\n * boxes are untouched. A box that is not running gets the line when it next runs.\n */\nexport async function trustCa(publicKeyText: string, p: Paths = paths()): Promise<TrustCaReport> {\n const publicKey = parseSshPublicKey(publicKeyText);\n const report: TrustCaReport = { publicKey, fingerprint: sshKeyFingerprint(publicKey), updated: [], pending: [], failed: [], local: 0, skipped: [] };\n const hostKey = await readHostPubkey(p);\n for (const listed of await readAllMeta(p)) {\n if (!isCloudBox(listed.owner)) {\n report.local++;\n continue;\n }\n const box = refKey(listed);\n try {\n await withBoxLock(listed, async () => {\n const meta = await readMeta(listed, p); // again, under the lock: the listing may be stale by now\n // A cloud box made without a CA line (a managed service's, #173) opens to no certificate: it gets none now either.\n if (!(meta.sshKeys ?? []).some(isCaLine)) {\n report.skipped!.push(box);\n return;\n }\n const sshKeys = [...(meta.sshKeys ?? []).filter((l) => !isCaLine(l)), caLineFor(meta.owner, publicKey)];\n authorizedKeysLines(hostKey, sshKeys);\n const { applied, why } = await applySshKeys(meta, sshKeys, p);\n if (applied === \"now\") report.updated.push(box);\n else report.pending.push(why === undefined ? { box, when: applied } : { box, when: applied, why });\n });\n } catch (err) {\n report.failed.push({ box, error: (err as Error).message });\n }\n }\n return report;\n}\n\n/** `kvbox pause`: freeze the VM in place. Memory and processes stay, no CPU is used; `resume` is instant. */\nexport const pauseMachine = locked(async function pauseMachine(ref: BoxRef, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const status = statusOf(meta, p);\n if (status === \"standby\") throw new KvboxError(`${stateMessage(ref, status)} already`);\n if (status === \"hibernated\") throw new KvboxError(`${stateMessage(ref, status)}; kvbox wake ${shown(ref)} brings it back`);\n if (status === \"stopped\") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be paused`);\n const fc = new FirecrackerClient(p.machine(ref.owner, ref.name).sock);\n try {\n await fc.pause();\n } finally {\n await fc.close();\n }\n const paused: MachineMeta = { ...meta, paused: true };\n await writeMachineMeta(paused, p);\n recordState(paused, \"standby\", \"pause\", p);\n return toMachine(paused, p);\n});\n\n/** `kvbox resume`: unfreeze a box in standby. */\nexport const resumeMachine = locked(async function resumeMachine(ref: BoxRef, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const status = statusOf(meta, p);\n if (status === \"running\") throw new KvboxError(`${stateMessage(ref, status)} already`);\n if (status === \"hibernated\") throw new KvboxError(`${stateMessage(ref, status)}, not in standby; kvbox wake ${shown(ref)} brings it back`);\n if (status === \"stopped\") throw new KvboxError(`${stateMessage(ref, status)}, not in standby; kvbox start ${shown(ref)} boots it`);\n const m = p.machine(ref.owner, ref.name);\n await resumeVm(m.sock);\n // Keys changed while it was frozen (#55): the agent can take them now.\n const stale = meta.sshKeysStale ? await pushAuthorizedKeys(meta, m.vsock, p) : undefined;\n const running: MachineMeta = { ...meta, paused: undefined, sshKeysStale: stale ? true : undefined };\n await writeMachineMeta(running, p);\n recordState(running, \"running\", \"resume\", p);\n return toMachine(running, p);\n});\n\n/**\n * `kvbox hibernate`: write the VM's memory and state into the box's own dir, then end the Firecracker\n * process. The host gets the RAM back; `wake` loads the image into a new process and the guest carries\n * on from the same instant. A snapshot that is not named and not copied: the overlay stays where it is.\n * Works from running or standby. The dump is a full one (the box's diff lineage ends here; wake starts\n * a new one from this image), sparse once the untouched pages are punched out.\n * `by` names who asked in the ledger: `hibernate` for a caller, `auto-hibernate` for core/idle.ts.\n */\nexport const hibernateMachine = locked(async function hibernateMachine(ref: BoxRef, p: Paths = paths(), by: string = \"hibernate\"): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const status = statusOf(meta, p);\n if (status === \"hibernated\") throw new KvboxError(`${stateMessage(ref, status)} already`);\n if (status === \"stopped\") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);\n const m = p.machine(ref.owner, ref.name);\n await rm(m.hibernateDir, { recursive: true, force: true });\n await mkdir(m.hibernateDir, { recursive: true, mode: 0o700 });\n const fc = new FirecrackerClient(m.sock);\n try {\n try {\n await fc.pause();\n await fc.snapshotCreate(m.hibernateVmstate, m.hibernateMem, \"Full\");\n } catch (err) {\n // Leave the box as it was: running, or in standby if it already was.\n await rm(m.hibernateDir, { recursive: true, force: true });\n if (!meta.paused) await fc.resume().catch(() => undefined);\n throw err;\n }\n } finally {\n await fc.close();\n }\n killQuietly(meta.pid!);\n await waitFor(() => !pidAlive(meta.pid), 5000, 50);\n await cleanupProcess(meta, cfg, p);\n // Pages the guest never touched are zeros in a full dump: punch them out so the image costs what was used.\n await run([\"fallocate\", \"--dig-holes\", m.hibernateMem]);\n await rm(m.memBase, { force: true });\n const hibernated: MachineMeta = { ...meta, pid: null, memSnapshots: undefined, paused: undefined };\n await writeMachineMeta(hibernated, p);\n recordState(hibernated, \"hibernated\", by, p);\n return toMachine(hibernated, p);\n});\n\n/**\n * `kvbox wake`: a hibernated box runs again from its memory image, same name, IP and MAC, so the guest\n * needs no new identity; kvbox-agent is still told, which is how its clock catches up on the time it\n * slept. The image becomes the box's memory lineage base (its next snapshot is a diff), like a box\n * restored from a snapshot. On failure the image is kept and the box stays hibernated.\n */\nexport const wakeMachine = locked(async function wakeMachine(ref: BoxRef, p: Paths = paths(), force: boolean = false): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const status = statusOf(meta, p);\n if (status === \"running\" || status === \"standby\") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated`);\n if (status === \"stopped\") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated; kvbox start ${shown(ref)} boots it`);\n assertAssets(cfg);\n if (!existsSync(imageFile(meta.image, meta.base, p))) {\n throw new KvboxError(`box ${shown(ref)} stacks on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);\n }\n // Hibernated, it reserved nothing; awake it takes its size again (#37).\n await assertRoomFor(meta.vcpu, meta.memMib, force, meta, \"start\", p);\n const m = p.machine(ref.owner, ref.name);\n await ensureHostNetwork(cfg);\n const tap = await createTap(meta, cfg, { detached: true });\n let pid: number | undefined;\n let stale: string | undefined;\n try {\n const spec: LaunchSpec = { id: meta.id, name: meta.name, owner: meta.owner, ip: meta.ip, mac: meta.mac, vcpu: meta.vcpu, memMib: meta.memMib, base: meta.base };\n pid = await loadSnapshot(spec, { vmstate: m.hibernateVmstate, mem: m.hibernateMem, label: `box ${shown(ref)}'s memory image` }, tap, cfg, p);\n await resumeVm(m.sock);\n await introduce(spec, m.vsock, cfg, {\n silent: `nothing answered on the box's control channel for 3 s; it stays hibernated, try kvbox wake ${shown(ref)} again`,\n noAnswer: `the box stays hibernated. kvbox-agent inside it took the request but gave no answer; try kvbox wake ${shown(ref)} again`,\n });\n // The guest's authorized_keys are the ones it slept with; the CA may have changed meanwhile (#55).\n stale = await pushAuthorizedKeys(meta, m.vsock, p);\n await attachTap(meta, cfg);\n await openPorts(meta, cfg, p);\n } catch (err) {\n if (pid !== undefined) killQuietly(pid);\n await closePorts(meta, cfg);\n await deleteTap(meta.id, cfg).catch(() => undefined);\n throw err;\n }\n // The image is now the lineage base; the hibernate dir goes, the hard link keeps the data.\n await rm(m.memBase, { force: true });\n await link(m.hibernateMem, m.memBase);\n await rm(m.hibernateDir, { recursive: true, force: true });\n const running: MachineMeta = { ...meta, pid, bootId: currentBootId(), memSnapshots: 1, paused: undefined, sshKeysStale: stale ? true : undefined };\n await writeMachineMeta(running, p);\n recordState(running, \"running\", \"wake\", p);\n return toMachine(running, p);\n});\n\n/**\n * Change a box's shape or base. Both only take effect at boot (Firecracker fixes vCPU and memory\n * when the VM starts, the base is stacked by overlay-init), so a running box is shut down and\n * started again; a stopped one just gets its meta updated. `whileStopped` runs in between, for\n * work that needs the disk unmounted. Returns the box, running again if it was.\n */\nasync function applyAtNextBoot(\n meta: MachineMeta,\n changes: Partial<MachineMeta>,\n by: \"rescale\" | \"update\" | \"attach\" | \"detach\" | \"restore\" | \"grow\",\n cfg: Config,\n p: Paths,\n whileStopped?: () => Promise<void>,\n): Promise<Machine> {\n const wasRunning = vmAlive(meta);\n if (wasRunning) {\n await shutdown(meta, cfg, p, 10_000);\n await rm(p.machine(meta.owner, meta.name).memBase, { force: true });\n }\n const updated: MachineMeta = { ...meta, ...changes, pid: null, memSnapshots: undefined, paused: undefined };\n await writeMachineMeta(updated, p);\n if (whileStopped) {\n try {\n await whileStopped();\n } catch (err) {\n // The change did not happen: the box keeps what it had, its ledger says it stopped, and one that\n // was running runs again (a box left down by a failed grow would be billed as running).\n const before: MachineMeta = { ...meta, pid: null, memSnapshots: undefined, paused: undefined };\n await writeMachineMeta(before, p);\n if (wasRunning) {\n recordState(before, \"stopped\", by, p);\n await startMachine(meta, p, true).catch((e: Error) => {\n throw new KvboxError(`${(err as Error).message}; and box ${shown(meta)} could not be started again: ${e.message}`);\n });\n }\n throw err;\n }\n }\n // The new shape is on this row (after the disk grew), so usage rates change from here on.\n recordState(updated, \"stopped\", by, p);\n // The box was running, so its room was its own (a rescale that grows checked the new shape first).\n return wasRunning ? startMachine(meta, p, true) : toMachine(updated, p);\n}\n\n/** A hibernated box's memory image fits its current shape and base; neither can change under it. */\nfunction assertNotHibernated(meta: MachineMeta, p: Paths): void {\n if (isHibernated(meta, p)) {\n throw new KvboxError(`${stateMessage(meta, \"hibernated\")}; its memory image was made with its current shape and base: kvbox wake ${shown(meta)} first`);\n }\n}\n\n/** `kvbox vm update <box>`: move the box onto the current version of its image (the one new boxes of that image get). Its overlay (its own writes) stays. */\nexport const updateMachine = locked(async function updateMachine(ref: BoxRef, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n assertNotHibernated(meta, p);\n assertAssets(cfg);\n // The current version of the box's own image (#87): a postgres box never lands on the base one.\n const base = await currentImage(meta.image, cfg, p);\n if (base.version === meta.base) return toMachine(meta, p);\n await assertOverlayCapable(base.file, meta.image, base.version);\n return applyAtNextBoot(meta, { base: base.version }, \"update\", cfg, p);\n});\n\n/**\n * `kvbox vm rescale <box>`: new vCPU count, memory and/or disk. The disk can only grow: the overlay\n * file is extended and its ext4 resized while the box is down (e2fsck first, resize2fs refuses\n * a filesystem that was mounted since its last check).\n */\nexport const rescaleMachine = locked(async function rescaleMachine(ref: BoxRef, req: RescaleMachineRequest, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n assertNotHibernated(meta, p);\n const disk = p.machine(ref.owner, ref.name).overlay;\n const currentDiskGib = Math.round(statSync(disk).size / 1024 ** 3);\n const preset = req.size !== undefined && isSizeName(req.size) ? SIZES[req.size] : undefined;\n const target = {\n vcpu: req.vcpu ?? preset?.vcpu ?? meta.vcpu,\n memMib: req.memMib ?? preset?.memMib ?? meta.memMib,\n diskGib: req.diskGib ?? preset?.diskGib ?? currentDiskGib,\n };\n if (target.diskGib < currentDiskGib) {\n throw new KvboxError(`box ${shown(ref)} has a ${currentDiskGib} GB disk and a disk cannot shrink; ${target.diskGib} GB is smaller`);\n }\n const changes: Partial<MachineMeta> = {};\n if (target.vcpu !== meta.vcpu) changes.vcpu = target.vcpu;\n if (target.memMib !== meta.memMib) changes.memMib = target.memMib;\n const growTo = target.diskGib > currentDiskGib ? target.diskGib : undefined;\n if (Object.keys(changes).length === 0 && growTo === undefined) return toMachine(meta, p);\n // A running box that grows needs the room now (its own size is given back at the restart); a\n // stopped one is checked when it starts (#37).\n if (vmAlive(meta) && (target.vcpu > meta.vcpu || target.memMib > meta.memMib)) {\n await assertRoomFor(target.vcpu, target.memMib, req.force ?? false, meta, \"rescale\", p);\n }\n return applyAtNextBoot(meta, changes, \"rescale\", cfg, p, growTo === undefined ? undefined : () => growDisk(disk, growTo));\n});\n\n/**\n * A backup's restore (decision \"Backups: encrypted 4 MiB chunks in object storage\"): `file`, a complete\n * disk built beside the box's own, becomes the box's disk, and `vars` its own variables (null: none).\n * The base it stacks on comes with it. Like a rescale: a running box is shut down and started again, a\n * stopped one stays stopped, a hibernated one is refused (its memory belongs to the disk it has). A disk\n * that has grown since the backup keeps its size: the restored filesystem is grown into it.\n */\nexport const replaceDisk = locked(async function replaceDisk(\n ref: BoxRef,\n file: string,\n disk: { base: string; image?: string | undefined; vars: BoxVarList | null },\n p: Paths = paths(),\n): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n assertNotHibernated(meta, p);\n const m = p.machine(ref.owner, ref.name);\n const currentGib = Math.round(statSync(m.overlay).size / 1024 ** 3);\n const restoredGib = Math.round(statSync(file).size / 1024 ** 3);\n return applyAtNextBoot(meta, { base: disk.base, image: disk.image }, \"restore\", cfg, p, async () => {\n if (disk.vars === null) await rm(m.env, { force: true });\n else await writeBoxEnv(ref, disk.vars, p);\n await rename(file, m.overlay);\n if (currentGib > restoredGib) await growDisk(m.overlay, currentGib);\n });\n});\n\ntype BoxVarList = Parameters<typeof writeBoxEnv>[1];\n\n/**\n * `kvbox volume attach <volume> <box>` (#52): the volume becomes one more drive of the box, which the\n * guest mounts at /mnt/<volume> at boot. Firecracker cannot add a drive to a running VM, so a running\n * box is shut down cleanly and started again; a stopped one just gets its meta updated; a hibernated\n * one is refused (its memory image has the drives it was frozen with). The volume must be the box\n * owner's and attached to no other box.\n */\nexport const attachVolume = locked(async function attachVolume(ref: BoxRef, volume: BoxRef, p: Paths = paths()): Promise<Machine> {\n const cfg = await loadConfig(p);\n // The claim first: one box per volume is decided by reading every box's meta.json, so the check and\n // the write that records the volume on this box happen under the host lock, which keeps two attaches\n // (or an attach and a `volume rm`) from both passing the check. The restart that gives the box the\n // drive takes seconds and only this box's lock, so it runs outside; until then the box lists a volume\n // it does not have yet, as a stopped box does.\n const claimed = await withHostLock(\"volumes\", async () => {\n const meta = await readMeta(ref, p);\n if (volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is ${volume.owner}'s; a box only takes its own owner's volumes`);\n await readVolume(volume, p);\n const holder = await attachedBox(volume, p);\n if (holder === meta.name) throw new KvboxError(`volume ${shown(volume)} is already attached to box ${shown(ref)}`);\n if (holder !== null) throw new KvboxError(`volume ${shown(volume)} is attached to box ${holder}; a volume attaches to one box at a time (kvbox volume detach ${shown(volume)} first)`);\n assertNotHibernated(meta, p);\n const updated: MachineMeta = { ...meta, volumes: [...(meta.volumes ?? []), volume.name] };\n await writeMachineMeta(updated, p);\n return updated;\n });\n return applyAtNextBoot(claimed, {}, \"attach\", cfg, p);\n});\n\n/**\n * `kvbox volume detach <volume>` (#52): the drive goes at the box's next boot, which a running box gets\n * now. The data stays on the volume. No host lock: the volume is let go by the meta write, which comes\n * after the running box is down, so an attach elsewhere sees it either held or free of a stopped VM.\n */\nexport const detachVolume = locked(async function detachVolume(ref: BoxRef, volume: BoxRef, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n if (!meta.volumes?.includes(volume.name) || volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is not attached to box ${shown(ref)}`);\n assertNotHibernated(meta, p);\n const kept = meta.volumes.filter((v) => v !== volume.name);\n return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : undefined }, \"detach\", cfg, p, () => rm(p.machine(ref.owner, ref.name).volumeDrive(volume.name), { force: true }));\n});\n\n/**\n * `kvbox volume grow <volume> <GB>` (#147): the volume's file is extended and its ext4 grown into it,\n * which needs it unmounted. A detached volume, or one on a stopped box, just grows; a running box is\n * shut down cleanly and started again, like an attach; a hibernated one is refused. A volume never shrinks.\n */\nexport async function resizeVolume(volume: BoxRef, sizeGib: number, p: Paths = paths()): Promise<Volume> {\n await assertCanGrow(volume, sizeGib, p); // before any box is stopped for it\n const holder = await attachedBox(volume, p);\n if (holder === null) {\n // Detached: the host lock an attach claims under, so no box boots with the disk mid-resize.\n return growVolume(volume, sizeGib, p, async () => {\n const now = await attachedBox(volume, p);\n if (now !== null) throw new KvboxError(`volume ${shown(volume)} was just attached to box ${now}; try again`);\n });\n }\n const box: BoxRef = { owner: volume.owner, name: holder };\n return withBoxLock(box, async () => {\n const meta = await readMeta(box, p);\n if (!meta.volumes?.includes(volume.name)) throw new KvboxError(`volume ${shown(volume)} was just detached from box ${holder}; try again`);\n assertNotHibernated(meta, p);\n const cfg = await loadConfig(p);\n let grown: Volume | undefined;\n await applyAtNextBoot(meta, {}, \"grow\", cfg, p, async () => {\n grown = await growVolume(volume, sizeGib, p);\n });\n return { ...grown!, attachedTo: holder };\n });\n}\n\n/**\n * A volume backup's restore (#168): `file`, a complete disk built beside the volume's own, becomes the\n * volume's disk. Like a grow: a detached volume, or one on a stopped box, is just swapped; a running box\n * that holds it is shut down cleanly and started again; a hibernated one is refused. A volume that has\n * grown since the backup keeps its size: the restored filesystem is grown into it, before the swap, so a\n * grow that fails leaves the volume as it was.\n */\nexport async function replaceVolumeDisk(volume: BoxRef, file: string, p: Paths = paths()): Promise<Volume> {\n const grow = async () => {\n const meta = await readVolume(volume, p);\n if (meta.sizeGib * 1024 ** 3 > statSync(file).size) await growDisk(file, meta.sizeGib);\n };\n // The file is this restore's own: grown (an e2fsck of the whole disk) before any lock is taken or box\n // stopped; under the lock only a `volume grow` that came in between grows it again.\n await grow();\n const swap = async () => {\n await grow();\n await rename(file, p.volume(volume.owner, volume.name).disk);\n };\n const holder = await attachedBox(volume, p);\n if (holder === null) {\n // Detached: the host lock an attach claims under, so no box boots with the disk mid-swap.\n await withHostLock(\"volumes\", async () => {\n const now = await attachedBox(volume, p);\n if (now !== null) throw new KvboxError(`volume ${shown(volume)} was just attached to box ${now}; try again`);\n await swap();\n });\n return getVolume(volume, p);\n }\n const box: BoxRef = { owner: volume.owner, name: holder };\n await withBoxLock(box, async () => {\n const meta = await readMeta(box, p);\n if (!meta.volumes?.includes(volume.name)) throw new KvboxError(`volume ${shown(volume)} was just detached from box ${holder}; try again`);\n assertNotHibernated(meta, p);\n await applyAtNextBoot(meta, {}, \"restore\", await loadConfig(p), p, swap);\n });\n return getVolume(volume, p);\n}\n\n/** `kvbox vm set <box>`: settings the VM itself never sees, so they apply in any state and at once. */\nexport const setMachine = locked(async function setMachine(ref: BoxRef, req: SetMachineRequest, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const next: MachineMeta = { ...meta };\n if (req.autoHibernateSec !== undefined) next.autoHibernateSec = req.autoHibernateSec || undefined;\n if (req.idleCheck !== undefined) next.idleCheck = req.idleCheck || undefined;\n await writeMachineMeta(next, p);\n return toMachine(next, p);\n});\n\ntype PortKey = { guestPort: number; proto: \"tcp\" | \"udp\" };\nconst portKeys = (req: PortsRequest): PortKey[] => {\n const keys = req.ports.map((x) => ({ guestPort: x.guestPort, proto: x.proto ?? \"tcp\" }));\n return keys.filter((k, i) => keys.findIndex((o) => o.guestPort === k.guestPort && o.proto === k.proto) === i);\n};\nconst samePort = (a: PortKey) => (b: PortKey) => a.guestPort === b.guestPort && a.proto === b.proto;\n\n/**\n * `kvbox vm proxy add` (#30): publish box ports on the host's public address, each on a host port\n * drawn at random. All or nothing: if one forward cannot be opened, the ones this call opened are\n * closed and nothing is stored. A box that is not running keeps them in meta.json; they open when\n * it next runs, like its SSH port. A port closed but kept (`rm` with `keep`, #173) opens again on the\n * host port it always had.\n */\nexport const addPorts = locked(async function addPorts(ref: BoxRef, req: PortsRequest, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const current = meta.ports ?? [];\n const wanted = portKeys(req);\n const isClosed = (k: PortKey) => current.some((f) => samePort(k)(f) && f.closed);\n const reopened = wanted.filter(isClosed);\n const fresh = wanted.filter((w) => !current.some(samePort(w)));\n const already = wanted.find((w) => current.some(samePort(w)) && !isClosed(w));\n if (already) throw new KvboxError(`box ${shown(ref)} already publishes port ${already.guestPort} (${already.proto})`);\n // The box's SSH forward already accepts 22/tcp into it; a second forward to 22 would share that\n // FORWARD rule, and closing it would cut the box's SSH.\n if (meta.sshPort !== undefined && wanted.some(samePort({ guestPort: 22, proto: \"tcp\" }))) {\n throw new KvboxError(`box ${shown(ref)} already reaches port 22 from outside on port ${meta.sshPort} (kvbox connect)`);\n }\n if (current.length + fresh.length > MAX_BOX_PORTS) {\n throw new KvboxError(`a box publishes at most ${MAX_BOX_PORTS} ports; box ${shown(ref)} has ${current.length}`);\n }\n const drawn = await drawPorts(fresh.length, p);\n const opened: Proxy[] = [];\n try {\n const added = fresh.map((w, i) => ({ ...w, hostPort: drawn.ports[i]! }));\n const open = ({ closed: _closed, ...f }: NonNullable<MachineMeta[\"ports\"]>[number]) => f;\n const again = current.filter((f) => reopened.some(samePort(f))).map(open);\n if (vmAlive(meta)) {\n for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: [...again, ...added] })) {\n await openProxy(proxy, cfg);\n opened.push(proxy);\n }\n }\n const next: MachineMeta = { ...meta, ports: [...current.map((f) => (reopened.some(samePort(f)) ? open(f) : f)), ...added] };\n await writeMachineMeta(next, p);\n return toMachine(next, p);\n } catch (err) {\n // Nothing stored, so nothing may stay open: a rule meta.json does not name could never be removed.\n for (const proxy of opened) await closeProxy(proxy, cfg).catch(() => undefined);\n throw err;\n } finally {\n drawn.release();\n }\n});\n\n/**\n * `kvbox vm proxy rm` (#30): stop publishing box ports. Their host ports go back to the pool, unless\n * `keep` (#173): then each stays the box's, closed, until it is published again or removed for good.\n */\nexport const removePorts = locked(async function removePorts(ref: BoxRef, req: PortsRequest, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n const current = meta.ports ?? [];\n const gone = portKeys(req);\n const missing = gone.find((g) => !current.some(samePort(g)));\n if (missing) throw new KvboxError(`box ${shown(ref)} does not publish port ${missing.guestPort} (${missing.proto})`);\n const removed = current.filter((f) => gone.some(samePort(f)));\n // Closed first: a rule that would not go keeps the port in meta.json, so trying again finds it.\n // Closed whether or not the box runs: one whose Firecracker died never ran cleanupProcess, and its\n // rules would outlive the port's return to the pool. Closing what is not there is fine.\n for (const proxy of boxProxies({ id: meta.id, ip: meta.ip, ports: removed })) await closeProxy(proxy, cfg);\n const kept = req.keep\n ? current.map((f) => (gone.some(samePort(f)) ? { ...f, closed: true as const } : f))\n : current.filter((f) => !gone.some(samePort(f)));\n const next: MachineMeta = { ...meta, ports: kept.length > 0 ? kept : undefined };\n await writeMachineMeta(next, p);\n return toMachine(next, p);\n});\n\n// ── links between boxes (#98) ─────────────────────────────────────────────────\n\n/**\n * The box a link comes from: by name (the caller's), `<owner>/<name>` over the socket, or `fromOwner`'s slug\n * from a control plane. Into a cloud box, a slug without a realm is taken in the target's, as `linkFrom`\n * shows it: what `vm links` lists over the socket can be unlinked as written.\n */\nfunction linkSource(req: LinkRequest, caller: string, target: string): BoxRef {\n if (req.fromOwner !== undefined) return { owner: ownerFor(req.fromOwner, caller), name: req.from, display: `${req.fromOwner}/${req.from}` };\n const ref = parseRef(req.from, caller);\n const realm = realmOf(target);\n return realm !== null && realmOf(ref.owner) === null && req.from.includes(\"/\") ? { ...ref, owner: `${ref.owner}@${realm}` } : ref;\n}\n\n/**\n * `kvbox vm link <from> <box> --port <port>` (#98): box `from` may open TCP connections to `port` of\n * this box, through the host, nothing else. Stored here; open while this box runs.\n */\nexport const addLink = locked(async function addLink(ref: BoxRef, req: LinkRequest, caller: string, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const fromRef = linkSource(req, caller, meta.owner);\n if (fromRef.owner === meta.owner && fromRef.name === meta.name) throw new KvboxError(`box ${shown(ref)} already reaches itself`);\n const from = await readMeta(fromRef, p);\n // A control plane never sees this host's own boxes, nor they its: neither side could name the other's box.\n if (realmOf(from.owner) !== realmOf(meta.owner)) {\n throw new KvboxError(`box ${shown(fromRef)} and box ${shown(ref)} belong to different realms (one is this host's, one a control plane's); a link joins boxes of one realm`);\n }\n // a stale entry of the same rule (a removed box of that name had this IP) gives way to the new link\n const links = (meta.links ?? []).filter((l) => !(l.stale && l.owner === from.owner && l.name === from.name && l.ip === from.ip && l.port === req.port));\n const same = (l: NonNullable<MachineMeta[\"links\"]>[number]) => !l.stale && l.owner === from.owner && l.name === from.name && l.port === req.port;\n if (links.some(same)) throw new KvboxError(`box ${shown(fromRef)} already reaches box ${shown(ref)} on port ${req.port}`);\n if (links.length >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${shown(ref)} has ${links.length}`);\n const added = { owner: from.owner, name: from.name, ip: from.ip, port: req.port };\n const cfg = await loadConfig(p);\n if (vmAlive(meta)) await openLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg);\n const next: MachineMeta = { ...meta, links: [...links, added] };\n try {\n await writeMachineMeta(next, p);\n } catch (err) {\n // Nothing stored, so nothing may stay open: a rule meta.json does not name could never be removed.\n await closeLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg).catch(() => undefined);\n throw err;\n }\n return toMachine(next, p);\n});\n\n/** `kvbox vm unlink <from> <box> --port <port>` (#98). The rule closes whether or not the box runs. */\nexport const removeLink = locked(async function removeLink(ref: BoxRef, req: LinkRequest, caller: string, p: Paths = paths()): Promise<Machine> {\n const meta = await readMeta(ref, p);\n const fromRef = linkSource(req, caller, meta.owner);\n const links = meta.links ?? [];\n const gone = links.filter((l) => !l.stale && l.owner === fromRef.owner && l.name === fromRef.name && l.port === req.port);\n if (gone.length === 0) throw new KvboxError(`box ${shown(fromRef)} is not linked to box ${shown(ref)} on port ${req.port}`);\n const cfg = await loadConfig(p);\n // Closed first: a rule that would not go keeps the link in meta.json, so trying again finds it.\n for (const l of gone) await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg);\n const kept = links.filter((l) => !gone.includes(l));\n const next: MachineMeta = { ...meta, links: kept.length > 0 ? kept : undefined };\n await writeMachineMeta(next, p);\n return toMachine(next, p);\n});\n\n/** Extend a box's (unmounted) ext4 disk file to `gib` GiB. */\nexport async function growDisk(file: string, gib: number): Promise<void> {\n await truncate(file, gib * 1024 ** 3);\n await run([\"e2fsck\", \"-f\", \"-p\", file], { okExitCodes: [1] });\n await run([\"resize2fs\", file]);\n}\n\nasync function readMeta(ref: BoxRef, p: Paths): Promise<MachineMeta> {\n try {\n return await readMachineMeta(ref, p);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") throw new NotFoundError(`box ${shown(ref)}`);\n throw err;\n }\n}\n\n/** `kvbox vm rm`: the box, then the links it had into other boxes (#98), each under that box's own lock. */\nexport async function destroyMachine(ref: BoxRef, p: Paths = paths()): Promise<void> {\n const gone = await destroyBox(ref, p);\n await dropLinksFrom(gone, p);\n}\n\nconst destroyBox = locked(async function destroyBox(ref: BoxRef, p: Paths = paths()): Promise<MachineMeta> {\n const meta = await readMeta(ref, p);\n const cfg = await loadConfig(p);\n await shutdown(meta, cfg, p, 2000);\n // Its IP is free once the dir goes: no rule may still let that IP into another box by then. A box\n // this stops short of removing stays in the ledger, stopped.\n await closeLinksFrom(meta, cfg, p).catch((err: unknown) => {\n recordState(meta, \"stopped\", \"stop\", p);\n throw err;\n });\n // The ledger keeps the box's history after it is gone: a final row, while the disk is still there to measure.\n recordState(meta, \"stopped\", \"rm\", p);\n await rm(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });\n boxListChanged(); // its IP is free for the next box: no name may still point there\n return meta;\n});\n\nconst linkOf = (gone: MachineMeta) => (l: { owner: string; name: string; ip: string }) => l.owner === gone.owner && l.name === gone.name && l.ip === gone.ip;\n\n/**\n * Close every rule from `gone`'s IP into another box, without the targets' locks (`link rm` is idempotent),\n * before its dir goes. One that will not close stops the rm: the box keeps its dir, and so its IP.\n */\nasync function closeLinksFrom(gone: MachineMeta, cfg: Config, p: Paths): Promise<void> {\n const isGone = linkOf(gone);\n for (const ref of await listMachineRefs(p)) {\n const meta = await readMachineMeta(ref, p).catch(() => null);\n for (const l of meta?.links?.filter(isGone) ?? []) {\n await closeLink({ box: meta!.id, fromIp: l.ip, toIp: meta!.ip, port: l.port }, cfg).catch((err: Error) => {\n throw new KvboxError(`box ${shown(gone)} is stopped but not removed: could not close its link into ${shown(meta!)} (${err.message}); try again`);\n });\n }\n }\n}\n\n/**\n * Then each link from the removed box leaves its target's meta.json, under that box's lock. Its rule is\n * closed again first (a target that booted meanwhile may have opened it); one that will not close keeps\n * its entry, so the target's next stop or unlink still finds it, and it never opens again (standingLinks).\n */\nasync function dropLinksFrom(gone: MachineMeta, p: Paths): Promise<void> {\n const cfg = await loadConfig(p);\n const isGone = linkOf(gone);\n for (const ref of await listMachineRefs(p)) {\n await withBoxLock(ref, async () => {\n const meta = await readMachineMeta(ref, p).catch(() => null);\n if (!meta?.links?.some(isGone)) return;\n const stuck = new Set<NonNullable<MachineMeta[\"links\"]>[number]>();\n for (const l of meta.links.filter(isGone)) {\n await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg).catch((err: Error) => {\n stuck.add(l);\n log.warn(`could not close the link from removed box ${gone.name} into ${meta.name}: ${err.message}`);\n });\n }\n const kept = meta.links.filter((l) => !isGone(l) || stuck.has(l)).map((l) => (stuck.has(l) ? { ...l, stale: true as const } : l));\n await writeMachineMeta({ ...meta, links: kept.length > 0 ? kept : undefined }, p);\n }).catch((err: Error) => log.warn(`links of removed box ${gone.name}: ${err.message}`));\n }\n}\n\n// ── after the host was down (#29) ─────────────────────────────────────────────\n/** Boxes booted at once when the server brings them back: each boot is a burst of disk and CPU. */\nconst RECOVERY_CONCURRENCY = 2;\n\n/**\n * At server start, the boxes whose Firecracker died with an earlier boot of the host: meta.json still\n * names a pid, but from another boot. Each one's open run in the ledger is closed (at the host's boot\n * when it predates it) and its memory image goes: the next boot is fresh. A box that was in standby\n * lost its memory with the process, so it is left stopped; the others keep the old pid and boot id,\n * which mark them as not brought back yet, and are returned to be booted (`bootRecovered`). A box\n * whose Firecracker died earlier in this boot (a crash) is not touched: it reads as stopped, as it has\n * since. Done before the server listens, so a listing cannot close those runs at \"now\" first.\n */\nexport async function settleDeadBoxes(p: Paths = paths()): Promise<{ boot: BoxRef[]; leftStopped: string[] }> {\n const now = new Date().toISOString();\n const bootAt = hostBootTime()?.toISOString() ?? now;\n const boot: BoxRef[] = [];\n const leftStopped: string[] = [];\n for (const meta of await readAllMeta(p)) {\n if (!cutByReboot(meta) || vmAlive(meta)) continue;\n try {\n closeRunCutByBoot(meta.id, bootAt, now, p);\n } catch (err) {\n log.warn(`usage ledger: ${(err as Error).message}`);\n }\n await rm(p.machine(meta.owner, meta.name).memBase, { force: true });\n if (meta.paused) {\n await writeMachineMeta({ ...meta, pid: null, bootId: undefined, memSnapshots: undefined, paused: undefined }, p);\n leftStopped.push(refKey(meta));\n } else {\n await writeMachineMeta({ ...meta, memSnapshots: undefined }, p);\n boot.push({ owner: meta.owner, name: meta.name });\n }\n }\n return { boot, leftStopped };\n}\n\n/** A pid launched in another boot of the host (or before #29, with no boot id): the reboot ended it. */\nfunction cutByReboot(meta: MachineMeta): boolean {\n return meta.pid !== null && meta.bootId !== currentBootId();\n}\n\n/**\n * At server start: pin the tap of every box that runs (#98). A server restart leaves the boxes running,\n * so after an upgrade their taps are the old code's, unpinned, and `link add` refuses while one is on the\n * bridge. A failure is logged; that box stays unpinned until it restarts.\n */\nexport async function pinRunningTaps(p: Paths = paths()): Promise<void> {\n const cfg = await loadConfig(p);\n if (!bridgeExists(cfg.bridge)) return;\n for (const meta of await readAllMeta(p)) {\n if (!vmAlive(meta) || !existsSync(`/sys/class/net/${tapName(meta.id)}`)) continue;\n await pinTap(meta, cfg).catch((err: Error) => log.warn(`could not pin box ${meta.name}'s tap: ${err.message}`));\n }\n}\n\nlet recovery: RecoveryReport | null = null;\nlet recoveryStopping = false;\nlet recoveryRun: Promise<unknown> = Promise.resolve();\n\n/** What `bootRecovered` did at this server's start (`/health`); null when nothing needed it. */\nexport function lastRecovery(): RecoveryReport | null {\n return recovery;\n}\n\n/**\n * For the server's shutdown: boot no further box, and resolve once the boots under way have written\n * their pid to meta.json (exiting halfway would leave a Firecracker no meta.json names). The boxes\n * not reached keep their old boot id, so the next server start brings them back.\n */\nexport async function stopRecovery(): Promise<void> {\n recoveryStopping = true;\n await recoveryRun;\n}\n\n/**\n * Boot the boxes `settleDeadBoxes` found, a few at a time, like `kvbox start` (fresh boot, current\n * SSH lines). A box someone started while it waited its turn now has this boot's id and is skipped.\n * One that does not come up is reported, never fatal: the server keeps serving.\n */\nexport async function bootRecovered(settled: { boot: readonly BoxRef[]; leftStopped: readonly string[] }, p: Paths = paths()): Promise<RecoveryReport | null> {\n const refs = settled.boot;\n if (refs.length === 0 && settled.leftStopped.length === 0) return null;\n const booted: string[] = [];\n const failed: RecoveryReport[\"failed\"] = [];\n const queue = [...refs];\n const worker = async () => {\n for (let ref = queue.shift(); ref !== undefined && !recoveryStopping; ref = queue.shift()) {\n try {\n if (!cutByReboot(await readMeta(ref, p))) continue;\n // It was running when the host went down: it gets its room back, as it had it.\n await startMachine(ref, p, true);\n booted.push(refKey(ref));\n } catch (err) {\n failed.push({ box: refKey(ref), error: (err as Error).message });\n }\n }\n };\n const run = Promise.all(Array.from({ length: Math.min(RECOVERY_CONCURRENCY, refs.length) }, worker));\n recoveryRun = run;\n await run;\n recovery = { at: new Date().toISOString(), booted, leftStopped: [...settled.leftStopped], failed };\n return recovery;\n}\n","/** Auto-hibernate's durations: the host checks once a minute, so minutes are the unit. */\nconst UNIT_SEC: Record<string, number> = { m: 60, h: 3600, d: 86400 };\n\n/** \"30m\", \"4h\", \"1d\", \"1h30m\" -> seconds; undefined when it is not such a duration. */\nexport function parseDuration(text: string): number | undefined {\n const t = text.trim().toLowerCase();\n if (!/^(\\d+[mhd])+$/.test(t)) return undefined;\n let sec = 0;\n for (const [, n, unit] of t.matchAll(/(\\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit!]!;\n return sec;\n}\n","/**\n * Wire shapes of the kvbox HTTP API, shared by the client (src/cli) and the\n * server (src/server). Validated with zod on both sides because the client\n * may be talking to an older or newer server.\n */\nimport { z } from \"zod\";\nimport { SIZE_NAMES } from \"./sizes.js\";\n\nexport const SizeSchema = z.enum(SIZE_NAMES as [string, ...string[]]);\n\n/** The guest account every box has; `ssh` logs in as it. */\nexport const BOX_SSH_USER = \"kvbox\";\n\n/**\n * A box's state. `running`: Firecracker up, guest executing. `standby`: Firecracker up but frozen (kvbox\n * pause): memory and processes kept, no CPU. `hibernated`: no process; memory dumped to the box's dir\n * (kvbox hibernate), wake continues where it left off. `stopped`: no process, memory gone, next start boots.\n * `unknown`: only from the control plane, for a box whose host did not answer in time (#20).\n */\nexport const BoxStatusSchema = z.enum([\"running\", \"standby\", \"hibernated\", \"stopped\", \"unknown\"]);\nexport type BoxStatus = z.infer<typeof BoxStatusSchema>;\n\n/** A published box port's protocol (#30). */\nexport const PortProtoSchema = z.enum([\"tcp\", \"udp\"]);\nexport type PortProto = z.infer<typeof PortProtoSchema>;\n\n/** At most this many published ports per box (#30): room for a lab of services, not for draining the host's range. */\nexport const MAX_BOX_PORTS = 16;\n\n/**\n * A box port published on the host's public address (#30, `kvbox vm proxy`): `hostPort` on the\n * host reaches `guestPort` in the box. The host port is drawn at random and stays the box's.\n */\nexport const PortForwardSchema = z.object({\n guestPort: z.number().int().min(1).max(65535),\n hostPort: z.number().int(),\n proto: PortProtoSchema,\n /** The host's public address; only the control plane fills it in, as for `ssh`. */\n address: z.string().optional(),\n /**\n * Closed but kept (#173): nothing reaches the box through it, and the host port stays the box's, so\n * publishing the same box port again opens the same number. Absent: open while the box runs.\n */\n closed: z.literal(true).optional(),\n});\nexport type PortForward = z.infer<typeof PortForwardSchema>;\n\n/** `POST /machines/:name/ports` adds these, `DELETE` removes them; the answer is the box. */\nexport const PortsRequest = z.object({\n ports: z.array(z.object({ guestPort: z.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),\n /** `DELETE` only (#173): close the ports but keep their host ports for the box (`closed`). */\n keep: z.boolean().optional(),\n});\nexport type PortsRequest = z.infer<typeof PortsRequest>;\n\nconst BoxPortSchema = z.number().int().min(1).max(65535);\n\n/** At most this many links into one box (#98). */\nexport const MAX_BOX_LINKS = 32;\n\n/**\n * A link into a box (#98, `kvbox vm link`): box `from` may open TCP connections to this box's `port`,\n * over the host's bridge, nothing else. `from` is the box's name when it has the same owner, else\n * `<slug>/<name>`. Same host only.\n */\nexport const BoxLinkSchema = z.object({ from: z.string(), port: BoxPortSchema });\nexport type BoxLink = z.infer<typeof BoxLinkSchema>;\n\n/**\n * `POST /machines/:name/links` adds a link into `:name`, `DELETE` removes it; the answer is the box.\n * `from` is a box name, or `<owner>/<name>` over the socket. Through a control plane, `fromOwner` is\n * its slug, bare (like ForkMachineRequest's `owner`); the host qualifies it with the caller's realm.\n */\nexport const LinkRequest = z.object({ from: z.string().min(1), fromOwner: z.string().optional(), port: BoxPortSchema });\nexport type LinkRequest = z.infer<typeof LinkRequest>;\n\n/** `PUT /machines/:name/subdomain` (#31): claim `<name>.kvbox.app` for the box, serving `port`. */\nexport const ClaimSubdomainRequest = z.object({ name: z.string(), port: BoxPortSchema });\nexport type ClaimSubdomainRequest = z.infer<typeof ClaimSubdomainRequest>;\n\n/** `POST /machines/:name/subdomain/port`: the default port changes. */\nexport const SubdomainPortRequest = z.object({ port: BoxPortSchema });\nexport type SubdomainPortRequest = z.infer<typeof SubdomainPortRequest>;\n\n/** `POST /machines/:name/subdomain/routes`: `<name>.<sub>.kvbox.app` serves `port`. */\nexport const SubdomainRouteRequest = z.object({ name: z.string(), port: BoxPortSchema });\nexport type SubdomainRouteRequest = z.infer<typeof SubdomainRouteRequest>;\n\n/**\n * A box's HTTPS subdomain (#31): `url` serves the box's `port`, each route's `url` its own port.\n * `owner` is the box's slug (a user's or an org's), `box` its name.\n */\nexport const SubdomainSchema = z.object({\n owner: z.string(),\n box: z.string(),\n subdomain: z.string(),\n port: BoxPortSchema,\n url: z.string(),\n routes: z.array(z.object({ name: z.string(), port: BoxPortSchema, url: z.string() })),\n});\nexport type Subdomain = z.infer<typeof SubdomainSchema>;\n\n/** `POST /machines/:name/domains` (#89): serve the box at `domain`, on `port` (default: its subdomain's). */\nexport const AddDomainRequest = z.object({ domain: z.string(), port: BoxPortSchema.optional() });\nexport type AddDomainRequest = z.infer<typeof AddDomainRequest>;\n\n/**\n * A custom domain (#89). `pending` until its A record gives the edge's address and its TXT record\n * `_kvbox.<domain>` holds the slug's token (checked when added and every minute after), then `live`: the edge serves it and Traefik gets its certificate by HTTP-01.\n * `www` is true when `www.<domain>` points here too and is served as the same site. `records` is what\n * to set at the domain's DNS; `error` why it is still pending.\n */\nexport const DomainSchema = z.object({\n owner: z.string(),\n box: z.string(),\n domain: z.string(),\n port: BoxPortSchema,\n status: z.enum([\"pending\", \"live\"]),\n www: z.boolean(),\n url: z.string(),\n error: z.string().nullable(),\n records: z.array(z.object({ type: z.enum([\"A\", \"TXT\", \"CNAME\"]), name: z.string(), value: z.string() })),\n createdAt: z.string(),\n});\nexport type Domain = z.infer<typeof DomainSchema>;\n\n/**\n * A wake hook (#101): a URL that wakes one box when called, for GitHub webhooks, cron or any other\n * automation. Calls are signed with the hook's secret, as GitHub signs (`X-Hub-Signature-256`) or as a\n * bearer; the secret is shown once, when the hook is made. `lastCalledAt` is the last call that passed\n * the signature check.\n */\nexport const WakeHookSchema = z.object({\n id: z.string(),\n owner: z.string(),\n box: z.string(),\n url: z.string(),\n createdBy: z.string().nullable(),\n createdAt: z.string(),\n lastCalledAt: z.string().nullable(),\n});\nexport type WakeHook = z.infer<typeof WakeHookSchema>;\n/** What `POST /machines/:name/hooks` answers: the hook and its secret, the only time it is shown. */\nexport const CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z.string() });\nexport type CreatedWakeHook = z.infer<typeof CreatedWakeHookSchema>;\n/** What a call to a hook answers (202): what was asked of the box, `none` with the reason when nothing was. */\nexport const WakeHookCallSchema = z.object({\n box: z.string(),\n action: z.enum([\"wake\", \"resume\", \"none\"]),\n reason: z.string().optional(),\n});\nexport type WakeHookCall = z.infer<typeof WakeHookCallSchema>;\n\n/**\n * Backups (decision \"Backups: encrypted 4 MiB chunks in object storage\"; format in `@kvbox/shared/backup`):\n * the control plane's only. A backup is the box's disk and its own variables at one instant, never its\n * memory or volumes; `running` until the host has uploaded every new chunk.\n */\nexport const BACKUP_STATUSES = [\"running\", \"ready\", \"failed\"] as const;\n/** What a backup is of: a box's disk, or a volume's (#168). */\nexport const BACKUP_KINDS = [\"box\", \"volume\"] as const;\nexport type BackupKind = (typeof BACKUP_KINDS)[number];\nexport const BackupSchema = z.object({\n id: z.string(),\n owner: z.string(),\n box: z.string(),\n status: z.enum(BACKUP_STATUSES),\n /** Why it failed; null otherwise. */\n error: z.string().nullable(),\n /** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */\n base: z.string().nullable(),\n image: z.string().optional(),\n vcpu: z.number().int().nullable(),\n memMib: z.number().int().nullable(),\n /** The disk's size. */\n diskBytes: z.number().int().nullable(),\n /** What it holds: the slots that are not all zeros. */\n dataBytes: z.number().int().nullable(),\n /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */\n uploadedBytes: z.number().int().nullable(),\n createdBy: z.string().nullable(),\n createdAt: z.string(),\n finishedAt: z.string().nullable(),\n});\nexport type Backup = z.infer<typeof BackupSchema>;\n\n/** Control plane → host, `POST /machines/:name/backup`: take the box's disk and name its chunks. */\nexport const HostBackupRequest = z.object({ id: z.string(), key: z.string() });\nexport type HostBackupRequest = z.infer<typeof HostBackupRequest>;\n/** The host's answer: the disk as chunk names (null: a slot of zeros), its variables sealed, and what the box was. */\nexport const HostBackupManifestSchema = z.object({\n id: z.string(),\n sizeBytes: z.number().int(),\n chunks: z.array(z.string().nullable()),\n env: z.string().nullable(),\n base: z.string(),\n image: z.string().optional(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n});\nexport type HostBackupManifest = z.infer<typeof HostBackupManifestSchema>;\n/**\n * `POST /backups/:id/upload`: a signed PUT URL per chunk the store does not have yet. `pin` is the sha256\n * fingerprint (`AA:BB:…`) of the certificate the store answers with: a store is another host, whose\n * certificate is self-signed, so the URLs are trusted by that fingerprint alone.\n */\nexport const HostUploadRequest = z.object({ key: z.string(), urls: z.record(z.string(), z.string()), pin: z.string().optional() });\nexport type HostUploadRequest = z.infer<typeof HostUploadRequest>;\n/** What was uploaded: the count, the total and each chunk's stored size (what storage is billed on). */\nexport const HostUploadResultSchema = z.object({ chunks: z.number().int(), bytes: z.number().int(), sizes: z.record(z.string(), z.number().int()) });\nexport type HostUploadResult = z.infer<typeof HostUploadResultSchema>;\n/**\n * `POST /machines/:name/restore`: the disk a backup describes, as a signed GET URL per slot that is\n * not zeros. The host builds it beside the box's disk, then swaps it in (a running box restarts).\n */\nexport const HostRestoreRequest = z.object({\n /** The backup's id: its variables were sealed under it. */\n id: z.string(),\n key: z.string(),\n sizeBytes: z.number().int().positive(),\n base: z.string(),\n image: z.string().optional(),\n env: z.string().nullable(),\n chunks: z.array(z.object({ index: z.number().int().nonnegative(), hash: z.string(), url: z.string() })),\n /** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */\n pin: z.string().optional(),\n});\nexport type HostRestoreRequest = z.infer<typeof HostRestoreRequest>;\n\n/**\n * A volume's backup (#168): the same chunks, stores and limits as a box's, of the volume's disk alone. It\n * has no base, shape or variables: a volume is only data.\n */\nexport const VolumeBackupSchema = z.object({\n id: z.string(),\n owner: z.string(),\n volume: z.string(),\n status: z.enum(BACKUP_STATUSES),\n /** Why it failed; null otherwise. */\n error: z.string().nullable(),\n /** The volume's size when taken. */\n diskBytes: z.number().int().nullable(),\n /** What it holds: the slots that are not all zeros. */\n dataBytes: z.number().int().nullable(),\n /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */\n uploadedBytes: z.number().int().nullable(),\n createdBy: z.string().nullable(),\n createdAt: z.string(),\n finishedAt: z.string().nullable(),\n});\nexport type VolumeBackup = z.infer<typeof VolumeBackupSchema>;\n/** The host's answer to `POST /volumes/:name/backup` (the request is a box's, `HostBackupRequest`): the disk as chunk names. */\nexport const HostVolumeBackupManifestSchema = z.object({ id: z.string(), sizeBytes: z.number().int(), chunks: z.array(z.string().nullable()) });\nexport type HostVolumeBackupManifest = z.infer<typeof HostVolumeBackupManifestSchema>;\n/**\n * `POST /volumes/:name/restore`: like a box's, without what a volume does not have. The host builds the\n * disk beside the volume's, then swaps it in (a running box that holds the volume restarts).\n */\nexport const HostVolumeRestoreRequest = z.object({\n id: z.string(),\n key: z.string(),\n sizeBytes: z.number().int().positive(),\n chunks: z.array(z.object({ index: z.number().int().nonnegative(), hash: z.string(), url: z.string() })),\n pin: z.string().optional(),\n});\nexport type HostVolumeRestoreRequest = z.infer<typeof HostVolumeRestoreRequest>;\n\n/**\n * A backup store (decision \"Backup stores: Garage on our own disks…\"): a host with a disk for backups,\n * running Garage there (`kvbox-server backup setup`). Chunks reach it through the host's own HTTPS port,\n * under the bucket's name as the first path segment, which is why the name is fixed.\n */\nexport const BACKUP_STORE_BUCKET = \"kvbox-backups\";\nexport const BACKUP_STORE_REGION = \"kvbox\";\n/** `kvbox-server backup setup`, over the host's socket. */\n/** `newStore`: the store's disk is gone for good; start a new store at the path (its backups are lost). */\nexport const BackupStoreSetupRequest = z.object({ path: z.string().min(1), force: z.boolean().optional(), newStore: z.boolean().optional() });\nexport type BackupStoreSetupRequest = z.infer<typeof BackupStoreSetupRequest>;\n/** What a host says about its store (`kvbox-server backup status`); the secret key is never in it. */\nexport const BackupStoreStatusSchema = z.object({\n path: z.string(),\n bucket: z.string(),\n accessKey: z.string(),\n /** Whether Garage is running and can store. */\n running: z.boolean(),\n /** The filesystem the path is on. */\n totalBytes: z.number().int(),\n freeBytes: z.number().int(),\n /** What the bucket holds, when Garage answers. */\n objects: z.number().int().optional(),\n storedBytes: z.number().int().optional(),\n /** Whether the control plane took the store's registration at setup. */\n registered: z.boolean().optional(),\n});\nexport type BackupStoreStatus = z.infer<typeof BackupStoreStatusSchema>;\n/** Host → control plane, `PUT /hosts/self/backup-store` by the host secret: the key the control plane signs chunk URLs with. */\nexport const BackupStoreRegistration = z.object({ bucket: z.string().min(1), region: z.string().min(1), accessKey: z.string().min(1), secretKey: z.string().min(1) });\nexport type BackupStoreRegistration = z.infer<typeof BackupStoreRegistration>;\n/** A store as the admin sees it (`GET /admin/backup-stores`): no secret. */\nexport const CloudBackupStoreSchema = z.object({\n id: z.string(),\n /** Null while no host serves it (its host left; it comes back when a host registers its key and secret again). */\n host: z.string().nullable(),\n endpoint: z.string().nullable(),\n bucket: z.string(),\n accessKey: z.string(),\n createdAt: z.string(),\n /** The host answered a poll in the last minute and its Garage runs. */\n live: z.boolean(),\n /** From the host's last poll; null when it never reported a store. */\n totalBytes: z.number().int().nullable(),\n freeBytes: z.number().int().nullable(),\n /** Ready backups kept here, and what their chunks take (encrypted, compressed). */\n backups: z.number().int(),\n storedBytes: z.number().int(),\n /** 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). */\n boxes: z.number().int(),\n volumes: z.number().int(),\n /** When the newest ready backup kept here finished; null when it keeps none. */\n lastBackupAt: z.string().nullable(),\n});\nexport type CloudBackupStore = z.infer<typeof CloudBackupStoreSchema>;\n\n/**\n * What a store keeps for one box or one volume (#168), as the admin sees it\n * (`GET /admin/backup-stores/:id/items`).\n */\nexport const StoredItemSchema = z.object({\n kind: z.enum(BACKUP_KINDS),\n owner: z.string(),\n name: z.string(),\n /** The host the box (or volume) is on now; null when it is gone (its backups stay). */\n host: z.string().nullable(),\n /** It is on the store's own host: losing that host loses it and its backups together. */\n sameHost: z.boolean(),\n /** Ready backups kept here, and what they added to the store together (encrypted, compressed). */\n backups: z.number().int(),\n uploadedBytes: z.number().int(),\n /** The newest backup sent here, whatever became of it. */\n latest: z.object({ id: z.string(), status: z.enum(BACKUP_STATUSES), error: z.string().nullable(), createdAt: z.string() }),\n});\nexport type StoredItem = z.infer<typeof StoredItemSchema>;\n\n/** A backup that failed lately, for the admin (`GET /admin/backups/failed`). */\nexport const FailedBackupSchema = z.object({\n id: z.string(),\n owner: z.string(),\n /** What it was a backup of: a box or a volume (#168), and its name. */\n kind: z.enum(BACKUP_KINDS),\n name: z.string(),\n error: z.string().nullable(),\n /** 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. */\n host: z.string().nullable(),\n store: z.string().nullable(),\n createdAt: z.string(),\n});\nexport type FailedBackup = z.infer<typeof FailedBackupSchema>;\n\nexport const MachineSchema = z.object({\n /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */\n id: z.string(),\n name: z.string(),\n /** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */\n owner: z.string(),\n ip: z.string(),\n mac: z.string(),\n pid: z.number().int().nullable(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n diskBytes: z.number().int(), // the box's own writable disk, as the guest sees it\n diskUsedBytes: z.number().int(), // what the box uses of it: the filesystem's own count, like the guest's `df` (#115)\n /** 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. */\n diskHostBytes: z.number().int().optional(),\n base: z.string(), // version of the image the box's overlay stacks on\n /** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */\n image: z.string().optional(),\n createdAt: z.string(),\n source: z.string(), // \"base\", \"snapshot:<owner/name>\" or \"fork:<owner/name>\" (#79)\n status: BoxStatusSchema,\n /**\n * Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made\n * through a control plane have one; the control plane adds the host's address for `connect` (#21).\n */\n sshPort: z.number().int().optional(),\n /**\n * Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only\n * the control plane fills it in (a host does not know its own public address); absent for a box\n * whose host reported no port or did not answer.\n */\n ssh: z.object({ host: z.string(), port: z.number().int(), user: z.string() }).optional(),\n /** Box ports published on the host (#30). Absent: none. */\n ports: z.array(PortForwardSchema).optional(),\n /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /**\n * The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box\n * links to, and a volume attaches to, only a box on the same host.\n */\n host: z.string().optional(),\n /** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */\n country: z.string().optional(),\n /**\n * The kind of managed service the box runs (`postgres`, `redis`, `storage`). Only an admin's\n * `GET /machines?all=1` lists such boxes, so a host's boxes add up; every other listing hides them.\n */\n managed: z.string().optional(),\n /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */\n autoHibernateSec: z.number().int().positive().optional(),\n /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */\n idleCheck: z.string().optional(),\n /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */\n volumes: z.array(z.object({ name: z.string(), sizeGib: z.number().int(), mountPath: z.string() })).optional(),\n /** Boxes that may reach this one, each on one port (#98). Absent: none. */\n links: z.array(BoxLinkSchema).optional(),\n /** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */\n url: z.string().optional(),\n /**\n * Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it\n * serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.\n */\n connect: z.string().optional(),\n});\nexport type Machine = z.infer<typeof MachineSchema>;\n\n/**\n * A volume (#52): a disk of its own, created apart from any box, attached to one box at a time and\n * kept when that box goes. `attachedTo` is the box's name (same owner), null when detached.\n */\nexport const VolumeSchema = z.object({\n /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n sizeGib: z.number().int(),\n /** What the sparse file really occupies on the host. */\n usedBytes: z.number().int(),\n attachedTo: z.string().nullable(),\n createdAt: z.string(),\n /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */\n host: z.string().optional(),\n});\nexport type Volume = z.infer<typeof VolumeSchema>;\n\n/** Volume sizes: whole GiB, at least 1, at most 4 TiB. */\nexport const MAX_VOLUME_GIB = 4096;\n/** Volume names are mount directories (/mnt/<name>) and go into an ext4 label: as plain as box names. */\nexport const VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;\nexport const VOLUME_NAME_RULE = \"1-12 chars, lowercase letters, digits and '-', starting with a letter or digit\";\n\nexport const CreateVolumeRequest = z.object({\n name: z.string(),\n sizeGib: z.number().int().min(1).max(MAX_VOLUME_GIB),\n /**\n * Through a control plane (#91): the box this volume is for, so it is made on that box's host; the\n * control plane requires it (a volume attaches only to a box on its own host, so one made for no box\n * could never attach) and the CLI attaches right after. A host ignores it.\n */\n box: z.string().optional(),\n});\nexport type CreateVolumeRequest = z.infer<typeof CreateVolumeRequest>;\n\n/** `POST /volumes/:name/attach`: the box, as the caller names it (a bare name is the caller's own). */\nexport const AttachVolumeRequest = z.object({\n box: z.string(),\n});\nexport type AttachVolumeRequest = z.infer<typeof AttachVolumeRequest>;\n\n/** `POST /volumes/:name/resize` (#147): the new size, larger than the current one. A volume never shrinks. */\nexport const ResizeVolumeRequest = z.object({\n sizeGib: z.number().int().min(1).max(MAX_VOLUME_GIB),\n});\nexport type ResizeVolumeRequest = z.infer<typeof ResizeVolumeRequest>;\n\n/**\n * `POST /machines/:name/scripts/:script` on a host (#173): run the script the box's image names `:script`\n * in its image.json, through kvbox-agent, with `input` on its stdin. The answer is what it printed.\n */\nexport const RunScriptRequest = z.object({ input: z.unknown().optional() });\nexport type RunScriptRequest = z.infer<typeof RunScriptRequest>;\nexport const ScriptOutputSchema = z.object({ output: z.unknown() });\nexport type ScriptOutput = z.infer<typeof ScriptOutputSchema>;\n\n/**\n * A command started in a box and left to run (#190, base v0.15.0+): host `POST /machines/:name/runs`\n * starts it through kvbox-agent (as the box's user, in its home, a login shell; its output stays in the\n * box at `/var/log/kvbox/runs/<id>.log`) and answers at once; `GET /machines/:name/runs/:id` says how\n * it stands. The caller picks the id; the same id twice starts nothing new. On the HTTPS app only.\n */\nexport const BOX_RUN_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;\nexport const StartRunRequest = z.object({\n id: z.string().regex(BOX_RUN_ID_RE),\n command: z.string().min(1).max(8192),\n /** The command and everything it started are killed after this long. */\n timeoutSec: z.number().int().min(1).max(86400),\n});\nexport type StartRunRequest = z.infer<typeof StartRunRequest>;\nexport const StartRunAnswerSchema = z.object({\n id: z.string(),\n /** False: a run of this id was already there. */\n started: z.boolean(),\n /** The box was asleep and this request woke it. */\n woke: z.boolean(),\n});\nexport type StartRunAnswer = z.infer<typeof StartRunAnswerSchema>;\n/** `unknown`: the box has no such run, which is also what a run becomes when the box restarts. */\nexport const BOX_RUN_STATES = [\"running\", \"exited\", \"timeout\", \"unknown\"] as const;\nexport const BoxRunSchema = z.object({\n id: z.string(),\n state: z.enum(BOX_RUN_STATES),\n /** With `exited`; 128 + the signal for a command a signal ended. */\n exitCode: z.number().int().optional(),\n});\nexport type BoxRun = z.infer<typeof BoxRunSchema>;\n/**\n * Why a run route could not go ahead, as `code` beside `error`: the box's state (as a forward to a\n * port answers it, `ProxyError` in names.ts) or `box-outdated`, an image whose kvbox-agent is from\n * before commands.\n */\nexport const RunRefusalSchema = z.object({ error: z.string(), code: z.string().optional() });\n\n/**\n * Environment variables (#88), through the control plane: a slug's list. A secret's value is never\n * sent back by any route (`value` absent), only that it is set.\n */\nexport const EnvVarSchema = z.object({\n name: z.string(),\n value: z.string().optional(),\n secret: z.boolean(),\n updatedAt: z.string(),\n});\nexport type EnvVar = z.infer<typeof EnvVarSchema>;\n\n/**\n * A box's own variables (#87), `GET /machines/:name/env`: kept on the box's host beside its meta.json,\n * merged over its owner's list at every boot. A secret's value is never sent back.\n */\nexport const BoxEnvSchema = z.object({\n box: z.string(),\n vars: z.array(EnvVarSchema),\n});\nexport type BoxEnv = z.infer<typeof BoxEnvSchema>;\n\n/** What `POST` and `DELETE /machines/:name/env/:var` answer (the body of a POST is a SetEnvRequest); the box gets it when it next starts. */\nexport const BoxEnvChangeSchema = z.object({\n box: z.string(),\n name: z.string(),\n /** Whether the box is running now: the change waits for its next start. */\n running: z.boolean(),\n});\nexport type BoxEnvChange = z.infer<typeof BoxEnvChangeSchema>;\n\n/** `PUT /env/:name` on the control plane. */\nexport const SetEnvRequest = z.object({\n value: z.string(),\n secret: z.boolean().optional(),\n});\nexport type SetEnvRequest = z.infer<typeof SetEnvRequest>;\n\n/** What `PUT` and `DELETE /env/:name` answer: whose list changed and how many boxes get it when they next start. */\nexport const EnvChangeSchema = z.object({\n owner: z.string(),\n name: z.string(),\n boxes: z.number().int(),\n});\nexport type EnvChange = z.infer<typeof EnvChangeSchema>;\n\n/**\n * `POST /env` on a host: an owner's whole list, values in the clear (the host admin is trusted, decision\n * \"Env vars belong to a slug…\"). `version` only grows; a host keeps the higher of what it has and this.\n */\nexport const HostEnvRequest = z.object({\n version: z.number().int().min(0),\n vars: z.array(z.object({ name: z.string(), value: z.string() })),\n});\nexport type HostEnvRequest = z.infer<typeof HostEnvRequest>;\n\n/** `GET /env` on a host: which list version it holds per owner (the realm's, without `X-Kvbox-Owner`). */\nexport const HostEnvVersionsSchema = z.array(z.object({ owner: z.string(), version: z.number().int() }));\nexport type HostEnvVersions = z.infer<typeof HostEnvVersionsSchema>;\n\nexport const CreateMachineRequest = z.object({\n name: z.string().optional(),\n /** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */\n owner: z.string().optional(),\n size: SizeSchema.optional(),\n from: z.string().optional(),\n force: z.boolean().optional(),\n /**\n * Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends\n * its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every\n * boot (#49); a host older than that ignores them.\n */\n sshKeys: z.array(z.string()).optional(),\n /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */\n autoHibernateSec: z.number().int().min(0).optional(),\n /**\n * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the\n * control plane reads it; a host has one place to put a box.\n */\n near: z.string().optional(),\n /**\n * Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,\n * `@kvbox/shared/country`. Only the control plane reads it.\n */\n country: z.string().optional(),\n /**\n * Place the box on the host of this name and nowhere else (`kvbox new --host kvbox2`, a hidden flag):\n * an admin's, to try a host out. Only the control plane reads it, and refuses it from anyone else.\n */\n host: z.string().optional(),\n /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */\n image: z.string().optional(),\n /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */\n env: z.array(z.object({ name: z.string(), value: z.string() })).optional(),\n});\nexport type CreateMachineRequest = z.infer<typeof CreateMachineRequest>;\n\n/**\n * `POST /machines/:name/fork` (#79): a new box from `:name` as it is right now. A running or paused\n * source is copied warm (memory and disk, processes keep running); a stopped one cold (its disk, then a\n * fresh boot). Absent fields come from the source: its size and its auto-hibernate.\n */\nexport const ForkMachineRequest = z.object({\n name: z.string().optional(),\n /**\n * The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host\n * qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.\n */\n owner: z.string().optional(),\n /** A cold fork only: a warm one keeps the source's vCPU and memory. */\n size: SizeSchema.optional(),\n force: z.boolean().optional(),\n /** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */\n sshKeys: z.array(z.string()).optional(),\n autoHibernateSec: z.number().int().min(0).optional(),\n});\nexport type ForkMachineRequest = z.infer<typeof ForkMachineRequest>;\n\n/**\n * `POST /machines/:name/ssh-keys` on a host (orgs phase 4): replace the authorized_keys lines the box\n * gets on top of the host's own key. Takes effect at the box's next boot (kvbox-init rewrites the\n * file from the kernel command line); a running or hibernated box keeps its current file until then.\n */\nexport const SetSshKeysRequest = z.object({\n sshKeys: z.array(z.string()),\n});\nexport type SetSshKeysRequest = z.infer<typeof SetSshKeysRequest>;\n\n/** `kvbox vm rescale`: a preset and/or explicit values; explicit ones win. Anything omitted stays as it is. */\nexport const RescaleMachineRequest = z.object({\n size: SizeSchema.optional(),\n vcpu: z.number().int().min(1).max(64).optional(),\n memMib: z.number().int().min(256).optional(),\n diskGib: z.number().int().min(1).optional(),\n /** Skip the capacity guard when a running box grows (#37). */\n force: z.boolean().optional(),\n});\nexport type RescaleMachineRequest = z.infer<typeof RescaleMachineRequest>;\n\n/** `POST /machines/:name/start` and `/wake`: `force` skips the capacity guard (#37). Both take no body too. */\nexport const StartMachineRequest = z.object({\n force: z.boolean().optional(),\n});\nexport type StartMachineRequest = z.infer<typeof StartMachineRequest>;\n\n/** `kvbox vm set`: settings that change nothing in the running VM. Anything omitted stays as it is. */\nexport const SetMachineRequest = z.object({\n /** Seconds without network traffic before the box is hibernated (#47); 0: never. */\n autoHibernateSec: z.number().int().min(0).optional(),\n /** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; \"\": none, back to network traffic. */\n idleCheck: z.union([z.literal(\"\"), z.string().max(255).regex(/^\\/[^\\0\\n]*$/, \"an absolute path inside the box\")]).optional(),\n});\nexport type SetMachineRequest = z.infer<typeof SetMachineRequest>;\n\nexport const SnapshotSchema = z.object({\n name: z.string(),\n owner: z.string(),\n source: z.string(), // the box it was taken from, as owner/name\n base: z.string(), // version of the image the overlay stacks on; a restore needs the same one\n /** As in MachineSchema: the image when it is not the base one (#87). */\n image: z.string().optional(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n sizeBytes: z.number().int(), // what vmstate + mem + overlay really occupy on the host\n createdAt: z.string(),\n});\nexport type Snapshot = z.infer<typeof SnapshotSchema>;\n\nexport const CreateSnapshotRequest = z.object({\n box: z.string(),\n name: z.string(),\n /** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */\n replace: z.boolean().optional(),\n});\nexport type CreateSnapshotRequest = z.infer<typeof CreateSnapshotRequest>;\n\n/**\n * The host's disk as volumes see it (#91). Volumes are sparse, so what they promise (`volumesGib`,\n * the sum of their sizes) and what they hold (`volumesUsedGib`) differ; a host may promise at most\n * the disk its boxes, snapshots and base images do not use, less `headroomGib` (@kvbox/shared/capacity `sellableGib`).\n */\nexport const DiskCapacitySchema = z.object({\n totalGib: z.number().int(),\n freeGib: z.number().int(),\n volumesGib: z.number().int(),\n volumesUsedGib: z.number().int(),\n headroomGib: z.number().int(),\n});\nexport type DiskCapacity = z.infer<typeof DiskCapacitySchema>;\n\nexport const CapacitySchema = z.object({\n hostMemMib: z.number().int(),\n hostCores: z.number().int(),\n reservedMemMib: z.number().int(),\n reservedVcpu: z.number().int(),\n running: z.number().int(),\n /** Absent on a host from before volumes (#91): it cannot take one. */\n disk: DiskCapacitySchema.optional(),\n /**\n * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.\n * Absent on a host from before images: it has only the base.\n */\n images: z.array(z.object({ name: z.string(), version: z.string() })).optional(),\n /** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */\n version: z.string().optional(),\n /** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */\n backupStore: z.object({ totalBytes: z.number().int(), freeBytes: z.number().int(), running: z.boolean() }).optional(),\n /** 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. */\n storeClient: z.boolean().optional(),\n});\nexport type Capacity = z.infer<typeof CapacitySchema>;\n\n/**\n * `GET /images` on the control plane: what a new box can boot from (`kvbox new --base <name>`), across\n * the hosts answering now. `version` is the newest a host offers; null for the base on a host from\n * before images, which does not say. The base comes first.\n */\nexport const ImageSchema = z.object({ name: z.string(), version: z.string().nullable() });\nexport type Image = z.infer<typeof ImageSchema>;\n\n/**\n * The index kvbox-images publishes with every release (`releases/download/index/images.json`): the\n * latest version of each guest image. `base` is the base rootfs, `kernel` the guest kernel, the rest\n * are the images of `kvbox new --base <name>` and the managed kinds. `minServer` is the oldest\n * kvbox-server that can run that version. install-server.sh installs by it; the control plane reads\n * it to say which hosts are behind (`GET /admin/images`).\n */\nexport const ImageIndexSchema = z.object({\n updatedAt: z.string(),\n images: z.record(z.string(), z.object({ version: z.string().min(1), minServer: z.string().min(1).optional() })),\n});\nexport type ImageIndex = z.infer<typeof ImageIndexSchema>;\n\n/**\n * `GET /admin/images`: the index as the control plane last read it. Without one (not published yet,\n * or never reached) `updatedAt` and `checkedAt` are null and `images` is empty. `checkedAt` is when\n * the control plane last read it successfully; a failed refresh keeps the older copy and its time.\n */\nexport const LatestImagesSchema = z.object({\n updatedAt: z.string().nullable(),\n images: ImageIndexSchema.shape.images,\n checkedAt: z.string().nullable(),\n});\nexport type LatestImages = z.infer<typeof LatestImagesSchema>;\n\n/**\n * What the server did at its last start about boxes whose Firecracker had died (host reboot or crash,\n * #29). Boxes are `owner/name`. `leftStopped`: they were in standby, their memory went with the process.\n */\nexport const RecoveryReportSchema = z.object({\n at: z.string(),\n booted: z.array(z.string()),\n leftStopped: z.array(z.string()),\n failed: z.array(z.object({ box: z.string(), error: z.string() })),\n});\nexport type RecoveryReport = z.infer<typeof RecoveryReportSchema>;\n\n/**\n * The host's last self-update (`install-server.sh --update`, started by the control plane's\n * `POST /admin/hosts/:name/update`), as `$KVBOX_HOME/update.json` holds it. The script writes it at\n * its start and its end; the daemon only reads it. `needsManual` names what the update left alone\n * because it needs root (a changed network script, the systemd unit, the /usr/local/bin links): run\n * install-server.sh on the host by hand for those.\n */\nexport const HostUpdateSchema = z.object({\n state: z.enum([\"running\", \"done\", \"failed\"]),\n startedAt: z.string(),\n finishedAt: z.string().nullable(),\n /** kvbox-server's version when the update started, and when it ended (null while running or when it failed before). */\n from: z.string(),\n to: z.string().nullable(),\n error: z.string().nullable(),\n needsManual: z.array(z.string()),\n});\nexport type HostUpdate = z.infer<typeof HostUpdateSchema>;\n\nexport const HealthSchema = z.object({\n ok: z.literal(true),\n version: z.string(),\n pid: z.number().int(),\n /** Base image version new boxes get (null when the host has no usable base image yet). */\n base: z.string().nullable(),\n /** Owner that boxes made over the local socket get (the Unix user running the server). */\n owner: z.string(),\n /** The control plane this host joined (null when none). */\n controlPlane: z\n .object({\n /** Realm name, e.g. kvbox.sh. */\n name: z.string(),\n url: z.string(),\n /** Where this host answers the control plane. */\n hostUrl: z.string(),\n })\n .nullable(),\n /** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */\n relay: z\n .object({\n name: z.string(),\n /** The public IP the relay owns for this host. */\n publicIp: z.string(),\n /** The relay's WireGuard endpoint the tunnel dials. */\n endpoint: z.string(),\n /** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */\n restarts: z.number().int().optional(),\n lastRestartAt: z.string().nullable().optional(),\n })\n .nullable()\n .optional(),\n /** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */\n recovery: RecoveryReportSchema.nullable().optional(),\n /** The last self-update; null when none ran. Older servers omit it. */\n update: HostUpdateSchema.nullable().optional(),\n});\nexport type Health = z.infer<typeof HealthSchema>;\n\n/**\n * `kvbox vm usage <box>`: how long the box spent in each state over a window and what that adds up\n * to. Hours are fractional; the CLI rounds. `cost` is present only when the host prices usage.\n * `historyFrom` is the first recorded moment, null when nothing is recorded yet.\n */\nexport const MachineUsageSchema = z.object({\n name: z.string(),\n owner: z.string(),\n status: BoxStatusSchema,\n window: z.object({ from: z.string(), to: z.string() }),\n seconds: z.object({\n running: z.number().int(),\n standby: z.number().int(),\n hibernated: z.number().int(),\n stopped: z.number().int(),\n }),\n vcpuHours: z.number(),\n ramGibHours: z.number(),\n diskGibHours: z.number(),\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */\n estimatedStops: z.number().int(),\n historyFrom: z.string().nullable(),\n});\nexport type MachineUsage = z.infer<typeof MachineUsageSchema>;\n\n/** What a running box says about itself through kvbox-agent's `stats` (base v0.7.0 and later). */\nexport const GuestStatsSchema = z.object({\n /** Load average over 1, 5 and 15 minutes. */\n load: z.tuple([z.number(), z.number(), z.number()]),\n cpus: z.number().int(),\n memTotalMib: z.number().int(),\n /** Total minus available: page cache counts as free. */\n memUsedMib: z.number().int(),\n /** The box's root, which is its overlay disk: the box's own writes, not the shared base. */\n diskTotalBytes: z.number().int(),\n diskUsedBytes: z.number().int(),\n uptimeSec: z.number().int(),\n});\nexport type GuestStats = z.infer<typeof GuestStatsSchema>;\n\n/** `GET /machines/:name/stats` (#67): `stats` is null when the box's image predates the request. */\nexport const MachineStatsSchema = z.object({\n name: z.string(),\n owner: z.string(),\n stats: GuestStatsSchema.nullable(),\n});\nexport type MachineStats = z.infer<typeof MachineStatsSchema>;\n\n/** A box's state as the usage ledger tells it: a box status, or `removed` when its last row is the `rm`. */\nexport const UsageStatusSchema = z.enum([...BoxStatusSchema.options, \"removed\"]);\nexport type UsageStatus = z.infer<typeof UsageStatusSchema>;\n\n/** One box's share of a `GET /usage` report (#41, #42): the same figures as `MachineUsage`, over the report's window. */\nexport const BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({\n /** The host's box id; a name removed and recreated appears twice, with two ids. */\n id: z.string(),\n status: UsageStatusSchema,\n /** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /**\n * Through a control plane: the username that made the box (#60), absent when the box is gone from\n * the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.\n */\n createdBy: z.string().optional(),\n});\nexport type BoxUsage = z.infer<typeof BoxUsageSchema>;\n\n/**\n * `GET /usage?since=&until=`: every box of the caller over the window (removed ones included) and\n * the totals. On a host over its socket: the host owner's boxes; through a control plane: every slug\n * the user can read (`X-Kvbox-Org` narrows to one). `cost` is present when the answering side prices usage.\n */\n/**\n * One volume's share of a `GET /usage` report (#91): the hours it existed over the window and its\n * GiB-hours (its size, not what it holds: a volume is a reservation). `removed` when its last row is\n * the `rm`. The price is per volume-hour plus per GiB-hour (decision \"Cloud pricing v1\").\n */\nexport const VolumeUsageSchema = z.object({\n /** The host's volume id; a name removed and made again appears twice, with two ids. */\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /** The size at the end of the window (or when removed). */\n sizeGib: z.number().int(),\n status: z.enum([\"present\", \"removed\"]),\n volumeHours: z.number(),\n volumeGibHours: z.number(),\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n historyFrom: z.string().nullable(),\n});\nexport type VolumeUsage = z.infer<typeof VolumeUsageSchema>;\n\n/**\n * A cron service over a report's window (#190, control plane only): the hours it existed and what\n * they cost. It is charged for existing, whatever it holds or fires.\n */\nexport const CronUsageSchema = z.object({\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n status: z.enum([\"present\", \"removed\"]),\n hours: z.number(),\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n /** When it was made. */\n historyFrom: z.string().nullable(),\n});\nexport type CronUsage = z.infer<typeof CronUsageSchema>;\n\n/** A box's or a volume's share of one day in `days`: what it cost that day, and nothing else. */\nexport const UsageDayItemSchema = z.object({\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n /** Removed by the end of the report's window. */\n removed: z.boolean(),\n cost: z.number(),\n});\nexport type UsageDayItem = z.infer<typeof UsageDayItemSchema>;\n\n/**\n * One UTC day of a `GET /usage?by=day` report (control plane only): its cost, and each box and volume\n * that existed that day with its share, most expensive first. The first and last day are clipped to\n * the window (today ends now). Every day of the window is listed, an empty one included.\n */\nexport const UsageDaySchema = z.object({\n /** `YYYY-MM-DD`, UTC. */\n date: z.string(),\n from: z.string(),\n to: z.string(),\n cost: z.number(),\n currency: z.string(),\n boxes: z.array(UsageDayItemSchema),\n volumes: z.array(UsageDayItemSchema),\n /** Object storage that existed that day (#182); absent on a day without any. */\n storage: z.array(UsageDayItemSchema).optional(),\n /** Cron services that existed that day (#190); absent on a day without any. */\n cron: z.array(UsageDayItemSchema).optional(),\n});\nexport type UsageDay = z.infer<typeof UsageDaySchema>;\n\n/** The longest window `?by=day` takes: a quarter of daily rows. */\nexport const MAX_USAGE_DAYS = 93;\n\nexport const UsageReportSchema = z.object({\n window: z.object({ from: z.string(), to: z.string() }),\n boxes: z.array(BoxUsageSchema),\n /** Absent from a side older than #91. */\n volumes: z.array(VolumeUsageSchema).optional(),\n /**\n * Object storage (#182, control plane only): one row per storage a slug has or had, shaped like a\n * volume's. `volumeHours` are the hours it existed, `volumeGibHours` those of the GiB beyond the\n * included ones, `sizeGib` its whole size. Absent when there is none.\n */\n storage: z.array(VolumeUsageSchema).optional(),\n /** Cron services (#190, control plane only): one row per service a slug has or had. Absent when there is none. */\n cron: z.array(CronUsageSchema).optional(),\n /** With `?by=day` only, oldest day first. */\n days: z.array(UsageDaySchema).optional(),\n totals: z.object({\n seconds: MachineUsageSchema.shape.seconds,\n vcpuHours: z.number(),\n ramGibHours: z.number(),\n diskGibHours: z.number(),\n volumeHours: z.number().optional(),\n volumeGibHours: z.number().optional(),\n /** Boxes, volumes, object storage and cron services together. */\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n }),\n});\nexport type UsageReport = z.infer<typeof UsageReportSchema>;\n\n/**\n * `GET /usage/events?after=<id>&limit=<n>` on a host (#42): the ledger rows after `after`, oldest\n * first, as the control plane pulls them. `next` is the last row's id (the cursor to store), equal\n * to `after` when there was nothing new. Over HTTPS only rows of the caller's realm come back.\n * `ledger` names the host's ledger: row ids are unique only within it, and a new one restarts at 1.\n */\nexport const UsageEventRowSchema = z.object({\n id: z.number().int(),\n boxId: z.string(),\n owner: z.string(),\n name: z.string(),\n at: z.string(),\n state: z.enum([\"running\", \"standby\", \"hibernated\", \"stopped\"]),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n diskGib: z.number().int(),\n by: z.string(),\n});\nexport type UsageEventRow = z.infer<typeof UsageEventRowSchema>;\n\nexport const UsageEventsResponseSchema = z.object({\n ledger: z.string().min(1),\n events: z.array(UsageEventRowSchema),\n next: z.number().int(),\n});\nexport type UsageEventsResponse = z.infer<typeof UsageEventsResponseSchema>;\n\n/**\n * `GET /usage/volume-events?after=<id>&limit=<n>` on a host (#91): the volume ledger, pulled like the\n * box ledger and in the same host ledger (one `ledger` id, its own row ids). A row per create, resize\n * and rm, carrying the size from that moment on.\n */\nexport const VolumeEventRowSchema = z.object({\n id: z.number().int(),\n volumeId: z.string(),\n owner: z.string(),\n name: z.string(),\n at: z.string(),\n sizeGib: z.number().int(),\n by: z.enum([\"create\", \"resize\", \"rm\"]),\n});\nexport type VolumeEventRow = z.infer<typeof VolumeEventRowSchema>;\n\nexport const VolumeEventsResponseSchema = z.object({\n ledger: z.string().min(1),\n events: z.array(VolumeEventRowSchema),\n next: z.number().int(),\n});\nexport type VolumeEventsResponse = z.infer<typeof VolumeEventsResponseSchema>;\n\n/**\n * Why a control plane answer is 402, so a client can tell the caller's own account (go and\n * activate it) from a slug it acted on (an org that is off, a balance at zero). The `error`\n * text stays the message to show. Every 402 a signed-in caller gets carries one; the public wake\n * hook's (`POST /hooks/:id`, routes/hooks.ts) has no caller account to speak of and carries none.\n */\nexport const API_ERROR_CODES = [\"account-inactive\", \"org-inactive\", \"out-of-credit\"] as const;\nexport const ApiErrorCodeSchema = z.enum(API_ERROR_CODES);\nexport type ApiErrorCode = z.infer<typeof ApiErrorCodeSchema>;\n\nexport const ApiErrorSchema = z.object({\n error: z.string(),\n code: ApiErrorCodeSchema.optional(),\n});\nexport type ApiError = z.infer<typeof ApiErrorSchema>;\n\n// ---- control plane (kvbox-cloud) ----\n\n/** Where `kvbox login` goes without a URL, and the control plane's own public URL by default. */\nexport const DEFAULT_CLOUD_URL = \"https://api.kvbox.sh\";\n\n/**\n * Who turned a slug (a user or an org) on: a card on file (`card`, #75) or an admin by hand\n * (`admin`, #74). Until one of them does, the account only logs in and looks: every other route\n * answers 402 (decision \"Signup is email + password… inactive until a card is on file\").\n */\nexport const ACTIVATED_BY = [\"card\", \"admin\"] as const;\nexport const ActivatedBySchema = z.enum(ACTIVATED_BY);\nexport type ActivatedBy = z.infer<typeof ActivatedBySchema>;\n\n/** A user account on the control plane; returned by `GET /me`, `GET /users` (#48). */\nexport const CloudUserSchema = z.object({\n /** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */\n username: z.string(),\n /** Display name, free text (\"Alexandru Ghiura\"). */\n name: z.string(),\n /** Login identity, unique. */\n email: z.string(),\n role: z.enum([\"admin\", \"user\"]),\n createdAt: z.string(),\n /**\n * False until a card is on file or an admin activates the account (#74): then only `/me` and\n * `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and\n * gates nobody, hence the defaults: a newer CLI must still parse its answers.\n */\n active: z.boolean().default(true),\n activatedBy: ActivatedBySchema.nullable().default(null),\n /** When too many wrong passwords locked the account (#161); null when it is not locked. Older control planes omit it. */\n lockedAt: z.string().nullable().default(null),\n});\nexport type CloudUser = z.infer<typeof CloudUserSchema>;\n\n// ---- orgs (plan \"Orgs, slugs and roles\") ----\n\nexport const ORG_ROLES = [\"owner\", \"admin\", \"member\"] as const;\nexport const OrgRoleSchema = z.enum(ORG_ROLES);\nexport type OrgRole = z.infer<typeof OrgRoleSchema>;\n\n/** An org as the API shows it; its slug owns boxes the way a username does. */\nexport const CloudOrgSchema = z.object({\n slug: z.string(),\n /** Display name; the slug never changes, this may. */\n name: z.string(),\n createdAt: z.string(),\n /** 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. */\n active: z.boolean().default(true),\n activatedBy: ActivatedBySchema.nullable().default(null),\n});\nexport type CloudOrg = z.infer<typeof CloudOrgSchema>;\n\n/** One of the caller's orgs with their role in it (`GET /orgs`, `GET /me`). */\nexport const OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });\nexport type OrgMembership = z.infer<typeof OrgMembershipSchema>;\n\nexport const OrgMemberSchema = z.object({\n username: z.string(),\n name: z.string(),\n role: OrgRoleSchema,\n addedAt: z.string(),\n});\nexport type OrgMember = z.infer<typeof OrgMemberSchema>;\n\n/** `GET /orgs/:slug`: the org and its members (members and up see it). */\nexport const OrgDetailSchema = CloudOrgSchema.extend({ members: z.array(OrgMemberSchema) });\nexport type OrgDetail = z.infer<typeof OrgDetailSchema>;\n\n/** `POST /orgs`: the caller becomes the org's owner. */\nexport const CreateOrgRequestSchema = z.object({\n slug: z.string().min(1),\n name: z.string().min(1),\n});\nexport type CreateOrgRequest = z.infer<typeof CreateOrgRequestSchema>;\n\n/** `PATCH /orgs/:slug` (owner): the display name. */\nexport const RenameOrgRequestSchema = z.object({ name: z.string().min(1) });\n\n/** `POST /orgs/:slug/members` (admin, owner): an existing user joins, as a member unless said otherwise. */\nexport const AddMemberRequestSchema = z.object({\n username: z.string().min(1),\n role: OrgRoleSchema.default(\"member\"),\n});\nexport type AddMemberRequest = z.infer<typeof AddMemberRequestSchema>;\n\n/** `PATCH /orgs/:slug/members/:username` (owner). */\nexport const SetRoleRequestSchema = z.object({ role: OrgRoleSchema });\n\n/** `GET /me`: the account plus the orgs it belongs to. */\nexport const MeResponseSchema = CloudUserSchema.extend({ orgs: z.array(OrgMembershipSchema) });\nexport type MeResponse = z.infer<typeof MeResponseSchema>;\n\n// ---- prepaid credit (#76) ----\n\n/**\n * `GET /billing/balance`: what a slug (the caller's own, or `X-Kvbox-Org`'s) has left. `balance` is\n * every top-up, plus promo credit (#163), minus what the usage ledger says its boxes cost since\n * `since`, the slug's first credit (null: it never had any); at or below zero the slug cannot start or\n * create anything (402). `topUps` and `spent` are the paid side of it. `promo` is the part of\n * `balance` that came from redeemed codes and expires: it is spent first, and what is left of it is\n * gone at its date.\n */\nexport const BalanceSchema = z.object({\n slug: z.string(),\n balance: z.number(),\n currency: z.string(),\n topUps: z.number(),\n spent: z.number(),\n /** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */\n since: z.string().nullable(),\n /** 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. */\n suspendedAt: z.string().nullable().default(null),\n /** Promo credit left (#163), already counted in `balance`; 0 with none. Absent from a control plane older than this field. */\n promo: z.number().default(0),\n /** When the next promo credit expires; null with none left. */\n promoExpiresAt: z.string().nullable().default(null),\n});\nexport type Balance = z.infer<typeof BalanceSchema>;\n\n/** `POST /admin/billing/top-ups` (platform admin): give a slug money by hand. */\nexport const TopUpRequestSchema = z.object({\n slug: z.string().min(1),\n /** In the control plane's currency; negative corrects a mistake. */\n amount: z.number().finite(),\n note: z.string().max(200).optional(),\n});\nexport type TopUpRequest = z.infer<typeof TopUpRequestSchema>;\n\n/** One top-up as recorded, answered by `POST /admin/billing/top-ups`. */\nexport const TopUpSchema = z.object({\n id: z.string(),\n slug: z.string(),\n amount: z.number(),\n currency: z.string(),\n /** `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. */\n source: z.enum([\"admin\", \"card\", \"trial\", \"transfer\"]),\n note: z.string().nullable(),\n at: z.string(),\n});\nexport type TopUp = z.infer<typeof TopUpSchema>;\n\n// ---- promo codes (#163) ----\n\n/** `POST /admin/billing/codes` (platform admin): make a code worth `amount` that expires on `expiresAt`. */\nexport const CreateCodeRequestSchema = z.object({\n /** In the control plane's currency, cents at most. */\n amount: z.number().positive().multipleOf(0.01, \"amount is in cents at most\"),\n /** 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. */\n expiresAt: z.string().min(1),\n note: z.string().max(200).optional(),\n});\nexport type CreateCodeRequest = z.infer<typeof CreateCodeRequestSchema>;\n\n/** One promo code as the admin sees it. `status`: `unused` can still be redeemed; the other three cannot. */\nexport const CreditCodeSchema = z.object({\n code: z.string(),\n amount: z.number(),\n currency: z.string(),\n expiresAt: z.string(),\n note: z.string().nullable(),\n status: z.enum([\"unused\", \"redeemed\", \"expired\", \"revoked\"]),\n createdBy: z.string(),\n createdAt: z.string(),\n /** Who redeemed it and the slug the credit went to (their own, or an org they own). */\n redeemedBy: z.string().nullable(),\n redeemedSlug: z.string().nullable(),\n redeemedAt: z.string().nullable(),\n revokedAt: z.string().nullable(),\n});\nexport type CreditCode = z.infer<typeof CreditCodeSchema>;\n\n/** `POST /billing/redeem` body: the code, and the org it is for (one the caller owns) when not their own account. */\nexport const RedeemRequestSchema = z.object({\n code: z.string().min(1).max(64),\n org: z.string().min(1).optional(),\n});\nexport type RedeemRequest = z.infer<typeof RedeemRequestSchema>;\n\n/** `POST /billing/redeem` answer: what the code gave, to which slug, and that slug's balance afterwards. */\nexport const RedeemResponseSchema = z.object({\n slug: z.string(),\n amount: z.number(),\n currency: z.string(),\n expiresAt: z.string(),\n balance: BalanceSchema,\n /** The slug was out of credit and this put it back above zero: it may start boxes again. */\n reinstated: z.boolean(),\n});\nexport type RedeemResponse = z.infer<typeof RedeemResponseSchema>;\n\n// ---- card and credit through Stripe (#93) ----\n\n/** The fixed top-up amounts, in the price list's currency (decision \"Card and credit v1\"): no custom amount. */\nexport const TOP_UP_AMOUNTS = [10, 25, 50, 100] as const;\n\n/**\n * `GET /billing`: the caller's own card and balance. `card` is the card Stripe holds as the customer's\n * default, null until one was saved through `POST /billing/card` and accepted; `cardInUse` says the\n * last card saved was refused because another account had already used it, and no other card is on file.\n */\nexport const BillingInfoSchema = z.object({\n card: z.object({ brand: z.string(), last4: z.string() }).nullable(),\n cardInUse: z.boolean(),\n balance: BalanceSchema,\n});\nexport type BillingInfo = z.infer<typeof BillingInfoSchema>;\n\n/** `POST /billing/card`, `/billing/top-up`, `/billing/portal`: where to send the browser (Stripe's hosted page). */\nexport const BillingRedirectSchema = z.object({ url: z.string() });\nexport type BillingRedirect = z.infer<typeof BillingRedirectSchema>;\n\n/** `POST /billing/top-up` body. */\nexport const TopUpCheckoutRequestSchema = z.object({\n amount: z.literal(TOP_UP_AMOUNTS),\n});\nexport type TopUpCheckoutRequest = z.infer<typeof TopUpCheckoutRequestSchema>;\n\n/** `POST /billing/transfers` body: move `amount` of the caller's credit to `org`, which they own. Cents at most. */\nexport const TransferRequestSchema = z.object({\n org: z.string().min(1),\n amount: z.number().positive().multipleOf(0.01, \"amount is in cents at most\"),\n});\nexport type TransferRequest = z.infer<typeof TransferRequestSchema>;\n\n/** `POST /billing/transfers` answer: both balances afterwards, and whether this transfer turned the org on. */\nexport const TransferResponseSchema = z.object({ from: BalanceSchema, to: BalanceSchema, activated: z.boolean() });\nexport type TransferResponse = z.infer<typeof TransferResponseSchema>;\n\n/** `POST /login` body from `kvbox login` (#48); `publicKey` is the user's SSH key to inject into new boxes. */\nexport const LoginRequestSchema = z.object({\n email: z.string().min(1),\n password: z.string().min(1),\n publicKey: z.string().optional(),\n});\nexport type LoginRequest = z.infer<typeof LoginRequestSchema>;\n\n/** `POST /signup` body from the website: a new account with the `user` role; answers like `/login` (logged in at once). */\nexport const SignupRequestSchema = z.object({\n username: z.string().min(1),\n name: z.string().min(1),\n email: z.string().min(1),\n password: z.string().min(1),\n});\nexport type SignupRequest = z.infer<typeof SignupRequestSchema>;\n\n/**\n * `POST /login` answer: the bearer token the CLI stores (#48). With a `publicKey` in the request,\n * also that key signed by the control plane's SSH CA (#51): the `-cert.pub` text and when it expires (ISO).\n */\nexport const LoginResponseSchema = z.object({\n token: z.string(),\n user: CloudUserSchema,\n sshCert: z.string().optional(),\n sshCertExpires: z.string().optional(),\n /** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */\n sshCertPrincipals: z.array(z.string()).optional(),\n});\nexport type LoginResponse = z.infer<typeof LoginResponseSchema>;\n\n/** `POST /ssh/cert` body: one of the caller's uploaded keys to sign again (#51). */\nexport const SshCertRequestSchema = z.object({\n publicKey: z.string().min(1),\n});\nexport type SshCertRequest = z.infer<typeof SshCertRequestSchema>;\n\n/** `POST /ssh/cert` answer: the certificate text, its expiry (ISO) and its principals. */\nexport const SshCertResponseSchema = z.object({\n cert: z.string(),\n expires: z.string(),\n principals: z.array(z.string()),\n});\nexport type SshCertResponse = z.infer<typeof SshCertResponseSchema>;\n\n/** `GET /ssh/ca` answer: the CA's public key, the line boxes trust after `cert-authority `. */\nexport const SshCaResponseSchema = z.object({\n publicKey: z.string(),\n /** 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. */\n retired: z.array(z.object({ publicKey: z.string(), retiredAt: z.string() })).optional(),\n});\nexport type SshCaResponse = z.infer<typeof SshCaResponseSchema>;\n\n/** `GET /hosts/self/ssh-ca` on the control plane, by the host secret: the CA every box should trust (`kvbox-server trust-ca --from-cloud`, #55). */\nexport const HostSshCaResponseSchema = z.object({\n publicKey: z.string(),\n});\n\n/** `GET /ssh/cloud-ca` on a host's socket: what its control plane says the CA is, with the fingerprint to confirm. */\nexport const CloudCaSchema = z.object({\n controlPlane: z.string(),\n publicKey: z.string(),\n fingerprint: z.string(),\n});\nexport type CloudCa = z.infer<typeof CloudCaSchema>;\n\n/** `POST /ssh/trust-ca` on a host's socket (#55): the CA public key (a pasted `cert-authority …` line is accepted too). */\nexport const TrustCaRequestSchema = z.object({\n publicKey: z.string().min(1),\n});\nexport type TrustCaRequest = z.infer<typeof TrustCaRequestSchema>;\n\n/**\n * When a box's new authorized_keys reach the guest: `now` (pushed through kvbox-agent), or at its\n * next `start` (stopped: kvbox-init writes the file at boot), `wake` (hibernated), `resume`\n * (standby), or `later` (running, but its agent could not take them: the next stop and start).\n */\nexport const SshKeysAppliedSchema = z.enum([\"now\", \"start\", \"wake\", \"resume\", \"later\"]);\nexport type SshKeysApplied = z.infer<typeof SshKeysAppliedSchema>;\n\n/** `POST /ssh/trust-ca` answer: every cloud box on the host, by what happened to it. Boxes are `owner/name`. */\nexport const TrustCaReportSchema = z.object({\n publicKey: z.string(),\n fingerprint: z.string(),\n /** The guest trusts the CA now. */\n updated: z.array(z.string()),\n /** meta.json has the line; the guest gets it at `when`. */\n pending: z.array(z.object({ box: z.string(), when: SshKeysAppliedSchema, why: z.string().optional() })),\n failed: z.array(z.object({ box: z.string(), error: z.string() })),\n /** Local boxes, untouched: they trust the host's key only. */\n local: z.number().int(),\n /** Cloud boxes made without a CA line (a managed service's, #173), untouched: no certificate opens them. Absent from older servers. */\n skipped: z.array(z.string()).optional(),\n});\nexport type TrustCaReport = z.infer<typeof TrustCaReportSchema>;\n\n/** `POST /hosts/join` body from `kvbox-server join` (#18); `fingerprint` is the host's TLS cert sha256, colon-separated. */\nexport const HostJoinRequestSchema = z.object({\n token: z.string().min(1),\n name: z.string().min(1),\n url: z.string().url(),\n fingerprint: z.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),\n publicAddress: z.string().min(1),\n /** Where the host is (`kvbox-server join --country`): a code or an English name. */\n country: z.string().optional(),\n});\nexport type HostJoinRequest = z.infer<typeof HostJoinRequestSchema>;\n\n/** `POST /hosts/join` answer: the secret the control plane will present to the host from now on (#18). */\nexport const HostJoinResponseSchema = z.object({\n hostSecret: z.string(),\n controlPlane: z.object({ name: z.string() }),\n});\nexport type HostJoinResponse = z.infer<typeof HostJoinResponseSchema>;\n\n/** A host as the control plane knows it; returned by `GET /hosts` (admin). */\nexport const CloudHostSchema = z.object({\n name: z.string(),\n url: z.string(),\n publicAddress: z.string(),\n joinedAt: z.string(),\n lastSeenAt: z.string().nullable(),\n capacity: CapacitySchema.nullable(),\n /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */\n country: z.string().nullable(),\n /** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */\n region: z.string().nullable(),\n /** 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. */\n version: z.string().nullable(),\n});\nexport type CloudHost = z.infer<typeof CloudHostSchema>;\n\n/**\n * `GET /admin/hosts/:name/info`: what the control plane knows about a host, and what the host says about\n * itself right now (its `/health`: versions, relay, control plane, last update). `health` is null and\n * `error` says why when the host did not answer.\n */\nexport const HostInfoSchema = z.object({\n host: CloudHostSchema,\n health: HealthSchema.nullable(),\n error: z.string().nullable(),\n});\nexport type HostInfo = z.infer<typeof HostInfoSchema>;\n\n/**\n * `PATCH /admin/hosts/:name`: change what the admin may say about a host; a field left out stays as it\n * is, null clears it. `region` is for storages made from now on: one already made keeps its own.\n */\nexport const HostPatchRequest = z\n .object({ country: z.string().nullable().optional(), region: z.string().nullable().optional() })\n .refine((b) => b.country !== undefined || b.region !== undefined, { message: \"give country, region or both\" });\nexport type HostPatchRequest = z.infer<typeof HostPatchRequest>;\n\n/** `GET /countries`: the countries a new box can be placed in now (a live host there), by name. */\nexport const CountrySchema = z.object({ code: z.string(), name: z.string() });\nexport type Country = z.infer<typeof CountrySchema>;\n","/**\n * SSH public keys as text, for the three places that handle the CA's: the control plane writes a\n * box's `cert-authority` line and prints a fingerprint after `ca rotate`, the host builds the same\n * line for every box at `kvbox-server trust-ca`, the CLI shows the fingerprint before asking.\n */\nimport { createHash } from \"node:crypto\";\nimport { KvboxError } from \"./errors.js\";\n\n/** `<type> <base64>[ <comment>]`, one line; the types OpenSSH signs certificates with. */\nexport const SSH_PUBLIC_KEY_RE =\n /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\\.com|sk-ecdsa-sha2-nistp256@openssh\\.com) ([A-Za-z0-9+/]+=*)(?: [^\\r\\n]*)?$/;\n\n/** The key, trimmed, with a leading `cert-authority ` (a pasted authorized_keys line) allowed and dropped. */\nexport function parseSshPublicKey(text: string): string {\n const key = text.trim().replace(/^cert-authority\\s+/, \"\");\n if (!SSH_PUBLIC_KEY_RE.test(key)) {\n throw new KvboxError(\"that is not an SSH public key; expected one line like: ssh-ed25519 AAAA… kvbox-ca@kvbox.sh\");\n }\n return key;\n}\n\n/** `SHA256:<base64, no padding>` of the key blob, what `ssh-keygen -l` prints. */\nexport function sshKeyFingerprint(publicKey: string): string {\n const m = SSH_PUBLIC_KEY_RE.exec(publicKey.trim());\n if (!m) throw new KvboxError(\"cannot fingerprint: not an SSH public key\");\n return `SHA256:${createHash(\"sha256\").update(Buffer.from(m[2]!, \"base64\")).digest(\"base64\").replace(/=+$/, \"\")}`;\n}\n\n/**\n * A box's authorized_keys line for a CA: trust it, but only for certificates naming `principal`\n * (the box's owner, `<slug>@<realm>`); sshd then ignores the login name and matches `principals=`.\n */\nexport function caLineFor(principal: string, caPublicKey: string): string {\n return `cert-authority,principals=\"${principal}\" ${caPublicKey}`;\n}\n\n/** Whether an authorized_keys line is a CA line (any options, the keyword first). */\nexport const isCaLine = (line: string): boolean => /^cert-authority(,|\\s)/.test(line.trim());\n","/**\n * Client for kvbox-agent, the small service every box runs (kvbox-images, /usr/local/sbin/kvbox-agent).\n * It listens on a vsock port, and Firecracker exposes that as a Unix socket next to the box's API\n * socket: connect, send `CONNECT <port>\\n`, get `OK <n>\\n` back once the guest accepted, then the\n * stream is the guest's. The agent speaks one JSON object per line, one request per connection.\n * Vsock does not touch the box's network, so this works whatever the box did to its own eth0.\n */\nimport { connect } from \"node:net\";\nimport { GuestStatsSchema, type GuestStats } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\n\n/** The vsock port kvbox-agent listens on; fixed in the image. */\nexport const AGENT_PORT = 52;\n\nexport interface Identity {\n name: string;\n ip: string;\n prefixLen: number;\n gateway: string;\n mac: string;\n /** Unix seconds for the guest's clock, which stopped at the snapshot. */\n time: number;\n}\n\ntype AgentReply = { ok: true; [k: string]: unknown } | { ok: false; error: string };\n\n/** One request/reply exchange with the agent behind `udsPath`. Rejects on connection errors, timeout or `ok: false`. */\nexport async function agentCall(udsPath: string, req: Record<string, unknown>, timeoutMs = 5000): Promise<Record<string, unknown>> {\n const reply = await new Promise<string>((resolve, reject) => {\n const sock = connect(udsPath);\n let buf = \"\";\n let handshaken = false;\n const fail = (err: Error) => {\n sock.destroy();\n reject(err);\n };\n // Before `OK` the guest has not taken the connection: its vsock driver may not be up yet (a slow boot).\n sock.setTimeout(timeoutMs, () => fail(new KvboxError(handshaken ? `kvbox-agent did not answer within ${timeoutMs} ms` : `the guest did not accept the vsock connection within ${timeoutMs} ms`)));\n sock.once(\"error\", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));\n sock.once(\"connect\", () => sock.write(`CONNECT ${AGENT_PORT}\\n`));\n sock.on(\"data\", (chunk) => {\n buf += chunk.toString(\"utf8\");\n let nl: number;\n while ((nl = buf.indexOf(\"\\n\")) !== -1) {\n const line = buf.slice(0, nl);\n buf = buf.slice(nl + 1);\n if (!handshaken) {\n if (!line.startsWith(\"OK \")) return fail(new KvboxError(`vsock connect refused: ${line}`));\n handshaken = true;\n sock.write(JSON.stringify(req) + \"\\n\");\n } else {\n sock.end();\n return resolve(line);\n }\n }\n });\n sock.once(\"close\", () => {\n if (!handshaken) fail(new KvboxError(\"vsock connection closed before the guest accepted\"));\n else fail(new KvboxError(\"kvbox-agent closed the connection without a reply\"));\n });\n });\n let parsed: AgentReply;\n try {\n parsed = JSON.parse(reply) as AgentReply;\n } catch {\n throw new KvboxError(`kvbox-agent sent something that is not JSON: ${reply}`);\n }\n if (!parsed.ok) throw new KvboxError(`kvbox-agent: ${parsed.error}`);\n return parsed;\n}\n\nexport function ping(udsPath: string, timeoutMs?: number) {\n return agentCall(udsPath, { op: \"ping\" }, timeoutMs);\n}\n\n/** Tell a restored box who it is now; it renames itself, re-addresses eth0 and sets its clock. */\nexport function setIdentity(udsPath: string, id: Identity, timeoutMs?: number) {\n return agentCall(udsPath, { op: \"identity\", ...id }, timeoutMs);\n}\n\n/**\n * Replace the kvbox user's authorized_keys with exactly these lines (base v0.6.0 and later): a\n * restored or woken box has the file it was frozen with, the host has the current one (#63, #55).\n */\nexport function setAuthorizedKeys(udsPath: string, lines: readonly string[], timeoutMs?: number) {\n return agentCall(udsPath, { op: \"authorizedKeys\", lines: [...lines] }, timeoutMs);\n}\n\n/** The box's own load, memory, disk and uptime (base v0.7.0 and later). */\nexport async function stats(udsPath: string, timeoutMs?: number): Promise<GuestStats> {\n const reply = GuestStatsSchema.safeParse(await agentCall(udsPath, { op: \"stats\" }, timeoutMs));\n if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? \"invalid\"}`);\n return reply.data;\n}\n\n/**\n * Force-unmount every volume the guest still has mounted (base v0.9.0 and later, #52): a box restored\n * from a snapshot has the source box's mounts in memory over empty placeholder disks. Answers the paths.\n */\nexport async function dropVolumes(udsPath: string, timeoutMs?: number): Promise<string[]> {\n const reply = await agentCall(udsPath, { op: \"dropVolumes\" }, timeoutMs);\n return Array.isArray(reply[\"dropped\"]) ? reply[\"dropped\"].map(String) : [];\n}\n\n/**\n * Replace the box owner's environment variables (base v0.10.0 and later, #88): the agent writes\n * /etc/kvbox/env and ~/.ssh/environment and restarts kvbox-app when the list changed.\n */\nexport function setEnv(udsPath: string, vars: readonly { name: string; value: string }[], timeoutMs?: number) {\n return agentCall(udsPath, { op: \"env\", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);\n}\n\n/**\n * Whether the box is idle by its own check (#102, base v0.12.0 and later): the agent runs `script` (at\n * most 10 s), exit 0 = idle. Rejects when the script fails to run or an older agent does not know the request.\n */\nexport async function idle(udsPath: string, script: string, timeoutMs = 15_000): Promise<boolean> {\n return (await agentCall(udsPath, { op: \"idle\", path: script }, timeoutMs))[\"idle\"] === true;\n}\n\n/**\n * Run a script the box's image names in its image.json (#173, base v0.14.0 and later): `input` is its\n * stdin as one JSON line, the JSON it prints is the answer. The agent gives it 30 s.\n */\nexport async function runScript(udsPath: string, path: string, input: unknown, timeoutMs = 35_000): Promise<unknown> {\n return (await agentCall(udsPath, { op: \"script\", path, input: input ?? null }, timeoutMs))[\"output\"];\n}\n\n/** An agent from an image older than the request it was sent. */\nexport interface AgentRun {\n state: \"running\" | \"exited\" | \"timeout\" | \"unknown\";\n exitCode?: number;\n}\n\n/**\n * Start a command of the box owner's and leave it running (#190, base v0.15.0 and later): the agent\n * makes it a systemd unit of the box's user and answers at once. False: a run of this id was already there.\n */\nexport async function startRun(udsPath: string, id: string, command: string, timeoutSec: number, timeoutMs = 15_000): Promise<boolean> {\n return (await agentCall(udsPath, { op: \"run\", id, command, timeoutSec }, timeoutMs))[\"started\"] === true;\n}\n\n/** How a run started with `startRun` stands; `unknown` for one the box does not have (any more: a reboot forgets them). */\nexport async function runStatus(udsPath: string, id: string, timeoutMs?: number): Promise<AgentRun> {\n const reply = await agentCall(udsPath, { op: \"runStatus\", id }, timeoutMs);\n const state = reply[\"state\"];\n if (state !== \"running\" && state !== \"exited\" && state !== \"timeout\" && state !== \"unknown\") throw new KvboxError(\"kvbox-agent sent a run state this server does not know\");\n return { state, ...(typeof reply[\"exitCode\"] === \"number\" ? { exitCode: reply[\"exitCode\"] } : {}) };\n}\n\nexport const isUnknownOp = (err: unknown): boolean => /unknown op/.test((err as Error).message ?? \"\");\n\n/** The guest is still booting (its vsock driver not up yet): a box that is running but cannot be asked anything yet. */\nexport const isGuestBooting = (err: unknown): boolean => /did not accept the vsock connection/.test((err as Error).message ?? \"\");\n\n/**\n * Nothing in the guest took the connection: an image older than kvbox-agent itself (before base\n * v0.5.0), so no vsock listener, a box booted without the vsock socket, or a guest still booting\n * (`isGuestBooting`, which a caller may want to tell apart: a wait for the agent retries on it,\n * `machineStats` reports it).\n */\nexport const isNoAgent = (err: unknown): boolean =>\n /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test((err as Error).message ?? \"\");\n","/**\n * Environment variables (#88). The control plane owns each slug's list and sends this host the whole\n * of it after every change (`POST /env`) and again from its sweep when the host's `version` lags; the\n * host keeps it per owner in env/<owner>.json (mode 600, values in the clear: the host admin can read\n * every box's disk and memory anyway, decision \"Env vars belong to a slug…\"). Every box of that owner\n * gets the list from core/machines.ts when it boots or is restored, through kvbox-agent's `env` request.\n * A running box is not touched: a change applies at its next start.\n */\nimport { existsSync } from \"node:fs\";\nimport { copyFile, mkdir, readFile, readdir, rename, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport type { EnvVar, HostEnvRequest, HostEnvVersions } from \"@kvbox/shared/api\";\nimport { ENV_MAX_VARS, envNameProblem, envValueProblem } from \"@kvbox/shared/env\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { withBoxLock, withHostLock } from \"./locks.js\";\nimport { inScope, OWNER_RE, realmOf, shown, type BoxRef, type ListScope } from \"./refs.js\";\nimport { log } from \"./log.js\";\n\nconst OwnerEnvSchema = z.object({\n /** The control plane's counter for the list; only ever grows. */\n version: z.number().int().min(0),\n vars: z.array(z.object({ name: z.string(), value: z.string() })),\n});\nexport type OwnerEnv = z.infer<typeof OwnerEnvSchema>;\n\n/** The owner's list, or null when the control plane never sent one (a local owner always). */\nexport async function readOwnerEnv(owner: string, p: Paths = paths()): Promise<OwnerEnv | null> {\n try {\n return OwnerEnvSchema.parse(JSON.parse(await readFile(p.ownerEnv(owner), \"utf8\")));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw err;\n }\n}\n\n/**\n * What a box of `owner` is handed when it boots or is restored: the owner's list, or an empty one for a\n * cloud owner the control plane never sent a list for, so a box forked from another slug's box does\n * not keep that slug's files (the agent replaces both with the empty list). Null only for a local\n * owner's box that never had variables of its own; once it had some (env.json exists, even emptied by\n * `env rm`), an empty list, so the guest drops what it was given last.\n */\nexport async function envForBoot(box: BoxRef, p: Paths = paths()): Promise<OwnerEnv[\"vars\"] | null> {\n const env = await readOwnerEnv(box.owner, p).catch(() => null);\n const own = await readBoxEnv(box, p).catch((err: Error) => {\n log.warn(`box ${shown(box)}: its own variables are unreadable, it boots without them: ${err.message}`);\n return [];\n });\n const slug = env?.vars ?? (realmOf(box.owner) !== null ? [] : null);\n if (own.length === 0) return slug ?? (existsSync(p.machine(box.owner, box.name).env) ? [] : null);\n // The box's own win over its owner's (#87): one list, the agent writes it as given.\n const mine = new Set(own.map((v) => v.name));\n return [...(slug ?? []).filter((v) => !mine.has(v.name)), ...own.map((v) => ({ name: v.name, value: v.value }))];\n}\n\n/**\n * A box's own variables (#87): machines/<owner>/<box>/env.json, mode 600, beside a meta.json that stays\n * free of them (meta.json is 0644 and read everywhere). Set at `new -e`, changed by `kvbox env --box`,\n * copied by a snapshot or a fork, gone with the box's dir.\n */\nconst BoxEnvFileSchema = z.object({\n vars: z.array(z.object({ name: z.string(), value: z.string(), secret: z.boolean(), updatedAt: z.string() })),\n});\nexport type BoxVar = z.infer<typeof BoxEnvFileSchema>[\"vars\"][number];\n\nexport async function readBoxEnv(box: BoxRef, p: Paths = paths()): Promise<BoxVar[]> {\n return readBoxEnvFile(p.machine(box.owner, box.name).env);\n}\n\n/** An env.json by its path (a box's or a snapshot's); none is no variables. */\nexport async function readBoxEnvFile(file: string): Promise<BoxVar[]> {\n try {\n return BoxEnvFileSchema.parse(JSON.parse(await readFile(file, \"utf8\"))).vars;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n}\n\n/** The checks `writeBoxEnv` makes, for a caller that must know a list will land before it changes anything. */\nexport function checkBoxEnv(vars: readonly BoxVar[]): void {\n if (vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);\n const seen = new Set<string>();\n for (const v of vars) {\n const problem = envNameProblem(v.name) ?? envValueProblem(v.value);\n if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);\n if (seen.has(v.name)) throw new KvboxError(`${v.name} is given twice`);\n seen.add(v.name);\n }\n}\n\n/** Checked like the owner's list, so a list the guest would refuse never lands. */\nexport async function writeBoxEnv(box: BoxRef, vars: readonly BoxVar[], p: Paths = paths()): Promise<void> {\n checkBoxEnv(vars);\n const file = p.machine(box.owner, box.name).env;\n const tmp = `${file}.tmp`;\n await writeFile(tmp, JSON.stringify({ vars }, null, 2) + \"\\n\", { mode: 0o600 });\n await rename(tmp, file);\n}\n\n/** `given` over the box's variables, each written as not secret: `new --from <snapshot> -e …`. */\nexport async function mergeBoxEnv(box: BoxRef, given: readonly { name: string; value: string }[], p: Paths = paths()): Promise<void> {\n const names = new Set(given.map((v) => v.name));\n const now = new Date().toISOString();\n const kept = (await readBoxEnv(box, p)).filter((v) => !names.has(v.name));\n await writeBoxEnv(box, [...kept, ...given.map((v) => ({ ...v, secret: false, updatedAt: now }))], p);\n}\n\n/** A snapshot or a fork takes its source's variables with it (#87). Nothing to copy: nothing happens. */\nexport async function copyBoxEnv(from: string, to: string): Promise<void> {\n if (!existsSync(from)) return;\n await copyFile(from, to);\n}\n\n/** What `GET /machines/:name/env` answers: the box's own variables, secrets without their value. */\nexport function shownBoxEnv(vars: readonly BoxVar[]): EnvVar[] {\n return vars.map((v) => ({ name: v.name, ...(v.secret ? {} : { value: v.value }), secret: v.secret, updatedAt: v.updatedAt }));\n}\n\n/** `kvbox env set NAME VALUE --box`: add or change one of the box's own variables. Applies at its next start. */\nexport async function setBoxVar(box: BoxRef, name: string, value: string, secret: boolean, p: Paths = paths()): Promise<void> {\n await withBoxLock(box, async () => {\n if (!existsSync(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);\n const vars = (await readBoxEnv(box, p)).filter((v) => v.name !== name);\n await writeBoxEnv(box, [...vars, { name, value, secret, updatedAt: new Date().toISOString() }], p);\n });\n}\n\n/** `kvbox env rm NAME --box`. A name the box does not have is an error, as for the owner's list. */\nexport async function rmBoxVar(box: BoxRef, name: string, p: Paths = paths()): Promise<void> {\n await withBoxLock(box, async () => {\n if (!existsSync(p.machine(box.owner, box.name).meta)) throw new NotFoundError(`box ${shown(box)}`);\n const vars = await readBoxEnv(box, p);\n if (!vars.some((v) => v.name === name)) throw new NotFoundError(`variable ${name} on box ${shown(box)}`);\n await writeBoxEnv(box, vars.filter((v) => v.name !== name), p);\n });\n}\n\n/**\n * Keep `req` as the owner's list unless the host already holds a newer one (two changes whose pushes\n * crossed). Answers the version the host holds now. Checked like at the control plane, so a list the\n * guest would refuse never lands here.\n */\nexport async function setOwnerEnv(owner: string, req: HostEnvRequest, p: Paths = paths()): Promise<{ version: number }> {\n if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner \"${owner}\"`);\n if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);\n const seen = new Set<string>();\n for (const v of req.vars) {\n const problem = envNameProblem(v.name) ?? envValueProblem(v.value);\n if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);\n if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);\n seen.add(v.name);\n }\n return withHostLock(\"env\", async () => {\n const have = await readOwnerEnv(owner, p);\n if (have !== null && have.version > req.version) return { version: have.version };\n const file = p.ownerEnv(owner);\n await mkdir(p.env, { recursive: true, mode: 0o700 });\n const tmp = `${file}.tmp`;\n await writeFile(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + \"\\n\", { mode: 0o600 });\n await rename(tmp, file);\n return { version: req.version };\n });\n}\n\n/** Which version this host holds for each owner in `scope`: what the control plane's sweep compares. */\nexport async function listEnvVersions(scope: ListScope, p: Paths = paths()): Promise<HostEnvVersions> {\n let files: string[];\n try {\n files = await readdir(p.env);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n const out: HostEnvVersions = [];\n for (const file of files.filter((f) => f.endsWith(\".json\")).sort()) {\n const owner = file.slice(0, -\".json\".length);\n if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;\n const env = await readOwnerEnv(owner, p).catch(() => null);\n if (env !== null) out.push({ owner, version: env.version });\n }\n return out;\n}\n","/**\n * Environment variables (#88): a slug's list (a user's or an org's), which every box of that slug gets\n * at boot. The rules live here so the CLI, the control plane and the host refuse the same things.\n * Inside the box kvbox-agent writes them to `/etc/kvbox/env` (systemd's EnvironmentFile=) and to the\n * kvbox user's `~/.ssh/environment` (sshd): both take any single line literally, so the only rule on a\n * value is that it is one line.\n */\n\n/** A name a shell, systemd and sshd all take: letters, digits and `_`, not starting with a digit. */\nexport const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Names that would break every shell or login in the box; `KVBOX_*` is kept for kvbox itself. */\nexport const ENV_RESERVED = [\"PATH\", \"HOME\", \"USER\", \"SHELL\"] as const;\n\nexport const ENV_MAX_VALUE_BYTES = 4096;\nexport const ENV_MAX_VARS = 100;\n\nexport function envNameProblem(name: string): string | null {\n if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;\n if ((ENV_RESERVED as readonly string[]).includes(name)) return `${name} is the box's own and cannot be set`;\n if (name.startsWith(\"KVBOX_\")) return `${name}: names starting with KVBOX_ are kept for kvbox`;\n return null;\n}\n\nexport function envValueProblem(value: string): string | null {\n if (/[\\n\\r\\0]/.test(value)) return \"a value is one line: no line breaks (base64 a multi-line value such as a key file)\";\n if (Buffer.byteLength(value, \"utf8\") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;\n return null;\n}\n","/**\n * One operation on a box at a time (#64). Every change to a box (its meta.json, its Firecracker process,\n * its memory image) runs under the box's lock, so a background job such as core/idle.ts cannot step into\n * a caller's snapshot, and two read-modify-writes of meta.json cannot lose each other's change.\n * In-process only: the server is the only writer. Reentrant, so an operation that calls another one on\n * the same box (rescale -> start) does not wait on itself.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { refKey, type BoxRef } from \"./refs.js\";\n\n/** box -> the promise the next caller waits on (resolved when the current holder and every earlier waiter are done). */\nconst tails = new Map<string, Promise<void>>();\n/** The boxes the current async call chain already holds. */\nconst held = new AsyncLocalStorage<ReadonlySet<string>>();\n\nexport function withBoxLock<T>(ref: BoxRef, fn: () => Promise<T>): Promise<T> {\n return withLock(refKey(ref), fn);\n}\n\n/**\n * A snapshot's files (#83): a restore reads them while it holds this, so a replace or an rm never swaps\n * or removes them under it. The key's prefix keeps it apart from the box of the same owner/name.\n */\nexport function withSnapshotLock<T>(ref: BoxRef, fn: () => Promise<T>): Promise<T> {\n return withLock(`snapshot:${refKey(ref)}`, fn);\n}\n\n/**\n * A lock for something the whole host shares rather than one box: `ports` guards drawing public\n * ports (#30), which reads every box's meta.json; `volumes` guards which box holds a volume (#52),\n * decided by reading every box's meta.json too, and a volume's files; `env` guards the owners' env files\n * (#88). The key has no '/', so it\n * never meets a box's. Take it inside a box lock, never the other way round, and only around the\n * check and the write it protects: never across a box's restart.\n */\nexport function withHostLock<T>(name: \"ports\" | \"volumes\" | \"env\", fn: () => Promise<T>): Promise<T> {\n return withLock(`host:${name}`, fn);\n}\n\nasync function withLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const mine = held.getStore();\n if (mine?.has(key)) return fn();\n const previous = tails.get(key);\n let release!: () => void;\n const tail = new Promise<void>((resolve) => (release = resolve));\n tails.set(key, tail);\n try {\n await previous;\n return await held.run(new Set([...(mine ?? []), key]), fn);\n } finally {\n release();\n if (tails.get(key) === tail) tails.delete(key);\n }\n}\n\n/** Whether something holds or waits for the box's lock right now. */\nexport function boxBusy(ref: BoxRef): boolean {\n return tails.has(refKey(ref));\n}\n\n/** `fn` with the lock of the box named by its first argument taken around every call. */\nexport function locked<A extends [BoxRef, ...unknown[]], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R> {\n return (...args) => withBoxLock(args[0], () => fn(...args));\n}\n","/**\n * The daemon's log: one line per event, `[time][level]: message`. info goes to stdout, the rest to\n * stderr; under the systemd unit install-server.sh writes, both land in $KVBOX_HOME/server.log.\n * Only `kvbox-server start` logs this way: the one-off subcommands (join, leave, relay, net) print\n * plain text for the terminal, since the CLI relays it to the user.\n */\nexport type Level = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport function formatLine(level: Level, message: string, at: Date = new Date()): string {\n return `[${at.toISOString()}][${level}]: ${message}`;\n}\n\nexport const log = {\n debug(message: string): void {\n console.error(formatLine(\"debug\", message));\n },\n info(message: string): void {\n console.log(formatLine(\"info\", message));\n },\n warn(message: string): void {\n console.error(formatLine(\"warn\", message));\n },\n error(message: string): void {\n console.error(formatLine(\"error\", message));\n },\n};\n","/**\n * Images (#87). A box boots from one read-only image and stacks its own disk on it. The base image is\n * assets/rootfs-<version>.ext4 with assets/rootfs.ext4 the symlink to the one `new` uses; every other\n * image (`postgres`) is assets/images/<image>/rootfs-<version>.ext4 with rootfs.ext4 there its symlink,\n * all put in place by install-server.sh. A box's meta.json names its image (absent: the base) and that\n * image's version; `vm update` moves it to the current version of the same image, never to another.\n *\n * An image may carry /etc/kvbox/image.json, read here with debugfs (no mount): the variables it wants\n * with their defaults, which of them the host generates when the caller gave none, and how to reach what\n * it serves. The host knows nothing else about any image (decision \"A box's own env vars…\").\n */\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { readdir, realpath } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport { z } from \"zod\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { parseDuration } from \"@kvbox/shared/duration\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport type { Config } from \"./config.js\";\nimport { run } from \"./exec.js\";\n\nexport const BASE_IMAGE = \"base\";\n\n/** An image name, as `--base` takes it and as its directory is named. */\nconst IMAGE_RE = /^[a-z][a-z0-9-]{0,30}$/;\n\n/** `assets/…/rootfs-<version>.ext4` -> `<version>`; anything else is not an installed image. */\nexport function baseVersionOf(file: string): string {\n const m = /^rootfs-(.+)\\.ext4$/.exec(basename(file));\n if (!m) throw new KvboxError(`base image ${file} is not versioned (expected assets/rootfs-<version>.ext4); run install-server.sh`);\n return m[1]!;\n}\n\n/** `undefined` and `base` both mean the base image; meta.json stores the base as absent. */\nexport function imageKey(image: string | undefined): string | undefined {\n return image === undefined || image === BASE_IMAGE ? undefined : image;\n}\n\n/** What an image is called in messages. */\nexport const imageLabel = (image: string | undefined) => (imageKey(image) === undefined ? \"base image\" : `image ${image}`);\n\n/** The file of `image` at `version`. */\nexport function imageFile(image: string | undefined, version: string, p: Paths): string {\n const key = imageKey(image);\n return key === undefined ? p.baseImage(version) : p.image(key).version(version);\n}\n\n/** The image a box (or snapshot) stacks on, refused when install-server.sh has since removed it. */\nexport function imageFileFor(meta: { name: string; base: string; image?: string | undefined }, p: Paths): string {\n const file = imageFile(meta.image, meta.base, p);\n if (!existsSync(file)) throw new KvboxError(`box ${meta.name} runs on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);\n return file;\n}\n\n/** Follow an image's symlink to the version a new box gets. */\nexport async function currentImage(image: string | undefined, cfg: Config, p: Paths): Promise<{ version: string; file: string }> {\n const key = imageKey(image);\n if (key !== undefined && !IMAGE_RE.test(key)) throw new KvboxError(`invalid image name \"${image}\"`);\n const link = key === undefined ? cfg.rootfs : p.image(key).rootfs;\n if (key !== undefined && !existsSync(link)) {\n const have = (await listImages(cfg, p)).map((i) => i.name).join(\", \");\n throw new KvboxError(`this host has no image ${key} (it has: ${have}); install-server.sh with IMAGES=\"${key}:<version>\" adds it`);\n }\n const file = await realpath(link);\n const version = baseVersionOf(file);\n const expected = imageFile(key, version, p);\n if (file !== expected) throw new KvboxError(`${imageLabel(key)} ${link} points outside its directory (${file})`);\n return { version, file };\n}\n\n/** Every image a new box can be made from here, base first: what `/capacity` reports to the control plane. */\nexport async function listImages(cfg: Config, p: Paths = paths()): Promise<{ name: string; version: string }[]> {\n const out: { name: string; version: string }[] = [];\n // The version a symlink names, when `currentImage` would take it: inside the image's own directory.\n const versionAt = async (image: string | undefined, link: string) => {\n const file = await realpath(link);\n const version = baseVersionOf(file);\n if (file !== imageFile(image, version, p)) throw new Error(\"outside its directory\");\n return version;\n };\n try {\n out.push({ name: BASE_IMAGE, version: await versionAt(undefined, cfg.rootfs) });\n } catch {\n // no base image yet: a host mid-install; `new` says so itself\n }\n let names: string[] = [];\n try {\n names = (await readdir(p.images)).sort();\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n for (const name of names) {\n if (!IMAGE_RE.test(name) || name === BASE_IMAGE) continue;\n try {\n out.push({ name, version: await versionAt(name, p.image(name).rootfs) });\n } catch {\n // a dir without a current version, or one pointing elsewhere: not an image `new` can use\n }\n }\n return out;\n}\n\nconst overlayCapable = new Map<string, boolean>();\n\n/** An image without /sbin/overlay-init (not built by kvbox-images) would panic at boot. debugfs reads the ext4 without mounting it. */\nexport async function assertOverlayCapable(file: string, image: string | undefined, version: string): Promise<void> {\n let ok = overlayCapable.get(file);\n if (ok === undefined) {\n const { stdout } = await run([\"debugfs\", \"-R\", \"stat /sbin/overlay-init\", file]);\n ok = /Type:\\s+regular/.test(stdout);\n overlayCapable.set(file, ok);\n }\n if (!ok) throw new KvboxError(`${imageLabel(image)} ${version} is not a kvbox image (no /sbin/overlay-init); rerun install-server.sh`);\n}\n\n/** /etc/kvbox/image.json. Every field is optional; the base image has no file at all. */\nexport const ImageManifestSchema = z.object({\n /**\n * false: a new box of this image does not auto-hibernate unless asked (nothing wakes it on a TCP connection).\n * A duration (`\"10m\"`, #102): a new box's idle time unless the caller gave one, instead of the host's default.\n */\n autoHibernate: z.union([z.boolean(), z.string().refine((s) => parseDuration(s) !== undefined, \"a duration like 10m, 4h or 1d\")]).optional(),\n /**\n * A script inside the box that says whether it is idle (#102), exit 0 = idle: a new box's `idleCheck`\n * (meta.json), which auto-hibernate asks through kvbox-agent instead of watching the traffic.\n */\n idle: z.string().optional(),\n /** Variables the box gets unless the caller or its owner set them; a value may name an earlier one, or a generated one, as `${NAME}`. */\n env: z.record(z.string(), z.string()).optional(),\n /** Variables the host fills with a random password when the caller gave none. */\n generate: z.array(z.string()).optional(),\n /** How to reach what the box serves, `${NAME}` taken from its variables and `${BOX}` its name. */\n connect: z.string().optional(),\n /**\n * Scripts in the box the host may run by name through kvbox-agent (#173): `status`, `password`, …\n * The host knows the names only; what each does and answers is the image's.\n */\n scripts: z.record(z.string(), z.string().startsWith(\"/\")).optional(),\n});\nexport type ImageManifest = z.infer<typeof ImageManifestSchema>;\n\nconst manifests = new Map<string, ImageManifest>();\n\n/** The image's manifest, `{}` when it has none. An image file never changes under its name, so it is read once. */\nexport async function imageManifest(file: string): Promise<ImageManifest> {\n const cached = manifests.get(file);\n if (cached !== undefined) return cached;\n // debugfs prints the file to stdout, or nothing (and a message on stderr) when it is not there.\n const { stdout } = await run([\"debugfs\", \"-R\", \"cat /etc/kvbox/image.json\", file]);\n let manifest: ImageManifest = {};\n if (stdout.trim() !== \"\") {\n try {\n manifest = ImageManifestSchema.parse(JSON.parse(stdout));\n } catch (err) {\n throw new KvboxError(`${file}: /etc/kvbox/image.json is not a valid image manifest: ${(err as Error).message}`);\n }\n }\n manifests.set(file, manifest);\n return manifest;\n}\n\n/** `${NAME}` from `vars`; a name that is not there expands to nothing. */\nexport function expand(text: string, vars: ReadonlyMap<string, string>): string {\n return text.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (_, name: string) => vars.get(name) ?? \"\");\n}\n\n/** 24 characters a connection string takes without escaping. */\nexport function generatedSecret(): string {\n return randomBytes(18).toString(\"base64url\");\n}\n\n/**\n * A new box's own variables: the caller's, plus the image's generated secrets and defaults for the\n * ones the caller left out, and the image's `connect` line filled in. `generated` names the variables\n * the host made up. Secrets are made first, so a default can name one (`${POSTGRES_PASSWORD}`), and a\n * default can name an earlier default. `inherited` is the owner's list: a name it has is left to it\n * (and a default may name it), since the box's own variables win over the owner's at boot.\n * `secrets` names what the box keeps as secrets: the generated ones and any default made from one or\n * from an owner's variable. `connect` never holds an owner's value (it may be a secret, which no route\n * answers with): it keeps `${NAME}` for it.\n */\nexport function imageEnv(\n manifest: ImageManifest,\n box: string,\n given: readonly { name: string; value: string }[],\n inherited: readonly { name: string; value: string }[] = [],\n) {\n const vars = new Map([...inherited, ...given].map((v) => [v.name, v.value]));\n const givenNames = new Set(given.map((v) => v.name));\n /** Names whose value is, or is made from, an owner's variable. */\n const owners = new Set(inherited.map((v) => v.name).filter((n) => !givenNames.has(n)));\n const defaults = manifest.env ?? {};\n const added: { name: string; value: string }[] = [];\n const generated: string[] = [];\n for (const name of manifest.generate ?? []) {\n if (vars.has(name) || name in defaults) continue;\n const v = generatedSecret();\n vars.set(name, v);\n added.push({ name, value: v });\n generated.push(name);\n }\n const secrets = new Set<string>();\n for (const [name, value] of Object.entries(defaults)) {\n if (vars.has(name)) continue;\n const v = expand(value, vars);\n vars.set(name, v);\n added.push({ name, value: v });\n const from = namesIn(value);\n if (from.some((n) => owners.has(n))) owners.add(name);\n if (from.some((n) => owners.has(n) || generated.includes(n) || secrets.has(n))) secrets.add(name);\n }\n // A URL's user, password and path take a value only percent-encoded (`p@ss/1` would end the userinfo).\n const encode = manifest.connect !== undefined && /^[a-z][a-z0-9+.-]*:\\/\\//i.test(manifest.connect);\n const connectVars = new Map([...vars].map(([k, v]) => [k, owners.has(k) ? `\\${${k}}` : encode ? encodeURIComponent(v) : v]));\n connectVars.set(\"BOX\", box);\n const connect = manifest.connect === undefined ? undefined : expand(manifest.connect, connectVars);\n return { vars: [...given, ...added], generated, secrets: [...generated, ...secrets], connect };\n}\n\n/** What hides a secret in a box's `url`. */\nexport const MASK = \"****\";\n\n/**\n * The box's `url` (#87): the image's `connect` line with every secret masked, kept in meta.json and shown by\n * `kvbox get` long after `new` printed the real one. A secret is a variable kept as one or one the image\n * generates (a `-e` password included); a name the box does not have (an owner's) and `${BOX}` stay as\n * `${NAME}`, the box's name filled in when it is shown (a fork or a restore has another).\n */\nexport function maskedUrl(manifest: ImageManifest, vars: readonly { name: string; value: string; secret: boolean }[]): string | undefined {\n if (manifest.connect === undefined) return undefined;\n const encode = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(manifest.connect);\n const generated = new Set(manifest.generate ?? []);\n const shown = new Map(vars.map((v) => [v.name, v.secret || generated.has(v.name) ? MASK : encode ? encodeURIComponent(v.value) : v.value]));\n return manifest.connect.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (all, name: string) => (name === \"BOX\" ? all : (shown.get(name) ?? all)));\n}\n\n/** A stored `url` for box `name`. */\nexport const urlFor = (url: string, name: string) => url.replaceAll(\"${BOX}\", name);\n\n/** The `${NAME}`s a manifest value names. */\nfunction namesIn(text: string): string[] {\n return [...text.matchAll(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g)].map((m) => m[1]!);\n}\n","/**\n * The one shell-out helper. Every `firecracker`, `ip`, `ssh`, `cp` call goes\n * through here: argv arrays only (never a shell string), the command is logged,\n * and stderr ends up in the thrown error.\n */\nimport { execFile, spawn } from \"node:child_process\";\nimport { openSync } from \"node:fs\";\nimport { promisify } from \"node:util\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { log } from \"./log.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface RunOptions {\n sudo?: boolean;\n cwd?: string;\n timeoutMs?: number;\n env?: NodeJS.ProcessEnv;\n /** Non-zero exit codes that are not failures (e2fsck: 1 = \"errors corrected\"). */\n okExitCodes?: readonly number[];\n}\n\nexport interface RunResult {\n stdout: string;\n stderr: string;\n}\n\nexport async function run(argv: readonly string[], opts: RunOptions = {}): Promise<RunResult> {\n const [cmd, ...args] = opts.sudo ? [\"sudo\", \"-n\", ...argv] : argv;\n if (!cmd) throw new KvboxError(\"run: empty argv\");\n if (process.env[\"KVBOX_DEBUG\"]) log.debug(`exec ${[cmd, ...args].join(\" \")}`);\n try {\n const { stdout, stderr } = await execFileAsync(cmd, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n timeout: opts.timeoutMs ?? 30_000,\n maxBuffer: 8 * 1024 * 1024,\n });\n return { stdout, stderr };\n } catch (err) {\n const e = err as NodeJS.ErrnoException & { stdout?: string; stderr?: string; code?: number | string };\n if (typeof e.code === \"number\" && opts.okExitCodes?.includes(e.code)) return { stdout: e.stdout ?? \"\", stderr: e.stderr ?? \"\" };\n const detail = (e.stderr ?? e.message ?? \"\").trim();\n throw new KvboxError(`${[cmd, ...args].join(\" \")} failed${detail ? `: ${detail}` : \"\"}`);\n }\n}\n\n/**\n * Start a command that must outlive this process (the self-update, which stops and restarts the daemon):\n * argv only, its own session, stdout and stderr appended to `logFile`. Returns once it is spawned, with its pid.\n */\nexport function spawnDetached(argv: readonly string[], logFile: string, env: NodeJS.ProcessEnv = process.env): Promise<number> {\n const [cmd, ...args] = argv;\n if (!cmd) throw new KvboxError(\"spawnDetached: empty argv\");\n const out = openSync(logFile, \"a\");\n const child = spawn(cmd, args, { detached: true, stdio: [\"ignore\", out, out], env });\n return new Promise((resolve, reject) => {\n child.once(\"error\", (err) => reject(new KvboxError(`${cmd} could not start: ${err.message}`)));\n child.once(\"spawn\", () => {\n child.unref();\n resolve(child.pid ?? -1);\n });\n });\n}\n","/**\n * Volumes (#52): a disk of its own under volumes/<owner>/<name>, a sparse ext4 the guest sees whole,\n * created apart from any box and attached to one box at a time (ext4 is a one-machine filesystem; two\n * guests writing one disk corrupt it). Attaching is the box's business (core/machines.ts: it changes\n * the box's drives, so a running box restarts); this module owns the volume's files and what a box's\n * drives look like. Decision \"A snapshot captures the box, never its volume\".\n */\nimport { existsSync, statSync } from \"node:fs\";\nimport { lstat, mkdir, readdir, rm, statfs, symlink, truncate, writeFile } from \"node:fs/promises\";\nimport { MAX_VOLUME_GIB, VOLUME_NAME_RE, VOLUME_NAME_RULE, type DiskCapacity, type Volume } from \"@kvbox/shared/api\";\nimport { hasDiskRoom, volumeRoomGib } from \"@kvbox/shared/capacity\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { paths, volumeDriveRel, volumeMountPath, type Paths } from \"@kvbox/shared/paths\";\nimport type { VolumeLedgerRow } from \"@kvbox/shared/usage\";\nimport { loadConfig } from \"./config.js\";\nimport { insertVolumeEvent } from \"./db.js\";\nimport { run } from \"./exec.js\";\nimport { withHostLock } from \"./locks.js\";\nimport { inScope, parseRef, shown, type BoxRef, type ListScope } from \"./refs.js\";\nimport { listMachineRefs, listVolumeRefs, newBoxId, readMachineMeta, readVolumeMeta, writeVolumeMeta, type MachineMeta, type VolumeMeta } from \"./state.js\";\nimport { log } from \"./log.js\";\n\n/** The ext4 label the image's kvbox-volumes.service mounts by: 16 bytes at most, hence the short prefix and the 12-char names. */\nexport const volumeLabel = (name: string) => `kv:${name}`;\n\nexport interface VolumeDrive {\n name: string;\n sizeGib: number;\n}\n\n/** What a volume is, from its files; `attachedTo` is looked up in the boxes' meta.json. */\nfunction toVolume(meta: VolumeMeta, attachedTo: string | null, p: Paths): Volume {\n let usedBytes = 0;\n try {\n usedBytes = statSync(p.volume(meta.owner, meta.name).disk).blocks * 512;\n } catch {\n /* a volume whose disk is gone shows as empty */\n }\n return { id: meta.id, name: meta.name, owner: meta.owner, sizeGib: meta.sizeGib, usedBytes, attachedTo, createdAt: meta.createdAt };\n}\n\n/** Append to the volume ledger (core/db.ts, #91). Bookkeeping never fails the operation it records. */\nfunction recordVolume(meta: VolumeMeta, by: VolumeLedgerRow[\"by\"], p: Paths, at = new Date().toISOString()): void {\n try {\n insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at, sizeGib: meta.sizeGib, by }, p);\n } catch (err) {\n log.warn(`volume ledger: ${(err as Error).message}`);\n }\n}\n\n/** Which box holds each of the owner's volumes: volume name -> box name. */\nasync function attachments(owner: string, p: Paths): Promise<Map<string, string>> {\n const out = new Map<string, string>();\n for (const ref of await listMachineRefs(p)) {\n if (ref.owner !== owner) continue;\n try {\n const meta = await readMachineMeta(ref, p);\n for (const v of meta.volumes ?? []) out.set(v, meta.name);\n } catch {\n /* an unreadable box attaches nothing */\n }\n }\n return out;\n}\n\nexport async function readVolume(ref: BoxRef, p: Paths): Promise<VolumeMeta> {\n try {\n return await readVolumeMeta(ref, p);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") throw new NotFoundError(`volume ${shown(ref)}`);\n throw err;\n }\n}\n\nexport async function getVolume(ref: BoxRef, p: Paths = paths()): Promise<Volume> {\n const meta = await readVolume(ref, p);\n return toVolume(meta, (await attachments(ref.owner, p)).get(ref.name) ?? null, p);\n}\n\nexport async function listVolumes(scope: ListScope, p: Paths = paths()): Promise<Volume[]> {\n const out: Volume[] = [];\n const byOwner = new Map<string, Map<string, string>>();\n for (const ref of await listVolumeRefs(p)) {\n if (!inScope(ref.owner, scope)) continue;\n try {\n const meta = await readVolumeMeta(ref, p);\n let attached = byOwner.get(ref.owner);\n if (attached === undefined) {\n attached = await attachments(ref.owner, p);\n byOwner.set(ref.owner, attached);\n }\n out.push(toVolume(meta, attached.get(meta.name) ?? null, p));\n } catch (err) {\n log.warn(`skipping volumes/${ref.owner}/${ref.name}: ${(err as Error).message}`);\n }\n }\n return out.sort((a, b) => a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name));\n}\n\n/**\n * The host's disk as volumes see it (#91): the filesystem holding volumes/, what every volume on the\n * host promises (its size) and holds (its blocks), and the headroom (config.json `volumeHeadroomGib`).\n * `GET /capacity` reports it; the control plane picks a host by it; `createVolume` applies the same rule.\n */\nexport async function diskCapacity(p: Paths = paths()): Promise<DiskCapacity> {\n // the same filesystem either way; volumes/ is made at server start, and a test may ask before\n const st = await statfs(existsSync(p.volumes) ? p.volumes : p.home);\n let volumesGib = 0;\n let usedBytes = 0;\n for (const ref of await listVolumeRefs(p)) {\n try {\n volumesGib += (await readVolumeMeta(ref, p)).sizeGib;\n usedBytes += statSync(p.volume(ref.owner, ref.name).disk).blocks * 512;\n } catch {\n /* an unreadable volume promises nothing it can be charged for */\n }\n }\n return {\n totalGib: Math.floor((st.blocks * st.bsize) / 1024 ** 3),\n freeGib: Math.floor((st.bavail * st.bsize) / 1024 ** 3),\n volumesGib,\n volumesUsedGib: Math.floor(usedBytes / 1024 ** 3),\n headroomGib: (await loadConfig(p)).volumeHeadroomGib,\n };\n}\n\n/**\n * `kvbox volume create`: a sparse ext4 of `sizeGib`, ready in a moment and occupying a few MB until\n * written to. Sparse files fill up later, so the check is what the host can promise, not what it has\n * right now: the sizes of all its volumes together stay under the disk beyond its boxes, snapshots and\n * base images, less the headroom those need (@kvbox/shared/capacity, decision in #91).\n */\nexport async function createVolume(req: { name: string; sizeGib: number }, owner: string, p: Paths = paths()): Promise<Volume> {\n if (!VOLUME_NAME_RE.test(req.name)) {\n throw new KvboxError(`invalid volume name \"${req.name}\": ${VOLUME_NAME_RULE}`);\n }\n if (!Number.isInteger(req.sizeGib) || req.sizeGib < 1 || req.sizeGib > MAX_VOLUME_GIB) {\n throw new KvboxError(`volume size: whole GB between 1 and ${MAX_VOLUME_GIB}`);\n }\n return withHostLock(\"volumes\", () => makeVolume(req, owner, p));\n}\n\nasync function makeVolume(req: { name: string; sizeGib: number }, owner: string, p: Paths): Promise<Volume> {\n const v = p.volume(owner, req.name);\n if (existsSync(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);\n await mkdir(p.ownerVolumes(owner), { recursive: true, mode: 0o700 });\n const disk = await diskCapacity(p);\n if (!hasDiskRoom(disk, req.sizeGib)) {\n throw new KvboxError(\n `not enough disk on this host for a ${req.sizeGib} GB volume: it can still promise ${volumeRoomGib(disk)} GB ` +\n `(${disk.freeGib} GB free, ${disk.volumesGib} GB promised to ${disk.volumesGib === 0 ? \"no volume yet\" : \"its volumes\"}, ${disk.headroomGib} GB kept for its boxes)`,\n );\n }\n const taken = new Set<string>();\n for (const ref of await listVolumeRefs(p)) {\n try {\n taken.add((await readVolumeMeta(ref, p)).id);\n } catch {\n /* an unreadable volume holds no id to avoid */\n }\n }\n // Not recursive: the dir is the claim on the name, and a second claim fails here instead of sharing the file.\n try {\n await mkdir(v.dir, { mode: 0o700 });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") throw new KvboxError(`volume ${req.name} already exists`);\n throw err;\n }\n try {\n await writeFile(v.disk, \"\", { mode: 0o600 });\n await truncate(v.disk, req.sizeGib * 1024 ** 3);\n // -F: a file, not a block device. -m 0: nothing held back for root, the whole disk is the user's.\n // Lazy init: the guest kernel zeroes the inode tables as it goes, so mkfs writes almost nothing.\n await run([\"mkfs.ext4\", \"-q\", \"-F\", \"-m\", \"0\", \"-L\", volumeLabel(req.name), \"-E\", \"lazy_itable_init=1,lazy_journal_init=1\", v.disk]);\n const meta: VolumeMeta = { id: newBoxId(taken), name: req.name, owner, sizeGib: req.sizeGib, createdAt: new Date().toISOString() };\n await writeVolumeMeta(meta, p);\n recordVolume(meta, \"create\", p, meta.createdAt);\n return toVolume(meta, null, p);\n } catch (err) {\n await rm(v.dir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/**\n * `kvbox volume rm`: only a detached volume goes; its data goes with it. The ledger's `rm` row is\n * written first and has to succeed: a volume gone without it would be billed for good (nothing\n * reconciles the ledger with the files), while a row for a volume still here only stops its billing\n * until the retry removes it.\n */\nexport async function deleteVolume(ref: BoxRef, p: Paths = paths()): Promise<void> {\n await withHostLock(\"volumes\", async () => {\n const meta = await readVolume(ref, p);\n const box = (await attachments(ref.owner, p)).get(ref.name);\n if (box !== undefined) throw new KvboxError(`volume ${shown(ref)} is attached to box ${box}; kvbox volume detach ${shown(ref)} first`);\n try {\n insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: new Date().toISOString(), sizeGib: meta.sizeGib, by: \"rm\" }, p);\n } catch (err) {\n throw new KvboxError(`volume ${shown(ref)} was not removed: its ledger row could not be written (${(err as Error).message}); try again`);\n }\n try {\n await rm(p.volume(ref.owner, ref.name).dir, { recursive: true, force: true });\n } catch (err) {\n throw new KvboxError(`volume ${shown(ref)}: its files could not be removed (${(err as Error).message}); it is no longer billed, run kvbox volume rm ${shown(ref)} again`);\n }\n });\n}\n\n/** What `growVolume` will refuse, said before anything is stopped for it: the size and the host's room. */\nexport async function assertCanGrow(ref: BoxRef, sizeGib: number, p: Paths = paths()): Promise<VolumeMeta> {\n const meta = await readVolume(ref, p);\n if (!Number.isInteger(sizeGib) || sizeGib > MAX_VOLUME_GIB) throw new KvboxError(`volume size: whole GB, at most ${MAX_VOLUME_GIB}`);\n if (sizeGib <= meta.sizeGib) {\n throw new KvboxError(`volume ${shown(ref)} is ${meta.sizeGib} GB and a volume only grows; ${sizeGib} GB is ${sizeGib === meta.sizeGib ? \"what it has\" : \"smaller\"}`);\n }\n const disk = await diskCapacity(p);\n const more = sizeGib - meta.sizeGib;\n if (!hasDiskRoom(disk, more)) {\n throw new KvboxError(`not enough disk on this host to grow volume ${shown(ref)} by ${more} GB: it can still promise ${volumeRoomGib(disk)} GB`);\n }\n return meta;\n}\n\n/**\n * Extend the volume's file and grow its ext4 into it (#147). The filesystem must not be mounted: the\n * caller (core/machines.ts `resizeVolume`) has stopped the box holding it. `check` runs under the same\n * host lock, right before the file changes. e2fsck first: resize2fs refuses a filesystem mounted since\n * its last check.\n */\nexport async function growVolume(ref: BoxRef, sizeGib: number, p: Paths = paths(), check?: () => Promise<void>): Promise<Volume> {\n return withHostLock(\"volumes\", async () => {\n const meta = await assertCanGrow(ref, sizeGib, p);\n await check?.();\n const disk = p.volume(ref.owner, ref.name).disk;\n await truncate(disk, sizeGib * 1024 ** 3);\n await run([\"e2fsck\", \"-f\", \"-p\", disk], { okExitCodes: [1] });\n await run([\"resize2fs\", disk]);\n const grown: VolumeMeta = { ...meta, sizeGib };\n await writeVolumeMeta(grown, p);\n recordVolume(grown, \"resize\", p);\n return toVolume(grown, (await attachments(ref.owner, p)).get(ref.name) ?? null, p);\n });\n}\n\n/** The volume a box names: the box owner's, as its meta.json lists it. */\nexport function volumeRef(box: Pick<MachineMeta, \"owner\">, name: string): BoxRef {\n return parseRef(name, box.owner);\n}\n\n/** The box's attached volumes with their sizes, in drive order; a volume whose files are gone is an error. */\nexport async function volumeDrivesOf(box: Pick<MachineMeta, \"owner\" | \"name\" | \"volumes\">, p: Paths): Promise<VolumeDrive[]> {\n const out: VolumeDrive[] = [];\n for (const name of box.volumes ?? []) {\n const ref = volumeRef(box, name);\n let meta: VolumeMeta;\n try {\n meta = await readVolume(ref, p);\n } catch (err) {\n if (err instanceof NotFoundError) throw new KvboxError(`box ${shown(box)} has volume ${name} attached, but the volume is gone from ${p.volumes}`);\n throw err;\n }\n out.push({ name, sizeGib: meta.sizeGib });\n }\n return out;\n}\n\n/**\n * The volume drives the box's VM has, for a capture (a snapshot, a warm fork): its attached volumes, plus\n * the placeholders a restore left in its dir, which stay in the VM's drive set until its next cold boot\n * (placeVolumeDrives removes them then). Recorded with the image so that a restore of it writes a file\n * at every drive path the vmstate names; a capture that forgot them would make an image nothing can load.\n */\nexport async function captureDrivesOf(box: Pick<MachineMeta, \"owner\" | \"name\" | \"volumes\">, p: Paths): Promise<VolumeDrive[]> {\n const drives = await volumeDrivesOf(box, p);\n const named = new Set(drives.map((d) => d.name));\n const dir = p.machine(box.owner, box.name).dir;\n for (const entry of (await readdir(dir).catch(() => [] as string[])).sort()) {\n const m = /^volume-(.+)\\.ext4$/.exec(entry);\n if (!m || named.has(m[1]!)) continue;\n const st = await lstat(`${dir}/${entry}`);\n if (!st.isFile()) continue; // not a placeholder: nothing the VM was given\n drives.push({ name: m[1]!, sizeGib: Math.round(st.size / 1024 ** 3) });\n }\n return drives;\n}\n\n/** What `Machine.volumes` shows for a box: never throws (a listing must not fail on one volume). */\nexport function volumeSummaries(box: Pick<MachineMeta, \"owner\" | \"volumes\">, p: Paths): { name: string; sizeGib: number; mountPath: string }[] | undefined {\n if (!box.volumes?.length) return undefined;\n return box.volumes.map((name) => {\n let sizeGib = 0;\n try {\n sizeGib = Math.round(statSync(p.volume(box.owner, name).disk).size / 1024 ** 3);\n } catch {\n /* gone: shown with size 0 */\n }\n return { name, sizeGib, mountPath: volumeMountPath(name) };\n });\n}\n\n/**\n * Before a box boots: one symlink per attached volume in the box dir, pointing at the volume's disk,\n * and nothing else that looks like a volume drive (a placeholder left by a restore, a link of a volume\n * detached since). Firecracker is then given the links by their relative names.\n */\nexport async function placeVolumeDrives(box: Pick<MachineMeta, \"owner\" | \"name\" | \"volumes\">, p: Paths): Promise<VolumeDrive[]> {\n const m = p.machine(box.owner, box.name);\n const drives = await volumeDrivesOf(box, p);\n await removeVolumeDrives(m.dir, new Set(drives.map((d) => d.name)));\n for (const d of drives) {\n const link = m.volumeDrive(d.name);\n await rm(link, { force: true });\n await symlink(p.volume(box.owner, d.name).disk, link);\n }\n return drives;\n}\n\n/** Every `volume-*.ext4` entry of a box dir whose name is not in `keep`. */\nexport async function removeVolumeDrives(boxDir: string, keep: ReadonlySet<string>): Promise<void> {\n for (const entry of await readdir(boxDir).catch(() => [] as string[])) {\n const m = /^volume-(.+)\\.ext4$/.exec(entry);\n if (m && !keep.has(m[1]!)) await rm(`${boxDir}/${entry}`, { force: true });\n }\n}\n\n/**\n * A box restored from a snapshot (or forked warm) whose source had volumes: the vmstate names their\n * drives and Firecracker refuses to load without a file at each path, so each gets an empty sparse file\n * of the same size. Never written: the guest drops the mounts right after the restore (kvbox-agent\n * `dropVolumes`), and the next cold boot removes them (placeVolumeDrives).\n */\nexport async function placeholderDrives(boxDir: string, volumes: readonly VolumeDrive[]): Promise<void> {\n for (const v of volumes) {\n const file = `${boxDir}/${volumeDriveRel(v.name)}`;\n // Never through a link a leftover dir may hold: a write there would empty the volume it points at.\n await rm(file, { force: true });\n await writeFile(file, \"\", { mode: 0o600 });\n await truncate(file, v.sizeGib * 1024 ** 3);\n }\n}\n\n/**\n * The drive id Firecracker knows a volume by: only letters, digits and underscores are allowed there, so a\n * '-' in the name becomes '_' (no two valid names collide: '_' is not a name character). Nothing keeps\n * the id: a boot sends it again, a snapshot holds its own. The guest mounts by label, not by it.\n */\nexport const volumeDriveId = (name: string) => `vol_${name.replace(/-/g, \"_\")}`;\n\n/** The box holding `ref`, by name, or null when it is detached. */\nexport async function attachedBox(ref: BoxRef, p: Paths): Promise<string | null> {\n return (await attachments(ref.owner, p)).get(ref.name) ?? null;\n}\n","/**\n * The capacity rule both sides apply. Firecracker reserves neither RAM nor cores, so a host counts\n * what its running boxes are sized at and refuses a box that would push the total past\n * memory: host RAM minus 2 GB the host keeps for itself (hard), or\n * vCPU: 2 x host cores (soft: vCPUs time-slice fine, this stops the absurd).\n * The host applies it box by box at `new` (server core/capacity.ts, with the names of the running\n * boxes in the refusal); the control plane applies it to each host's reported totals to choose\n * where a box lands (#20). Decision \"`zbox new` guards host capacity\".\n */\nimport type { Capacity, DiskCapacity } from \"./api.js\";\n\nexport const MEM_HEADROOM_MIB = 2048;\n\n/**\n * Disk for volumes (#91). A volume is sparse, so a host could promise more than it has; the rule is that\n * the sizes of its volumes add up to at most what the disk has beyond its boxes, snapshots and base\n * images (free space plus what the volumes already hold), less the headroom those keep growing into.\n * The host applies it at `volume create` (server core/volumes.ts), the control plane to pick a host.\n */\nexport function sellableGib(d: DiskCapacity): number {\n return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);\n}\n\n/** Whole GiB of volume a host can still promise. Never negative. */\nexport function volumeRoomGib(d: DiskCapacity): number {\n return Math.max(0, sellableGib(d) - d.volumesGib);\n}\n\nexport function hasDiskRoom(d: DiskCapacity, sizeGib: number): boolean {\n return sizeGib <= volumeRoomGib(d);\n}\nexport const VCPU_OVERSUBSCRIPTION = 2;\n\nexport interface Want {\n vcpu: number;\n memMib: number;\n}\n\n/** What a host can still take: memory after the headroom and what is reserved, vCPUs under the cap. Never negative. */\nexport function freeOf(c: Capacity): { memMib: number; vcpu: number } {\n return {\n memMib: Math.max(0, c.hostMemMib - MEM_HEADROOM_MIB - c.reservedMemMib),\n vcpu: Math.max(0, c.hostCores * VCPU_OVERSUBSCRIPTION - c.reservedVcpu),\n };\n}\n\nexport function hasRoom(c: Capacity, want: Want): boolean {\n const free = freeOf(c);\n return want.memMib <= free.memMib && want.vcpu <= free.vcpu;\n}\n","/**\n * The capacity guard. Firecracker reserves neither RAM nor cores on the host, so without a rule\n * of our own the kernel's OOM-killer is what ends an over-full host: a Firecracker process dies\n * and a box vanishes without a trace. Before a box is started (`new`, a restore or fork, `start`,\n * `wake`, a `rescale` that grows a running box: #37), its size is added to what the other\n * running boxes already reserve (their sizes, not what they touch right now) and refuses when\n * memory: reserved + new > host RAM - 2 GB (hard: the host needs room of its own), or\n * vCPU: reserved + new > 2 x host cores (soft: vCPUs time-slice fine, this stops the absurd).\n * `--force` skips both. The constants live in shared/capacity.ts: the control plane applies the same\n * rule to each host's totals to place a box (#20). Decision \"`zbox new` guards host capacity\".\n */\nimport { cpus, totalmem } from \"node:os\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { Capacity } from \"@kvbox/shared/api\";\nimport { MEM_HEADROOM_MIB, VCPU_OVERSUBSCRIPTION } from \"@kvbox/shared/capacity\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { listMachineRefs, readMachineMeta, vmAlive } from \"./state.js\";\nimport { loadConfig } from \"./config.js\";\nimport { listImages } from \"./images.js\";\nimport { diskCapacity } from \"./volumes.js\";\nimport { backupStoreCapacity } from \"./backupStore.js\";\n\nexport { MEM_HEADROOM_MIB, VCPU_OVERSUBSCRIPTION };\n\nexport interface Host {\n memMib: number;\n cores: number;\n}\nexport interface Reservation {\n /** Whose box it is; a refusal names only the caller's own boxes (another user's box names are theirs). */\n owner?: string;\n name: string;\n vcpu: number;\n memMib: number;\n}\n\nexport function hostResources(): Host {\n return { memMib: Math.floor(totalmem() / 1024 ** 2), cores: cpus().length };\n}\n\n/** The sizes of every box whose Firecracker process is alive; a dead pid reserves nothing. */\nexport async function runningReservations(p: Paths = paths()): Promise<Reservation[]> {\n const out: Reservation[] = [];\n for (const ref of await listMachineRefs(p)) {\n try {\n const meta = await readMachineMeta(ref, p);\n if (vmAlive(meta)) out.push({ owner: meta.owner, name: meta.name, vcpu: meta.vcpu, memMib: meta.memMib });\n } catch {\n // unreadable meta: not a running box we can account for\n }\n }\n return out;\n}\n\nexport async function capacity(p: Paths = paths()): Promise<Capacity> {\n const host = hostResources();\n const running = await runningReservations(p);\n return {\n hostMemMib: host.memMib,\n hostCores: host.cores,\n reservedMemMib: running.reduce((n, r) => n + r.memMib, 0),\n reservedVcpu: running.reduce((n, r) => n + r.vcpu, 0),\n running: running.length,\n disk: await diskCapacity(p),\n // What a box can be made from here (#87): the control plane places `--base postgres` by it.\n images: await listImages(await loadConfig(p), p),\n ...(await backupStoreCapacity(p).then((store) => (store ? { backupStore: store } : {}))),\n // Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).\n storeClient: true,\n };\n}\n\nfunction gb(mib: number): string {\n const g = mib / 1024;\n return `${Number.isInteger(g) ? g : g.toFixed(1)} GB`;\n}\n\nfunction describeRunning(running: Reservation[], viewer: string | undefined): string {\n if (running.length === 0) return \"no box is running\";\n const own = viewer === undefined ? running : running.filter((r) => r.owner === viewer);\n const others = running.length - own.length;\n const named = own.map((r) => `${r.name} ${r.vcpu} vCPU/${gb(r.memMib)}`);\n if (others > 0) named.push(`${others} ${others === 1 ? \"box\" : \"boxes\"} of other users`);\n const list = named.join(\", \");\n const vcpu = running.reduce((n, r) => n + r.vcpu, 0);\n const mem = running.reduce((n, r) => n + r.memMib, 0);\n return `${running.length} running ${running.length === 1 ? \"box reserves\" : \"boxes reserve\"} ${vcpu} vCPU and ${gb(mem)} (${list})`;\n}\n\n/** What the refusal suggests: `new` can pick a smaller size, `start` and `wake` cannot, `rescale` can ask for less. */\nexport type RoomFor = \"new\" | \"start\" | \"rescale\";\n\nconst HINTS: Record<RoomFor, string> = {\n new: \"stop or remove a box (kvbox stop, kvbox rm), pick a smaller --size, or pass --force to start it anyway\",\n start: \"stop or remove a box (kvbox stop, kvbox rm), or pass --force to start it anyway\",\n rescale: \"stop or remove a box (kvbox stop, kvbox rm), ask for less, or pass --force to rescale it anyway\",\n};\n\n/**\n * Why a box of `want` cannot start on `host` next to `running`, or undefined when it can.\n * `viewer` is the box's owner: only their boxes are named, the rest are counted. Pure, so the rule\n * is testable without a host.\n */\nexport function roomFor(\n host: Host,\n running: Reservation[],\n want: { vcpu: number; memMib: number },\n opts: { viewer?: string; by?: RoomFor } = {},\n): string | undefined {\n const { viewer, by = \"new\" } = opts;\n const reservedMem = running.reduce((n, r) => n + r.memMib, 0);\n const reservedVcpu = running.reduce((n, r) => n + r.vcpu, 0);\n const memLimit = host.memMib - MEM_HEADROOM_MIB;\n const vcpuLimit = host.cores * VCPU_OVERSUBSCRIPTION;\n const hint = HINTS[by];\n if (reservedMem + want.memMib > memLimit) {\n return (\n `not enough memory for a ${gb(want.memMib)} box: ${describeRunning(running, viewer)}; ` +\n `this host has ${gb(host.memMib)} and keeps ${gb(MEM_HEADROOM_MIB)} for itself, so boxes may reserve ${gb(memLimit)} in total. ` +\n hint\n );\n }\n if (reservedVcpu + want.vcpu > vcpuLimit) {\n return (\n `too many vCPUs for a ${want.vcpu} vCPU box: ${describeRunning(running, viewer)}; ` +\n `this host has ${host.cores} cores and allows ${vcpuLimit} vCPUs in total (${VCPU_OVERSUBSCRIPTION}x). ` +\n hint\n );\n }\n return undefined;\n}\n\n/**\n * Throws (HTTP 400, exit 1) when the host cannot take a box of this size for `box`'s owner; `force`\n * skips the check. A named `box` is left out of what is reserved: a rescale checks the new shape\n * in place of the old one (#37).\n */\nexport async function assertRoomFor(\n vcpu: number,\n memMib: number,\n force: boolean,\n box: { owner: string; name?: string },\n by: RoomFor,\n p: Paths = paths(),\n): Promise<void> {\n if (force) return;\n const running = (await runningReservations(p)).filter((r) => box.name === undefined || !(r.owner === box.owner && r.name === box.name));\n const reason = roomFor(hostResources(), running, { vcpu, memMib }, { viewer: box.owner, by });\n if (reason !== undefined) throw new KvboxError(reason);\n}\n","/**\n * This host as a backup store (decision \"Backup stores: Garage on our own disks…\"): `kvbox-server backup\n * setup --path <dir>` runs Garage with its data on a disk the operator bought for backups, makes one\n * bucket and one key, and tells the control plane, which from then on signs chunk URLs with that key.\n *\n * Garage is not ours to write, only to run: one node that is the whole cluster, listening on localhost.\n * It is started detached, like Firecracker, so it outlives a daemon restart; the daemon starts it again\n * when it finds it gone (a reboot, a crash). Chunks reach it through the host's own HTTPS listener\n * (`storeProxy`): a request whose path starts with the bucket's name is piped to Garage untouched, so\n * the certificate the control plane already pins and the port the relay already forwards serve it, and\n * Garage itself checks the signature of every request.\n */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { chmod, mkdir, readFile, rename, rm, stat, statfs, writeFile } from \"node:fs/promises\";\nimport { request as httpRequest, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { userInfo } from \"node:os\";\nimport { isAbsolute, join } from \"node:path\";\nimport { pipeline } from \"node:stream\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { request } from \"undici\";\nimport { BACKUP_STORE_BUCKET, BACKUP_STORE_REGION, type BackupStoreRegistration, type BackupStoreSetupRequest, type BackupStoreStatus, type Capacity } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { loadConfig, saveConfig, type BackupStore, type Config } from \"./config.js\";\nimport { run, spawnDetached } from \"./exec.js\";\nimport { log } from \"./log.js\";\nimport { pidAlive } from \"./state.js\";\n\n/** The Garage every store runs; the same release as the `garage` box image. A new one: change it and both checksums; each store takes it when its daemon next starts. */\nexport const GARAGE_VERSION = \"2.5.0\";\nconst GARAGE_SHA256: Record<string, { arch: string; sha256: string }> = {\n x64: { arch: \"x86_64\", sha256: \"2ff667286217cd73ebcb1c03af993822365000441dfe31a80cb64c5189a9dea8\" },\n arm64: { arch: \"aarch64\", sha256: \"69b6040cef428b993500c17dd0d0c1240acf2f3f667b9b05ceba4b9660db4e8c\" },\n};\n/** Garage on this host: S3 for the proxy, RPC for its own command line. Localhost only. */\nexport const GARAGE_S3_PORT = 3900;\nconst GARAGE_RPC_PORT = 3901;\n/** The name of the one key a store has: the control plane's. */\nconst KEY_NAME = \"kvbox-control-plane\";\n/** How long Garage may take to answer after it is started. */\nconst START_WAIT_MS = 60_000;\n/** How often the daemon looks whether Garage is still there. */\nexport const WATCH_MS = 30_000;\n\n/** What setup needs from the outside world; tests hand in fakes. */\nexport interface StoreDeps {\n /** Put Garage `GARAGE_VERSION` at `p.garage` unless it is there already; whether it put a new binary there. */\n install: (p: Paths) => Promise<boolean>;\n /** Start Garage detached; its pid. */\n start: (p: Paths) => Promise<number>;\n /** Whether the Garage started here is still there. */\n running: (p: Paths) => Promise<boolean>;\n /** Stop the Garage started here, and wait until it is gone. */\n stop: (p: Paths) => Promise<void>;\n /** One admin call (`garage json-api <operation> [body]`): its JSON answer. */\n api: (p: Paths, operation: string, body?: unknown) => Promise<unknown>;\n /** One `garage` command line call, for what the admin API does not do in one step. */\n cli: (p: Paths, args: readonly string[]) => Promise<string>;\n /** Tell the control plane (`PUT /hosts/self/backup-store`). */\n register: (cfg: Config, body: BackupStoreRegistration) => Promise<void>;\n /** The filesystem a path is on. */\n device: (path: string) => Promise<number>;\n}\n\nconst garage = (p: Paths, args: readonly string[], timeoutMs = 20_000) => run([p.garage, \"-c\", p.backupStore.conf, ...args], { timeoutMs });\n\nexport const realDeps: StoreDeps = {\n install: installGarage,\n start: (p) => spawnDetached([p.garage, \"-c\", p.backupStore.conf, \"server\"], p.backupStore.log),\n running: (p) => garageRunning(p),\n stop: stopGarage,\n api: async (p, operation, body) => {\n const { stdout } = await garage(p, [\"json-api\", operation, ...(body === undefined ? [] : [JSON.stringify(body)])]);\n const text = stdout.trim();\n return text === \"\" ? null : (JSON.parse(text) as unknown);\n },\n cli: async (p, args) => (await garage(p, args)).stdout,\n register: registerWithControlPlane,\n device: async (path) => (await stat(path)).dev,\n};\n\n/** The file beside the binary saying which Garage it is: a `GARAGE_VERSION` bump then reaches hosts that have one. */\nconst versionFile = (p: Paths) => `${p.garage}.version`;\n\n/** Download Garage's own static binary and keep it only if it is the file we expect; false when that version is there already. */\nexport async function installGarage(p: Paths): Promise<boolean> {\n if (existsSync(p.garage) && (await readFile(versionFile(p), \"utf8\").catch(() => \"\")).trim() === GARAGE_VERSION) return false;\n const build = GARAGE_SHA256[process.arch];\n if (!build) throw new KvboxError(`there is no Garage build for this machine (${process.arch})`);\n const url = `https://garagehq.deuxfleurs.fr/_releases/v${GARAGE_VERSION}/${build.arch}-unknown-linux-musl/garage`;\n const res = await fetch(url, { signal: AbortSignal.timeout(300_000) }).catch((err: Error) => {\n throw new KvboxError(`could not download Garage from ${url} (${err.message})`);\n });\n if (!res.ok) throw new KvboxError(`could not download Garage from ${url}: HTTP ${res.status}`);\n const bytes = Buffer.from(await res.arrayBuffer());\n const got = createHash(\"sha256\").update(bytes).digest(\"hex\");\n if (got !== build.sha256) throw new KvboxError(`the Garage download is not the expected file (sha256 ${got}); nothing was installed`);\n await mkdir(p.bin, { recursive: true });\n const tmp = `${p.garage}.tmp`;\n await writeFile(tmp, bytes, { mode: 0o755 });\n await chmod(tmp, 0o755);\n await rename(tmp, p.garage);\n await writeFile(versionFile(p), `${GARAGE_VERSION}\\n`);\n return true;\n}\n\nasync function registerWithControlPlane(cfg: Config, body: BackupStoreRegistration): Promise<void> {\n const cp = cfg.controlPlane;\n if (!cp) throw new KvboxError(\"this host has not joined a control plane\");\n const res = await request(`${cp.url}/hosts/self/backup-store`, {\n method: \"PUT\",\n headers: { authorization: `Bearer ${cp.secret}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n headersTimeout: 10_000,\n bodyTimeout: 10_000,\n }).catch((err: Error) => {\n throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);\n });\n const text = await res.body.text();\n if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not know backup stores yet: it is older than this host`);\n if (res.statusCode < 200 || res.statusCode >= 300) {\n let error: unknown;\n try {\n error = (JSON.parse(text) as { error?: unknown }).error;\n } catch {\n // not JSON: the status says enough\n }\n throw new KvboxError(typeof error === \"string\" ? error : `${cp.name} answered ${res.statusCode}`);\n }\n}\n\n/** Garage's configuration for a store whose files are under `path`. */\nexport function garageToml(path: string): string {\n const q = (s: string) => JSON.stringify(s);\n return [\n \"# written by kvbox-server backup setup: this host's backup store\",\n `metadata_dir = ${q(join(path, \"meta\"))}`,\n `data_dir = ${q(join(path, \"data\"))}`,\n 'db_engine = \"lmdb\"',\n \"metadata_fsync = true\",\n \"data_fsync = true\",\n \"replication_factor = 1\",\n `rpc_bind_addr = \"127.0.0.1:${GARAGE_RPC_PORT}\"`,\n `rpc_public_addr = \"127.0.0.1:${GARAGE_RPC_PORT}\"`,\n `rpc_secret_file = ${q(join(path, \"rpc_secret\"))}`,\n \"\",\n \"[s3_api]\",\n `s3_region = ${q(BACKUP_STORE_REGION)}`,\n `api_bind_addr = \"127.0.0.1:${GARAGE_S3_PORT}\"`,\n \"\",\n ].join(\"\\n\");\n}\n\nasync function readPid(p: Paths): Promise<number | null> {\n const n = Number((await readFile(p.backupStore.pid, \"utf8\").catch(() => \"\")).trim());\n return Number.isInteger(n) && n > 0 ? n : null;\n}\n\n/** Whether the Garage this daemon started is still there: its pid lives and is Garage, not a pid reused since a reboot. */\nexport async function garageRunning(p: Paths = paths()): Promise<boolean> {\n const pid = await readPid(p);\n if (!pidAlive(pid)) return false;\n const cmdline = await readFile(`/proc/${pid}/cmdline`, \"utf8\").catch(() => null);\n return cmdline === null || cmdline.split(\"\\0\")[0] === p.garage;\n}\n\n/** Stop the Garage started here (SIGTERM), waiting until it is gone. */\nexport async function stopGarage(p: Paths): Promise<void> {\n const pid = await readPid(p);\n if (pid === null || !(await garageRunning(p))) return;\n // `garageRunning` gives an unreadable command line the benefit of the doubt; a kill does not.\n const cmdline = await readFile(`/proc/${pid}/cmdline`, \"utf8\").catch(() => null);\n if (cmdline?.split(\"\\0\")[0] !== p.garage) throw new KvboxError(`cannot tell whether pid ${pid} is this host's Garage, so it was not stopped; stop Garage by hand and run this again`);\n process.kill(pid, \"SIGTERM\");\n const until = Date.now() + 15_000;\n while (pidAlive(pid)) {\n if (Date.now() > until) throw new KvboxError(`Garage (pid ${pid}) did not stop within 15s`);\n await sleep(200);\n }\n await rm(p.backupStore.pid, { force: true });\n}\n\n/** Start Garage unless it runs, and wait until it answers. */\nasync function ensureGarage(p: Paths, deps: StoreDeps): Promise<void> {\n if (!(await deps.running(p))) {\n const pid = await deps.start(p);\n await writeFile(p.backupStore.pid, `${pid}\\n`);\n }\n const until = Date.now() + START_WAIT_MS;\n for (;;) {\n try {\n await deps.cli(p, [\"status\"]);\n return;\n } catch (err) {\n if (Date.now() > until) throw new KvboxError(`Garage did not answer after ${START_WAIT_MS / 1000}s (see ${p.backupStore.log}): ${(err as Error).message}`);\n await sleep(500);\n }\n }\n}\n\n/**\n * `kvbox-server backup setup`: make this host a backup store with its data under `req.path`, or, run\n * again with the same path, finish a setup that stopped half way (every step is safe to repeat) and\n * register the store with the control plane again.\n */\nexport function setupBackupStore(req: BackupStoreSetupRequest, p: Paths = paths(), deps: StoreDeps = realDeps): Promise<BackupStoreStatus> {\n return serial(() => setup(req, p, deps));\n}\n\n/**\n * One store step at a time in this daemon: a setup, or the watch starting Garage again. Two of them at\n * once would each start a Garage (the loser exits, and its pid may be the one kept) or each make a key.\n */\nlet turn: Promise<unknown> = Promise.resolve();\nfunction serial<T>(step: () => Promise<T>): Promise<T> {\n const mine = turn.then(step, step);\n turn = mine.catch(() => undefined);\n return mine;\n}\n\nasync function setup(req: BackupStoreSetupRequest, p: Paths, deps: StoreDeps): Promise<BackupStoreStatus> {\n const path = req.path.replace(/\\/+$/, \"\") || \"/\";\n if (!isAbsolute(path) || /[\"\\\\\\n\\0]/.test(path)) throw new KvboxError(`${req.path} is not a path a store can use: give the full path of a directory on the backup disk`);\n const cfg = await loadConfig(p);\n if (!cfg.controlPlane) throw new KvboxError(\"this host has not joined a control plane, which is what takes backups; run kvbox-server join first\");\n if (cfg.backupStore && cfg.backupStore.path !== path) {\n throw new KvboxError(`this host already is a backup store, with its data in ${cfg.backupStore.path}; a host has one store`);\n }\n const dir = await stat(path).catch(() => null);\n if (!dir?.isDirectory()) throw new KvboxError(`${path} is not a directory: mount the backup disk and give a directory on it`);\n if (!req.force && (await deps.device(path)) === (await deps.device(p.home))) {\n throw new KvboxError(`${path} is on the same disk as this host's boxes, so the backups would be lost with them; mount a disk for backups there, or pass --force to use it anyway`);\n }\n\n // A store set up before whose files are not at the path: its disk is not mounted, or another (empty)\n // one is. Nothing is written or started there unless the operator says the old disk is gone for good:\n // a new store makes a new key, and the control plane then forgets every backup the old one kept.\n if (cfg.backupStore && !req.newStore && !existsSync(join(path, \"rpc_secret\"))) throw notTheStoreDisk(path);\n\n const newBinary = await deps.install(p);\n await mkdir(p.backupStore.dir, { recursive: true, mode: 0o700 });\n try {\n for (const sub of [\"meta\", \"data\"]) await mkdir(join(path, sub), { recursive: true, mode: 0o700 });\n const rpcSecret = join(path, \"rpc_secret\");\n if (!existsSync(rpcSecret)) await writeFile(rpcSecret, `${randomBytes(32).toString(\"hex\")}\\n`, { mode: 0o600 });\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"EACCES\" && code !== \"EPERM\" && code !== \"EROFS\") throw err;\n const user = userInfo().username;\n throw new KvboxError(`kvbox-server (user ${user}) cannot write in ${path}: make the directory ${user}'s (sudo chown ${user} ${path}) and run this again`);\n }\n // A Garage still running from a setup that stopped half way may have its data elsewhere (another\n // --path that time): it is started again on this configuration rather than trusted.\n const conf = garageToml(path);\n const had = await readFile(p.backupStore.conf, \"utf8\").catch(() => null);\n await writeFile(p.backupStore.conf, conf, { mode: 0o600 });\n if ((newBinary || (had !== null && had !== conf)) && (await deps.running(p))) await deps.stop(p);\n await ensureGarage(p, deps);\n\n // The layout says which nodes hold data: this one, alone. A disk that held a store before comes with its own.\n const layout = (await deps.api(p, \"GetClusterLayout\")) as { version?: number } | null;\n if ((layout?.version ?? 0) === 0) {\n const node = (await deps.cli(p, [\"node\", \"id\", \"-q\"])).trim().split(\"@\")[0]!;\n const fs = await statfs(path);\n await deps.cli(p, [\"layout\", \"assign\", \"-z\", \"kvbox\", \"-c\", String(fs.blocks * fs.bsize), node]);\n await deps.cli(p, [\"layout\", \"apply\", \"--version\", \"1\"]);\n }\n const bucket = await bucketInfo(p, deps).then(async (info) => info ?? ((await deps.api(p, \"CreateBucket\", { globalAlias: BACKUP_STORE_BUCKET })) as { id: string }));\n\n // The key is made once and kept here too, so a second setup registers the same one, as long as Garage\n // still has it: a disk that was replaced (or wiped) comes with an empty Garage, which needs a key of its\n // own. Registering it tells the control plane the store was made anew.\n let store: BackupStore;\n if (cfg.backupStore && (await hasKey(p, deps, cfg.backupStore.accessKey))) {\n store = cfg.backupStore;\n } else {\n if (cfg.backupStore && !req.newStore) {\n // Another store's disk: stop the Garage just started on it, so this host does not serve it as its own.\n await deps.stop(p);\n throw notTheStoreDisk(path);\n }\n if (cfg.backupStore) log.warn(`backup store: a new store in ${path} replaces the one with key ${cfg.backupStore.accessKey}; the backups kept on the old disk are gone`);\n const key = (await deps.api(p, \"CreateKey\", { name: KEY_NAME })) as { accessKeyId: string; secretAccessKey: string };\n store = { path, bucket: BACKUP_STORE_BUCKET, region: BACKUP_STORE_REGION, accessKey: key.accessKeyId, secretKey: key.secretAccessKey, registered: false };\n }\n await deps.api(p, \"AllowBucketKey\", { bucketId: bucket.id, accessKeyId: store.accessKey, permissions: { read: true, write: true, owner: false } });\n // Read again: the download and Garage's start take minutes, and config.json may have changed meanwhile.\n const now = await loadConfig(p);\n // Not registered until the control plane says so this time: a failed attempt must not keep an earlier yes.\n await saveConfig({ ...now, backupStore: { ...store, registered: false } }, p);\n log.info(`backup store: Garage keeps its data in ${path}`);\n\n try {\n await deps.register(now, { bucket: store.bucket, region: store.region, accessKey: store.accessKey, secretKey: store.secretKey });\n } catch (err) {\n throw new KvboxError(`the store is set up, but the control plane did not take it: ${(err as Error).message}. Run the same command again once that is solved`);\n }\n await saveConfig({ ...(await loadConfig(p)), backupStore: { ...store, registered: true } }, p);\n log.info(`backup store: registered with ${now.controlPlane?.name ?? cfg.controlPlane.name}`);\n return backupStoreStatus(p, deps);\n}\n\nconst notTheStoreDisk = (path: string) =>\n new KvboxError(\n `${path} does not hold this host's backup store: is its disk mounted there? Mount it and run this again. If that disk is gone for good, pass --new-store to start a new store here (the backups kept on the old disk can no longer be restored)`,\n );\n\n/** Whether Garage knows the access key `id`. */\nasync function hasKey(p: Paths, deps: StoreDeps, id: string): Promise<boolean> {\n const keys = (await deps.api(p, \"ListKeys\")) as { id: string }[] | null;\n return (keys ?? []).some((k) => k.id === id);\n}\n\nasync function bucketInfo(p: Paths, deps: StoreDeps): Promise<{ id: string; objects?: number; bytes?: number } | null> {\n try {\n return (await deps.api(p, \"GetBucketInfo\", { globalAlias: BACKUP_STORE_BUCKET })) as { id: string; objects?: number; bytes?: number };\n } catch (err) {\n if (/not found|nosuchbucket/i.test((err as Error).message)) return null;\n throw err;\n }\n}\n\n/** `kvbox-server backup status`: where the store is, whether Garage runs, how full its disk is. */\nexport async function backupStoreStatus(p: Paths = paths(), deps: StoreDeps = realDeps): Promise<BackupStoreStatus> {\n const store = (await loadConfig(p)).backupStore;\n if (!store) throw new KvboxError(\"this host is not a backup store; make it one with: kvbox-server backup setup --path <directory on the backup disk>\");\n const fs = await statfs(store.path).catch(() => null);\n const running = await deps.running(p);\n const info = running ? await bucketInfo(p, deps).catch(() => null) : null;\n return {\n path: store.path,\n bucket: store.bucket,\n accessKey: store.accessKey,\n running: running && info !== null,\n totalBytes: fs ? fs.blocks * fs.bsize : 0,\n freeBytes: fs ? fs.bavail * fs.bsize : 0,\n ...(info ? { objects: info.objects ?? 0, storedBytes: info.bytes ?? 0 } : {}),\n registered: store.registered,\n };\n}\n\n/** What `/capacity` says about the store, for the control plane to pick one with room; undefined on a host without one. */\nexport async function backupStoreCapacity(p: Paths = paths(), deps: Pick<StoreDeps, \"running\"> = realDeps): Promise<Capacity[\"backupStore\"]> {\n const store = (await loadConfig(p)).backupStore;\n if (!store) return undefined;\n const fs = await statfs(store.path).catch(() => null);\n return { totalBytes: fs ? fs.blocks * fs.bsize : 0, freeBytes: fs ? fs.bavail * fs.bsize : 0, running: fs !== null && (await deps.running(p)) };\n}\n\n/**\n * At daemon start and every `WATCH_MS` after: a store's Garage that is gone (a reboot, a crash) is\n * started again. A disk that is not mounted is left alone, so Garage never starts empty beside it.\n */\nexport function reviveBackupStore(p: Paths = paths(), deps: StoreDeps = realDeps): Promise<\"none\" | \"running\" | \"started\" | \"upgraded\" | \"no-disk\"> {\n return serial(() => revive(p, deps));\n}\n\n/** Homes whose Garage this daemon has made sure is `GARAGE_VERSION`: once per run, so a failed download does not repeat every tick. */\nconst upgraded = new Set<string>();\n/** Homes where a new binary was installed and Garage has not been started on it yet. */\nconst restartDue = new Set<string>();\n\nasync function revive(p: Paths, deps: StoreDeps): Promise<\"none\" | \"running\" | \"started\" | \"upgraded\" | \"no-disk\"> {\n const store = (await loadConfig(p)).backupStore;\n if (!store) return \"none\";\n if (!upgraded.has(p.home)) {\n upgraded.add(p.home);\n const fresh = await deps.install(p).catch((err: Error) => {\n log.warn(`backup store: Garage ${GARAGE_VERSION} could not be installed, the one there keeps running (${err.message})`);\n return false;\n });\n if (fresh) restartDue.add(p.home);\n }\n // A new binary is owed a start until one happens: not beside a disk that is not mounted, so a later tick does it.\n if (restartDue.has(p.home) && existsSync(join(store.path, \"rpc_secret\"))) {\n if (await deps.running(p)) await deps.stop(p);\n const pid = await deps.start(p);\n await writeFile(p.backupStore.pid, `${pid}\\n`);\n restartDue.delete(p.home);\n return \"upgraded\";\n }\n if (await deps.running(p)) return \"running\";\n if (!existsSync(join(store.path, \"rpc_secret\"))) return \"no-disk\";\n await rm(p.backupStore.pid, { force: true });\n const pid = await deps.start(p);\n await writeFile(p.backupStore.pid, `${pid}\\n`);\n return \"started\";\n}\n\nlet watch: NodeJS.Timeout | undefined;\n/** Keep the store's Garage up for as long as the daemon runs; says once when the disk is missing. */\nexport function startBackupStoreWatch(p: Paths = paths()): void {\n let warned = false;\n const tick = (): void => {\n reviveBackupStore(p)\n .then((state) => {\n if (state === \"started\") log.info(\"backup store: Garage was not running; started it\");\n if (state === \"upgraded\") log.info(`backup store: Garage ${GARAGE_VERSION} installed and started`);\n if (state === \"no-disk\" && !warned) log.warn(\"backup store: its disk is not mounted, so Garage is not started; backups to this host fail until it is back\");\n warned = state === \"no-disk\";\n })\n .catch((err: Error) => log.warn(`backup store: Garage did not start (${err.message})`));\n };\n tick();\n watch ??= setInterval(tick, WATCH_MS);\n watch.unref();\n}\n\n/** Whether a request to the HTTPS listener is for the store: `/<bucket>/…`, the path-style URLs the control plane signs. */\nexport function isStoreRequest(url: string | undefined): boolean {\n return url !== undefined && (url.startsWith(`/${BACKUP_STORE_BUCKET}/`) || url.startsWith(`/${BACKUP_STORE_BUCKET}?`) || url === `/${BACKUP_STORE_BUCKET}`);\n}\n\n/**\n * Whether the HTTPS listener hands this request to Garage: a store path, on a host that is a store (its\n * Garage configuration is written by the first setup). On any other host it goes to the app, so nothing\n * that happens to listen on the store's port here is reachable without a credential.\n */\nexport function forStore(url: string | undefined, p: Paths = paths()): boolean {\n return isStoreRequest(url) && existsSync(p.backupStore.conf);\n}\n\n/**\n * Pipe one request to Garage and its answer back, headers as they came: Garage checks the signature\n * over the `Host` the caller used, so nothing may be rewritten. No kvbox credential is asked for:\n * a signed URL is the credential, and Garage refuses anything else.\n */\nexport function storeProxy(req: IncomingMessage, res: ServerResponse, port = GARAGE_S3_PORT): void {\n const up = httpRequest({ host: \"127.0.0.1\", port, method: req.method, path: req.url, headers: req.headers }, (answer) => {\n res.writeHead(answer.statusCode ?? 502, answer.headers);\n // Either side ending early ends the other: a Garage that dies mid-answer resets the caller (who\n // retries at once), a caller that goes away closes the connection to Garage.\n pipeline(answer, res, (err) => {\n if (err) res.destroy();\n });\n });\n up.on(\"error\", () => {\n if (res.headersSent) return res.destroy();\n res.writeHead(503, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"this host's backup store is not running\" }));\n });\n res.once(\"close\", () => {\n if (!res.writableFinished) up.destroy();\n });\n req.pipe(up);\n}\n","/**\n * An ext4 image's own accounting, read from the file without mounting it: its size and what the\n * filesystem holds.\n *\n * Firecracker's block device has no discard, so a box's sparse disk file only ever grows while the\n * box runs, and its allocation on the host (st_blocks) says nothing about what the guest still uses\n * (#115). The group descriptors do: their free-block counts are journaled metadata, written back\n * within seconds of a change, so on a running box they are at most a journal commit behind the\n * guest's `df`; on a stopped box they are exact. The superblock's own free count is not used: ext4\n * only writes that at unmount.\n */\nimport { closeSync, openSync, readSync } from \"node:fs\";\n\nconst SUPERBLOCK_OFFSET = 1024;\nconst EXT4_MAGIC = 0xef53;\n/** Group descriptors spread over the disk instead of one table after the superblock; mke2fs never sets it at box sizes. */\nconst INCOMPAT_META_BG = 0x10;\nconst INCOMPAT_64BIT = 0x80;\n\nexport interface Ext4Usage {\n /** Block count times block size: the disk as the guest's `df` sizes it. */\n sizeBytes: number;\n /** Blocks in use. Matches `df` \"Used\": the overlay is made with `-m 0`, so no blocks are held back for root. */\n usedBytes: number;\n}\n\n/** `null` when the file is missing, not ext4, or laid out in a way this reader does not know. */\nexport function ext4Usage(file: string): Ext4Usage | null {\n let fd: number | undefined;\n try {\n fd = openSync(file, \"r\");\n const sb = Buffer.alloc(1024);\n if (readSync(fd, sb, 0, sb.length, SUPERBLOCK_OFFSET) !== sb.length) return null;\n if (sb.readUInt16LE(0x38) !== EXT4_MAGIC) return null;\n const incompat = sb.readUInt32LE(0x60);\n if (incompat & INCOMPAT_META_BG) return null;\n const is64 = (incompat & INCOMPAT_64BIT) !== 0;\n const blockSize = 1024 << sb.readUInt32LE(0x18);\n const blocks = sb.readUInt32LE(0x04) + (is64 ? sb.readUInt32LE(0x150) * 2 ** 32 : 0);\n const firstDataBlock = sb.readUInt32LE(0x14);\n const blocksPerGroup = sb.readUInt32LE(0x20);\n const descSize = is64 ? sb.readUInt16LE(0xfe) : 32;\n if (blocksPerGroup === 0 || descSize < 32) return null;\n const groups = Math.ceil((blocks - firstDataBlock) / blocksPerGroup);\n // The descriptor table is the block after the superblock's.\n const table = Buffer.alloc(groups * descSize);\n if (readSync(fd, table, 0, table.length, (firstDataBlock + 1) * blockSize) !== table.length) return null;\n let free = 0;\n for (let g = 0; g < groups; g++) {\n const at = g * descSize;\n free += table.readUInt16LE(at + 0x0c) + (descSize >= 64 ? table.readUInt16LE(at + 0x2c) * 65536 : 0);\n }\n return { sizeBytes: blocks * blockSize, usedBytes: (blocks - free) * blockSize };\n } catch {\n return null;\n } finally {\n if (fd !== undefined) closeSync(fd);\n }\n}\n","/**\n * Snapshots: a running box frozen into `snapshots/<name>/` as vmstate + mem (a complete memory image)\n * + a copy of the box's overlay. The base image is referenced by version, not copied, so a snapshot costs\n * what the guest touched (memory pages + overlay blocks), not the box's size.\n *\n * Memory is captured incrementally. Boxes run with dirty page tracking, so Firecracker can write only\n * the pages dirtied since the last snapshot (a \"Diff\": sub-second, sparse) instead of dumping all of\n * guest memory (~10 s frozen for 4 GB). A diff is only a complete image when merged onto the previous\n * one, so each box keeps `mem.base`, a hard link to its last snapshot's `mem`, and the merge happens\n * after the box is already running again. See state.ts `memSnapshots` for the bookkeeping.\n */\nimport { existsSync } from \"node:fs\";\nimport { link, mkdir, readdir, rename, rm, stat } from \"node:fs/promises\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport type { CreateSnapshotRequest, Snapshot } from \"@kvbox/shared/api\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { loadConfig, type Config } from \"./config.js\";\nimport { run } from \"./exec.js\";\nimport { FirecrackerClient } from \"./firecracker.js\";\nimport { withBoxLock, withSnapshotLock } from \"./locks.js\";\nimport { inScope, parseRef, refKey, shown, type BoxRef, type ListScope } from \"./refs.js\";\nimport { copyBoxEnv } from \"./env.js\";\nimport { captureDrivesOf } from \"./volumes.js\";\nimport {\n listSnapshotRefs,\n readMachineMeta,\n readSnapshotMeta,\n vmAlive,\n writeMachineMeta,\n writeSnapshotMeta,\n type MachineMeta,\n type SnapshotMeta,\n} from \"./state.js\";\nimport { log } from \"./log.js\";\n\n/** Snapshot names are directory names shown in tables: letters, digits, dots, dashes, underscores. */\nconst NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;\n\nfunction toSnapshot(meta: SnapshotMeta): Snapshot {\n return {\n name: meta.name,\n owner: meta.owner,\n source: meta.source,\n base: meta.base,\n ...(meta.image !== undefined ? { image: meta.image } : {}),\n vcpu: meta.vcpu,\n memMib: meta.memMib,\n sizeBytes: meta.sizeBytes,\n createdAt: meta.createdAt,\n };\n}\n\n/** One owner's snapshots, or every snapshot on the host when `owner` is null. */\nexport async function listSnapshots(scope: ListScope, p: Paths = paths()): Promise<Snapshot[]> {\n const out: Snapshot[] = [];\n for (const ref of await listSnapshotRefs(p)) {\n if (!inScope(ref.owner, scope)) continue;\n try {\n out.push(toSnapshot(await readSnapshotMeta(ref, p)));\n } catch (err) {\n log.warn(`skipping snapshots/${refKey(ref)}: ${(err as Error).message}`);\n }\n }\n return out;\n}\n\n/** Bytes the snapshot really occupies: its files are sparse, so allocated blocks, not sizes. */\nasync function usedBytes(dir: string): Promise<number> {\n let total = 0;\n for (const entry of await readdir(dir)) {\n total += (await stat(`${dir}/${entry}`)).blocks * 512;\n }\n return total;\n}\n\nasync function readBox(ref: BoxRef, p: Paths): Promise<MachineMeta> {\n try {\n return await readMachineMeta(ref, p);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") throw new NotFoundError(`box ${shown(ref)}`);\n throw err;\n }\n}\n\n/** The snapshot belongs to `owner` (the caller); `req.box` may name another owner's box as owner/name. */\nexport async function saveSnapshot(req: CreateSnapshotRequest, owner: string, p: Paths = paths()): Promise<Snapshot> {\n if (!NAME_RE.test(req.name)) {\n throw new KvboxError(`invalid snapshot name \"${req.name}\": 1-64 chars, lowercase letters, digits, '.', '_' and '-', starting with a letter or digit`);\n }\n const ref = parseRef(req.box, owner);\n return withBoxLock(ref, () => snapshotBox(ref, req, owner, p));\n}\n\nasync function snapshotBox(ref: BoxRef, req: CreateSnapshotRequest, owner: string, p: Paths): Promise<Snapshot> {\n const box = await readBox(ref, p);\n if (!vmAlive(box)) {\n if (existsSync(p.machine(box.owner, box.name).hibernateVmstate)) {\n throw new KvboxError(`box ${req.box} is hibernated; a snapshot freezes a running box (kvbox wake ${req.box} first)`);\n }\n throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);\n }\n const final = p.snapshot(owner, req.name);\n if (existsSync(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);\n // A replace (#83) captures beside the old snapshot, which stays whole and restorable until the new one\n // is complete. Named after the box: two replaces of one name from two boxes never share it.\n const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;\n const cfg = await loadConfig(p);\n\n if (s !== final) await rm(s.dir, { recursive: true, force: true }); // left by a replace the daemon never finished\n await mkdir(s.dir, { recursive: true, mode: 0o700 });\n try {\n // The VM's volume drives (attached ones, placeholders of a restore) end up in the vmstate; a restore\n // needs their names and sizes for the placeholders (#52).\n const volumes = await captureDrivesOf(box, p);\n await captureBox(box, s, cfg, p);\n // The box's own variables go with it (#87): a postgres box's data was made with its password.\n await copyBoxEnv(p.machine(box.owner, box.name).env, s.env);\n const meta: SnapshotMeta = {\n ...(volumes.length > 0 ? { volumes } : {}),\n name: req.name,\n owner,\n source: refKey(box),\n base: box.base,\n ...(box.image !== undefined ? { image: box.image } : {}),\n vcpu: box.vcpu,\n memMib: box.memMib,\n sizeBytes: await usedBytes(s.dir),\n createdAt: new Date().toISOString(),\n };\n await writeSnapshotMeta(meta, p, s);\n if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);\n return toSnapshot(meta);\n } catch (err) {\n await rm(s.dir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/**\n * Move the complete snapshot at `from` into `ref`'s name, the old one (if any) out of the way first.\n * Under the snapshot's lock, so a restore never reads half of each; the old files are removed after.\n * The old one's dir is named after the box like `from`: a replace from another box that swaps while\n * this one still removes never has its old dir (its rollback) removed under it.\n */\nasync function swapIn(ref: BoxRef, from: string, boxId: string, p: Paths): Promise<void> {\n const to = p.snapshot(ref.owner, ref.name).dir;\n const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;\n await withSnapshotLock(ref, async () => {\n await rm(old, { recursive: true, force: true });\n const hadOld = existsSync(to);\n if (hadOld) await rename(to, old);\n try {\n await rename(from, to);\n } catch (err) {\n if (hadOld) await rename(old, to);\n throw err;\n }\n });\n await rm(old, { recursive: true, force: true });\n}\n\n/** Where a capture writes: a snapshot's files, or a fork's own box dir (#79). */\nexport interface Capture {\n vmstate: string;\n /** Becomes a complete memory image, hard-linked as the box's `mem.base`. */\n mem: string;\n overlay: string;\n}\n\n/**\n * Freeze the running (or paused) `box` into `to`: VM state, a complete memory image and a copy of its\n * overlay, all of the same instant. The box carries on as it was. The caller holds the box's lock and\n * removes `to`'s files on a throw; the box's memory lineage is left consistent either way.\n */\nexport async function captureBox(box: MachineMeta, to: Capture, cfg: Config, p: Paths): Promise<void> {\n const m = p.machine(box.owner, box.name);\n const fc = new FirecrackerClient(m.sock);\n let lineageTouched = false;\n try {\n const since = box.memSnapshots ?? 0;\n // A diff is standalone right after boot, or once merged onto the previous image. Otherwise (a\n // lineage broken by an earlier failure) dump everything.\n const mode: \"Diff\" | \"Full\" = since === 0 || existsSync(m.memBase) ? \"Diff\" : \"Full\";\n\n // The guest is frozen for the whole capture so memory and overlay describe the same instant.\n // A box in standby (kvbox pause) is frozen already and stays that way afterwards.\n let failure: unknown;\n await fc.pause();\n try {\n await fc.snapshotCreate(to.vmstate, to.mem, mode);\n lineageTouched = true; // Firecracker reset its dirty bitmap: the box's next diff is relative to this image\n await run([\"cp\", \"--sparse=always\", \"--reflink=auto\", m.overlay, to.overlay]);\n } catch (err) {\n failure = err;\n } finally {\n if (!box.paused) await fc.resume();\n }\n if (lineageTouched) {\n // Recorded before anything else can fail: memSnapshots > 0 without mem.base reads as a broken\n // lineage, and the next snapshot falls back to a full dump instead of a diff missing pages.\n await writeMachineMeta({ ...box, memSnapshots: since + 1 }, p);\n }\n if (failure !== undefined) throw failure;\n\n if (mode === \"Full\") {\n // A full dump is dense; pages the guest never touched are zeros, so punch them out.\n await run([\"fallocate\", \"--dig-holes\", to.mem]);\n } else if (since > 0) {\n await mergeOntoPrevious(m.memBase, to.mem, cfg.snapshotEditor ?? p.snapshotEditor);\n }\n await rm(m.memBase, { force: true });\n await link(to.mem, m.memBase);\n } catch (err) {\n // The diff that was just discarded took pages with it: never let the next diff build on the old image.\n if (lineageTouched) await rm(m.memBase, { force: true }).catch(() => undefined);\n throw err;\n } finally {\n await fc.close();\n }\n}\n\n/**\n * Turn the diff at `diffFile` into a complete image: copy the previous image and apply the diff's pages\n * over it. Holes in the diff are untouched pages; a page dirtied to zeros is data and overwrites.\n */\nasync function mergeOntoPrevious(previous: string, diffFile: string, editor: string): Promise<void> {\n if (!existsSync(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);\n const merged = `${diffFile}.merged`;\n await run([\"cp\", \"--sparse=always\", \"--reflink=auto\", previous, merged]);\n await run([editor, \"edit-memory\", \"rebase\", \"--memory-path\", merged, \"--diff-path\", diffFile]);\n await rename(merged, diffFile);\n}\n\nexport async function deleteSnapshot(ref: BoxRef, p: Paths = paths()): Promise<void> {\n const dir = p.snapshot(ref.owner, ref.name).dir;\n if (ref.name.startsWith(\".\") || !existsSync(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);\n await withSnapshotLock(ref, () => rm(dir, { recursive: true, force: true }));\n}\n","/**\n * Client for one Firecracker process's API socket. Ten-odd endpoints, all\n * PUT/PATCH with JSON bodies, so a thin wrapper over undici beats an SDK.\n */\nimport { Agent, request } from \"undici\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { log } from \"./log.js\";\n\n/** Said once per daemon: every box on a host that cannot do Async would repeat the same line. */\nlet syncFallbackLogged = false;\n\nexport class FirecrackerClient {\n private readonly agent: Agent;\n\n constructor(readonly socketPath: string) {\n this.agent = new Agent({ connect: { socketPath } });\n }\n\n private async call(method: \"GET\" | \"PUT\" | \"PATCH\", path: string, body?: unknown): Promise<unknown> {\n const res = await request(`http://localhost${path}`, {\n dispatcher: this.agent,\n method,\n headers: body === undefined ? {} : { \"content-type\": \"application/json\" },\n body: body === undefined ? null : JSON.stringify(body),\n });\n const text = await res.body.text();\n if (res.statusCode >= 300) {\n throw new KvboxError(`firecracker ${method} ${path} -> ${res.statusCode}: ${text}`);\n }\n return text ? JSON.parse(text) : undefined;\n }\n\n bootSource(kernelImagePath: string, bootArgs: string) {\n return this.call(\"PUT\", \"/boot-source\", { kernel_image_path: kernelImagePath, boot_args: bootArgs });\n }\n\n /** /dev/vda: the shared base image, read-only. Firecracker adds `root=/dev/vda ro` to the boot args to match. */\n rootDrive(pathOnHost: string) {\n return this.drive(\"rootfs\", pathOnHost, { root: true, readOnly: true, engine: \"Sync\" });\n }\n\n /** The box's own writable disk, /dev/vdb: the guest stacks it on the base as an overlay. */\n overlayDrive(pathOnHost: string) {\n return this.writableDrive(\"overlay\", pathOnHost);\n }\n\n /** A volume (#52): /dev/vdc and up, in the order they are added; the guest mounts it by label. */\n volumeDrive(id: string, pathOnHost: string) {\n return this.writableDrive(id, pathOnHost);\n }\n\n /**\n * A drive the guest writes to gets the Async engine (io_uring, #175): with Sync, Firecracker's one\n * VMM thread sits in the write or the fsync and the box's network waits behind it, seconds under a\n * heavy write. The base image stays on Sync, which is the faster of the two for reads the host has\n * cached. A host that cannot do Async (kernel before 5.10.51, io_uring turned off) keeps Sync.\n * The engine is part of a snapshot: a box frozen on Sync wakes on Sync, until its next cold boot.\n */\n private async writableDrive(id: string, pathOnHost: string) {\n const opts = { root: false, readOnly: false };\n try {\n return await this.drive(id, pathOnHost, { ...opts, engine: \"Async\" });\n } catch (asyncErr) {\n // Not told apart by its wording: whatever was wrong, Sync either works or gives the real error.\n const done = await this.drive(id, pathOnHost, { ...opts, engine: \"Sync\" });\n if (!syncFallbackLogged) {\n syncFallbackLogged = true;\n log.warn(`this host cannot give box disks the Async engine, they keep Sync (heavy writes in a box can stall its network): ${(asyncErr as Error).message}`);\n }\n return done;\n }\n }\n\n private drive(id: string, pathOnHost: string, opts: { root: boolean; readOnly: boolean; engine: \"Sync\" | \"Async\" }) {\n return this.call(\"PUT\", `/drives/${id}`, {\n drive_id: id,\n path_on_host: pathOnHost,\n is_root_device: opts.root,\n is_read_only: opts.readOnly,\n // \"Unsafe\" (the default) acks guest flushes without doing anything, so the last journal\n // commit of a clean shutdown can be lost when the guest resets and Firecracker exits.\n // Writeback makes a guest flush a real fsync; a box's writes must survive `kvbox stop`.\n cache_type: \"Writeback\",\n io_engine: opts.engine,\n });\n }\n\n /**\n * The host's control channel into the box: Firecracker listens on `udsPath`, a connection there\n * followed by `CONNECT <port>\\n` reaches whatever listens on that vsock port in the guest (kvbox-agent).\n */\n vsock(guestCid: number, udsPath: string) {\n return this.call(\"PUT\", \"/vsock\", { guest_cid: guestCid, uds_path: udsPath });\n }\n\n machineConfig(vcpuCount: number, memSizeMib: number) {\n // Dirty page tracking lets a snapshot write only the pages the guest touched since the last one\n // (a \"Diff\" snapshot) instead of dumping all of guest memory: sub-second instead of ~10 s frozen.\n return this.call(\"PUT\", \"/machine-config\", { vcpu_count: vcpuCount, mem_size_mib: memSizeMib, track_dirty_pages: true });\n }\n\n networkInterface(ifaceId: string, hostDevName: string, guestMac: string) {\n return this.call(\"PUT\", `/network-interfaces/${ifaceId}`, {\n iface_id: ifaceId,\n host_dev_name: hostDevName,\n guest_mac: guestMac,\n });\n }\n\n start() {\n return this.call(\"PUT\", \"/actions\", { action_type: \"InstanceStart\" });\n }\n\n /** Ask the guest to shut down cleanly (systemd handles Ctrl+Alt+Del as poweroff on Firecracker). */\n sendCtrlAltDel() {\n return this.call(\"PUT\", \"/actions\", { action_type: \"SendCtrlAltDel\" });\n }\n\n pause() {\n return this.call(\"PATCH\", \"/vm\", { state: \"Paused\" });\n }\n\n resume() {\n return this.call(\"PATCH\", \"/vm\", { state: \"Resumed\" });\n }\n\n /**\n * Full: all of guest memory, dense (seconds for a 4 GB box). Diff: only pages dirtied since the last\n * snapshot (or since boot), written sparse; needs dirty page tracking and resets its bitmap.\n */\n snapshotCreate(snapshotPath: string, memFilePath: string, type: \"Full\" | \"Diff\" = \"Full\") {\n return this.call(\"PUT\", \"/snapshot/create\", {\n snapshot_type: type,\n snapshot_path: snapshotPath,\n mem_file_path: memFilePath,\n });\n }\n\n /**\n * Restore a snapshot into this (fresh) process. The memory file is mapped privately: the guest's\n * writes never reach the snapshot. The vmstate carries the source box's tap and vsock paths; the\n * overrides point them at this box's. Drive paths are not overridable here: the vmstate names the overlay relative to the box dir (spawnFirecracker).\n */\n snapshotLoad(opts: {\n snapshotPath: string;\n memFilePath: string;\n tap: { ifaceId: string; hostDevName: string };\n vsockPath: string;\n /** Required for diff snapshots later: the flag is not part of the vmstate. */\n trackDirtyPages: boolean;\n resume: boolean;\n }) {\n return this.call(\"PUT\", \"/snapshot/load\", {\n snapshot_path: opts.snapshotPath,\n mem_backend: { backend_type: \"File\", backend_path: opts.memFilePath },\n network_overrides: [{ iface_id: opts.tap.ifaceId, host_dev_name: opts.tap.hostDevName }],\n vsock_override: { uds_path: opts.vsockPath },\n track_dirty_pages: opts.trackDirtyPages,\n resume_vm: opts.resume,\n });\n }\n\n info() {\n return this.call(\"GET\", \"/\");\n }\n\n async close() {\n await this.agent.close();\n }\n}\n","/**\n * Host networking: bridge `kvbox0`, one tap `kv-<box id>` per box, IP allocation\n * inside the subnet. Everything that needs root goes through one script,\n * `net-setup.sh`, which re-execs itself with `sudo -n` when run from here.\n * `install-server.sh` installs a root-owned copy at PRIVILEGED_SCRIPT plus a\n * sudoers rule for exactly that path; the package copy is the dev fallback.\n */\nimport { randomInt } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { Config } from \"./config.js\";\nimport { run } from \"./exec.js\";\n\nexport const TAP_PREFIX = \"kv-\";\nexport const PRIVILEGED_SCRIPT = \"/usr/local/lib/kvbox/net-setup.sh\";\n\ntype NetConfig = Pick<Config, \"bridge\" | \"subnet\" | \"gateway\">;\n\nexport function tapName(box: string): string {\n // Linux interface names are limited to 15 characters.\n return `${TAP_PREFIX}${box}`.slice(0, 15);\n}\n\n/** The script to run: KVBOX_NET_SETUP override, the root-owned install, else the package copy (dist/ or src/core/). */\nexport function netSetupScript(): string {\n const override = process.env[\"KVBOX_NET_SETUP\"];\n if (override) return override;\n if (existsSync(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;\n for (const rel of [\"../scripts/net-setup.sh\", \"../../scripts/net-setup.sh\"]) {\n const candidate = fileURLToPath(new URL(rel, import.meta.url));\n if (existsSync(candidate)) return candidate;\n }\n throw new KvboxError(\"net-setup.sh not found next to kvbox-server\");\n}\n\nexport function bridgeExists(bridge: string): boolean {\n return existsSync(`/sys/class/net/${bridge}`);\n}\n\nfunction netRun(cfg: NetConfig, args: string[]) {\n return run([netSetupScript(), ...args], {\n env: { ...process.env, KVBOX_BRIDGE: cfg.bridge, KVBOX_SUBNET: cfg.subnet, KVBOX_GATEWAY: cfg.gateway },\n }).catch((err: Error) => {\n throw new KvboxError(\n `${err.message}\\n (root is needed for host networking; install-server.sh sets up a sudoers rule for ${PRIVILEGED_SCRIPT})`,\n );\n });\n}\n\n/** The host's end of a relay tunnel (core/relay.ts, #50): `relay up <conf> | down`, root via the script. */\nexport async function netSetup(cfg: NetConfig, args: string[]): Promise<void> {\n await netRun(cfg, args);\n}\n\n/** Run `net-setup.sh up` when the bridge is missing, which is the case after every host reboot. */\nexport async function ensureHostNetwork(cfg: NetConfig): Promise<\"present\" | \"created\"> {\n if (bridgeExists(cfg.bridge)) return \"present\";\n await netRun(cfg, [\"up\"]);\n return \"created\";\n}\n\n/** The box behind a tap: the tap lets it send as this IP and MAC only (#98, a link trusts the source IP). */\nexport interface TapBox {\n id: string;\n ip: string;\n mac: string;\n}\n\n/**\n * Create the box's tap (owned by this user) and return its name. Plugged into the bridge unless\n * `detached`: a box restored from a snapshot still carries the source box's MAC and IP, so its tap\n * stays off the switch until kvbox-agent has given it its own (attachTap).\n */\nexport async function createTap(box: TapBox, cfg: NetConfig, opts: { detached?: boolean } = {}): Promise<string> {\n const tap = tapName(box.id);\n await netRun(cfg, [\"tap\", \"add\", tap, box.ip, box.mac, ...(opts.detached ? [\"detached\"] : [])]);\n return tap;\n}\n\nexport async function attachTap(box: TapBox, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"tap\", \"attach\", tapName(box.id), box.ip, box.mac]);\n}\n\n/** Pin a tap already on the bridge (a box running from before the pin, #98); `attachTap` pins the others. */\nexport async function pinTap(box: TapBox, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"tap\", \"pin\", tapName(box.id), box.ip, box.mac]);\n}\n\nexport async function deleteTap(box: string, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"tap\", \"del\", tapName(box)]);\n}\n\n// ── public ports (#49) ────────────────────────────────────────────────────────\n/** Where a box's public SSH port is drawn from: high, random, and never 22 (which every bot scans). */\nexport const SSH_PORT_MIN = 20000;\nexport const SSH_PORT_MAX = 60000;\n\n/**\n * A random port in [SSH_PORT_MIN, SSH_PORT_MAX] that is not in `taken` (other boxes' ports and\n * whatever listens on the host). Random so two boxes never get adjacent, guessable ports; after\n * a few unlucky draws it walks the range from a random start so a crowded host still gets one.\n */\nexport function pickSshPort(taken: ReadonlySet<number>): number {\n const span = SSH_PORT_MAX - SSH_PORT_MIN + 1;\n for (let i = 0; i < 32; i++) {\n const port = SSH_PORT_MIN + randomInt(span);\n if (!taken.has(port)) return port;\n }\n const start = randomInt(span);\n for (let i = 0; i < span; i++) {\n const port = SSH_PORT_MIN + ((start + i) % span);\n if (!taken.has(port)) return port;\n }\n throw new KvboxError(`no free port left between ${SSH_PORT_MIN} and ${SSH_PORT_MAX} on this host`);\n}\n\n/** Local ports out of `ss -ltnH` / `ss -lunH` output (one socket per line, the address in the 4th column). */\nexport function parseListeningPorts(ssOutput: string): Set<number> {\n const ports = new Set<number>();\n for (const line of ssOutput.split(\"\\n\")) {\n const cols = line.trim().split(/\\s+/);\n const local = cols[3];\n if (!local) continue;\n const port = Number(local.slice(local.lastIndexOf(\":\") + 1));\n if (Number.isInteger(port) && port > 0) ports.add(port);\n }\n return ports;\n}\n\n/**\n * TCP and UDP ports something on the host listens on right now, so a box's public port never\n * shadows one: a UDP forward drawn onto, say, WireGuard's random port would swallow the relay tunnel.\n * One set for both protocols: a port either one uses is not drawn.\n */\nexport async function listeningPorts(): Promise<Set<number>> {\n const ports = new Set<number>();\n for (const flags of [\"-ltnH\", \"-lunH\"]) {\n try {\n for (const port of parseListeningPorts((await run([\"ss\", flags])).stdout)) ports.add(port);\n } catch {\n // no ss: the draw still avoids other boxes' ports\n }\n }\n return ports;\n}\n\nexport interface Proxy {\n /** Box id; the rules are tagged `kvbox:<id>` so `status` and `down` find them. */\n box: string;\n boxIp: string;\n hostPort: number;\n guestPort: number;\n /** tcp unless said otherwise (#30 publishes UDP too). */\n proto?: \"tcp\" | \"udp\";\n}\n\nconst proxyArgs = (p: Proxy) => [p.box, p.boxIp, String(p.hostPort), String(p.guestPort), p.proto ?? \"tcp\"];\n\n/** DNAT `hostPort` on every non-bridge interface of the host to `boxIp:guestPort`. Idempotent. */\nexport async function openProxy(proxy: Proxy, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"proxy\", \"add\", ...proxyArgs(proxy)]);\n}\n\nexport interface Link {\n /** The target box's id: the rule is tagged `kvbox:<id>`, like its forwards. */\n box: string;\n fromIp: string;\n toIp: string;\n port: number;\n}\n\nconst linkArgs = (l: Link) => [l.box, l.fromIp, l.toIp, String(l.port)];\n\n/** Let `fromIp` open TCP connections to `toIp:port` through the host (#98). Idempotent. */\nexport async function openLink(link: Link, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"link\", \"add\", ...linkArgs(link)]);\n}\n\n/** Remove what `openLink` added, and its open connections; nothing to remove is fine. */\nexport async function closeLink(link: Link, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"link\", \"rm\", ...linkArgs(link)]);\n}\n\n/** Remove what `openProxy` added; nothing to remove is fine. */\nexport async function closeProxy(proxy: Proxy, cfg: NetConfig): Promise<void> {\n await netRun(cfg, [\"proxy\", \"rm\", ...proxyArgs(proxy)]);\n}\n\n// ── addresses ────────────────────────────────────────────────────────────────\nconst ipToInt = (ip: string) => ip.split(\".\").reduce((acc, o) => (acc << 8) + Number(o), 0) >>> 0;\nconst intToIp = (n: number) => [24, 16, 8, 0].map((s) => (n >>> s) & 255).join(\".\");\n\n/** Lowest free host address in `subnet` (a.b.c.d/len), skipping network, gateway (.1) and broadcast. */\nexport function nextFreeIp(subnet: string, inUse: readonly string[]): string {\n const [base, lenStr] = subnet.split(\"/\");\n const len = Number(lenStr);\n if (!base || !Number.isInteger(len) || len < 8 || len > 30) throw new KvboxError(`bad subnet: ${subnet}`);\n const mask = len === 0 ? 0 : (~0 << (32 - len)) >>> 0;\n const network = (ipToInt(base) & mask) >>> 0;\n const broadcast = (network | (~mask >>> 0)) >>> 0;\n const used = new Set(inUse.map(ipToInt));\n for (let n = network + 2; n < broadcast; n++) {\n if (!used.has(n)) return intToIp(n);\n }\n throw new KvboxError(`no free IP left in ${subnet}`);\n}\n\n/** Locally administered MAC derived from the IP: 06:00:<a>:<b>:<c>:<d>, unique per box and readable. */\nexport function macFor(ip: string): string {\n const hex = ip.split(\".\").map((o) => Number(o).toString(16).padStart(2, \"0\").toUpperCase());\n return [\"06\", \"00\", ...hex].join(\":\");\n}\n","/**\n * Box backups on the host (decision \"Backups: encrypted 4 MiB chunks in object storage\"; format in\n * `@kvbox/shared/backup`). The control plane drives every step and holds every key; the host never\n * holds bucket credentials, only the signed URLs it is handed for one backup or one restore.\n *\n * 1. `stageBackup`: the box's disk is copied into backups/<id>/ (a running box is paused for the copy,\n * like a snapshot, so the copy is one instant), then cut into slots and each slot named. The answer\n * is the list of names: the control plane works out which ones the bucket lacks.\n * 2. `uploadBackup`: those chunks, sealed, go to the signed PUT URLs; the staging dir goes.\n * 3. `restoreBackup`: the reverse, beside the box's disk while the box keeps running; then the box is\n * stopped, the disk swapped in and the box started again (`replaceDisk`).\n *\n * `downloadDisk` and `stageBackup` know nothing about which box the disk ends up in, so moving a box to\n * another host is a backup here and a download there.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, open, readdir, readFile, rm, stat, statfs, writeFile } from \"node:fs/promises\";\nimport { basename, join } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport type { HostBackupManifest, HostBackupRequest, HostRestoreRequest, HostUploadRequest, HostUploadResult, HostVolumeBackupManifest, HostVolumeRestoreRequest, Machine, Volume } from \"@kvbox/shared/api\";\nimport { BACKUP_ID_RE, backupKeys, CHUNK_HASH_RE, CHUNK_SIZE, chunkCount, chunkName, isZero, openChunk, openText, sealChunk, sealText, type BackupKeys } from \"@kvbox/shared/backup\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { loadConfig } from \"./config.js\";\nimport { checkBoxEnv, readBoxEnvFile } from \"./env.js\";\nimport { cloneDisk } from \"./clone.js\";\nimport { FirecrackerClient } from \"./firecracker.js\";\nimport { imageFile, imageLabel } from \"./images.js\";\nimport { withBoxLock, withHostLock } from \"./locks.js\";\nimport { recordState, replaceDisk, replaceVolumeDisk } from \"./machines.js\";\nimport { refKey, shown, type BoxRef } from \"./refs.js\";\nimport { listMachineRefs, listVolumeRefs, readMachineMeta, vmAlive, writeMachineMeta, type MachineMeta } from \"./state.js\";\nimport { chunkFetcher } from \"./storeFetch.js\";\nimport { attachedBox, readVolume } from \"./volumes.js\";\n\n/** Chunks in flight at once, each way. */\nconst PARALLEL = 4;\n/** Tries per chunk before the whole upload or download gives up. */\nconst TRIES = 4;\n/** How long one chunk's request may take. */\nconst CHUNK_TIMEOUT_MS = 120_000;\n\n/**\n * Refuse a copy of `bytes` into `dir` that would leave the filesystem every box's disk lives on with\n * less than config.json `volumeHeadroomGib` free: a full disk fails other boxes' writes.\n */\nasync function assertRoom(dir: string, bytes: number, what: string, p: Paths): Promise<void> {\n const st = await statfs(dir);\n const free = st.bavail * st.bsize;\n const headroom = (await loadConfig(p)).volumeHeadroomGib * 1024 ** 3;\n if (free - bytes < headroom) {\n const gib = (n: number) => (n / 1024 ** 3).toFixed(1);\n const needs = bytes === 0 ? \"cannot be made:\" : `needs ${gib(bytes)} GiB and`;\n throw new KvboxError(`${what} ${needs} this host has ${gib(free)} GiB free (keeping ${gib(headroom)} GiB spare); try again when it has room`);\n }\n}\n\nfunction checkId(id: string): void {\n if (!BACKUP_ID_RE.test(id)) throw new KvboxError(`not a backup id: ${id}`);\n}\n\nasync function readBox(ref: BoxRef, p: Paths): Promise<MachineMeta> {\n try {\n return await readMachineMeta(ref, p);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") throw new NotFoundError(`box ${shown(ref)}`);\n throw err;\n }\n}\n\n/** Every chunk name of a disk file, in slot order; null for a slot of zeros. */\nexport async function chunkNames(file: string, keys: BackupKeys): Promise<{ sizeBytes: number; chunks: (string | null)[] }> {\n const { size } = await stat(file);\n const chunks: (string | null)[] = [];\n const fh = await open(file, \"r\");\n try {\n const buf = Buffer.alloc(CHUNK_SIZE);\n for (let i = 0; i < chunkCount(size); i++) {\n const slot = await readSlot(fh, buf, i, size);\n chunks.push(isZero(slot) ? null : chunkName(keys, slot));\n }\n } finally {\n await fh.close();\n }\n return { sizeBytes: size, chunks };\n}\n\nasync function readSlot(fh: Awaited<ReturnType<typeof open>>, buf: Buffer, index: number, size: number): Promise<Buffer> {\n const length = Math.min(CHUNK_SIZE, size - index * CHUNK_SIZE);\n let got = 0;\n while (got < length) {\n const { bytesRead } = await fh.read(buf, got, length - got, index * CHUNK_SIZE + got);\n if (bytesRead === 0) break;\n got += bytesRead;\n }\n return buf.subarray(0, length);\n}\n\n/**\n * Step 1: clone the box's disk into the backup's own dir and name its chunks. Under the box's lock while\n * the clone is made; a running box is frozen for it only (a moment: `cloneDisk`), so what is uploaded is\n * the disk of one instant, like after a power cut.\n */\nexport async function stageBackup(ref: BoxRef, req: HostBackupRequest, p: Paths = paths()): Promise<HostBackupManifest> {\n checkId(req.id);\n const keys = backupKeys(req.key);\n const s = p.backup(req.id);\n await rm(s.dir, { recursive: true, force: true });\n await mkdir(s.dir, { recursive: true, mode: 0o700 });\n try {\n const { meta, envText } = await withBoxLock(ref, async () => {\n const meta = await readBox(ref, p);\n const m = p.machine(meta.owner, meta.name);\n // The copy is a reflink clone (core/clone.ts; a host that cannot make one takes no backups), which\n // takes almost no room when it is made: only the headroom has to be free, for what the clone grows\n // by while the box keeps writing during the upload (#185).\n await assertRoom(s.dir, 0, `a backup of box ${shown(ref)}`, p);\n await frozenClone(meta, m.overlay, s.disk, p);\n const envText = existsSync(m.env) ? await readFile(m.env, \"utf8\") : null;\n return { meta, envText };\n });\n const { sizeBytes, chunks } = await chunkNames(s.disk, keys);\n await writeFile(s.chunks, JSON.stringify({ chunks }), { mode: 0o600 });\n return {\n id: req.id,\n sizeBytes,\n chunks,\n env: envText === null ? null : sealText(keys, envText, `env:${req.id}`),\n base: meta.base,\n ...(meta.image !== undefined ? { image: meta.image } : {}),\n vcpu: meta.vcpu,\n memMib: meta.memMib,\n };\n } catch (err) {\n await rm(s.dir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/** Clone `from` to `to` as one instant of it: a running box that writes to it is paused for the clone. */\nasync function frozenClone(box: MachineMeta, from: string, to: string, p: Paths): Promise<void> {\n if (!vmAlive(box) || box.paused) return cloneDisk(from, to);\n const fc = new FirecrackerClient(p.machine(box.owner, box.name).sock);\n try {\n await fc.pause();\n try {\n await cloneDisk(from, to);\n } finally {\n await resumeAfterCopy(fc, box, p);\n }\n } finally {\n await fc.close();\n }\n}\n\n/**\n * A volume's backup, step 1 (#168): the same as a box's, of the volume's disk. The box that holds the\n * volume is the one that writes to it, so the clone is made under that box's lock, with that box paused\n * when it runs; a detached volume is cloned under the host lock an attach claims under. Steps 2 and 3 of\n * the upload are a box's (`uploadBackup`, `dropBackup`): a staged disk does not know what it came from.\n */\nexport async function stageVolumeBackup(ref: BoxRef, req: HostBackupRequest, p: Paths = paths()): Promise<HostVolumeBackupManifest> {\n checkId(req.id);\n const keys = backupKeys(req.key);\n await readVolume(ref, p);\n const from = p.volume(ref.owner, ref.name).disk;\n const s = p.backup(req.id);\n await rm(s.dir, { recursive: true, force: true });\n await mkdir(s.dir, { recursive: true, mode: 0o700 });\n try {\n await assertRoom(s.dir, 0, `a backup of volume ${shown(ref)}`, p);\n const holder = await attachedBox(ref, p);\n if (holder === null) {\n await withHostLock(\"volumes\", async () => {\n const now = await attachedBox(ref, p);\n if (now !== null) throw new KvboxError(`volume ${shown(ref)} was just attached to box ${now}; try again`);\n await cloneDisk(from, s.disk);\n });\n } else {\n const box: BoxRef = { owner: ref.owner, name: holder };\n await withBoxLock(box, async () => {\n const meta = await readBox(box, p);\n if (!meta.volumes?.includes(ref.name)) throw new KvboxError(`volume ${shown(ref)} was just detached from box ${holder}; try again`);\n await frozenClone(meta, from, s.disk, p);\n });\n }\n const { sizeBytes, chunks } = await chunkNames(s.disk, keys);\n await writeFile(s.chunks, JSON.stringify({ chunks }), { mode: 0o600 });\n return { id: req.id, sizeBytes, chunks };\n } catch (err) {\n await rm(s.dir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/**\n * A box frozen for its copy runs again. Tried twice; a box whose Firecracker is still alive but will not\n * resume is marked paused (meta.json and the usage ledger, like `kvbox pause`), so listings show it frozen\n * and `kvbox resume` can try again. One whose Firecracker died is left to show as stopped. Either way the\n * backup fails.\n */\nasync function resumeAfterCopy(fc: FirecrackerClient, meta: MachineMeta, p: Paths): Promise<void> {\n try {\n await fc.resume();\n } catch {\n try {\n await fc.resume();\n } catch (err) {\n const why = (err as Error).message;\n if (!vmAlive(meta)) throw new KvboxError(`box ${shown(meta)} stopped while its disk was copied for the backup (${why}); kvbox start ${shown(meta)}`);\n const paused: MachineMeta = { ...meta, paused: true };\n await writeMachineMeta(paused, p);\n recordState(paused, \"standby\", \"backup\", p);\n throw new KvboxError(`box ${shown(meta)} was paused for its backup and did not resume (${why}); kvbox resume ${shown(meta)}`);\n }\n }\n}\n\n/**\n * Step 2: seal and PUT each chunk the control plane asked for (the ones the bucket lacks), then drop\n * the staging dir. A chunk that fails is tried again a few times; one that keeps failing fails the\n * whole upload and leaves the dir for the control plane's `DELETE /backups/:id`.\n */\n/** Uploads in flight, by backup id: `dropBackup` aborts one, so a dropped backup stops putting chunks no row will count. */\nconst uploads = new Map<string, AbortController>();\n\nexport async function uploadBackup(id: string, req: HostUploadRequest, p: Paths = paths()): Promise<HostUploadResult> {\n checkId(id);\n const abort = new AbortController();\n uploads.get(id)?.abort();\n uploads.set(id, abort);\n try {\n return await uploadOnce(id, req, abort.signal, p);\n } finally {\n if (uploads.get(id) === abort) uploads.delete(id);\n }\n}\n\nasync function uploadOnce(id: string, req: HostUploadRequest, signal: AbortSignal, p: Paths): Promise<HostUploadResult> {\n const s = p.backup(id);\n if (!existsSync(s.chunks)) throw new NotFoundError(`backup ${id}`);\n const keys = backupKeys(req.key);\n const { chunks } = JSON.parse(await readFile(s.chunks, \"utf8\")) as { chunks: (string | null)[] };\n const slotOf = new Map<string, number>();\n chunks.forEach((name, i) => {\n if (name !== null && !slotOf.has(name)) slotOf.set(name, i);\n });\n const work = Object.entries(req.urls).map(([name, url]) => {\n const index = slotOf.get(name);\n if (index === undefined) throw new KvboxError(`backup ${id} has no chunk ${name.slice(0, 12)}`);\n return { name, url, index };\n });\n const { size } = await stat(s.disk);\n const fetchChunk = await chunkFetcher(req.pin, work[0]?.url, p);\n const fh = await open(s.disk, \"r\");\n let bytes = 0;\n const sizes: Record<string, number> = {};\n try {\n await pool(work, async ({ name, url, index }) => {\n const slot = Buffer.from(await readSlot(fh, Buffer.alloc(CHUNK_SIZE), index, size));\n const sealed = await sealChunk(keys, name, slot);\n await withTries(`upload of chunk ${index}`, async () => {\n const res = await fetchChunk(url, { method: \"PUT\", body: sealed, signal: AbortSignal.any([signal, AbortSignal.timeout(CHUNK_TIMEOUT_MS)]) });\n if (!res.ok) throw new Error(`storage answered ${res.status}: ${(await res.text()).slice(0, 200)}`);\n }, signal);\n bytes += sealed.length;\n sizes[name] = sealed.length;\n });\n } finally {\n await fh.close();\n }\n await rm(s.dir, { recursive: true, force: true });\n return { chunks: work.length, bytes, sizes };\n}\n\n/** A backup the control plane gave up on: its staging dir goes. Nothing there is not fine. */\nexport async function dropBackup(id: string, p: Paths = paths()): Promise<void> {\n checkId(id);\n uploads.get(id)?.abort();\n await rm(p.backup(id).dir, { recursive: true, force: true });\n}\n\n/**\n * Backups and restores a daemon restart cut short: nothing will upload the staged copies, and a half\n * downloaded disk (with the box's variables in the clear beside it) will never be swapped in.\n */\nexport async function clearStagedBackups(p: Paths = paths()): Promise<void> {\n await rm(p.backups, { recursive: true, force: true });\n const prefix = basename(p.machine(\"x\", \"x\").restoring);\n for (const ref of await listMachineRefs(p)) {\n const dir = p.machine(ref.owner, ref.name).dir;\n for (const f of await readdir(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm(join(dir, f), { force: true });\n }\n const volumePrefix = basename(p.volume(\"x\", \"x\").restoring);\n for (const ref of await listVolumeRefs(p)) {\n const dir = p.volume(ref.owner, ref.name).dir;\n for (const f of await readdir(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await rm(join(dir, f), { force: true });\n }\n}\n\n/**\n * A disk of `sizeBytes` at `file`, made from chunks at signed GET URLs: each is opened with the slug's\n * key and checked against its name before it is written into its slot. Slots not listed stay holes\n * (zeros). Throws, leaving `file` for the caller to remove, when a chunk cannot be fetched or opened.\n */\nexport async function downloadDisk(file: string, req: Pick<HostRestoreRequest, \"key\" | \"sizeBytes\" | \"chunks\" | \"pin\">, p: Paths = paths()): Promise<void> {\n const keys = backupKeys(req.key);\n const slots = chunkCount(req.sizeBytes);\n for (const c of req.chunks) {\n if (c.index >= slots) throw new KvboxError(`chunk ${c.index} is past the end of a ${req.sizeBytes}-byte disk`);\n if (!CHUNK_HASH_RE.test(c.hash)) throw new KvboxError(`chunk ${c.index}: not a chunk name`);\n }\n const fetchChunk = await chunkFetcher(req.pin, req.chunks[0]?.url, p);\n await writeFile(file, \"\", { mode: 0o600 });\n const fh = await open(file, \"r+\");\n try {\n await fh.truncate(req.sizeBytes);\n await pool(req.chunks, async ({ index, hash, url }) => {\n const plain = await withTries(`download of chunk ${index}`, async () => {\n const res = await fetchChunk(url, { signal: AbortSignal.timeout(CHUNK_TIMEOUT_MS) });\n if (!res.ok) throw new Error(`storage answered ${res.status}`);\n return Buffer.from(await res.arrayBuffer());\n });\n const slot = await openChunk(keys, hash, plain);\n const want = Math.min(CHUNK_SIZE, req.sizeBytes - index * CHUNK_SIZE);\n if (slot.length !== want) throw new KvboxError(`chunk ${index}: ${slot.length} bytes where the disk has room for ${want}`);\n await fh.write(slot, 0, slot.length, index * CHUNK_SIZE);\n });\n } finally {\n await fh.close();\n }\n}\n\n/** Boxes with a restore in flight: one at a time per box, since the download runs outside the box's lock. */\nconst restoring = new Set<string>();\n/** Boxes holding a volume whose restore is in flight (how many such restores): the swap stops them, so they are busy too. */\nconst holding = new Map<string, number>();\n\n/** Whether a restore of the box, or of a volume it holds, is downloading or swapping right now. */\nexport function restoreRunning(ref: BoxRef): boolean {\n return restoring.has(refKey(ref)) || holding.has(refKey(ref));\n}\n\n/**\n * Step 3: the box's disk and own variables become the backup's. The download happens beside the\n * box's disk while it keeps running; only the swap stops it (`replaceDisk`). A second restore of the\n * same box while one runs is refused, and each restore downloads into a file of its own, so two\n * never write into one disk.\n */\nexport async function restoreBackup(ref: BoxRef, req: HostRestoreRequest, p: Paths = paths()): Promise<Machine> {\n checkId(req.id);\n const k = refKey(ref);\n if (restoring.has(k)) throw new KvboxError(`a restore of box ${shown(ref)} is already running; wait for it to finish`);\n restoring.add(k);\n try {\n return await restoreOnce(ref, req, p);\n } finally {\n restoring.delete(k);\n }\n}\n\nasync function restoreOnce(ref: BoxRef, req: HostRestoreRequest, p: Paths): Promise<Machine> {\n const meta = await readBox(ref, p);\n if (!vmAlive(meta) && existsSync(p.machine(ref.owner, ref.name).hibernateVmstate)) {\n throw new KvboxError(`box ${shown(ref)} is hibernated; its memory belongs to the disk it has: kvbox wake ${shown(ref)} or kvbox stop ${shown(ref)} first`);\n }\n if (!existsSync(imageFile(req.image, req.base, p))) {\n throw new KvboxError(`this backup stacks on ${imageLabel(req.image)} ${req.base}, which this host does not have`);\n }\n const keys = backupKeys(req.key);\n const m = p.machine(ref.owner, ref.name);\n // A backup of an earlier, bigger box of the name would make this one bigger than its plan allows.\n const current = (await stat(m.overlay)).size;\n if (req.sizeBytes > current) {\n const gb = (n: number) => `${Math.ceil(n / 1024 ** 3)}GB`;\n throw new KvboxError(`this backup's disk is ${gb(req.sizeBytes)} and box ${shown(ref)}'s is ${gb(current)}: kvbox vm rescale ${shown(ref)} --disk ${gb(req.sizeBytes)} first`);\n }\n const file = `${m.restoring}.${randomBytes(4).toString(\"hex\")}`;\n const envFile = `${file}.env`;\n try {\n let vars = null;\n if (req.env !== null) {\n // Checked like any box's variables before anything is swapped.\n await writeFile(envFile, openText(keys, req.env, `env:${req.id}`), { mode: 0o600 });\n vars = await readBoxEnvFile(envFile);\n checkBoxEnv(vars); // now, not after replaceDisk has shut the box down\n }\n await assertRoom(m.dir, req.chunks.length * CHUNK_SIZE, `a restore of box ${shown(ref)}`, p);\n await downloadDisk(file, req, p);\n return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);\n } finally {\n await rm(file, { force: true });\n await rm(envFile, { force: true });\n }\n}\n\n/**\n * A volume's restore (#168): its disk becomes the backup's. Like a box's: the download happens beside\n * the volume's disk while the box that holds it keeps running on the old one; only the swap stops that\n * box (`replaceVolumeDisk`). One at a time per volume.\n */\nexport async function restoreVolumeBackup(ref: BoxRef, req: HostVolumeRestoreRequest, p: Paths = paths()): Promise<Volume> {\n checkId(req.id);\n const k = `volume:${refKey(ref)}`;\n if (restoring.has(k)) throw new KvboxError(`a restore of volume ${shown(ref)} is already running; wait for it to finish`);\n restoring.add(k);\n const v = p.volume(ref.owner, ref.name);\n const file = `${v.restoring}.${randomBytes(4).toString(\"hex\")}`;\n let held: string | null = null;\n try {\n const meta = await readVolume(ref, p);\n // Said before anything is downloaded; `replaceVolumeDisk` checks again under the box's lock.\n const holder = await attachedBox(ref, p);\n if (holder !== null) {\n // Busy to the idle watch for the whole restore: a box it hibernated mid-download would refuse the swap.\n held = refKey({ owner: ref.owner, name: holder });\n holding.set(held, (holding.get(held) ?? 0) + 1);\n const box = await readBox({ owner: ref.owner, name: holder }, p);\n if (!vmAlive(box) && existsSync(p.machine(box.owner, box.name).hibernateVmstate)) {\n throw new KvboxError(`volume ${shown(ref)} is attached to box ${shown(box)}, which is hibernated; its memory belongs to the disks it has: kvbox wake ${shown(box)} or kvbox stop ${shown(box)} first`);\n }\n }\n // A backup of an earlier, bigger volume of the name would not fit in this one.\n if (req.sizeBytes > meta.sizeGib * 1024 ** 3) {\n const gib = Math.ceil(req.sizeBytes / 1024 ** 3);\n throw new KvboxError(`this backup's volume was ${gib} GB and volume ${shown(ref)} is ${meta.sizeGib} GB: kvbox volume grow ${shown(ref)} ${gib} first`);\n }\n await assertRoom(v.dir, req.chunks.length * CHUNK_SIZE, `a restore of volume ${shown(ref)}`, p);\n await downloadDisk(file, req, p);\n return await replaceVolumeDisk(ref, file, p);\n } finally {\n restoring.delete(k);\n if (held !== null) {\n const n = (holding.get(held) ?? 1) - 1;\n if (n > 0) holding.set(held, n);\n else holding.delete(held);\n }\n await rm(file, { force: true });\n }\n}\n\n/** Run `fn` over `items`, PARALLEL at a time; the first failure stops new work and is thrown. */\nasync function pool<T>(items: readonly T[], fn: (item: T) => Promise<void>): Promise<void> {\n let next = 0;\n let failed: unknown;\n const worker = async () => {\n while (failed === undefined && next < items.length) {\n const item = items[next++]!;\n try {\n await fn(item);\n } catch (err) {\n failed ??= err;\n }\n }\n };\n await Promise.all(Array.from({ length: Math.min(PARALLEL, items.length) }, worker));\n if (failed !== undefined) throw failed;\n}\n\nasync function withTries<T>(what: string, fn: () => Promise<T>, signal?: AbortSignal): Promise<T> {\n let last: unknown;\n for (let i = 0; i < TRIES; i++) {\n if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);\n try {\n return await fn();\n } catch (err) {\n if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);\n last = err;\n await sleep(250 * 2 ** i);\n }\n }\n throw new KvboxError(`${what} failed ${TRIES} times: ${(last as Error).message}`);\n}\n","/**\n * Box backups (decision \"Backups: encrypted 4 MiB chunks in object storage\"): the format both ends\n * agree on. A box's disk is cut into fixed CHUNK_SIZE slots; a slot of zeros is not stored, every\n * other one is named by a keyed hash of its contents and stored once per slug, so a backup only sends\n * the slots that changed since any earlier backup of the same slug.\n *\n * Keys: each slug has one random data key (the control plane keeps it sealed). Two keys come out of\n * it: one names chunks (HMAC-SHA256 of the plaintext, so equal data in two slugs never shares a name\n * and a name says nothing about the data), one encrypts them. The host gets the data key for the one\n * backup or restore it runs; the bucket only ever sees ciphertext.\n *\n * A stored chunk: [flag][12-byte nonce][AES-256-GCM ciphertext][16-byte tag]. `flag` says whether the\n * plaintext was deflated (data that does not shrink is stored raw); it and the chunk's name are the\n * GCM associated data, so a chunk swapped for another, or its flag flipped, fails to open.\n *\n * Pure node:crypto and node:zlib: the host encrypts and decrypts, the control plane only signs URLs.\n */\nimport { createCipheriv, createDecipheriv, createHmac, randomBytes } from \"node:crypto\";\nimport { promisify } from \"node:util\";\nimport { deflateRaw as deflateRawCb, inflateRaw as inflateRawCb, constants as zlib } from \"node:zlib\";\n\nconst deflateRaw = promisify(deflateRawCb);\nconst inflateRaw = promisify(inflateRawCb);\n\n/** One slot of a box's disk: 4 MiB. A disk writes blocks in place, so unchanged slots keep their hash. */\nexport const CHUNK_SIZE = 4 * 1024 * 1024;\n\n/** What a backup's `id` looks like (`bk_` and 12 characters): checked by the host before it names a directory with it. */\nexport const BACKUP_ID_RE = /^bk_[A-Za-z0-9_-]{12}$/;\n\n/** A chunk's name: 64 hex characters. */\nexport const CHUNK_HASH_RE = /^[0-9a-f]{64}$/;\n\nconst FLAG_RAW = 0x01;\nconst FLAG_DEFLATE = 0x02;\nconst NONCE = 12;\nconst TAG = 16;\n\nexport interface BackupKeys {\n /** Names chunks: HMAC-SHA256 of the plaintext. */\n name: Buffer;\n /** Encrypts chunks and the box's variables. */\n seal: Buffer;\n}\n\n/** The two working keys of a slug's 32-byte data key (base64 on the wire). */\nexport function backupKeys(dataKeyB64: string): BackupKeys {\n const dk = Buffer.from(dataKeyB64, \"base64\");\n if (dk.length !== 32) throw new Error(\"backup key: expected 32 bytes\");\n return {\n name: createHmac(\"sha256\", dk).update(\"kvbox-backup chunk-name v1\").digest(),\n seal: createHmac(\"sha256\", dk).update(\"kvbox-backup chunk-seal v1\").digest(),\n };\n}\n\n/** A new slug data key, base64. */\nexport function newBackupKey(): string {\n return randomBytes(32).toString(\"base64\");\n}\n\n/** Whether a slot holds nothing but zeros (never stored: it is a hole when restored). */\nexport function isZero(buf: Buffer): boolean {\n return buf.equals(zeros(buf.length));\n}\n\nlet zeroBuf = Buffer.alloc(0);\nfunction zeros(n: number): Buffer {\n if (zeroBuf.length < n) zeroBuf = Buffer.alloc(n);\n return zeroBuf.subarray(0, n);\n}\n\n/** A chunk's name: the keyed hash of its plaintext, hex. */\nexport function chunkName(keys: BackupKeys, plain: Buffer): string {\n return createHmac(\"sha256\", keys.name).update(plain).digest(\"hex\");\n}\n\n/** The stored form of a chunk named `name`: deflated when that helps, then sealed. */\nexport async function sealChunk(keys: BackupKeys, name: string, plain: Buffer): Promise<Buffer> {\n const packed = await deflateRaw(plain, { level: zlib.Z_BEST_SPEED });\n const [flag, body] = packed.length < plain.length ? [FLAG_DEFLATE, packed] : [FLAG_RAW, plain];\n return seal(keys.seal, Buffer.from([flag]), body, `${name}:${flag}`);\n}\n\n/**\n * The plaintext of a stored chunk, checked: it must open under the slug's key with its own name, and\n * hash back to that name. Anything else (another slug's chunk, a corrupted object) throws.\n */\nexport async function openChunk(keys: BackupKeys, name: string, stored: Buffer): Promise<Buffer> {\n if (stored.length < 1 + NONCE + TAG) throw new Error(`chunk ${name.slice(0, 12)}: too short to be one`);\n const flag = stored[0]!;\n if (flag !== FLAG_RAW && flag !== FLAG_DEFLATE) throw new Error(`chunk ${name.slice(0, 12)}: unknown format ${flag}`);\n const body = unseal(keys.seal, stored.subarray(1), `${name}:${flag}`, `chunk ${name.slice(0, 12)}`);\n const plain = flag === FLAG_DEFLATE ? await inflateRaw(body, { maxOutputLength: CHUNK_SIZE }) : body;\n if (chunkName(keys, plain) !== name) throw new Error(`chunk ${name.slice(0, 12)}: contents do not match its name`);\n return plain;\n}\n\n/** A box's own variables file (env.json), sealed for the backup row: base64. */\nexport function sealText(keys: BackupKeys, text: string, label: string): string {\n return seal(keys.seal, Buffer.alloc(0), Buffer.from(text, \"utf8\"), label).toString(\"base64\");\n}\n\nexport function openText(keys: BackupKeys, sealedB64: string, label: string): string {\n return unseal(keys.seal, Buffer.from(sealedB64, \"base64\"), label, label).toString(\"utf8\");\n}\n\nfunction seal(key: Buffer, prefix: Buffer, plain: Buffer, aad: string): Buffer {\n const nonce = randomBytes(NONCE);\n const cipher = createCipheriv(\"aes-256-gcm\", key, nonce);\n cipher.setAAD(Buffer.from(aad));\n const data = Buffer.concat([cipher.update(plain), cipher.final()]);\n return Buffer.concat([prefix, nonce, data, cipher.getAuthTag()]);\n}\n\nfunction unseal(key: Buffer, sealed: Buffer, aad: string, what: string): Buffer {\n if (sealed.length < NONCE + TAG) throw new Error(`${what}: too short`);\n const nonce = sealed.subarray(0, NONCE);\n const tag = sealed.subarray(sealed.length - TAG);\n const data = sealed.subarray(NONCE, sealed.length - TAG);\n try {\n const decipher = createDecipheriv(\"aes-256-gcm\", key, nonce);\n decipher.setAAD(Buffer.from(aad));\n decipher.setAuthTag(tag);\n return Buffer.concat([decipher.update(data), decipher.final()]);\n } catch {\n throw new Error(`${what}: does not open with this slug's backup key (changed or not this slug's)`);\n }\n}\n\n/** How many slots a disk of `bytes` has. */\nexport function chunkCount(bytes: number): number {\n return Math.ceil(bytes / CHUNK_SIZE);\n}\n","/**\n * The copy a backup is taken from (decision \"A backup's disk copy is a reflink clone or nothing…\"): a\n * clone, which the host's filesystem (XFS) makes in an instant and which takes no room until the\n * original changes. Where the filesystem cannot clone there is no backup: a full copy would freeze a\n * running box for as long as it takes (#157) and need the disk's whole size free.\n */\nimport { rm } from \"node:fs/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { run } from \"./exec.js\";\n\n/**\n * How long a clone may take: an instant, but a heavily fragmented disk of terabytes on XFS takes a while,\n * and the box stays paused for all of it. The full copy this replaced had the same bound.\n */\nexport const CLONE_TIMEOUT_MS = 600_000;\n\nexport async function cloneDisk(from: string, to: string, timeoutMs = CLONE_TIMEOUT_MS): Promise<void> {\n const started = Date.now();\n try {\n await run([\"cp\", \"--reflink=always\", from, to], { timeoutMs });\n } catch (err) {\n await rm(to, { force: true });\n if (Date.now() - started >= timeoutMs) {\n throw new KvboxError(`the instant copy of the disk took more than ${Math.round(timeoutMs / 1000)} s and was stopped; the box was paused for that long. Try again; if it keeps happening, the host's operator should look at its disk`);\n }\n const why = (err as Error).message;\n if (/failed to clone|not supported|cross-device|Invalid cross/i.test(why)) {\n throw new KvboxError(\"this host cannot take backups: its disk cannot make an instant copy of a box's disk (kvbox hosts keep their boxes on XFS); the host's operator has to move it to XFS\");\n }\n throw err;\n }\n}\n","/**\n * How a host reaches a backup store for a chunk (core/backups.ts). A store is another host's HTTPS\n * listener, whose certificate is self-signed: the control plane hands over that certificate's sha256\n * fingerprint (`pin`) with the signed URLs, and a connection is kept only when the peer presents it.\n * When the store is this very host, the connection goes to localhost instead of out to its public\n * address and back (through a relay, that is the whole uplink twice); the URL, and so the `Host` the\n * signature covers, stay as they were. Without a pin (a store with a public certificate) it is a plain fetch.\n */\nimport type { TLSSocket } from \"node:tls\";\nimport { Agent, buildConnector, fetch as pinnedFetch, type Dispatcher } from \"undici\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { loadConfig } from \"./config.js\";\n\nexport interface ChunkResponse {\n ok: boolean;\n status: number;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n}\nexport type ChunkFetch = (url: string, init: { method?: \"PUT\"; body?: Buffer; signal: AbortSignal }) => Promise<ChunkResponse>;\n\nconst dispatchers = new Map<string, Dispatcher>();\n\n/** One dispatcher per fingerprint (and per \"it is this host\"): full handshakes only, a resumed session has no certificate to check. */\nexport function storeDispatcher(pin: string, local: boolean): Dispatcher {\n const id = `${pin}|${local}`;\n const have = dispatchers.get(id);\n if (have) return have;\n const plain = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0, timeout: 10_000 });\n const connect: buildConnector.connector = (opts, cb) => {\n plain(local ? { ...opts, hostname: \"127.0.0.1\" } : opts, (err, socket) => {\n if (err || !socket) return cb(err ?? new Error(\"no socket\"), null);\n const tls = socket as TLSSocket;\n const got = typeof tls.getPeerCertificate === \"function\" ? tls.getPeerCertificate().fingerprint256 : undefined;\n if (got !== pin) {\n socket.destroy();\n return cb(new Error(\"the backup store's certificate is not the one the control plane knows (fingerprint mismatch)\"), null);\n }\n cb(null, socket);\n });\n };\n const agent = new Agent({ connect });\n dispatchers.set(id, agent);\n return agent;\n}\n\n/** The fetch for one backup's or one restore's URLs. */\nexport async function chunkFetcher(pin: string | undefined, sampleUrl: string | undefined, p: Paths = paths()): Promise<ChunkFetch> {\n if (pin === undefined) return (url, init) => fetch(url, init);\n const cfg = await loadConfig(p);\n const cp = cfg.controlPlane;\n let local = false;\n if (cfg.backupStore && cp && sampleUrl !== undefined) {\n const target = new URL(sampleUrl);\n local = target.hostname === cp.advertise && Number(target.port || 443) === cp.port;\n }\n const dispatcher = storeDispatcher(pin, local);\n return (url, init) => pinnedFetch(url, { ...init, dispatcher }) as Promise<ChunkResponse>;\n}\n","/**\n * The host's side of a relay (#50). A home host behind a router has no public address of its own;\n * a relay (a small public VM, set up with install-relay.sh) owns one for it and forwards it down a\n * WireGuard tunnel the host dials out. `kvbox-relay add` on the relay prints a join string; here it\n * becomes a wg-quick conf under relay/, which net-setup.sh installs as /etc/wireguard/kvbox.conf\n * and enables (root). config.json keeps what the rest of the server needs: the public IP `join`\n * advertises by default, the tunnel address, the endpoint. The private key stays in the conf.\n */\nimport { access, chmod, mkdir, rm, writeFile } from \"node:fs/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { decodeRelayJoin, RELAY_TUNNEL_GATEWAY, type RelayJoin } from \"@kvbox/shared/relay\";\nimport { loadConfig, saveConfig, type Relay } from \"./config.js\";\nimport { DEFAULT_HTTPS_PORT } from \"./controlPlane.js\";\nimport { netSetup } from \"./network.js\";\n\n/** The wg-quick conf for the host's end of the tunnel. */\nexport function relayConf(join: RelayJoin): string {\n return [\n \"# kvbox relay tunnel: made by `kvbox-server relay`, installed by net-setup.sh. Do not edit.\",\n \"[Interface]\",\n `PrivateKey = ${join.privateKey}`,\n `Address = ${join.tunnelIp}/32`,\n \"\",\n \"[Peer]\",\n `PublicKey = ${join.relayKey}`,\n `Endpoint = ${join.relay}`,\n // Only the relay's own tunnel address goes through the tunnel: the host keeps its normal internet\n // route, and the relay SNATs forwarded connections so their replies come back this way.\n `AllowedIPs = ${RELAY_TUNNEL_GATEWAY}/32`,\n // The router forgets an idle outbound mapping; a packet every 25 s keeps the relay able to reach us.\n \"PersistentKeepalive = 25\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Decode the join string, write the conf, bring the tunnel up (root via net-setup.sh), remember the relay. */\nexport async function useRelay(joinString: string, p: Paths = paths()): Promise<Relay> {\n const join = decodeRelayJoin(joinString);\n if (!join) throw new KvboxError(\"that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay\");\n const cfg = await loadConfig(p);\n if (cfg.relay && cfg.relay.name !== join.name) {\n throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox-server relay off first`);\n }\n // A re-issued string may carry another public IP; the control plane would keep calling the old one.\n if (cfg.relay && cfg.relay.publicIp !== join.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {\n throw new KvboxError(\n `${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join.publicIp}; run kvbox-server leave first, then join again`,\n );\n }\n await mkdir(p.relay, { recursive: true, mode: 0o700 });\n await writeFile(p.relayConf, relayConf(join), { mode: 0o600 });\n await chmod(p.relayConf, 0o600);\n // The root helper also lets the control plane's port in on the tunnel interface (a host firewall would drop it).\n await netSetup(cfg, [\"relay\", \"up\", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);\n const relay: Relay = { name: join.name, publicIp: join.publicIp, tunnelIp: join.tunnelIp, endpoint: join.relay };\n await saveConfig({ ...cfg, relay }, p);\n return relay;\n}\n\n/**\n * Put the tunnel's firewall rule back after a host reboot (#114). wg-quick@kvbox is enabled, so the\n * tunnel itself comes back on its own, but iptables rules are not persisted (and ufw rebuilds the tables\n * at boot): the INPUT rule letting the control plane's port in on the tunnel interface was gone, and\n * every box showed `unknown`. `relay up` is idempotent: the installed conf and an existing rule are\n * skipped, a live tunnel is only reloaded. Returns the relay, or null when the host has none.\n */\nexport async function restoreRelay(p: Paths = paths()): Promise<Relay | null> {\n const cfg = await loadConfig(p);\n if (!cfg.relay) return null;\n // The conf is what `relay up` installs; without it (removed by hand) there is nothing to re-apply.\n await access(p.relayConf);\n await netSetup(cfg, [\"relay\", \"up\", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);\n return cfg.relay;\n}\n\n/** Take the tunnel down and forget the relay. Refused while a control plane still reaches this host through it. */\nexport async function dropRelay(p: Paths = paths()): Promise<Relay> {\n const cfg = await loadConfig(p);\n const relay = cfg.relay;\n if (!relay) throw new KvboxError(\"this host does not go through a relay\");\n if (cfg.controlPlane?.advertise === relay.publicIp) {\n throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);\n }\n await netSetup(cfg, [\"relay\", \"down\"]);\n await rm(p.relayConf, { force: true });\n const { relay: _gone, ...rest } = cfg;\n await saveConfig(rest, p);\n return relay;\n}\n","/**\n * The relay join string (#50). A home host behind a router gets a public address through a relay:\n * a small public VM with one extra IPv4 per host and a WireGuard tunnel the host dials out. The\n * relay's `kvbox-relay add <name> --ip <public-ip>` (kvbox-relay.sh at the repo root, bash: it builds\n * the same base64url token) makes the host's keypair and prints this string once; the host's\n * `kvbox-server relay <string>` turns it into its tunnel. It carries the host's\n * private key, so it is a secret. The control plane never sees any of it: the host just advertises\n * the public IP.\n */\nimport { z } from \"zod\";\n\n/** Where WireGuard listens on the relay's primary address. */\nexport const RELAY_WG_PORT = 51820;\n/** The tunnel network: the relay is .1, hosts are .2 onwards. */\nexport const RELAY_TUNNEL_SUBNET = \"10.77.0.0/24\";\nexport const RELAY_TUNNEL_GATEWAY = \"10.77.0.1\";\n\nconst IPV4_RE = /^(\\d{1,3})(\\.\\d{1,3}){3}$/;\nconst WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;\n\nexport const RelayJoinSchema = z.object({\n v: z.literal(1),\n /** How the relay lists this host. */\n name: z.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),\n /** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */\n relay: z.string().regex(/^(\\d{1,3})(\\.\\d{1,3}){3}:\\d{1,5}$/),\n /** The relay's WireGuard public key. */\n relayKey: z.string().regex(WG_KEY_RE),\n /** This host's address inside the tunnel. */\n tunnelIp: z.string().regex(IPV4_RE),\n /** This host's WireGuard private key, generated on the relay, kept nowhere else. */\n privateKey: z.string().regex(WG_KEY_RE),\n /** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */\n publicIp: z.string().regex(IPV4_RE),\n});\nexport type RelayJoin = z.infer<typeof RelayJoinSchema>;\n\n/** The string the relay prints: base64url of the JSON, one token the owner can paste. */\nexport function encodeRelayJoin(join: RelayJoin): string {\n return Buffer.from(JSON.stringify(RelayJoinSchema.parse(join)), \"utf8\").toString(\"base64url\");\n}\n\n/** The string back into its fields, or null when it is not a relay join string. */\nexport function decodeRelayJoin(text: string): RelayJoin | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(text.trim(), \"base64url\").toString(\"utf8\"));\n } catch {\n return null;\n }\n const res = RelayJoinSchema.safeParse(parsed);\n return res.success ? res.data : null;\n}\n","/**\n * The host's side of the control plane (#18, design in the brain's multi-host doc). A host joins\n * exactly one control plane with a one-time token an admin minted there; it gets back a secret the\n * control plane will present on every call, and from its next start it also serves the API over\n * HTTPS. The control plane trusts the host by the fingerprint of the self-signed certificate made\n * here (no CA), so the certificate is generated once and kept for the host's life.\n */\nimport { X509Certificate } from \"node:crypto\";\nimport { chmod, mkdir, readFile } from \"node:fs/promises\";\nimport { hostname as osHostname } from \"node:os\";\nimport { request } from \"undici\";\nimport { parseCountry } from \"@kvbox/shared/country\";\nimport { HostJoinResponseSchema, HostSshCaResponseSchema, type CloudCa, type HostJoinRequest } from \"@kvbox/shared/api\";\nimport { parseSshPublicKey, sshKeyFingerprint } from \"@kvbox/shared/ssh\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { loadConfig, saveConfig } from \"./config.js\";\nimport { run } from \"./exec.js\";\nimport { REALM_RE } from \"./refs.js\";\n\nexport const DEFAULT_HTTPS_PORT = 7777;\n\n/** The certificate's sha256 fingerprint, `AA:BB:…`, the form the control plane pins. */\nexport interface TlsIdentity {\n fingerprint: string;\n}\n\n/** Generate `tls/key.pem` + `tls/cert.pem` on first use (openssl, EC P-256, 10 years); return the fingerprint either way. */\nexport async function ensureTlsCert(p: Paths = paths()): Promise<TlsIdentity> {\n const have = await readFile(p.tlsCert, \"utf8\").catch(() => null);\n const haveKey = await readFile(p.tlsKey).then(() => true, () => false);\n if (have === null || !haveKey) {\n await mkdir(p.tls, { recursive: true, mode: 0o700 });\n try {\n await run([\n \"openssl\", \"req\", \"-x509\", \"-newkey\", \"ec\", \"-pkeyopt\", \"ec_paramgen_curve:prime256v1\", \"-nodes\",\n \"-keyout\", p.tlsKey, \"-out\", p.tlsCert, \"-subj\", \"/CN=kvbox-host\", \"-days\", \"3650\",\n ]);\n } catch (err) {\n throw new KvboxError(`could not make the host's certificate (is openssl installed?): ${(err as Error).message}`);\n }\n await chmod(p.tlsKey, 0o600);\n }\n const pem = await readFile(p.tlsCert, \"utf8\");\n return { fingerprint: new X509Certificate(pem).fingerprint256 };\n}\n\nexport interface JoinOptions {\n /** The control plane, e.g. https://api.kvbox.sh. */\n url: string;\n /** One-time token an admin minted there. */\n token: string;\n /** Host or IP the control plane reaches this host at; default: the address of this host's default route. */\n advertise?: string;\n /** How the control plane lists this host; default: the hostname. */\n name?: string;\n /** Where this host is (`romania`, `RO`): `kvbox new --country` places boxes by it. */\n country?: string;\n port?: number;\n}\n\nexport interface Joined {\n hostName: string;\n controlPlane: string;\n /** Where the control plane will call this host: https://<advertise>:<port>. */\n hostUrl: string;\n}\n\n/** RFC 1918, loopback, link-local and carrier-grade NAT: addresses a control plane on the internet cannot reach. */\nexport function isPrivateAddress(ip: string): boolean {\n const m = /^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(ip);\n if (!m) return false;\n const [a, b] = [Number(m[1]), Number(m[2])];\n return a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);\n}\n\n/** The IPv4 this host would use to reach the internet: the `src` of the default route. */\nexport async function defaultAdvertise(): Promise<string> {\n const { stdout } = await run([\"ip\", \"-4\", \"route\", \"get\", \"1.1.1.1\"]).catch((err: Error) => {\n throw new KvboxError(`cannot tell this host's address (${err.message}); pass --advertise <host-or-ip>`);\n });\n const m = /\\bsrc\\s+(\\S+)/.exec(stdout);\n if (!m) throw new KvboxError(\"cannot tell this host's address from its routes; pass --advertise <host-or-ip>\");\n return m[1]!;\n}\n\n/**\n * Register this host with a control plane: make sure it has a certificate, send the join, keep the\n * secret in config.json. The server picks the HTTPS listener up at its next start.\n */\nexport async function joinControlPlane(opts: JoinOptions, p: Paths = paths(), guessAddress: () => Promise<string> = defaultAdvertise): Promise<Joined> {\n const url = opts.url.replace(/\\/+$/, \"\");\n const port = opts.port ?? DEFAULT_HTTPS_PORT;\n const cfg = await loadConfig(p);\n if (cfg.controlPlane) throw new KvboxError(`this host has already joined ${cfg.controlPlane.name} (${cfg.controlPlane.url}); run kvbox-server leave first`);\n let advertise = opts.advertise;\n if (advertise === undefined && cfg.relay) {\n // Behind a relay the host's own addresses are beside the point: the relay's public IP is where it is reached.\n advertise = cfg.relay.publicIp;\n } else if (advertise === undefined) {\n advertise = await guessAddress();\n if (isPrivateAddress(advertise)) {\n throw new KvboxError(\n `${advertise} is a private address: a control plane on the internet cannot reach this host there.\\n` +\n ` Pass --advertise <public host or ip>, or --advertise ${advertise} if the control plane is on the same network.`,\n );\n }\n }\n const name = opts.name ?? osHostname();\n const country = opts.country === undefined ? undefined : parseCountry(opts.country); // a typo fails here, before the token is spent\n const { fingerprint } = await ensureTlsCert(p);\n const hostUrl = `https://${advertise}:${port}`;\n const body: HostJoinRequest = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...(country !== undefined ? { country } : {}) };\n\n const res = await request(`${url}/hosts/join`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n headersTimeout: 10_000,\n bodyTimeout: 10_000,\n }).catch((err: Error) => {\n throw new KvboxError(`cannot reach ${url} (${err.message})`);\n });\n const text = await res.body.text();\n if (res.statusCode < 200 || res.statusCode >= 300) {\n throw new KvboxError(errorIn(text) ?? `control plane answered ${res.statusCode}`);\n }\n const parsed = HostJoinResponseSchema.safeParse(jsonOrNull(text));\n if (!parsed.success) throw new KvboxError(`${url} did not answer like a kvbox control plane`);\n if (!REALM_RE.test(parsed.data.controlPlane.name)) {\n throw new KvboxError(`${url} calls itself \"${parsed.data.controlPlane.name}\", which cannot name a realm (letters, digits, '.', '-')`);\n }\n\n await saveConfig({ ...cfg, controlPlane: { url, name: parsed.data.controlPlane.name, secret: parsed.data.hostSecret, advertise, port } }, p);\n return { hostName: name, controlPlane: parsed.data.controlPlane.name, hostUrl };\n}\n\n/**\n * Ask the joined control plane which SSH CA boxes should trust (`GET /hosts/self/ssh-ca`, by the\n * host secret), with its fingerprint, for `kvbox-server trust-ca --from-cloud` to show before\n * anything changes (#55).\n */\nexport async function fetchCloudCa(p: Paths = paths()): Promise<CloudCa> {\n const cfg = await loadConfig(p);\n const cp = cfg.controlPlane;\n if (!cp) throw new KvboxError(\"this host has not joined a control plane, so there is no CA to fetch; paste the key instead: kvbox-server trust-ca <public-key>\");\n const res = await request(`${cp.url}/hosts/self/ssh-ca`, {\n headers: { authorization: `Bearer ${cp.secret}` },\n headersTimeout: 10_000,\n bodyTimeout: 10_000,\n }).catch((err: Error) => {\n throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);\n });\n const text = await res.body.text();\n if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not answer /hosts/self/ssh-ca: it is older than this host; paste the key instead`);\n if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(errorIn(text) ?? `${cp.name} answered ${res.statusCode}`);\n const parsed = HostSshCaResponseSchema.safeParse(jsonOrNull(text));\n if (!parsed.success) throw new KvboxError(`${cp.name} did not answer with a CA key`);\n const publicKey = parseSshPublicKey(parsed.data.publicKey);\n return { controlPlane: cp.name, publicKey, fingerprint: sshKeyFingerprint(publicKey) };\n}\n\n/**\n * What the joined control plane calls itself now (`GET /health`, its `name`): the realm\n * `kvbox-server rename-realm` moves this host's cloud boxes to when no name is given.\n */\nexport async function fetchCloudName(p: Paths = paths()): Promise<string> {\n const cfg = await loadConfig(p);\n const cp = cfg.controlPlane;\n if (!cp) throw new KvboxError(\"this host has not joined a control plane, so there is no name to ask for; give it: kvbox-server rename-realm <name>\");\n const res = await request(`${cp.url}/health`, { headersTimeout: 10_000, bodyTimeout: 10_000 }).catch((err: Error) => {\n throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);\n });\n const text = await res.body.text();\n if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(`${cp.url} answered ${res.statusCode}`);\n const name = (jsonOrNull(text) as { name?: unknown } | null)?.name;\n if (typeof name !== \"string\" || !REALM_RE.test(name)) throw new KvboxError(`${cp.url} did not say its name; give it: kvbox-server rename-realm <name>`);\n return name;\n}\n\nexport interface Left {\n controlPlane: string;\n /** Whether the control plane acknowledged; false means an admin has to remove the host there. */\n told: boolean;\n}\n\n/** Forget the control plane (the HTTPS listener stops at the next start) and tell it so, best effort. */\nexport async function leaveControlPlane(p: Paths = paths()): Promise<Left> {\n const cfg = await loadConfig(p);\n const cp = cfg.controlPlane;\n if (!cp) throw new KvboxError(\"this host has not joined a control plane\");\n const told = await request(`${cp.url}/hosts/self`, {\n method: \"DELETE\",\n headers: { authorization: `Bearer ${cp.secret}` },\n headersTimeout: 3000,\n bodyTimeout: 3000,\n })\n .then(async (res) => {\n await res.body.dump();\n return res.statusCode >= 200 && res.statusCode < 300;\n })\n .catch(() => false);\n const { controlPlane: _gone, ...rest } = cfg;\n // A backup store stays set up, but the control plane no longer knows it: `backup setup` registers it again after a join.\n await saveConfig({ ...rest, ...(rest.backupStore ? { backupStore: { ...rest.backupStore, registered: false } } : {}) }, p);\n return { controlPlane: cp.name, told };\n}\n\nfunction jsonOrNull(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n\n/** The `{ error }` of a kvbox JSON answer, if that is what the text is. */\nfunction errorIn(text: string): string | undefined {\n const v = jsonOrNull(text);\n if (v && typeof v === \"object\" && typeof (v as { error?: unknown }).error === \"string\") return (v as { error: string }).error;\n return undefined;\n}\n","/**\n * Where a host is: an ISO 3166-1 alpha-2 code (`RO`, `US`). People type a code or an English name\n * (`romania`, `United States`, `usa`); Node's own ICU (`Intl.DisplayNames`) maps between the two, so\n * there is no table to keep.\n */\nimport { KvboxError } from \"./errors.js\";\n\nconst names = new Intl.DisplayNames([\"en\"], { type: \"region\", fallback: \"none\" });\n\n/** Region codes ICU knows that are not a country a host can be in. */\nconst NOT_COUNTRIES = new Set([\"EU\", \"EZ\", \"UN\", \"QO\", \"XA\", \"XB\", \"ZZ\"]);\n\n/** Common short names ICU's English names do not cover. */\nconst ALIASES: Record<string, string> = { usa: \"US\", america: \"US\", uk: \"GB\", britain: \"GB\", england: \"GB\", holland: \"NL\" };\n\nconst fold = (s: string) =>\n s\n .normalize(\"NFD\")\n .replace(/[̀-ͯ]/g, \"\")\n .toLowerCase()\n .replace(/[^a-z]/g, \"\");\n\nlet byName: Map<string, string> | undefined;\nfunction nameIndex(): Map<string, string> {\n if (byName) return byName;\n byName = new Map(Object.entries(ALIASES));\n for (let a = 65; a <= 90; a++) {\n for (let b = 65; b <= 90; b++) {\n const code = String.fromCharCode(a, b);\n const name = countryName(code);\n // a retired code (DD, UK, YU) shares or outlived its country's name: only current codes name one\n if (name !== undefined && canonical(code) === code) byName.set(fold(name), code);\n }\n }\n return byName;\n}\n\n/** ICU's current code for a retired one (UK -> GB, DD -> DE); the code itself otherwise. */\nfunction canonical(code: string): string {\n return /-([A-Z]{2})$/.exec(Intl.getCanonicalLocales(`und-${code}`)[0] ?? \"\")?.[1] ?? code;\n}\n\n/** The English name of a country code, or undefined when it is not one. */\nexport function countryName(code: string): string | undefined {\n if (!/^[A-Z]{2}$/.test(code) || NOT_COUNTRIES.has(code)) return undefined;\n return names.of(code);\n}\n\n/** `ro`, `RO`, `Romania`, `usa` -> the country code; a KvboxError for anything else. */\nexport function parseCountry(input: string): string {\n const t = input.trim();\n const upper = t.toUpperCase();\n const code = countryName(upper) !== undefined ? canonical(upper) : nameIndex().get(fold(t));\n if (code !== undefined) return code;\n throw new KvboxError(`unknown country \"${input}\": give its name or its two-letter code, e.g. RO or US`);\n}\n","/**\n * Auto-hibernate (#47): a box with `autoHibernateSec` whose tap has carried no traffic, either way, for\n * that long is hibernated, so the host gets its RAM back and the meter moves to the cheaper state.\n * `connect` and `exec` already wake a hibernated box, and their ssh sends a keepalive every minute, so a\n * quiet open session counts as traffic. Any byte counts as activity; CPU-only work with nobody connected\n * looks idle (the guest's own view comes with #67). Only running boxes are watched: one in standby was\n * paused on purpose, for an instant resume. When a box was last active is kept in memory only, so a\n * server restart gives every box its full timeout again.\n *\n * A box may decide itself (#102): one with an `idleCheck` (its image's `idle` by default, or `kvbox vm set\n * --idle-check`) is asked through kvbox-agent instead, and its answer alone counts (a GitHub runner's open\n * connection never goes quiet). An error, a timeout or an agent too old to know the request is a busy answer.\n */\nimport { readFile } from \"node:fs/promises\";\nimport type { Machine } from \"@kvbox/shared/api\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { idle as agentIdle } from \"./agent.js\";\nimport { restoreRunning } from \"./backups.js\";\nimport { boxBusy, withBoxLock } from \"./locks.js\";\nimport { getMachine, hibernateMachine, listMachines } from \"./machines.js\";\nimport { tapName } from \"./network.js\";\nimport { boxHasRun } from \"./runs.js\";\nimport { log as daemonLog } from \"./log.js\";\n\n/** Hibernations at once: each one dumps a box's whole memory to disk. */\nconst HIBERNATE_CONCURRENCY = 2;\n\nexport interface IdleWatchOptions {\n intervalMs?: number;\n /** Every box on the host. */\n list?: () => Promise<Machine[]>;\n /** rx + tx bytes of a box's tap; null when it cannot be read (no tap). */\n traffic?: (id: string) => Promise<number | null>;\n /** For a box with an idle check (#102): whether it says idle. null: no check, watch the traffic. A rejection is a busy answer. */\n guestIdle?: (box: Machine) => Promise<boolean | null>;\n /** Hibernate the box if it still runs; false when it no longer did. */\n hibernate?: (box: Machine) => Promise<boolean>;\n /** Whether a caller's operation holds the box right now. */\n busy?: (box: Machine) => boolean;\n now?: () => number;\n log?: (line: string) => void;\n p?: Paths;\n}\n\n/** Bytes the box's tap has moved in both directions since it was created. */\nexport async function tapTraffic(id: string): Promise<number | null> {\n const dir = `/sys/class/net/${tapName(id)}/statistics`;\n try {\n const [rx, tx] = await Promise.all([readFile(`${dir}/rx_bytes`, \"utf8\"), readFile(`${dir}/tx_bytes`, \"utf8\")]);\n return Number(rx) + Number(tx);\n } catch {\n return null;\n }\n}\n\n/** The box's idle check (#102), if it has one: asked through kvbox-agent. Rejects when the check could not answer. */\nasync function boxIdle(box: Machine, p: Paths): Promise<boolean | null> {\n if (box.idleCheck === undefined) return null;\n return agentIdle(p.machine(box.owner, box.name).vsock, box.idleCheck);\n}\n\n/**\n * Under the box's lock: hibernate it unless something paused, stopped or hibernated it since the listing,\n * or a command was started in it since the round's check (runs are started outside the lock).\n */\nasync function hibernateIfRunning(box: Machine, p: Paths): Promise<boolean> {\n const ref = { owner: box.owner, name: box.name };\n return withBoxLock(ref, async () => {\n if ((await getMachine(ref, p)).status !== \"running\" || restoreRunning(ref) || boxHasRun(ref)) return false;\n await hibernateMachine(ref, p, \"auto-hibernate\");\n return true;\n });\n}\n\n/**\n * Start watching; returns a stop function. Also returns `round` so tests can drive it without timers:\n * one check plus the hibernations it started. The timer runs only the check, so a long dump does not\n * hold back the next minute's check of every other box.\n */\nexport function startIdleWatch(opts: IdleWatchOptions = {}): { stop: () => void; round: () => Promise<void> } {\n const intervalMs = opts.intervalMs ?? 60_000;\n const p = opts.p ?? paths();\n const list = opts.list ?? (() => listMachines(null, p));\n const traffic = opts.traffic ?? tapTraffic;\n const guestIdle = opts.guestIdle ?? ((box: Machine) => boxIdle(box, p));\n const hibernate = opts.hibernate ?? ((box: Machine) => hibernateIfRunning(box, p));\n // A restore downloads outside the box's lock and refuses a hibernated box at the swap: busy too.\n // So is a command a cron trigger started in it (core/runs.ts): it must not be frozen half way.\n const busy = opts.busy ?? ((box: Machine) => boxBusy(box) || restoreRunning(box) || boxHasRun(box));\n const now = opts.now ?? Date.now;\n const log = opts.log ?? ((line: string) => daemonLog.info(line));\n // box id -> the tap's byte count when it last changed (-1 for a box its own check watches), and when that was\n const seen = new Map<string, { bytes: number; since: number }>();\n // box id -> why its idle check last failed, so the log says it once rather than every minute\n const checkErrors = new Map<string, string>();\n let timer: NodeJS.Timeout | undefined;\n let stopped = false;\n\n // boxes being hibernated right now\n const inflight = new Set<string>();\n\n const hibernateOne = async (box: Machine, quiet: number, bytes: number, t: number) => {\n inflight.add(box.id);\n const byImage = bytes < 0;\n try {\n if (await hibernate(box)) log(`box ${box.owner}/${box.name}: ${byImage ? \"idle by its own check\" : \"no network traffic\"} for ${quiet} min; hibernated it (kvbox connect wakes it)`);\n seen.delete(box.id);\n } catch (err) {\n // Try again after another full timeout rather than every round.\n log(`warning: box ${box.owner}/${box.name}: could not hibernate it after ${quiet} min ${byImage ? \"idle\" : \"without traffic\"}: ${(err as Error).message}`);\n seen.set(box.id, { bytes, since: t });\n } finally {\n inflight.delete(box.id);\n }\n };\n\n /** The box's idle check answer; a failure is busy, logged once per reason. */\n const askIdle = (box: Machine): Promise<boolean | null> =>\n guestIdle(box).then(\n (v) => (checkErrors.delete(box.id), v),\n (err: Error) => {\n if (checkErrors.get(box.id) !== err.message) log(`warning: box ${box.owner}/${box.name}: its idle check ${box.idleCheck ?? \"\"} failed, so it counts as busy and does not hibernate: ${err.message}`);\n checkErrors.set(box.id, err.message);\n return false;\n },\n );\n\n const check = async (): Promise<Promise<void>[]> => {\n const started: Promise<void>[] = [];\n const watched = new Set<string>();\n const due: Machine[] = [];\n for (const box of await list()) {\n // A box other boxes link to waits for their TCP, which does not wake it (#98): it stays up.\n if (!box.autoHibernateSec || box.status !== \"running\" || box.links?.length) continue;\n if (inflight.has(box.id)) watched.add(box.id);\n else due.push(box);\n }\n // Every box's idle check at once: each may take up to 15 s, and one slow guest must not hold up the round.\n const verdicts = await Promise.all(due.map(askIdle));\n for (const [i, box] of due.entries()) {\n const verdict = verdicts[i] ?? null;\n const bytes = verdict === null ? await traffic(box.id) : -1;\n if (bytes === null) continue;\n watched.add(box.id);\n const t = now();\n const last = seen.get(box.id);\n // A caller working on the box (a snapshot, a resize) is activity too.\n if (!last || last.bytes !== bytes || verdict === false || busy(box)) {\n seen.set(box.id, { bytes, since: t });\n continue;\n }\n if (t - last.since < box.autoHibernateSec! * 1000) continue;\n if (inflight.size >= HIBERNATE_CONCURRENCY) continue; // next round: it stays due\n started.push(hibernateOne(box, Math.round((t - last.since) / 60_000), bytes, t));\n }\n // A box that slept, stopped or lost its timeout starts over when it is watched again.\n for (const id of seen.keys()) if (!watched.has(id)) seen.delete(id);\n for (const id of checkErrors.keys()) if (!watched.has(id)) checkErrors.delete(id);\n return started;\n };\n\n const round = async () => {\n await Promise.all(await check());\n };\n\n const schedule = () => {\n if (stopped) return;\n timer = setTimeout(() => void check().catch((err: Error) => log(`warning: idle watch: ${err.message}`)).finally(schedule), intervalMs);\n timer.unref();\n };\n schedule();\n return {\n stop: () => {\n stopped = true;\n clearTimeout(timer);\n },\n round,\n };\n}\n","/**\n * Commands started in a box and left to run (#190: a cron trigger's command). The host only passes\n * the request to kvbox-agent, which runs the command as a systemd unit of the box's user and remembers\n * how it ended; the caller asks again until it is over. Unlocked, like `runBoxScript`: a box that stops\n * mid-question just fails this one answer.\n *\n * A box with a command going is not idle: auto-hibernate (core/idle.ts) asks `boxHasRun`, which knows\n * the runs started or asked about through this daemon. Kept in memory only, like the idle watch's own\n * clock: a restart forgets them until the caller's next question about a run brings it back.\n */\nimport type { BoxRun, StartRunRequest } from \"@kvbox/shared/api\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { isNoAgent, isUnknownOp, runStatus, startRun } from \"./agent.js\";\nimport { stateMessage, statusOf } from \"./machines.js\";\nimport { shown, type BoxRef } from \"./refs.js\";\nimport { readMachineMeta } from \"./state.js\";\n\n/** The box's image has a kvbox-agent from before commands. */\nexport class BoxOutdatedError extends KvboxError {}\n\n/** A run seen `running` counts for this long without another answer: the caller asks at least once a minute. */\nconst SEEN_RUNNING_MS = 3 * 60_000;\n/** box key -> run id -> until when it counts as going */\nconst going = new Map<string, Map<string, number>>();\nconst keyOf = (ref: BoxRef) => `${ref.owner}/${ref.name}`;\n\nfunction note(ref: BoxRef, id: string, until: number | null): void {\n const key = keyOf(ref);\n const runs = going.get(key);\n if (until === null) {\n runs?.delete(id);\n if (runs?.size === 0) going.delete(key);\n return;\n }\n // a question never shortens the hold a start gave (its time limit): only an ended run clears it\n if (runs) runs.set(id, Math.max(until, runs.get(id) ?? 0));\n else going.set(key, new Map([[id, until]]));\n}\n\n/** Whether a command started here may still be running in the box. */\nexport function boxHasRun(ref: BoxRef, now = Date.now()): boolean {\n const runs = going.get(keyOf(ref));\n if (!runs) return false;\n for (const [id, until] of runs) if (until <= now) runs.delete(id);\n if (runs.size === 0) going.delete(keyOf(ref));\n return runs.size > 0;\n}\n\n/** Tests start from nothing. */\nexport const forgetRuns = (): void => going.clear();\n\nasync function socketOf(ref: BoxRef, p: Paths): Promise<string> {\n const meta = await readMachineMeta(ref, p).catch((err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") throw new NotFoundError(`box ${shown(ref)}`);\n throw err;\n });\n const status = statusOf(meta, p);\n if (status !== \"running\") throw new KvboxError(`${stateMessage(ref, status)}; only a running box runs a command`);\n return p.machine(meta.owner, meta.name).vsock;\n}\n\nconst outdated = (ref: BoxRef, err: unknown): never => {\n if (isUnknownOp(err)) throw new BoxOutdatedError(`box ${shown(ref)} runs on an image from before commands (it needs base v0.15.0 or later)`);\n if (isNoAgent(err)) throw new KvboxError(`box ${shown(ref)} did not take the request: its kvbox-agent is not answering (${(err as Error).message})`);\n throw err;\n};\n\n/** Start `req.command` in a running box. False: a run of that id was already there. */\nexport async function startBoxRun(ref: BoxRef, req: StartRunRequest, p: Paths = paths()): Promise<boolean> {\n const vsock = await socketOf(ref, p);\n // Held before the agent is asked, so an auto-hibernate deciding meanwhile sees it; a little past its\n // deadline: the agent kills it then, and the next question clears it anyway.\n const had = going.get(keyOf(ref))?.has(req.id) ?? false;\n note(ref, req.id, Date.now() + req.timeoutSec * 1000 + 60_000);\n return startRun(vsock, req.id, req.command, req.timeoutSec).catch((err) => {\n if (!had) note(ref, req.id, null);\n return outdated(ref, err);\n });\n}\n\nexport async function boxRunStatus(ref: BoxRef, id: string, p: Paths = paths()): Promise<BoxRun> {\n const vsock = await socketOf(ref, p);\n const run = await runStatus(vsock, id).catch((err) => outdated(ref, err));\n note(ref, id, run.state === \"running\" ? Date.now() + SEEN_RUNNING_MS : null);\n return { id, ...run };\n}\n","/**\n * Keeps a relay tunnel (#50) carrying traffic. After the relay VM reboots, the home router can keep a\n * stale mapping for the tunnel's UDP flow: the relay still gets our handshakes, but nothing it sends\n * reaches us, and wg-quick never notices (seen 2026-10-26, every box went `unknown`). Restarting the\n * tunnel makes WireGuard dial from a new port, which the router maps afresh. So while the host uses\n * a relay, the server pings the relay's tunnel address and restarts the tunnel after a few misses.\n */\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { RELAY_TUNNEL_GATEWAY } from \"@kvbox/shared/relay\";\nimport { loadConfig } from \"./config.js\";\nimport { run } from \"./exec.js\";\nimport { netSetup } from \"./network.js\";\nimport { log as daemonLog } from \"./log.js\";\n\n/** What `/health` reports: restarts since this server started. */\nexport interface RelayWatchReport {\n restarts: number;\n lastRestartAt: string | null;\n}\n\nexport interface RelayWatchOptions {\n intervalMs?: number;\n /** Misses in a row before a restart. */\n misses?: number;\n /** Does the relay answer through the tunnel? */\n probe?: () => Promise<boolean>;\n restart?: () => Promise<void>;\n log?: (line: string) => void;\n p?: Paths;\n}\n\nlet report: RelayWatchReport = { restarts: 0, lastRestartAt: null };\n\nexport function relayWatchReport(): RelayWatchReport {\n return report;\n}\n\n/** One ICMP echo to the relay's end of the tunnel. */\nexport async function pingRelay(): Promise<boolean> {\n try {\n await run([\"ping\", \"-c\", \"1\", \"-W\", \"3\", RELAY_TUNNEL_GATEWAY], { timeoutMs: 5000 });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Start watching; returns a stop function. The config is read on every round, so `kvbox-server relay`\n * (no daemon restart) starts or ends the watching without telling us. While the relay itself is down\n * the tunnel is restarted every `misses` rounds; that costs nothing and only the first is logged.\n */\nexport function startRelayWatch(opts: RelayWatchOptions = {}): () => void {\n const intervalMs = opts.intervalMs ?? 30_000;\n const misses = opts.misses ?? 3;\n const probe = opts.probe ?? pingRelay;\n const p = opts.p ?? paths();\n const log = opts.log ?? ((line: string) => daemonLog.info(line));\n const restart = opts.restart ?? (async () => netSetup(await loadConfig(p), [\"relay\", \"restart\"]));\n report = { restarts: 0, lastRestartAt: null };\n let missed = 0;\n let stuck = false; // restarted, and the relay has not answered since\n let timer: NodeJS.Timeout | undefined;\n let stopped = false;\n\n const round = async () => {\n const cfg = await loadConfig(p).catch(() => null);\n if (!cfg?.relay) {\n missed = 0;\n return;\n }\n if (await probe()) {\n if (stuck) log(`relay ${cfg.relay.name}: the tunnel carries traffic again`);\n missed = 0;\n stuck = false;\n return;\n }\n if (++missed < misses) return;\n missed = 0;\n if (!stuck) log(`relay ${cfg.relay.name}: no answer through the tunnel for ${(misses * intervalMs) / 1000} s; restarting it`);\n try {\n await restart();\n report = { restarts: report.restarts + 1, lastRestartAt: new Date().toISOString() };\n } catch (err) {\n if (!stuck) daemonLog.warn(`relay ${cfg.relay.name}: could not restart the tunnel: ${(err as Error).message}`);\n }\n stuck = true;\n };\n\n const schedule = () => {\n if (stopped) return;\n timer = setTimeout(() => void round().catch((err: Error) => daemonLog.warn(`relay watch: ${err.message}`)).finally(schedule), intervalMs);\n timer.unref();\n };\n schedule();\n return () => {\n stopped = true;\n clearTimeout(timer);\n };\n}\n","/**\n * The daemon as a process, for the operator subcommands (`kvbox-server status|stop|start -d`, and the\n * restart after `join` / `leave`): is it running, stop it, start it in the background. Where\n * install-server.sh set up the systemd unit for this home (#29), the start goes through systemd, so the\n * server running is the one it keeps and brings back at boot; otherwise this binary spawns itself\n * detached with its output in server.log. Boxes are Firecracker processes of their own: none of this\n * touches them.\n */\nimport { spawn } from \"node:child_process\";\nimport { accessSync, constants, openSync, readFileSync, statSync } from \"node:fs\";\nimport { mkdir, readFile, stat } from \"node:fs/promises\";\nimport { userInfo } from \"node:os\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { hasUnitFor, startUnitProcess, UNIT, unitActive, unitPid } from \"@kvbox/shared/systemd\";\nimport { KVM_DEVICE } from \"./core/kvm.js\";\nimport { SocketClient } from \"./socketClient.js\";\n\n/** The pid in server.pid when that process exists, else null. */\nexport async function runningPid(p: Paths = paths()): Promise<number | null> {\n let pid: number;\n try {\n pid = Number.parseInt(await readFile(p.serverPid, \"utf8\"), 10);\n } catch {\n return null;\n }\n return Number.isInteger(pid) && alive(pid) ? pid : null;\n}\n\n/**\n * The daemon's pid: server.pid's when that process lives, else the systemd unit's when it serves this home\n * (a daemon whose pid file was deleted under it, #159, is still found, so status and stop can reach it).\n */\nexport async function daemonPid(p: Paths = paths()): Promise<number | null> {\n return (await runningPid(p)) ?? (hasUnitFor(p) ? unitPid() : null);\n}\n\n/**\n * Throws when another kvbox-server already serves this home (#159). A second daemon must never start: it\n * clears the staged backups, then takes the socket and pid file from the first, or, failing its HTTPS bind,\n * deletes them and leaves the first running but unreachable. Checked by every foreground start, before it\n * touches anything. This process's own pid does not count (a stale pid file from before a reboot may\n * name it, and under systemd the unit's pid is this process).\n */\nexport async function refuseSecondDaemon(p: Paths = paths()): Promise<void> {\n const live = await answering(p);\n if (live) throw new KvboxError(`kvbox-server is already running (pid ${live.pid}); kvbox-server status shows it`);\n const pid = await daemonPid(p);\n if (pid !== null && pid !== process.pid && isKvboxServer(pid)) {\n throw new KvboxError(`kvbox-server is already running (pid ${pid}) but its socket is gone, so nothing can reach it; restart it: kvbox-server stop, then kvbox-server start -d`);\n }\n}\n\n/**\n * A pid file outlives its process, and the pid may be reused by something else by now. argv[0] is left\n * out: it is the interpreter (node), whose own path may well contain \"kvbox\" (a runner on a kvbox box).\n */\nfunction isKvboxServer(pid: number): boolean {\n try {\n return readFileSync(`/proc/${pid}/cmdline`, \"utf8\").split(\"\\0\").slice(1).some((arg) => arg.includes(\"kvbox\"));\n } catch (err) {\n return (err as NodeJS.ErrnoException).code !== \"ENOENT\";\n }\n}\n\nfunction alive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** SIGTERM the daemon and resolve once the process is gone (boxes keep running; systemd does not restart a clean stop). */\nexport async function stopDaemon(pid: number, timeoutMs = 10_000): Promise<void> {\n process.kill(pid, \"SIGTERM\");\n const deadline = Date.now() + timeoutMs;\n while (alive(pid)) {\n if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1000}s`);\n await sleep(100);\n }\n}\n\nexport interface Started {\n pid: number;\n socketPath: string;\n /** The group `sg` switched to so the daemon can open /dev/kvm (#61); undefined for a plain start. */\n viaGroup: string | undefined;\n /** True when systemd started it (the unit install-server.sh wrote serves this home). */\n viaUnit: boolean;\n /** Set when a daemon already answered on the socket: nothing was started, this is its version. */\n alreadyRunning?: string;\n}\n\n/**\n * The daemon answering on this home's socket, else null. A second daemon must never start beside it:\n * before listening it clears the staged backups (a backup running in the first is lost), then takes the\n * socket and pid file, or, failing its HTTPS bind, deletes them and leaves the first unreachable.\n */\nexport async function answering(p: Paths = paths()): Promise<{ pid: number; version: string } | null> {\n if (!(await stat(p.serverSock).then(() => true, () => false))) return null;\n const probe = new SocketClient(p.serverSock);\n try {\n const health = await probe.health();\n return { pid: health.pid, version: health.version };\n } catch {\n return null;\n } finally {\n await probe.close();\n }\n}\n\n/**\n * Start the daemon in the background and resolve once its socket answers /health (or reject after\n * `timeoutMs`, or as soon as it exits); when one already answers, start nothing and return it. With the systemd unit for this home, `systemctl start` does it.\n * Without, this binary spawns itself (`start`), detached, stdout and stderr appended to server.log; through\n * `sg <group>` when this shell cannot open /dev/kvm but the user is in its group (#61).\n */\nexport async function startDetached(p: Paths = paths(), timeoutMs = 5000): Promise<Started> {\n await mkdir(p.home, { recursive: true });\n const running = await answering(p);\n if (running) return { pid: running.pid, socketPath: p.serverSock, viaGroup: undefined, viaUnit: false, alreadyRunning: running.version };\n if (hasUnitFor(p)) return startUnit(p, timeoutMs);\n const log = openSync(p.serverLog, \"a\");\n const launcher = selfLauncher();\n const child = spawn(launcher.cmd, launcher.args, { detached: true, stdio: [\"ignore\", log, log], env: { ...process.env, KVBOX_HOME: p.home } });\n\n const failed = new Promise<never>((_, reject) => {\n child.once(\"error\", (err: Error) => reject(new KvboxError(`could not start kvbox-server: ${err.message}`)));\n child.once(\"exit\", (code) => {\n void lastErrorLine(p.serverLog).then((why) => {\n reject(new KvboxError(why === undefined ? `kvbox-server exited with code ${String(code)} before listening; see ${p.serverLog}` : `kvbox-server could not start: ${why}`));\n });\n });\n });\n\n await Promise.race([serving(p, timeoutMs), failed]);\n child.removeAllListeners(\"exit\");\n child.unref();\n return { pid: await pidFile(p, child.pid ?? -1), socketPath: p.serverSock, viaGroup: launcher.viaGroup, viaUnit: false };\n}\n\n/** Stop the daemon when it runs, then start it: how a join or a leave takes effect. */\nexport async function restartDaemon(p: Paths = paths()): Promise<Started> {\n const pid = await runningPid(p);\n if (pid !== null) await stopDaemon(pid);\n return startDetached(p);\n}\n\nasync function startUnit(p: Paths, timeoutMs: number): Promise<Started> {\n const logFrom = await stat(p.serverLog).then((s) => s.size, () => 0);\n const res = startUnitProcess();\n if (!res.ok) {\n const why = res.out || (await lastErrorLine(p.serverLog, logFrom)) || \"systemctl start failed\";\n throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT}; rerun install-server.sh if sudo asked for a password)`);\n }\n await serving(p, timeoutMs, async () => {\n if (unitActive()) return;\n const why = (await lastErrorLine(p.serverLog, logFrom)) ?? \"it exited right after starting\";\n throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT})`);\n });\n return { pid: await pidFile(p, -1), socketPath: p.serverSock, viaGroup: undefined, viaUnit: true };\n}\n\n/** The pid the daemon wrote itself (the child here may be sg or systemd's), else `fallback`. */\nasync function pidFile(p: Paths, fallback: number): Promise<number> {\n const pid = Number.parseInt(await readFile(p.serverPid, \"utf8\").catch(() => \"\"), 10);\n return Number.isNaN(pid) ? fallback : pid;\n}\n\n/** Resolve once the socket answers /health; reject after `timeoutMs`, or when `check` throws (polled while waiting). */\nasync function serving(p: Paths, timeoutMs: number, check?: () => Promise<void>): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n await check?.();\n if (await stat(p.serverSock).then(() => true, () => false)) {\n const probe = new SocketClient(p.serverSock);\n try {\n await probe.health();\n return;\n } catch {\n // socket exists but not serving yet\n } finally {\n await probe.close();\n }\n }\n await sleep(100);\n }\n throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1000}s; see ${p.serverLog}`);\n}\n\n/**\n * The last error line of server.log, which is why a daemon that just died did not come up: a\n * `[time][error]: …` line (core/log.ts), or a plain `error: …` from an older server. `from`: only\n * what was written past that byte offset (this start's lines, not an earlier run's).\n */\nexport async function lastErrorLine(logPath: string, from = 0): Promise<string | undefined> {\n const text = (await readFile(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString(\"utf8\");\n for (const line of text.trimEnd().split(\"\\n\").slice(-20).reverse()) {\n const m = /^(?:\\[[^\\]]*\\])?\\[?error\\]?: (.*)$/.exec(line);\n if (m?.[1] !== undefined) return m[1];\n }\n return undefined;\n}\n\ninterface Launcher {\n cmd: string;\n args: string[];\n viaGroup?: string;\n}\n\n/**\n * The argv that runs this very binary's `start`: plain, or through `sg <group>` when this process cannot\n * open /dev/kvm but /etc/group says the user is in the device's group (#61: a shell from before the user\n * was added to the group hands its stale group list to everything it spawns). Anything else (no device,\n * user not in the group) is left to the daemon's own check, which explains it in plain words.\n */\nexport function selfLauncher(opts: { device?: string; groupFile?: string; user?: string } = {}): Launcher {\n const device = opts.device ?? KVM_DEVICE;\n const argv = [process.execPath, ...process.execArgv, process.argv[1] ?? \"kvbox-server\", \"start\"];\n const plain: Launcher = { cmd: argv[0]!, args: argv.slice(1) };\n try {\n accessSync(device, constants.R_OK | constants.W_OK);\n return plain;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"EACCES\" && code !== \"EPERM\") return plain;\n }\n let gid: number;\n try {\n gid = statSync(device).gid;\n } catch {\n return plain;\n }\n const group = groupWithMember(gid, opts.user ?? userInfo().username, opts.groupFile ?? \"/etc/group\");\n if (group === undefined) return plain;\n // sg runs a shell string: every word is single-quoted, so a path with a space or a quote survives.\n return { cmd: \"sg\", args: [group, \"-c\", argv.map(shellQuote).join(\" \")], viaGroup: group };\n}\n\nfunction shellQuote(word: string): string {\n return `'${word.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/** The name of the group with this gid when the group file lists `user` among its members, else undefined. */\nexport function groupWithMember(gid: number, user: string, groupFile: string): string | undefined {\n let text: string;\n try {\n text = readFileSync(groupFile, \"utf8\");\n } catch {\n return undefined;\n }\n for (const line of text.split(\"\\n\")) {\n const [name, , id, members = \"\"] = line.split(\":\");\n if (name === undefined || id === undefined || Number.parseInt(id, 10) !== gid) continue;\n return members.split(\",\").includes(user) ? name : undefined;\n }\n return undefined;\n}\n","/**\n * The systemd unit install-server.sh writes so kvbox-server starts at boot (#29): a system unit that\n * runs the server as the installing user. When it serves this KVBOX_HOME, the CLI starts the daemon\n * through it (`sudo -n`, the sudoers rule allows exactly that) instead of spawning one beside it.\n */\nimport { spawnSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { Paths } from \"./paths.js\";\n\nexport const UNIT = \"kvbox-server\";\nexport const UNIT_FILE = `/etc/systemd/system/${UNIT}.service`;\n\n/** True when the unit exists and runs the server on `p.home` (a dev or test KVBOX_HOME has none). */\nexport function hasUnitFor(p: Paths, file = UNIT_FILE): boolean {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch {\n return false;\n }\n const home = /^Environment=\"?KVBOX_HOME=([^\"\\n]+)\"?$/m.exec(text)?.[1];\n return home !== undefined && resolve(home) === resolve(p.home);\n}\n\n/** `sudo -n systemctl start kvbox-server`; what it said when it failed. */\nexport function startUnitProcess(): { ok: boolean; out: string } {\n const res = spawnSync(\"sudo\", [\"-n\", \"systemctl\", \"start\", UNIT], { encoding: \"utf8\" });\n return { ok: res.status === 0, out: `${res.stdout ?? \"\"}${res.stderr ?? \"\"}`.trim() };\n}\n\n/**\n * False once the unit's server has exited: systemd then shows it waiting to restart (\"activating\")\n * or given up (\"failed\"). `systemctl start` returns as soon as a Type=simple unit forks, so this is\n * how a server that dies right away is told apart from one still coming up.\n */\nexport function unitActive(): boolean {\n const res = spawnSync(\"systemctl\", [\"is-active\", UNIT], { encoding: \"utf8\" });\n return (res.stdout ?? \"\").trim() === \"active\";\n}\n\n/** The unit's running process, or null (no systemd, or the unit is not running). */\nexport function unitPid(): number | null {\n const res = spawnSync(\"systemctl\", [\"show\", UNIT, \"-p\", \"MainPID\", \"--value\"], { encoding: \"utf8\" });\n const pid = Number.parseInt((res.stdout ?? \"\").trim(), 10);\n return Number.isInteger(pid) && pid > 0 ? pid : null;\n}\n\n/** Whether the server comes back by itself after a reboot: the unit serves this home and is enabled. */\nexport function startsAtBoot(p: Paths): boolean {\n return hasUnitFor(p) && spawnSync(\"systemctl\", [\"is-enabled\", \"--quiet\", UNIT]).status === 0;\n}\n","/**\n * The operator subcommands' way to the running daemon: plain HTTP over its Unix socket, the API the CLI\n * speaks. `status` reads /health here; `trust-ca` goes through the socket rather than core because a box's\n * lock (core/locks.ts) is in-process, so only the daemon may change a box.\n */\nimport { Agent, request } from \"undici\";\nimport type { z } from \"zod\";\nimport { ApiErrorSchema, BackupStoreStatusSchema, CloudCaSchema, HealthSchema, TrustCaReportSchema, type BackupStoreSetupRequest, type TrustCaRequest } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\n\nexport class SocketClient {\n private readonly agent: Agent;\n\n constructor(socketPath: string) {\n this.agent = new Agent({ connect: { socketPath } });\n }\n\n health() {\n return this.call(\"GET\", \"/health\", HealthSchema);\n }\n\n cloudCa() {\n return this.call(\"GET\", \"/ssh/cloud-ca\", CloudCaSchema);\n }\n\n trustCa(req: TrustCaRequest) {\n return this.call(\"POST\", \"/ssh/trust-ca\", TrustCaReportSchema, req);\n }\n\n backupStore() {\n return this.call(\"GET\", \"/backup-store\", BackupStoreStatusSchema);\n }\n /** Downloads Garage the first time, so it may take minutes. */\n setupBackupStore(req: BackupStoreSetupRequest) {\n return this.call(\"POST\", \"/backup-store\", BackupStoreStatusSchema, req, 15 * 60_000);\n }\n async close(): Promise<void> {\n await this.agent.close();\n }\n\n private async call<T>(method: \"GET\" | \"POST\", path: string, schema: z.ZodType<T>, body?: unknown, timeoutMs?: number): Promise<T> {\n let res: Awaited<ReturnType<typeof request>>;\n try {\n res = await request(`http://kvbox-server${path}`, {\n method,\n dispatcher: this.agent,\n ...(timeoutMs === undefined ? {} : { headersTimeout: timeoutMs, bodyTimeout: timeoutMs }),\n ...(body === undefined ? {} : { headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(body) }),\n });\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code ?? \"\";\n if (code === \"ENOENT\" || code === \"ECONNREFUSED\") throw new KvboxError(\"kvbox-server is not running; start it with: kvbox-server start -d\");\n throw new KvboxError(`cannot reach kvbox-server: ${(err as Error).message}`);\n }\n const text = await res.body.text();\n if (res.statusCode >= 300) {\n const parsed = ApiErrorSchema.safeParse(safeJson(text) ?? {});\n if (!parsed.success) throw new KvboxError(`kvbox-server answered ${res.statusCode}`);\n throw new KvboxError(parsed.data.error, res.statusCode === 501 ? 2 : 1);\n }\n const json = safeJson(text);\n if (json === undefined) throw new KvboxError(`kvbox-server answered ${res.statusCode} with something that is not JSON`);\n return schema.parse(json);\n }\n}\n\nfunction safeJson(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n","/**\n * Bind the app to the local Unix socket and write the pid file. A host that joined a control plane\n * (`kvbox-server join`) also serves a second instance of the app over HTTPS with its own\n * certificate; that instance demands the host secret on every call (caller.ts).\n */\nimport { readFile, rm, writeFile } from \"node:fs/promises\";\nimport { createServer as createHttpsServer } from \"node:https\";\nimport type { IncomingMessage, Server, ServerResponse } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { createAdaptorServer, type ServerType } from \"@hono/node-server\";\nimport { ensureLayout } from \"./core/state.js\";\nimport { loadConfig } from \"./core/config.js\";\nimport { stopRecovery } from \"./core/machines.js\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { REQUEST_TIMEOUT_MS } from \"@kvbox/shared/names\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { createApp } from \"./app.js\";\nimport { refuseSecondDaemon } from \"./daemon.js\";\nimport { cronCheck, edgeCheck, secretCheck } from \"./caller.js\";\nimport { boxUpgradeHandler } from \"./routes/boxHttp.js\";\nimport { forStore, storeProxy } from \"./core/backupStore.js\";\n\nexport interface ListenOptions {\n socketPath?: string;\n /** Overrides the joined control plane's port (tests: 0 picks a free one). */\n httpsPort?: number;\n}\n\nexport interface Listening {\n socketPath: string;\n server: ServerType;\n /** Present when the host has joined a control plane. */\n https?: { port: number; url: string };\n close: () => Promise<void>;\n}\n\nexport async function listen(opts: ListenOptions = {}): Promise<Listening> {\n const p = await ensureLayout(paths());\n const cfg = await loadConfig(p);\n const socketPath = opts.socketPath ?? p.serverSock;\n // Linux limits a Unix socket path (sun_path) to 108 bytes; bind() fails with EINVAL past it.\n if (Buffer.byteLength(socketPath) > 100) {\n throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);\n }\n\n // Never beside a running daemon (#159): the rm below would take its socket from it.\n if (socketPath === p.serverSock) await refuseSecondDaemon(p);\n // A stale socket file from a crashed server blocks bind(); the pid file tells\n // `kvbox-server status` whether anything is actually alive.\n await rm(socketPath, { force: true });\n\n const server = createAdaptorServer({ fetch: createApp().fetch });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(socketPath, () => resolve());\n });\n await writeFile(p.serverPid, `${process.pid}\\n`);\n\n let https: Listening[\"https\"];\n let httpsServer: ServerType | undefined;\n const cp = cfg.controlPlane;\n if (cp) {\n const [key, cert] = await Promise.all([readFile(p.tlsKey), readFile(p.tlsCert)]).catch((err: Error) => {\n throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);\n });\n httpsServer = createAdaptorServer({\n fetch: createApp({ controlPlane: { name: cp.name, secret: cp.secret } }).fetch,\n createServer: createHttpsServer,\n // A body forwarded to a box may take long to arrive (a large upload through the edge, #182).\n serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS },\n });\n // A backup store's chunks (core/backupStore.ts) come in on this listener too and never reach the app:\n // a path under the bucket's name is Garage's, which checks the signed URL itself.\n const appListeners = httpsServer.listeners(\"request\") as ((req: IncomingMessage, res: ServerResponse) => void)[];\n httpsServer.removeAllListeners(\"request\");\n httpsServer.on(\"request\", (req: IncomingMessage, res: ServerResponse) => {\n if (forStore(req.url, p)) return storeProxy(req, res);\n for (const l of appListeners) l.call(httpsServer, req, res);\n });\n const secret = secretCheck(cp);\n const edge = edgeCheck(cp);\n const cron = cronCheck(cp);\n limitUntrusted(httpsServer as Server, (req) => secret(req.headers.authorization) || edge(req.headers.authorization) || cron(req.headers.authorization));\n // WebSockets to a box's web server (#31) never reach the app: the server hands them over raw.\n httpsServer.on(\"upgrade\", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));\n const port = opts.httpsPort ?? cp.port;\n await new Promise<void>((resolve, reject) => {\n httpsServer!.once(\"error\", reject);\n httpsServer!.listen(port, \"0.0.0.0\", () => resolve());\n }).catch(async (err: Error) => {\n server.close();\n await rm(socketPath, { force: true });\n await rm(p.serverPid, { force: true });\n throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);\n });\n const bound = (httpsServer.address() as AddressInfo).port;\n https = { port: bound, url: `https://${cp.advertise}:${bound}` };\n }\n\n /** Tests: wait for both listeners to let go. */\n const close = async () => {\n await Promise.all([\n new Promise<void>((resolve) => server.close(() => resolve())),\n httpsServer ? new Promise<void>((resolve) => httpsServer!.close(() => resolve())) : undefined,\n ]);\n await rm(socketPath, { force: true });\n await rm(p.serverPid, { force: true });\n };\n // A signal must end the process even mid-request (a box creation can take a while and\n // `kvbox-server stop` sends one SIGTERM): stop accepting, drop the files, exit. Only boxes being\n // brought back after a reboot are waited for, so none is left running unrecorded (#29).\n const shutdown = async () => {\n server.close();\n httpsServer?.close();\n await stopRecovery();\n await rm(socketPath, { force: true });\n await rm(p.serverPid, { force: true });\n process.exit(0);\n };\n process.once(\"SIGINT\", () => void shutdown());\n process.once(\"SIGTERM\", () => void shutdown());\n\n return https ? { socketPath, server, https, close } : { socketPath, server, close };\n}\n\n/** Node's own limit on receiving a request, which a caller without credentials keeps. */\nexport const UNTRUSTED_REQUEST_MS = 300_000;\n\n/**\n * The HTTPS server gives a request `REQUEST_TIMEOUT_MS` (an hour) to arrive, for uploads forwarded\n * from the edge; a caller with neither the host secret nor the edge's credential still gets Node's\n * five minutes, so a body dripped by anyone on the internet does not hold a socket for an hour.\n */\nexport function limitUntrusted(server: Server, trusted: (req: IncomingMessage) => boolean, ms = UNTRUSTED_REQUEST_MS): void {\n server.on(\"request\", (req: IncomingMessage) => {\n if (trusted(req)) return;\n const timer = setTimeout(() => req.socket.destroy(), ms);\n timer.unref();\n const done = () => clearTimeout(timer);\n req.once(\"end\", done);\n req.once(\"close\", done);\n });\n}\n","/**\n * HTTPS names for boxes (#31, decision \"A box claims one subdomain\"): a box claims one subdomain\n * `<sub>.kvbox.app` with a default port, and named ports nest under it as `<name>.<sub>.kvbox.app`.\n * Both are single DNS labels. The CLI checks them before calling; the control plane checks again.\n */\nimport { createHmac } from \"node:crypto\";\nimport { KvboxError } from \"./errors.js\";\n\n/** Where box URLs live (decision d2cb4d88's domain); the control plane and the edge can be told otherwise. */\nexport const DEFAULT_PROXY_DOMAIN = \"kvbox.app\";\n/**\n * Names kvbox gives out itself (#182): `s3-<slug>` is a slug's object storage address, so a box never\n * claims a name starting like one.\n */\nexport const STORAGE_SUBDOMAIN_PREFIX = \"s3-\";\n\n/** Subdomains one box may claim (`<sub>.kvbox.app`); every one is covered by the `*.kvbox.app` certificate. */\nexport const MAX_BOX_SUBDOMAINS = 5;\n\n/** A domain box names may live under (`kvbox.app`): the control plane's and the edge's must match. */\nexport function assertProxyDomain(text: string, key: string): string {\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(text)) throw new KvboxError(`${key} must be a domain like ${DEFAULT_PROXY_DOMAIN}: ${text}`);\n return text;\n}\n\n/** One DNS label: lowercase letters, digits and `-`, never at either end. */\nconst LABEL_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n\n/** Subdomains nobody may claim: the platform's own names, and ones that would read as ours. */\nexport const RESERVED_SUBDOMAINS: ReadonlySet<string> = new Set([\n \"admin\",\n \"api\",\n \"app\",\n \"assets\",\n \"auth\",\n \"billing\",\n \"blog\",\n \"cdn\",\n \"dashboard\",\n \"dev\",\n \"docs\",\n \"edge\",\n \"help\",\n \"install\",\n \"kvbox\",\n \"login\",\n \"mail\",\n \"relay\",\n \"root\",\n \"smtp\",\n \"static\",\n \"status\",\n \"support\",\n \"www\",\n]);\n\n/** Why `text` cannot be a claimed subdomain, or null when it can. */\nexport function subdomainProblem(text: string): string | null {\n if (text.length < 3 || text.length > 63) return `\"${text}\" must be 3 to 63 characters`;\n if (!LABEL_RE.test(text)) return `\"${text}\" may hold only lowercase letters, digits and '-', not at either end`;\n if (RESERVED_SUBDOMAINS.has(text)) return `\"${text}\" is reserved; pick another name`;\n return null;\n}\n\n/** Why `text` cannot be a name under a subdomain (`<name>.<sub>`), or null when it can. */\nexport function routeNameProblem(text: string): string | null {\n if (text.length < 1 || text.length > 63) return `\"${text}\" must be 1 to 63 characters`;\n if (!LABEL_RE.test(text)) return `\"${text}\" may hold only lowercase letters, digits and '-', not at either end`;\n return null;\n}\n\nexport function assertSubdomain(text: string): string {\n const problem = subdomainProblem(text);\n if (problem) throw new KvboxError(`subdomain ${problem}`);\n return text;\n}\n\nexport function assertRouteName(text: string): string {\n const problem = routeNameProblem(text);\n if (problem) throw new KvboxError(`name ${problem}`);\n return text;\n}\n\n/** `https://<sub>.<domain>`, or `https://<name>.<sub>.<domain>` for a named port. */\nexport function subdomainUrl(domain: string, sub: string, name?: string): string {\n return `https://${name === undefined ? \"\" : `${name}.`}${sub}.${domain}`;\n}\n\n/** Domains a user may not bring (#89): the platform's own, and everything under them. */\nexport const PLATFORM_DOMAINS: readonly string[] = [\"kvbox.sh\", DEFAULT_PROXY_DOMAIN];\n\n/**\n * Why `text` cannot be a custom domain (#89), or null when it can: a lowercase host name of at least\n * two labels ending in a letters-only top-level label, not the platform's own nor under it.\n * `proxyDomain` is the control plane's, when it is not kvbox.app.\n */\nexport function domainProblem(text: string, proxyDomain?: string): string | null {\n if (text.length > 253) return `\"${text}\" is longer than a domain may be`;\n const labels = text.split(\".\");\n if (labels.length < 2 || labels.some((l) => l.length > 63 || !LABEL_RE.test(l))) return `\"${text}\" is not a domain like example.com or www.example.com (lowercase, no \"*\", no \"https://\")`;\n if (!/^[a-z]{2,}$/.test(labels.at(-1)!) && !labels.at(-1)!.startsWith(\"xn--\")) return `\"${text}\" does not end in a top-level domain`;\n const ours = [...PLATFORM_DOMAINS, ...(proxyDomain ? [proxyDomain] : [])];\n if (ours.some((d) => text === d || text.endsWith(`.${d}`))) return `\"${text}\" belongs to kvbox; bring a domain of your own`;\n return null;\n}\n\nexport function assertDomain(text: string, proxyDomain?: string): string {\n const problem = domainProblem(text, proxyDomain);\n if (problem) throw new KvboxError(`domain ${problem}`);\n return text;\n}\n\n/** A visitor's `Host` as a domain row is keyed: lowercase, no port, no trailing dot. */\nexport function bareHost(host: string): string {\n return host.toLowerCase().replace(/:\\d+$/, \"\").replace(/\\.$/, \"\");\n}\n\n/**\n * What a request's `Host` names under `domain`: the subdomain and, for `<name>.<sub>`, the name.\n * Null for anything else (the bare domain, deeper names, another domain).\n */\nexport function parseProxyHost(host: string, domain: string): { sub: string; name?: string } | null {\n const bare = bareHost(host);\n const suffix = `.${domain}`;\n if (!bare.endsWith(suffix)) return null;\n const labels = bare.slice(0, -suffix.length).split(\".\");\n if (labels.some((l) => !LABEL_RE.test(l))) return null;\n if (labels.length === 1) return { sub: labels[0]! };\n if (labels.length === 2) return { sub: labels[1]!, name: labels[0]! };\n return null;\n}\n\n/**\n * How the edge and a host carry a visitor's request to a box (#31). The host's answers of its own\n * (no such box, box not running, nothing listening) carry `PROXY_ERROR_HEADER`, and the box's carry\n * `PROXIED_HEADER`, so the edge can tell the box's own 404 or 401 from the host's and show its page\n * for the latter. The edge strips every `x-kvbox-*` header before a visitor sees the answer.\n */\nexport const PROXY_ERROR_HEADER = \"x-kvbox-proxy-error\";\n/**\n * `hibernated`, `standby` and `stopped` say why a box is not running (#80): the edge may ask for the\n * first two to be woken, never the last. `waking`: a wake asked for is still under way. `wake-failed`:\n * it did not work. `not-running` is what a host from before #80 says for all three.\n */\nexport type ProxyError = \"not-found\" | \"hibernated\" | \"standby\" | \"stopped\" | \"not-running\" | \"waking\" | \"wake-failed\" | \"unreachable\" | \"timeout\";\n/** Set by the host on every answer that came from the box: anything without it is the host's own (a refusal, a host too old for #31). */\nexport const PROXIED_HEADER = \"x-kvbox-proxied\";\n/**\n * The visitor's path and query. It never goes into the URL the edge calls on the host: a URL resolves\n * `..`, and `/machines/<box>/http/<port>/../../..` would reach any route on the host with the host\n * secret. The host URL is always exactly `/machines/<box>/http/<port>`.\n */\nexport const VISITOR_PATH_HEADER = \"x-kvbox-path\";\n/**\n * Sent by the edge when the box may be woken for this request (#80): its slug is not suspended and\n * the edge has not had it woken in the last minute. A host then wakes a hibernated box (resumes one in\n * standby) before forwarding, and stamps its answer with WOKE_HEADER when it did.\n */\nexport const WAKE_HEADER = \"x-kvbox-wake\";\n/**\n * The longest a host holds a request on a wake before answering `waking` (the wake itself goes on).\n * The edge adds it to its own wait for the host's answer when it sends WAKE_HEADER.\n */\nexport const WAKE_WAIT_MS = 30_000;\n/**\n * How long a visitor may take to send one request, body included, at the edge and at the host's HTTPS\n * server (#182). Node's own limit is five minutes, which cut a large upload to a box (an object put in\n * a bucket) in the middle; the headers alone keep Node's one-minute limit. Traefik, in front of the\n * edge, has a limit of its own (its entry point's `readTimeout`, 60 s by default in v3): the\n * deployment must raise it to match (packages/edge/docker-compose.yml), or this one is never reached.\n */\nexport const REQUEST_TIMEOUT_MS = 3_600_000;\n/**\n * On a host's answer: this request woke the box, so the edge counts it against the box's wake limit.\n * Also on the host's own `unreachable` or `timeout` after a wake: the box was woken all the same.\n */\nexport const WOKE_HEADER = \"x-kvbox-woke\";\n/** The visitor's own `Authorization`, carried past the host secret that takes its place between edge and host. */\nexport const VISITOR_AUTH_HEADER = \"x-kvbox-authorization\";\n\n/**\n * Request headers neither hop passes on although they are not hop-by-hop: undici refuses to send\n * `expect` at all, so `Expect: 100-continue` (curl on a large upload) would fail every forward.\n * Node's server already answers the `100 Continue` itself.\n */\nexport const NOT_FORWARDED: ReadonlySet<string> = new Set([\"expect\"]);\n\n/** Headers that describe one connection, never passed along by a proxy (RFC 9110 §7.6.1). */\nexport const HOP_BY_HOP: ReadonlySet<string> = new Set([\"connection\", \"keep-alive\", \"proxy-authenticate\", \"proxy-authorization\", \"proxy-connection\", \"te\", \"trailer\", \"transfer-encoding\", \"upgrade\"]);\n\n/** The one host path the edge calls: a box's port, `/machines/<box>/http/<port>`. */\nexport const BOX_HTTP_PATH_RE = /^\\/machines\\/([^/]+)\\/http\\/(\\d{1,5})\\/?$/;\n\n/**\n * The edge's bearer for a host, derived from the host secret so neither side stores anything new.\n * A host takes it on `BOX_HTTP_PATH_RE` alone, so the internet-facing edge never holds a key to the\n * rest of a host's API; the control plane keeps it in `hosts.edge_secret` for the edge to read.\n */\nexport function edgeCredential(hostSecret: string): string {\n return createHmac(\"sha256\", hostSecret).update(\"kvbox-edge-v1\").digest(\"base64url\");\n}\n\n/** Starting a command in a box and asking how it ended: `/machines/<box>/runs` and `/machines/<box>/runs/<id>`. */\nexport const BOX_RUN_PATH_RE = /^\\/machines\\/([^/]+)\\/runs(\\/[A-Za-z0-9_-]{1,64})?\\/?$/;\n\n/**\n * kvbox-cron's bearer for a host (#190), derived like the edge's: a host takes it on `BOX_HTTP_PATH_RE`\n * (a trigger's request to a port) and on `BOX_RUN_PATH_RE` (a trigger's command), nothing else. It is\n * its own value so that the internet-facing edge's credential never opens the second.\n * The control plane keeps it in `hosts.cron_secret` for the worker to read.\n */\nexport function cronCredential(hostSecret: string): string {\n return createHmac(\"sha256\", hostSecret).update(\"kvbox-cron-v1\").digest(\"base64url\");\n}\n","/**\n * The hono app behind `kvbox-server`. Served over `~/.kvbox/server.sock` to the host owner, and,\n * once the host joined a control plane, a second instance over HTTPS that demands the host secret\n * (see caller.ts).\n */\nimport { Hono } from \"hono\";\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport { VERSION } from \"./version.js\";\nimport { resolveCaller, type CallerOptions, type Env } from \"./caller.js\";\nimport { loadConfig } from \"./core/config.js\";\nimport { currentBaseVersion, lastRecovery } from \"./core/machines.js\";\nimport { relayWatchReport } from \"./core/relayWatch.js\";\nimport { readUpdateState, startUpdate } from \"./core/update.js\";\nimport { backupMachineRoutes, backupRoutes, backupVolumeRoutes } from \"./routes/backups.js\";\nimport { backupStoreRoutes } from \"./routes/backupStore.js\";\nimport { boxHttpRoutes } from \"./routes/boxHttp.js\";\nimport { capacityRoutes } from \"./routes/capacity.js\";\nimport { envRoutes } from \"./routes/env.js\";\nimport { machineRoutes } from \"./routes/machines.js\";\nimport { runRoutes } from \"./routes/runs.js\";\nimport { snapshotRoutes } from \"./routes/snapshots.js\";\nimport { sshRoutes } from \"./routes/ssh.js\";\nimport { usageRoutes } from \"./routes/usage.js\";\nimport { volumeRoutes } from \"./routes/volumes.js\";\nimport { log } from \"./core/log.js\";\n\nexport function createApp(opts: CallerOptions = {}) {\n const app = new Hono<Env>();\n app.use(resolveCaller(opts));\n\n app.get(\"/health\", async (c) => {\n const cfg = await loadConfig();\n const cp = cfg.controlPlane;\n return c.json({\n ok: true as const,\n version: VERSION,\n pid: process.pid,\n base: await currentBaseVersion().catch(() => null),\n owner: cfg.owner,\n controlPlane: cp ? { name: cp.name, url: cp.url, hostUrl: `https://${cp.advertise}:${cp.port}` } : null,\n relay: cfg.relay ? { name: cfg.relay.name, publicIp: cfg.relay.publicIp, endpoint: cfg.relay.endpoint, ...relayWatchReport() } : null,\n recovery: lastRecovery(),\n update: await readUpdateState(),\n });\n });\n // The admin's host update (core/update.ts): the control plane's door only, the operator runs the installer.\n if (opts.controlPlane) app.post(\"/update\", async (c) => c.json(await startUpdate(VERSION), 202));\n // A box's web servers for the edge (#31): only what came from the control plane's side.\n if (opts.controlPlane) app.route(\"/machines\", boxHttpRoutes());\n // A command in a box for kvbox-cron (#190): the control plane's side only, like the forward above.\n if (opts.controlPlane) app.route(\"/machines\", runRoutes());\n // Backups: the control plane holds the keys and the bucket, so the socket has no such routes.\n if (opts.controlPlane) {\n app.route(\"/machines\", backupMachineRoutes());\n app.route(\"/volumes\", backupVolumeRoutes());\n app.route(\"/backups\", backupRoutes());\n }\n app.route(\"/machines\", machineRoutes());\n app.route(\"/snapshots\", snapshotRoutes());\n app.route(\"/volumes\", volumeRoutes());\n app.route(\"/capacity\", capacityRoutes());\n app.route(\"/env\", envRoutes());\n app.route(\"/ssh\", sshRoutes(opts));\n app.route(\"/backup-store\", backupStoreRoutes(opts));\n app.route(\"/usage\", usageRoutes(opts));\n\n app.notFound((c) => c.json({ error: `no route: ${c.req.method} ${c.req.path}` }, 404));\n app.onError((err, c) => {\n if (err instanceof NotFoundError) return c.json({ error: err.message }, 404);\n if (err instanceof KvboxError) {\n return c.json({ error: err.message }, err.exitCode === 2 ? 501 : 400);\n }\n log.error(`${c.req.method} ${c.req.path}: ${err.stack ?? err.message}`);\n return c.json({ error: err.message }, 500);\n });\n\n return app;\n}\n\nexport type App = ReturnType<typeof createApp>;\n","/**\n * Each binary's version comes from its own package.json: tsup injects\n * `__KVBOX_VERSION__` at build time; the dev path (tsx) reads the file.\n * Usage in a package: `versionOf(import.meta.url)` from its `src/version.ts`.\n */\nimport { createRequire } from \"node:module\";\n\nexport function versionOf(srcFileUrl: string, injected?: string): string {\n if (typeof injected === \"string\") return injected;\n try {\n const require = createRequire(srcFileUrl);\n return (require(\"../package.json\") as { version: string }).version;\n } catch {\n return \"0.0.0-dev\";\n }\n}\n","import { versionOf } from \"@kvbox/shared/version\";\n\ndeclare const __KVBOX_VERSION__: string | undefined;\n\nexport const VERSION: string = versionOf(import.meta.url, typeof __KVBOX_VERSION__ === \"string\" ? __KVBOX_VERSION__ : undefined);\n","/**\n * Who is calling. Every request carries an `owner` the routes file boxes under and scope listings\n * to. Two callers exist:\n * - the host owner over the local Unix socket: no credential (the socket's permissions are the\n * auth), owner = the server's configured `owner` (the Unix user running it);\n * - the control plane this host joined (#18), over HTTPS: it presents the host secret from `join`\n * as a bearer on every call and names the user it acts for in `X-Kvbox-Owner`, qualified here\n * and nowhere else to `<user>@<control plane name>` (decision \"Owner realms\"). `/health` and\n * `/capacity` need no owner; box, snapshot, volume and env routes do, except the listings: without the\n * header `GET /machines`, `GET /snapshots`, `GET /volumes` and `GET /env` cover every owner of the realm (the\n * control plane reconciling its index, #20). The host owner's local boxes are never in that answer.\n * The edge (#31) presents `edgeCredential(secret)` instead, which opens a box's port\n * (`BOX_HTTP_PATH_RE`) and nothing else. kvbox-cron (#190) presents `cronCredential(secret)`, which\n * opens what a trigger does: a request to a box's port, and a command in a box (`BOX_RUN_PATH_RE`).\n */\nimport { createHash, timingSafeEqual } from \"node:crypto\";\nimport type { MiddlewareHandler } from \"hono\";\nimport { BOX_HTTP_PATH_RE, BOX_RUN_PATH_RE, cronCredential, edgeCredential } from \"@kvbox/shared/names\";\nimport { loadConfig } from \"./core/config.js\";\nimport { LOCAL_OWNER_RE, type ListScope } from \"./core/refs.js\";\n\nexport type Env = { Variables: { owner: string; listScope: ListScope } };\n\nexport interface ControlPlaneCaller {\n /** The realm name owners are qualified with. */\n name: string;\n /** The host secret minted at join. */\n secret: string;\n}\n\nexport interface CallerOptions {\n /** Set on the HTTPS app only; the socket app trusts its caller. */\n controlPlane?: ControlPlaneCaller;\n}\n\nexport const OWNER_HEADER = \"x-kvbox-owner\";\n\nexport function resolveCaller(opts: CallerOptions = {}): MiddlewareHandler<Env> {\n const cp = opts.controlPlane;\n if (!cp) {\n return async (c, next) => {\n const cfg = await loadConfig();\n c.set(\"owner\", cfg.owner);\n c.set(\"listScope\", cfg.owner);\n await next();\n };\n }\n const authorized = secretCheck(cp);\n const edge = edgeCheck(cp);\n const cron = cronCheck(cp);\n return async (c, next) => {\n const auth = c.req.header(\"authorization\");\n const narrow = (edge(auth) && BOX_HTTP_PATH_RE.test(c.req.path)) || (cron(auth) && (BOX_HTTP_PATH_RE.test(c.req.path) || BOX_RUN_PATH_RE.test(c.req.path)));\n if (!authorized(auth) && !narrow) return c.json({ error: \"not authorized\" }, 401);\n const user = c.req.header(OWNER_HEADER);\n if (user === undefined) {\n const path = c.req.path.replace(/\\/$/, \"\");\n const realmListing = c.req.method === \"GET\" && (path === \"/machines\" || path === \"/snapshots\" || path === \"/volumes\" || path === \"/env\");\n if (!realmListing && /^\\/(machines|snapshots|volumes|env)(\\/|$)/.test(c.req.path)) {\n return c.json({ error: \"X-Kvbox-Owner header required\" }, 400);\n }\n c.set(\"owner\", \"\");\n c.set(\"listScope\", { realm: cp.name });\n } else {\n if (!LOCAL_OWNER_RE.test(user)) return c.json({ error: \"X-Kvbox-Owner: letters, digits, '.', '_', '-'\" }, 400);\n const owner = `${user}@${cp.name}`;\n c.set(\"owner\", owner);\n c.set(\"listScope\", owner);\n }\n await next();\n };\n}\n\n/** Whether an `Authorization` header carries the host secret (constant time). */\nexport function secretCheck(cp: ControlPlaneCaller): (authorization: string | undefined) => boolean {\n return bearerCheck(cp.secret);\n}\n\n/** Whether it carries the edge's credential, good for a box's port only. */\nexport function edgeCheck(cp: ControlPlaneCaller): (authorization: string | undefined) => boolean {\n return bearerCheck(edgeCredential(cp.secret));\n}\n\n/** Whether it carries kvbox-cron's credential (#190), good for a box's port and for a command in a box. */\nexport function cronCheck(cp: ControlPlaneCaller): (authorization: string | undefined) => boolean {\n return bearerCheck(cronCredential(cp.secret));\n}\n\nfunction bearerCheck(token: string): (authorization: string | undefined) => boolean {\n const expected = digest(token);\n return (authorization) => {\n const m = /^Bearer\\s+(\\S+)$/i.exec(authorization ?? \"\");\n return m !== null && timingSafeEqual(digest(m[1]!), expected);\n };\n}\n\n/** Fixed-length form of a secret so the compare is constant time whatever the caller sent. */\nfunction digest(secret: string): Buffer {\n return createHash(\"sha256\").update(secret).digest();\n}\n","/**\n * The host updating itself, at the control plane's request (`POST /update`, the HTTPS app only; the admin's\n * `POST /admin/hosts/:name/update`). It downloads install-server.sh from kvbox.sh and runs it with\n * `--update`: new packages, images and kernel, then a daemon restart, never sudo (decision \"Hosts update\n * over the API with install-server.sh --update\"). The script runs detached, since it stops this very\n * process; it writes `update.json` at its start and end, which `/health` reports. Where the script comes\n * from is the host's own setting (`KVBOX_INSTALL_SERVER_URL`), never the caller's.\n */\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { HostUpdateSchema, type HostUpdate } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { spawnDetached } from \"./exec.js\";\nimport { log } from \"./log.js\";\n\nexport const INSTALL_SERVER_URL = \"https://kvbox.sh/install-server.sh\";\n\n/** An update still `running` after this long never finished (the host rebooted, the script was killed). */\nexport const UPDATE_STALE_MS = 60 * 60_000;\n\n/** The last update as update.json says, a stale `running` one turned into `failed`; null when none ran or the file is unreadable. */\nexport async function readUpdateState(p: Paths = paths(), now = Date.now()): Promise<HostUpdate | null> {\n let raw: unknown;\n try {\n raw = JSON.parse(await readFile(p.updateState, \"utf8\"));\n } catch {\n return null;\n }\n const parsed = HostUpdateSchema.safeParse(raw);\n if (!parsed.success) return null;\n const u = parsed.data;\n if (u.state === \"running\" && now - Date.parse(u.startedAt) > UPDATE_STALE_MS) {\n return { ...u, state: \"failed\", error: `never finished; see ${p.updateLog}` };\n }\n return u;\n}\n\nexport interface UpdateDeps {\n fetch?: typeof fetch;\n spawn?: (argv: readonly string[], logFile: string, env: NodeJS.ProcessEnv) => Promise<number>;\n url?: string;\n}\n\n/** Start the update and answer at once with its `running` state; refuses while one is already running. */\nexport async function startUpdate(version: string, p: Paths = paths(), deps: UpdateDeps = {}): Promise<HostUpdate> {\n const current = await readUpdateState(p);\n if (current?.state === \"running\") throw new KvboxError(`an update is already running since ${current.startedAt}`);\n const url = deps.url ?? process.env[\"KVBOX_INSTALL_SERVER_URL\"] ?? INSTALL_SERVER_URL;\n const res = await (deps.fetch ?? fetch)(url, { signal: AbortSignal.timeout(20_000) });\n if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);\n const script = await res.text();\n if (!script.startsWith(\"#!\") || !script.includes(\"--update\")) throw new KvboxError(`${url} is not an install-server.sh that knows --update`);\n\n await mkdir(p.updateDir, { recursive: true });\n await writeFile(p.updateScript, script, { mode: 0o700 });\n const state: HostUpdate = { state: \"running\", startedAt: new Date().toISOString(), finishedAt: null, from: version, to: null, error: null, needsManual: [] };\n await writeFile(p.updateState, `${JSON.stringify(state, null, 2)}\\n`);\n await writeFile(p.updateLog, `--- ${state.startedAt} update from ${version}, ${url}\\n`, { flag: \"a\" });\n const env = { ...process.env, KVBOX_HOME: p.home, KVBOX_YES: \"1\" };\n try {\n await (deps.spawn ?? spawnDetached)([\"bash\", p.updateScript, \"--update\"], p.updateLog, env);\n } catch (err) {\n const failed: HostUpdate = { ...state, state: \"failed\", finishedAt: new Date().toISOString(), error: (err as Error).message };\n await writeFile(p.updateState, `${JSON.stringify(failed, null, 2)}\\n`);\n throw err;\n }\n log.info(`update started from ${version}: install-server.sh --update, log in ${p.updateLog}`);\n return state;\n}\n","/**\n * Backups (decision \"Backups: encrypted 4 MiB chunks in object storage\"): the control plane's only, so\n * served on the HTTPS app alone (app.ts), never on the socket. core/backups.ts does the work; the\n * control plane calls these in order: `POST /machines/:name/backup`, then `POST /backups/:id/upload`\n * (or `DELETE /backups/:id` when it gives up); `POST /machines/:name/restore` on its own. A volume's\n * (#168) are the same two under `/volumes/:name`, sharing the upload and the drop.\n */\nimport { Hono } from \"hono\";\nimport { HostBackupRequest, HostRestoreRequest, HostUploadRequest, HostVolumeRestoreRequest } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { dropBackup, restoreBackup, restoreVolumeBackup, stageBackup, stageVolumeBackup, uploadBackup } from \"../core/backups.js\";\nimport { parseRef } from \"../core/refs.js\";\nimport type { Env } from \"../caller.js\";\n\nexport function backupMachineRoutes() {\n const r = new Hono<Env>();\n r.post(\"/:name/backup\", async (c) => {\n const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"backup: expected {id, key}\");\n return c.json(await stageBackup(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data));\n });\n r.post(\"/:name/restore\", async (c) => {\n const body = HostRestoreRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"restore: expected {id, key, sizeBytes, base, env, chunks}\");\n return c.json(await restoreBackup(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data));\n });\n return r;\n}\n\n/** A volume's (#168): `POST /volumes/:name/backup`, then the same upload or drop as a box's; `POST /volumes/:name/restore`. */\nexport function backupVolumeRoutes() {\n const r = new Hono<Env>();\n r.post(\"/:name/backup\", async (c) => {\n const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"backup: expected {id, key}\");\n return c.json(await stageVolumeBackup(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data));\n });\n r.post(\"/:name/restore\", async (c) => {\n const body = HostVolumeRestoreRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"restore: expected {id, key, sizeBytes, chunks}\");\n return c.json(await restoreVolumeBackup(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data));\n });\n return r;\n}\n\nexport function backupRoutes() {\n const r = new Hono<Env>();\n r.post(\"/:id/upload\", async (c) => {\n const body = HostUploadRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"upload: expected {key, urls}\");\n return c.json(await uploadBackup(c.req.param(\"id\"), body.data));\n });\n r.delete(\"/:id\", async (c) => {\n await dropBackup(c.req.param(\"id\"));\n return c.body(null, 204);\n });\n return r;\n}\n","/**\n * This host as a backup store (core/backupStore.ts): `POST /backup-store` sets it up, `GET` says how it\n * is. On the Unix socket only: which disk a host gives to backups is decided by someone on the host\n * (`kvbox-server backup`), never by the control plane.\n */\nimport { Hono } from \"hono\";\nimport { BackupStoreSetupRequest } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { CallerOptions, Env } from \"../caller.js\";\nimport { backupStoreStatus, setupBackupStore } from \"../core/backupStore.js\";\n\nexport function backupStoreRoutes(opts: CallerOptions = {}) {\n const r = new Hono<Env>();\n if (opts.controlPlane) {\n r.all(\"/*\", (c) => c.json({ error: \"a backup store is set up on the host itself (kvbox-server backup setup there)\" }, 403));\n return r;\n }\n r.get(\"/\", async (c) => c.json(await backupStoreStatus()));\n r.post(\"/\", async (c) => {\n const body = BackupStoreSetupRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"backup setup: expected the directory as path\");\n return c.json(await setupBackupStore(body.data));\n });\n return r;\n}\n","/**\n * A box's web servers for the edge (#31): `ANY /machines/:name/http/:port` on the HTTPS app only\n * (never the socket) is passed to `<box ip>:<port><x-kvbox-path>` with its body streamed both ways,\n * and the same call as a WebSocket upgrade (listen.ts) is piped. The visitor's path comes in a\n * header, never in the URL (see VISITOR_PATH_HEADER). The control plane already decided\n * the name is the box's; this only forwards to a box of the caller's realm that is running.\n *\n * The edge sends the visitor's `Authorization` as `x-kvbox-authorization` (the host secret holds the\n * real header between edge and host) and the visitor's host name as `x-forwarded-host`; the box\n * gets them back as `authorization` and `host`, and never sees the secret or `x-kvbox-owner`.\n * Answers the host gives itself carry `x-kvbox-proxy-error`; the box's carry `x-kvbox-proxied`,\n * and any `x-kvbox-*` the box sent itself is dropped, so a box cannot pass for the host.\n * The caller is the control plane (host secret) or the edge (its credential, caller.ts).\n *\n * Wake on request (#80): with WAKE_HEADER, a hibernated box is woken (one in standby resumed) before\n * the forward, one wake per box however many requests wait on it; the edge decides whether a box\n * may be woken (credit, its rate limit), the host only how. A stopped box is never started.\n */\nimport type { IncomingHttpHeaders, IncomingMessage } from \"node:http\";\nimport { connect, type Socket } from \"node:net\";\nimport { Readable } from \"node:stream\";\nimport { Hono } from \"hono\";\nimport { request } from \"undici\";\nimport type { BoxStatus, Machine } from \"@kvbox/shared/api\";\nimport { NotFoundError } from \"@kvbox/shared/errors\";\nimport { HeadTimeoutError, readHead, rewriteHead } from \"@kvbox/shared/httpHead\";\nimport {\n BOX_HTTP_PATH_RE,\n HOP_BY_HOP,\n NOT_FORWARDED,\n PROXIED_HEADER,\n PROXY_ERROR_HEADER,\n VISITOR_AUTH_HEADER,\n VISITOR_PATH_HEADER,\n WAKE_HEADER,\n WAKE_WAIT_MS,\n WOKE_HEADER,\n type ProxyError,\n} from \"@kvbox/shared/names\";\nimport { edgeCheck, OWNER_HEADER, secretCheck, type ControlPlaneCaller, type Env } from \"../caller.js\";\nimport { getMachine, resumeMachine, wakeMachine } from \"../core/machines.js\";\nimport { LOCAL_OWNER_RE, parseRef, type BoxRef } from \"../core/refs.js\";\n\n/**\n * How long the box may take to start answering; a stream (SSE, a long download) then has no limit.\n * Shorter than the edge's wait for the host (edge proxy.ts), so the host's `timeout` answer gets there first.\n */\nconst HEADERS_TIMEOUT_MS = 55_000;\n/** The most a box's answer to a WebSocket handshake may hold before its blank line. */\nconst MAX_HANDSHAKE_BYTES = 16 * 1024;\n/** Connecting to the box: it is on the host's own bridge, so anything slower means nothing is there. */\nconst CONNECT_TIMEOUT_MS = 5_000;\n/** Headers that never reach the box: the edge-to-host credentials and what the forward rewrites. */\nconst DROPPED = new Set([...HOP_BY_HOP, ...NOT_FORWARDED, \"host\", \"authorization\", OWNER_HEADER, VISITOR_AUTH_HEADER, VISITOR_PATH_HEADER, WAKE_HEADER]);\n\nexport class ProxyFailure extends Error {\n constructor(\n readonly status: number,\n readonly code: ProxyError,\n message: string,\n ) {\n super(message);\n }\n}\n\ninterface Target {\n ip: string;\n port: number;\n /** The path and query on the box. */\n path: string;\n /** This request woke the box (WOKE_HEADER on the answer). */\n woke: boolean;\n}\n\n/** Brings a hibernated or standby box back. Resolves once it runs; tests pass their own. */\nexport type Waker = (ref: BoxRef, status: \"hibernated\" | \"standby\") => Promise<void>;\n\n/**\n * A Waker that runs one wake per box at a time, the requests that arrive meanwhile waiting on the\n * same one, and gives up waiting (not waking) after `capMs` with a `waking` failure.\n */\nexport function sharedWaker(bring: Waker = defaultBring, capMs = WAKE_WAIT_MS): Waker {\n const inFlight = new Map<string, Promise<void>>();\n return async (ref, status) => {\n const key = `${ref.owner}/${ref.name}`;\n let wake = inFlight.get(key);\n if (!wake) {\n wake = bring(ref, status).finally(() => inFlight.delete(key));\n inFlight.set(key, wake);\n // a wake nobody waits on any more (they all hit the cap) must not be an unhandled rejection\n wake.catch(() => {});\n }\n let timer: NodeJS.Timeout | undefined;\n const cap = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new ProxyFailure(503, \"waking\", `box ${ref.name} is waking up`)), capMs);\n });\n try {\n await Promise.race([wake, cap]);\n } finally {\n clearTimeout(timer);\n }\n };\n}\n\nconst defaultBring: Waker = async (ref, status) => {\n await (status === \"hibernated\" ? wakeMachine(ref) : resumeMachine(ref));\n};\n\n/** Shared by the plain route and the upgrade handler, so a page and its WebSocket wake the box once. */\nexport const wakeBox = sharedWaker();\n\n/** The answer code for a box that is not running. */\nconst notRunning = (status: BoxStatus): ProxyError => (status === \"hibernated\" || status === \"standby\" ? status : \"stopped\");\n\n/** The path on the box: the edge's header, a plain origin-form path; anything else is the box's `/`. */\nfunction visitorPath(value: string | string[] | null | undefined): string {\n const path = Array.isArray(value) ? value[0] : value;\n return path !== undefined && path !== null && path.startsWith(\"/\") && !/[\\s]/.test(path) ? path : \"/\";\n}\n\n/** The running box and port a forward path names, or a ProxyFailure saying why not. */\nasync function targetOf(url: URL, owner: string, path: string, wake?: Waker): Promise<Target> {\n const m = BOX_HTTP_PATH_RE.exec(url.pathname);\n const port = Number(m?.[2]);\n if (!m || port < 1 || port > 65535) throw new ProxyFailure(404, \"not-found\", `no route: ${url.pathname}`);\n const { box, woke } = await runningBox(decodeURIComponent(m[1]!), owner, wake);\n return { ip: box.ip, port, path, woke };\n}\n\n/**\n * The caller's box of that name once it runs, or a ProxyFailure saying why it does not. With `wake`, a\n * hibernated or standby box is brought back first. Also what starting a command in a box waits on (routes/runs.ts).\n */\nexport async function runningBox(name: string, owner: string, wake?: Waker): Promise<{ ref: BoxRef; box: Machine; woke: boolean }> {\n const ref = parseRef(name, owner);\n let box;\n try {\n box = await getMachine(ref);\n } catch (err) {\n if (err instanceof NotFoundError) throw new ProxyFailure(404, \"not-found\", err.message);\n throw err;\n }\n let woke = false;\n if (box.status !== \"running\" && wake && (box.status === \"hibernated\" || box.status === \"standby\")) {\n try {\n await wake(ref, box.status);\n woke = true;\n } catch (err) {\n if (err instanceof ProxyFailure) throw err;\n // another wake may have finished between our look and our call: then the box is up all the same\n box = await getMachine(ref);\n if (box.status !== \"running\") throw new ProxyFailure(502, \"wake-failed\", `box ${name} did not wake: ${(err as Error).message}`);\n }\n if (woke) box = await getMachine(ref);\n }\n if (box.status !== \"running\") throw new ProxyFailure(409, notRunning(box.status), `box ${name} is ${box.status}`);\n return { ref, box, woke };\n}\n\n/** The request headers as the box gets them. `upgrade` keeps the two headers a WebSocket handshake needs. */\nfunction boxHeaders(incoming: Iterable<[string, string]>, target: Target, upgrade = false): [string, string][] {\n const out: [string, string][] = [];\n let host = `${target.ip}:${target.port}`;\n for (const [name, value] of incoming) {\n const key = name.toLowerCase();\n if (key === \"x-forwarded-host\") host = value;\n if (key === VISITOR_AUTH_HEADER) out.push([\"authorization\", value]);\n if (upgrade && (key === \"upgrade\" || key === \"connection\")) out.push([name, value]);\n else if (!DROPPED.has(key)) out.push([name, value]);\n }\n out.push([\"host\", host]);\n return out;\n}\n\n/** `woke`: this request woke the box before failing, so the edge still counts the wake (WOKE_HEADER). */\nconst failure = (err: ProxyFailure, woke = false) =>\n new Response(JSON.stringify({ error: err.message }), { status: err.status, headers: { \"content-type\": \"application/json\", [PROXY_ERROR_HEADER]: err.code, ...(woke ? { [WOKE_HEADER]: \"1\" } : {}) } });\n\n/** Whether the caller asked for the box to be woken (WAKE_HEADER). */\nexport const wants = (value: string | string[] | null | undefined) => value === \"1\";\n\nexport function boxHttpRoutes(wake: Waker = wakeBox) {\n const r = new Hono<Env>();\n r.all(\"/:name/http/:port\", (c) => forward(c, wake));\n return r;\n}\n\nasync function forward(c: import(\"hono\").Context<Env>, wake: Waker): Promise<Response> {\n let target: Target;\n try {\n target = await targetOf(new URL(c.req.url), c.get(\"owner\"), visitorPath(c.req.header(VISITOR_PATH_HEADER)), wants(c.req.header(WAKE_HEADER)) ? wake : undefined);\n } catch (err) {\n if (err instanceof ProxyFailure) return failure(err);\n throw err;\n }\n const raw = c.req.raw;\n const pairs: [string, string][] = [];\n raw.headers.forEach((value, name) => pairs.push([name, value]));\n let res;\n try {\n res = await request(`http://${target.ip}:${target.port}${target.path}`, {\n method: raw.method as \"GET\",\n headers: boxHeaders(pairs, target).flat(),\n body: raw.body === null ? null : Readable.fromWeb(raw.body as import(\"node:stream/web\").ReadableStream),\n headersTimeout: HEADERS_TIMEOUT_MS,\n bodyTimeout: 0,\n signal: raw.signal,\n });\n } catch (err) {\n const e = err as Error & { code?: string };\n if (e.code === \"UND_ERR_HEADERS_TIMEOUT\") return failure(new ProxyFailure(504, \"timeout\", `box took over ${HEADERS_TIMEOUT_MS / 1000} s to answer on port ${target.port}`), target.woke);\n return failure(new ProxyFailure(502, \"unreachable\", `box answered nothing on port ${target.port} (${e.code ?? e.message})`), target.woke);\n }\n const headers = new Headers();\n for (const [name, value] of Object.entries(res.headers)) {\n if (value === undefined || HOP_BY_HOP.has(name) || name.startsWith(\"x-kvbox-\")) continue;\n for (const v of Array.isArray(value) ? value : [value]) headers.append(name, v);\n }\n headers.set(PROXIED_HEADER, \"1\");\n if (target.woke) headers.set(WOKE_HEADER, \"1\");\n const empty = res.statusCode === 204 || res.statusCode === 304 || raw.method === \"HEAD\";\n if (empty) res.body.resume();\n return new Response(empty ? null : (Readable.toWeb(res.body) as ReadableStream), { status: res.statusCode, headers });\n}\n\n/**\n * An answer written straight on a socket, for an upgrade that cannot go ahead. It always carries\n * PROXY_ERROR_HEADER (`refused` when no box reason applies) and never PROXIED_HEADER, which only a\n * box's own answer gets.\n */\nfunction refuse(socket: Socket, status: number, text: string, code: ProxyError | \"refused\" = \"refused\", woke = false): void {\n const body = JSON.stringify({ error: text });\n socket.end(`HTTP/1.1 ${status} ${status === 401 ? \"Unauthorized\" : \"Error\"}\\r\\ncontent-type: application/json\\r\\ncontent-length: ${Buffer.byteLength(body)}\\r\\n${PROXY_ERROR_HEADER}: ${code}\\r\\n${woke ? `${WOKE_HEADER}: 1\\r\\n` : \"\"}connection: close\\r\\n\\r\\n${body}`);\n}\n\nfunction headerPairs(raw: readonly string[]): [string, string][] {\n const out: [string, string][] = [];\n for (let i = 0; i + 1 < raw.length; i += 2) out.push([raw[i]!, raw[i + 1]!]);\n return out;\n}\n\n/**\n * The HTTPS server's `upgrade` handler: a WebSocket to a box. Checked like any call from the control\n * plane's side (host secret or the edge's credential, owner), then the handshake is written to the\n * box as it came, rewritten the same way as a plain forward. The box's answer is read up to its\n * blank line (a box that says nothing in `headersTimeoutMs` is our `timeout`), stamped like a plain\n * forward's, and from then on the two sockets are piped.\n */\nexport function boxUpgradeHandler(cp: ControlPlaneCaller, headersTimeoutMs = HEADERS_TIMEOUT_MS, wake: Waker = wakeBox) {\n const full = secretCheck(cp);\n const edge = edgeCheck(cp);\n const authorized = (auth: string | undefined) => full(auth) || edge(auth);\n return (req: IncomingMessage, socket: Socket, head: Buffer): void => {\n // Node drops its own error listener on an upgraded socket: without this one, a visitor resetting\n // the connection while we look the box up (or write a refusal) would crash the daemon.\n socket.on(\"error\", () => socket.destroy());\n void (async () => {\n const headers: IncomingHttpHeaders = req.headers;\n if (!authorized(headers.authorization)) return refuse(socket, 401, \"not authorized\");\n const user = headers[OWNER_HEADER];\n if (typeof user !== \"string\" || !LOCAL_OWNER_RE.test(user)) return refuse(socket, 400, \"X-Kvbox-Owner header required\");\n let target: Target;\n try {\n target = await targetOf(new URL(req.url ?? \"/\", \"https://host\"), `${user}@${cp.name}`, visitorPath(headers[VISITOR_PATH_HEADER]), wants(headers[WAKE_HEADER]) ? wake : undefined);\n } catch (err) {\n if (err instanceof ProxyFailure) return refuse(socket, err.status, err.message, err.code);\n return refuse(socket, 500, (err as Error).message);\n }\n // the visitor may have left while we looked: then there is nobody to open the box for\n if (socket.destroyed) return;\n const box = connect({ host: target.ip, port: target.port, timeout: CONNECT_TIMEOUT_MS });\n let connected = false;\n let piped = false;\n box.once(\"timeout\", () => box.destroy(new Error(\"timed out\")));\n box.once(\"error\", (err: Error & { code?: string }) => {\n if (!connected && !socket.destroyed) refuse(socket, 502, `box answered nothing on port ${target.port} (${err.code ?? err.message})`, \"unreachable\", target.woke);\n else if (piped) socket.destroy();\n });\n socket.once(\"close\", () => box.destroy());\n box.once(\"close\", () => {\n if (piped) socket.destroy();\n });\n box.once(\"connect\", () => {\n connected = true;\n box.setTimeout(0);\n const lines = boxHeaders(headerPairs(req.rawHeaders), target, true).map(([k, v]) => `${k}: ${v}\\r\\n`);\n box.write(`${req.method ?? \"GET\"} ${target.path} HTTP/1.1\\r\\n${lines.join(\"\")}\\r\\n`);\n if (head.length > 0) box.write(head);\n readHead(box, { maxBytes: MAX_HANDSHAKE_BYTES, timeoutMs: headersTimeoutMs }).then(\n (answer) => {\n if (socket.destroyed) return void box.destroy();\n socket.write(rewriteHead(answer.head, (name) => name.startsWith(\"x-kvbox-\"), { [PROXIED_HEADER]: \"1\", ...(target.woke ? { [WOKE_HEADER]: \"1\" } : {}) }));\n if (answer.rest.length > 0) socket.write(answer.rest);\n piped = true;\n box.pipe(socket);\n socket.pipe(box);\n },\n (err: Error) => {\n box.destroy();\n if (socket.destroyed) return;\n if (err instanceof HeadTimeoutError) refuse(socket, 504, `box took over ${headersTimeoutMs / 1000} s to answer on port ${target.port}`, \"timeout\", target.woke);\n else refuse(socket, 502, `box gave no answer on port ${target.port} (${err.message})`, \"unreachable\", target.woke);\n },\n );\n });\n })();\n };\n}\n","/**\n * The head of an HTTP/1.1 answer read off a raw socket (#31). A WebSocket goes edge → host → box as\n * piped bytes, so both hops read the answer to the handshake themselves: the host to stamp the box's\n * answer as the box's and drop any `x-kvbox-*` it sent, the edge to tell that from the host's refusal.\n */\nimport type { Duplex } from \"node:stream\";\n\nconst END = \"\\r\\n\\r\\n\";\n\n/** Nothing came before `timeoutMs`: the box (or host) took the connection and said nothing. */\nexport class HeadTimeoutError extends Error {}\n\n/**\n * What `socket` answers, up to its blank line: the head (status line and headers, no blank line) and\n * whatever came after it in the same reads. The socket is left paused with nothing more consumed.\n */\nexport function readHead(socket: Duplex, opts: { maxBytes: number; timeoutMs: number }): Promise<{ head: string; rest: Buffer }> {\n return new Promise((resolve, reject) => {\n let bytes = Buffer.alloc(0);\n const done = (err?: Error) => {\n clearTimeout(timer);\n socket.off(\"data\", onData);\n socket.off(\"close\", onClose);\n socket.pause();\n if (err) return reject(err);\n const end = bytes.indexOf(END);\n resolve({ head: bytes.subarray(0, end).toString(\"latin1\"), rest: bytes.subarray(end + END.length) });\n };\n const onData = (chunk: Buffer) => {\n bytes = Buffer.concat([bytes, chunk]);\n if (bytes.includes(END)) done();\n else if (bytes.length > opts.maxBytes) done(new Error(\"answer head too large\"));\n };\n const onClose = () => done(new Error(\"closed before answering\"));\n const timer = setTimeout(() => done(new HeadTimeoutError(`no answer within ${opts.timeoutMs / 1000} s`)), opts.timeoutMs);\n socket.on(\"data\", onData);\n socket.once(\"close\", onClose);\n });\n}\n\n/** The value of header `name` (lowercase) in a head, or undefined. */\nexport function headHeader(head: string, name: string): string | undefined {\n const line = head.split(\"\\r\\n\").slice(1).find((l) => l.slice(0, l.indexOf(\":\")).trim().toLowerCase() === name);\n return line?.slice(line.indexOf(\":\") + 1).trim();\n}\n\n/** The head again with the headers `drop` names left out and `add` appended, blank line included. */\nexport function rewriteHead(head: string, drop: (name: string) => boolean, add: Record<string, string> = {}): Buffer {\n const [status, ...lines] = head.split(\"\\r\\n\");\n const kept = lines.filter((l) => !drop(l.slice(0, l.indexOf(\":\")).trim().toLowerCase()));\n const extra = Object.entries(add).map(([k, v]) => `${k}: ${v}`);\n return Buffer.from(`${[status, ...kept, ...extra].join(\"\\r\\n\")}${END}`, \"latin1\");\n}\n","import { Hono } from \"hono\";\nimport { capacity } from \"../core/capacity.js\";\nimport { VERSION } from \"../version.js\";\n\nexport function capacityRoutes() {\n const r = new Hono();\n // The version rides along so the control plane's poller keeps it on the host row (`GET /admin/hosts`).\n r.get(\"/\", async (c) => c.json({ ...(await capacity()), version: VERSION }));\n return r;\n}\n","/**\n * Environment variables (#88). `POST /env` is the control plane handing this host an owner's whole\n * list (the caller's: `X-Kvbox-Owner`); `GET /env` says which version is held per owner, the realm's\n * without the header, for the control plane's sweep. Values are never sent back.\n */\nimport { Hono } from \"hono\";\nimport { HostEnvRequest } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { listEnvVersions, setOwnerEnv } from \"../core/env.js\";\nimport type { Env } from \"../caller.js\";\n\nexport function envRoutes() {\n const r = new Hono<Env>();\n r.get(\"/\", async (c) => c.json(await listEnvVersions(c.get(\"listScope\"))));\n r.post(\"/\", async (c) => {\n const body = HostEnvRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"env: expected {version, vars: [{name, value}]}\");\n return c.json(await setOwnerEnv(c.get(\"owner\"), body.data));\n });\n return r;\n}\n","import { Hono } from \"hono\";\nimport {\n CreateMachineRequest,\n ForkMachineRequest,\n LinkRequest,\n PortsRequest,\n RescaleMachineRequest,\n RunScriptRequest,\n StartMachineRequest,\n SetEnvRequest,\n SetMachineRequest,\n SetSshKeysRequest,\n type BoxEnv,\n type BoxEnvChange,\n} from \"@kvbox/shared/api\";\nimport { envNameProblem } from \"@kvbox/shared/env\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport {\n addLink,\n addPorts,\n createMachine,\n destroyMachine,\n forkMachine,\n getMachine,\n hibernateMachine,\n listMachines,\n pauseMachine,\n removeLink,\n removePorts,\n rescaleMachine,\n resumeMachine,\n setMachine,\n setSshKeys,\n startMachine,\n stopMachine,\n updateMachine,\n wakeMachine,\n} from \"../core/machines.js\";\nimport { readBoxEnv, rmBoxVar, setBoxVar, shownBoxEnv } from \"../core/env.js\";\nimport { ownerFor, parseRef } from \"../core/refs.js\";\nimport { machineStats } from \"../core/stats.js\";\nimport { runBoxScript } from \"../core/scripts.js\";\nimport { machineUsage } from \"../core/usage.js\";\nimport type { Env } from \"../caller.js\";\n\nexport function machineRoutes() {\n const r = new Hono<Env>();\n r.get(\"/\", async (c) => c.json(await listMachines(c.get(\"listScope\"))));\n r.post(\"/\", async (c) => {\n const body = CreateMachineRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await createMachine(body, c.get(\"owner\")), 201);\n });\n // The source is the caller's (X-Kvbox-Owner), like every box route; the copy goes to `owner` (#79).\n r.post(\"/:name/fork\", async (c) => {\n const body = ForkMachineRequest.parse(await c.req.json().catch(() => ({})));\n const caller = c.get(\"owner\");\n const into = body.owner === undefined ? caller : ownerFor(body.owner, caller);\n return c.json(await forkMachine(parseRef(c.req.param(\"name\"), caller), into, body), 201);\n });\n r.post(\"/:name/stop\", async (c) => c.json(await stopMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.post(\"/:name/start\", async (c) => {\n const body = StartMachineRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await startMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")), undefined, body.force ?? false));\n });\n r.post(\"/:name/pause\", async (c) => c.json(await pauseMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.post(\"/:name/resume\", async (c) => c.json(await resumeMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.post(\"/:name/hibernate\", async (c) => c.json(await hibernateMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.post(\"/:name/wake\", async (c) => {\n const body = StartMachineRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await wakeMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")), undefined, body.force ?? false));\n });\n r.post(\"/:name/update\", async (c) => c.json(await updateMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.post(\"/:name/rescale\", async (c) => {\n const body = RescaleMachineRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await rescaleMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body));\n });\n r.post(\"/:name/set\", async (c) => {\n const body = SetMachineRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await setMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body));\n });\n r.post(\"/:name/ssh-keys\", async (c) => {\n const body = SetSshKeysRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"sshKeys: expected a list of authorized_keys lines\");\n const { machine, applied } = await setSshKeys(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data.sshKeys);\n return c.json({ ...machine, sshKeysApplied: applied });\n });\n // Published box ports (#30): both answer with the box, its `ports` as they are now.\n r.post(\"/:name/ports\", async (c) => {\n const body = PortsRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"ports: expected a list of box ports\");\n return c.json(await addPorts(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data), 201);\n });\n r.delete(\"/:name/ports\", async (c) => {\n const body = PortsRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"ports: expected a list of box ports\");\n return c.json(await removePorts(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.data));\n });\n // Links into a box (#98): both answer with the box, its `links` as they are now.\n const linkBody = async (c: { req: { json: () => Promise<unknown> } }) => {\n const body = LinkRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"links: expected {from, port}\");\n return body.data;\n };\n r.post(\"/:name/links\", async (c) => c.json(await addLink(parseRef(c.req.param(\"name\"), c.get(\"owner\")), await linkBody(c), c.get(\"owner\")), 201));\n r.delete(\"/:name/links\", async (c) => c.json(await removeLink(parseRef(c.req.param(\"name\"), c.get(\"owner\")), await linkBody(c), c.get(\"owner\"))));\n r.get(\"/:name/usage\", async (c) => {\n const since = c.req.query(\"since\");\n let from: string | undefined;\n if (since !== undefined) {\n const t = Date.parse(since);\n if (Number.isNaN(t)) throw new KvboxError(`since: \"${since}\" is not a date; write it like 2026-10-19 or 2026-10-19T08:00:00Z`);\n from = new Date(t).toISOString();\n }\n return c.json(await machineUsage(parseRef(c.req.param(\"name\"), c.get(\"owner\")), from));\n });\n // A box's own variables (#87): kept beside its meta.json, over its owner's at its next start.\n r.get(\"/:name/env\", async (c) => {\n const ref = parseRef(c.req.param(\"name\"), c.get(\"owner\"));\n await getMachine(ref);\n return c.json({ box: ref.name, vars: shownBoxEnv(await readBoxEnv(ref)) } satisfies BoxEnv);\n });\n r.post(\"/:name/env/:var\", async (c) => {\n const ref = parseRef(c.req.param(\"name\"), c.get(\"owner\"));\n const name = c.req.param(\"var\");\n const problem = envNameProblem(name);\n if (problem !== null) throw new KvboxError(problem);\n const body = SetEnvRequest.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"expected {value, secret?}\");\n await setBoxVar(ref, name, body.data.value, body.data.secret ?? false);\n const box = await getMachine(ref);\n return c.json({ box: ref.name, name, running: box.status !== \"stopped\" } satisfies BoxEnvChange);\n });\n r.delete(\"/:name/env/:var\", async (c) => {\n const ref = parseRef(c.req.param(\"name\"), c.get(\"owner\"));\n const name = c.req.param(\"var\");\n await rmBoxVar(ref, name);\n const box = await getMachine(ref);\n return c.json({ box: ref.name, name, running: box.status !== \"stopped\" } satisfies BoxEnvChange);\n });\n // A script the box's image names (#173); the answer is `{output}`, whatever the script printed.\n r.post(\"/:name/scripts/:script\", async (c) => {\n const body = RunScriptRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await runBoxScript(parseRef(c.req.param(\"name\"), c.get(\"owner\")), c.req.param(\"script\"), body.input));\n });\n r.get(\"/:name/stats\", async (c) => c.json(await machineStats(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.delete(\"/:name\", async (c) => {\n await destroyMachine(parseRef(c.req.param(\"name\"), c.get(\"owner\")));\n return c.body(null, 204);\n });\n return r;\n}\n","/**\n * `kvbox vm top` (#67): a running box's own load, memory and disk, asked of kvbox-agent over vsock,\n * so it answers whatever the box did to its network. Read-only and unlocked: a box that stops\n * mid-question just fails this one answer.\n */\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { MachineStats } from \"@kvbox/shared/api\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { isGuestBooting, isNoAgent, isUnknownOp, stats } from \"./agent.js\";\nimport { getMachine, stateMessage } from \"./machines.js\";\nimport type { BoxRef } from \"./refs.js\";\n\n/** The guest is asked live; a busy one gets this long before the caller hears it did not answer. */\nconst STATS_REPLY_MS = 3_000;\n\nexport async function machineStats(ref: BoxRef, p: Paths = paths(), replyMs = STATS_REPLY_MS): Promise<MachineStats> {\n const m = await getMachine(ref, p);\n if (m.status !== \"running\") throw new KvboxError(`${stateMessage(ref, m.status)}; only a running box can say how it is doing`);\n try {\n return { name: m.name, owner: m.owner, stats: await stats(p.machine(m.owner, m.name).vsock, replyMs) };\n } catch (err) {\n // An image older than base v0.7.0 (an agent without \"stats\", or no agent at all): no numbers, not an\n // error. A guest that is still booting is neither: the caller hears it did not answer, like a busy one.\n if (isUnknownOp(err) || (isNoAgent(err) && !isGuestBooting(err))) return { name: m.name, owner: m.owner, stats: null };\n throw err;\n }\n}\n","/**\n * Image scripts (#173): an image names scripts in its image.json (`scripts`: `status`, `password`, …)\n * and the host runs one by name inside a running box, through kvbox-agent over vsock. The host knows\n * nothing about what a script does: its input and its answer are the image's and the caller's (the\n * control plane's managed services). Unlocked, like `machineStats`: a box that stops mid-question just\n * fails this one answer.\n */\nimport { KvboxError, NotFoundError } from \"@kvbox/shared/errors\";\nimport type { ScriptOutput } from \"@kvbox/shared/api\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { isNoAgent, isUnknownOp, runScript } from \"./agent.js\";\nimport { imageFileFor, imageLabel, imageManifest } from \"./images.js\";\nimport { stateMessage, statusOf } from \"./machines.js\";\nimport { shown, type BoxRef } from \"./refs.js\";\nimport { readMachineMeta } from \"./state.js\";\n\nexport async function runBoxScript(ref: BoxRef, script: string, input: unknown, p: Paths = paths()): Promise<ScriptOutput> {\n const meta = await readMachineMeta(ref, p).catch((err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") throw new NotFoundError(`box ${shown(ref)}`);\n throw err;\n });\n const manifest = await imageManifest(imageFileFor(meta, p));\n const path = Object.hasOwn(manifest.scripts ?? {}, script) ? manifest.scripts![script] : undefined;\n if (path === undefined) throw new KvboxError(`box ${shown(ref)} runs on ${imageLabel(meta.image)} ${meta.base}, which has no \"${script}\" script`);\n const status = statusOf(meta, p);\n if (status !== \"running\") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be asked`);\n try {\n return { output: await runScript(p.machine(meta.owner, meta.name).vsock, path, input) };\n } catch (err) {\n if (isUnknownOp(err) || isNoAgent(err)) {\n throw new KvboxError(`box ${shown(ref)} did not take the request: its image's kvbox-agent is too old or still starting (${(err as Error).message})`);\n }\n throw err;\n }\n}\n","/**\n * What the usage_events ledger (db.ts) adds up to: one box (`kvbox vm usage <box>`) or every box of\n * an owner (`kvbox usage`, #41). The arithmetic is `computeUsage` in @kvbox/shared/usage, shared with\n * the control plane, which sums the same rows after pulling them (#42).\n */\nimport type { MachineUsage, UsageReport } from \"@kvbox/shared/api\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { computeUsage, groupUsage, groupVolumeUsage, reportTotals } from \"@kvbox/shared/usage\";\nimport { loadConfig } from \"./config.js\";\nimport { usageEventsFor, usageEventsInScope, volumeEventsInScope } from \"./db.js\";\nimport { getMachine, listMachines } from \"./machines.js\";\nimport type { BoxRef, ListScope } from \"./refs.js\";\n\nexport { computeUsage, type UsageEvent, type UsageState, type UsageTotals, type UsageWindow } from \"@kvbox/shared/usage\";\n\n/**\n * Usage of one box from its creation (or `since`, already an ISO string) until now. Reading the box\n * (getMachine) also closes the run of a box whose Firecracker died, so the ledger is current before\n * it is summed.\n */\nexport async function machineUsage(ref: BoxRef, since: string | undefined, p: Paths = paths()): Promise<MachineUsage> {\n const box = await getMachine(ref, p);\n const cfg = await loadConfig(p);\n const now = new Date().toISOString();\n const events = usageEventsFor(box.id, box.createdAt, p);\n const window = { from: since ?? box.createdAt, to: now };\n return { name: box.name, owner: box.owner, status: box.status, window, ...computeUsage(events, { ...window, pricing: cfg.pricing }) };\n}\n\n/**\n * Every box of the owners in `scope` over the window, removed ones included: the ledger keeps their\n * rows, and a name removed and made again is two boxes (two ids). Listing the live boxes first closes\n * any run whose Firecracker died, so the ledger is current. A box with no row inside the window is\n * left out: it did not exist then. Volumes (#91) the same way from their own ledger.\n */\nexport async function usageReport(scope: ListScope, window: { from: string; to: string }, p: Paths = paths()): Promise<UsageReport> {\n const cfg = await loadConfig(p);\n const live = new Map((await listMachines(scope, p)).map((m) => [m.id, m.status]));\n const boxes = groupUsage(usageEventsInScope(scope, window, p), window, cfg.pricing, live);\n const volumes = groupVolumeUsage(volumeEventsInScope(scope, window, p), window, cfg.pricing);\n return { window, boxes, volumes, totals: reportTotals(boxes, volumes, cfg.pricing) };\n}\n","/**\n * A command in a box (#190: what a cron trigger with a command asks), on the HTTPS app only:\n *\n * POST /machines/:name/runs {id, command, timeoutSec} -> 202 {id, started, woke}\n * GET /machines/:name/runs/:id -> {id, state, exitCode?}\n *\n * The start answers as soon as kvbox-agent took the command; the caller asks the second until the\n * state is no longer `running`. With WAKE_HEADER a hibernated box is woken first (one in standby\n * resumed), by the same waker a forward to a port uses, so a request and a command that arrive\n * together wake the box once; a stopped box is never started. A refusal carries `code` beside\n * `error`: the box's state as a forward names it, or `box-outdated`. The caller is the control plane\n * (host secret) or kvbox-cron (its credential, caller.ts); the edge's credential does not open these.\n */\nimport { Hono } from \"hono\";\nimport { BoxRunSchema, StartRunAnswerSchema, StartRunRequest, type BoxRun, type StartRunAnswer } from \"@kvbox/shared/api\";\nimport { NotFoundError } from \"@kvbox/shared/errors\";\nimport { WAKE_HEADER } from \"@kvbox/shared/names\";\nimport type { Env } from \"../caller.js\";\nimport { BoxOutdatedError, boxRunStatus, startBoxRun } from \"../core/runs.js\";\nimport { ProxyFailure, runningBox, wakeBox, wants, type Waker } from \"./boxHttp.js\";\n\nconst refusal = (c: import(\"hono\").Context<Env>, err: unknown) => {\n if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status as 409);\n if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: \"box-outdated\" }, 409);\n if (err instanceof NotFoundError) return c.json({ error: err.message, code: \"not-found\" }, 404);\n throw err;\n};\n\nexport function runRoutes(wake: Waker = wakeBox) {\n const r = new Hono<Env>();\n r.post(\"/:name/runs\", async (c) => {\n const body = StartRunRequest.parse(await c.req.json().catch(() => ({})));\n try {\n const { ref, woke } = await runningBox(c.req.param(\"name\"), c.get(\"owner\"), wants(c.req.header(WAKE_HEADER)) ? wake : undefined);\n const started = await startBoxRun(ref, body);\n return c.json(StartRunAnswerSchema.parse({ id: body.id, started, woke } satisfies StartRunAnswer), 202);\n } catch (err) {\n return refusal(c, err);\n }\n });\n r.get(\"/:name/runs/:id\", async (c) => {\n try {\n const { ref } = await runningBox(c.req.param(\"name\"), c.get(\"owner\"));\n return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param(\"id\")) satisfies BoxRun));\n } catch (err) {\n return refusal(c, err);\n }\n });\n return r;\n}\n","import { Hono } from \"hono\";\nimport { CreateSnapshotRequest } from \"@kvbox/shared/api\";\nimport { deleteSnapshot, listSnapshots, saveSnapshot } from \"../core/snapshots.js\";\nimport { parseRef } from \"../core/refs.js\";\nimport type { Env } from \"../caller.js\";\n\nexport function snapshotRoutes() {\n const r = new Hono<Env>();\n r.get(\"/\", async (c) => c.json(await listSnapshots(c.get(\"listScope\"))));\n r.post(\"/\", async (c) => {\n const body = CreateSnapshotRequest.parse(await c.req.json());\n return c.json(await saveSnapshot(body, c.get(\"owner\")), 201);\n });\n r.delete(\"/:name\", async (c) => {\n await deleteSnapshot(parseRef(c.req.param(\"name\"), c.get(\"owner\")));\n return c.body(null, 204);\n });\n return r;\n}\n","/**\n * The SSH CA on a host (#55). `POST /ssh/trust-ca` makes every cloud box trust a new CA, `GET\n * /ssh/cloud-ca` asks the joined control plane which CA that should be. Both exist on the Unix\n * socket only: adding a trusted CA to every box is the most powerful thing a host can do, so it\n * takes someone on the host itself, never the control plane (or whoever holds its token).\n */\nimport { Hono } from \"hono\";\nimport { TrustCaRequestSchema } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { CallerOptions, Env } from \"../caller.js\";\nimport { fetchCloudCa } from \"../core/controlPlane.js\";\nimport { trustCa } from \"../core/machines.js\";\n\nexport function sshRoutes(opts: CallerOptions = {}) {\n const r = new Hono<Env>();\n if (opts.controlPlane) {\n r.all(\"/*\", (c) => c.json({ error: \"trusting a CA is done on the host itself (kvbox-server trust-ca there); the control plane cannot ask a host to\" }, 403));\n return r;\n }\n r.get(\"/cloud-ca\", async (c) => c.json(await fetchCloudCa()));\n r.post(\"/trust-ca\", async (c) => {\n const body = TrustCaRequestSchema.safeParse(await c.req.json().catch(() => ({})));\n if (!body.success) throw new KvboxError(\"trust-ca: expected the CA public key as publicKey\");\n return c.json(await trustCa(body.data.publicKey));\n });\n return r;\n}\n","/**\n * The usage ledger over HTTP. `GET /usage?since=&until=` is the host-wide report (#41) for the\n * caller's boxes. `GET /usage/events?after=&limit=` hands out raw ledger rows by id for a control\n * plane to pull (#42): over HTTPS only the caller's realm (or, with `X-Kvbox-Owner`, that one\n * owner) comes back, so the host owner's local boxes never leave the host; over the socket the\n * host owner gets every row.\n */\nimport { Hono } from \"hono\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { usageWindow } from \"@kvbox/shared/usage\";\nimport type { CallerOptions, Env } from \"../caller.js\";\nimport { ledgerId, usageEventsAfter, volumeEventsAfter } from \"../core/db.js\";\nimport { usageReport } from \"../core/usage.js\";\n\n/** Rows per pull; the control plane keeps pulling while a page comes back full. */\nexport const PULL_LIMIT = 1000;\n\nexport function usageRoutes(opts: CallerOptions = {}) {\n const r = new Hono<Env>();\n r.get(\"/\", async (c) => {\n let window;\n try {\n window = usageWindow(c.req.query(\"since\"), c.req.query(\"until\"));\n } catch (err) {\n throw new KvboxError((err as Error).message);\n }\n return c.json(await usageReport(c.get(\"listScope\"), window));\n });\n r.get(\"/events\", async (c) => {\n const after = whole(c.req.query(\"after\") ?? \"0\", \"after\");\n const limit = Math.min(whole(c.req.query(\"limit\") ?? String(PULL_LIMIT), \"limit\") || PULL_LIMIT, PULL_LIMIT);\n // The socket app trusts its caller: the whole ledger. The HTTPS app's scope is its realm or the named owner.\n const scope = opts.controlPlane === undefined ? null : c.get(\"listScope\");\n const events = usageEventsAfter(after, limit, scope);\n return c.json({ ledger: ledgerId(), events, next: events.length === 0 ? after : events[events.length - 1]!.id });\n });\n // The volume ledger (#91), pulled the same way: same ledger id, its own row ids and cursor.\n r.get(\"/volume-events\", async (c) => {\n const after = whole(c.req.query(\"after\") ?? \"0\", \"after\");\n const limit = Math.min(whole(c.req.query(\"limit\") ?? String(PULL_LIMIT), \"limit\") || PULL_LIMIT, PULL_LIMIT);\n const scope = opts.controlPlane === undefined ? null : c.get(\"listScope\");\n const events = volumeEventsAfter(after, limit, scope);\n return c.json({ ledger: ledgerId(), events, next: events.length === 0 ? after : events[events.length - 1]!.id });\n });\n return r;\n}\n\nfunction whole(value: string, name: string): number {\n const n = Number(value);\n if (!Number.isInteger(n) || n < 0) throw new KvboxError(`${name}: expected a whole number, got \"${value}\"`);\n return n;\n}\n","/**\n * Volumes (#52). A volume is the caller's (`X-Kvbox-Owner` over HTTPS, the host owner over the socket),\n * named bare or as owner/name like a box. Attach and detach answer with the box, as it is after the\n * change (running again if it was running: Firecracker takes drives at boot only).\n */\nimport { Hono } from \"hono\";\nimport { AttachVolumeRequest, CreateVolumeRequest, ResizeVolumeRequest } from \"@kvbox/shared/api\";\nimport { attachVolume, detachVolume, resizeVolume } from \"../core/machines.js\";\nimport { parseRef } from \"../core/refs.js\";\nimport { createVolume, deleteVolume, getVolume, listVolumes } from \"../core/volumes.js\";\nimport type { Env } from \"../caller.js\";\n\nexport function volumeRoutes() {\n const r = new Hono<Env>();\n r.get(\"/\", async (c) => c.json(await listVolumes(c.get(\"listScope\"))));\n r.post(\"/\", async (c) => {\n const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await createVolume(body, c.get(\"owner\")), 201);\n });\n r.get(\"/:name\", async (c) => c.json(await getVolume(parseRef(c.req.param(\"name\"), c.get(\"owner\")))));\n r.delete(\"/:name\", async (c) => {\n await deleteVolume(parseRef(c.req.param(\"name\"), c.get(\"owner\")));\n return c.body(null, 204);\n });\n r.post(\"/:name/attach\", async (c) => {\n const body = AttachVolumeRequest.parse(await c.req.json().catch(() => ({})));\n const owner = c.get(\"owner\");\n return c.json(await attachVolume(parseRef(body.box, owner), parseRef(c.req.param(\"name\"), owner)));\n });\n r.post(\"/:name/detach\", async (c) => {\n const body = AttachVolumeRequest.parse(await c.req.json().catch(() => ({})));\n const owner = c.get(\"owner\");\n return c.json(await detachVolume(parseRef(body.box, owner), parseRef(c.req.param(\"name\"), owner)));\n });\n // #147: answers the volume at its new size; the box holding it, if it was running, is running again.\n r.post(\"/:name/resize\", async (c) => {\n const body = ResizeVolumeRequest.parse(await c.req.json().catch(() => ({})));\n return c.json(await resizeVolume(parseRef(c.req.param(\"name\"), c.get(\"owner\")), body.sizeGib));\n });\n return r;\n}\n","/**\n * Builds the kvbox-server commander tree, one file per command under commands/. Importable without side\n * effects (tests); src/index.ts runs it. `start` is the daemon (the systemd unit runs `kvbox-server start`);\n * everything else manages it from the host's terminal. A bare `kvbox-server` prints help, like `kvbox`.\n */\nimport { Command } from \"commander\";\nimport { backupCommand } from \"./commands/backup/index.js\";\nimport { joinCommand } from \"./commands/join.js\";\nimport { leaveCommand } from \"./commands/leave.js\";\nimport { logsCommand } from \"./commands/logs.js\";\nimport { netCommand } from \"./commands/net.js\";\nimport { relayCommand } from \"./commands/relay.js\";\nimport { renameRealmCommand } from \"./commands/rename-realm.js\";\nimport { startCommand } from \"./commands/start.js\";\nimport { statusCommand } from \"./commands/status.js\";\nimport { stopCommand } from \"./commands/stop.js\";\nimport { trustCaCommand } from \"./commands/trust-ca.js\";\nimport { VERSION } from \"./version.js\";\n\nexport function buildProgram(): Command {\n return new Command(\"kvbox-server\")\n .description(\"kvbox host daemon: owns Firecracker and $KVBOX_HOME (~/.kvbox), serves the kvbox API\")\n .version(VERSION, \"-v, --version\")\n .showHelpAfterError()\n .addCommand(startCommand)\n .addCommand(stopCommand)\n .addCommand(statusCommand)\n .addCommand(logsCommand)\n .addCommand(joinCommand)\n .addCommand(leaveCommand)\n .addCommand(relayCommand)\n .addCommand(trustCaCommand)\n .addCommand(renameRealmCommand)\n .addCommand(backupCommand)\n .addCommand(netCommand);\n}\n","import { Command } from \"commander\";\nimport { setupCommand } from \"./setup.js\";\nimport { statusCommand } from \"./status.js\";\n\nexport const backupCommand = new Command(\"backup\")\n .description(\"make this host a backup store: box backups are kept on a disk of its own, in Garage\")\n .addCommand(setupCommand)\n .addCommand(statusCommand);\n","/**\n * kvbox-server backup setup --path <dir> [--force] [--new-store] [--json] — make this host a backup store: Garage is\n * installed and keeps its data in <dir> (a directory on the disk bought for backups, already mounted),\n * one key is made, and the control plane this host joined is told. Run again with the same path, it\n * finishes a setup that stopped half way and registers the store again; a path that does not hold the\n * store (its disk not mounted, or a new disk) is refused unless --new-store says the old disk is gone. Through the running daemon's\n * socket: the daemon is what keeps Garage up afterwards.\n * --json output: BackupStoreStatus {path, bucket, accessKey, running, totalBytes, freeBytes, objects?, storedBytes?, registered}\n */\nimport { resolve } from \"node:path\";\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { SocketClient } from \"../../socketClient.js\";\nimport { printStore } from \"./output.js\";\n\nexport const setupCommand = new Command(\"setup\")\n .description(\"keep box backups on this host: run Garage with its data in a directory on the backup disk, and tell the control plane\")\n .requiredOption(\"--path <dir>\", \"a directory on the disk for backups (mounted already)\")\n .option(\"--force\", \"use the path even when it is on the same disk as this host's boxes\")\n .option(\"--new-store\", \"the store's disk is gone for good: start a new store at the path (the old backups are lost)\")\n .option(\"--json\", \"print the store as JSON\")\n .action(async (opts: { path: string; force?: boolean; newStore?: boolean; json?: boolean }) => {\n const client = new SocketClient(paths().serverSock);\n try {\n if (!opts.json) console.log(\"setting up the backup store (the first time downloads Garage, which can take a minute)\");\n const store = await client.setupBackupStore({ path: resolve(opts.path), ...(opts.force ? { force: true } : {}), ...(opts.newStore ? { newStore: true } : {}) });\n if (opts.json) return console.log(JSON.stringify(store, null, 2));\n console.log(\"this host is now a backup store; new backups can be kept here\");\n printStore(store);\n } finally {\n await client.close();\n }\n });\n","/** How `backup setup` and `backup status` print a store: one aligned `label value` row per fact. */\nimport type { BackupStoreStatus } from \"@kvbox/shared/api\";\n\nfunction size(bytes: number): string {\n const gib = bytes / 1024 ** 3;\n return gib >= 1024 ? `${(gib / 1024).toFixed(1)} TB` : `${gib.toFixed(1)} GB`;\n}\n\nexport function printStore(s: BackupStoreStatus): void {\n const rows: [string, string][] = [\n [\"path\", s.path],\n [\"storage\", s.running ? \"running\" : \"not running (the daemon starts it again within a minute; kvbox-server logs says why if it does not)\"],\n [\"disk\", `${size(s.totalBytes - s.freeBytes)} used of ${size(s.totalBytes)}, ${size(s.freeBytes)} free`],\n ];\n if (s.storedBytes !== undefined) rows.push([\"backups\", `${size(s.storedBytes)} in ${s.objects ?? 0} chunks`]);\n rows.push([\"key\", s.accessKey]);\n rows.push([\"control plane\", s.registered ? \"knows this store\" : \"does not know this store yet: run kvbox-server backup setup again with the same path\"]);\n const width = Math.max(...rows.map(([label]) => label.length));\n for (const [label, value] of rows) console.log(`${label.padEnd(width)} ${value}`);\n}\n","/**\n * kvbox-server backup status [--json] — this host's backup store: where its data is, whether Garage\n * runs, how full the disk is, what the backups take, and whether the control plane knows it.\n * --json output: BackupStoreStatus {path, bucket, accessKey, running, totalBytes, freeBytes, objects?, storedBytes?, registered}\n */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { SocketClient } from \"../../socketClient.js\";\nimport { printStore } from \"./output.js\";\n\nexport const statusCommand = new Command(\"status\")\n .description(\"show this host's backup store: its disk, whether it runs and what it holds\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }) => {\n const client = new SocketClient(paths().serverSock);\n try {\n const store = await client.backupStore();\n if (opts.json) console.log(JSON.stringify(store, null, 2));\n else printStore(store);\n } finally {\n await client.close();\n }\n });\n","/**\n * kvbox-server join <url> --token <t> — register this host with a control plane (M2), then restart a\n * running daemon so it answers that control plane over HTTPS now.\n */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { joinControlPlane } from \"../core/controlPlane.js\";\nimport { restartDaemon, runningPid } from \"../daemon.js\";\n\nexport const joinCommand = new Command(\"join\")\n .description(\"put this host behind a control plane (needs a one-time token minted there) and restart the daemon\")\n .argument(\"<control-plane-url>\", \"the control plane, e.g. https://api.kvbox.sh\")\n .requiredOption(\"--token <token>\", \"one-time join token from the control plane\")\n .option(\"--advertise <host-or-ip>\", \"address the control plane reaches this host at (default: this host's default-route address)\")\n .option(\"--name <name>\", \"how the control plane lists this host (default: hostname)\")\n .option(\"--country <country>\", \"where this host is, a name or a code (romania, US); kvbox new --country places boxes by it\")\n .action(async (url: string, opts: { token: string; advertise?: string; name?: string; country?: string }) => {\n const p = paths();\n const joined = await joinControlPlane({ url, ...opts }, p);\n console.log(`joined ${joined.controlPlane} as host ${joined.hostName}`);\n console.log(`make sure port ${new URL(joined.hostUrl).port} is reachable from the control plane`);\n if ((await runningPid(p)) === null) {\n console.log(`it answers the control plane on ${joined.hostUrl} once the daemon starts (kvbox-server start -d)`);\n return;\n }\n const started = await restartDaemon(p);\n console.log(`kvbox-server restarted (pid ${started.pid}); it answers the control plane on ${joined.hostUrl} now`);\n });\n","/** kvbox-server leave — forget the control plane this host joined, then restart a running daemon so the HTTPS port closes now. */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { leaveControlPlane } from \"../core/controlPlane.js\";\nimport { restartDaemon, runningPid } from \"../daemon.js\";\n\nexport const leaveCommand = new Command(\"leave\")\n .description(\"take this host out from behind its control plane and restart the daemon\")\n .action(async () => {\n const p = paths();\n const left = await leaveControlPlane(p);\n console.log(`left ${left.controlPlane}`);\n if (!left.told) console.log(`(the control plane could not be told; remove this host there)`);\n if ((await runningPid(p)) === null) {\n console.log(\"the HTTPS port stays closed from the daemon's next start\");\n return;\n }\n const started = await restartDaemon(p);\n console.log(`kvbox-server restarted (pid ${started.pid}); only this machine talks to it now`);\n });\n","/**\n * kvbox-server logs [-n <lines>] [-f] — the daemon's log, $KVBOX_HOME/server.log: its own lines\n * (core/log.ts, `[time][level]: message`) and, under the systemd unit, everything else it printed.\n * The last `-n` lines (50), then with `-f` every line as it is written, until Ctrl-C.\n */\nimport { open, readFile, stat } from \"node:fs/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\n\nexport const logsCommand = new Command(\"logs\")\n .description(\"show the daemon's log ($KVBOX_HOME/server.log); -f keeps printing as it grows\")\n .option(\"-n, --lines <n>\", \"how many lines to show from the end\", \"50\")\n .option(\"-f, --follow\", \"keep printing new lines until Ctrl-C\")\n .action(async (opts: { lines: string; follow?: boolean }) => {\n const n = Number.parseInt(opts.lines, 10);\n if (!Number.isInteger(n) || n < 0) throw new KvboxError(`--lines: expected a number, got ${opts.lines}`);\n const p = paths();\n const text = await readFile(p.serverLog, \"utf8\").catch((err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") throw new KvboxError(`no log yet at ${p.serverLog} (the daemon writes it once it has run)`);\n throw err;\n });\n const tail = tailLines(text, n);\n if (tail !== \"\") process.stdout.write(`${tail}\\n`);\n if (!opts.follow) return;\n const ac = new AbortController();\n process.once(\"SIGINT\", () => ac.abort());\n process.once(\"SIGTERM\", () => ac.abort());\n await follow(p.serverLog, (chunk) => process.stdout.write(chunk), { from: Buffer.byteLength(text), signal: ac.signal });\n });\n\n/** The last `n` lines of `text` (a trailing newline is not a line); \"\" for n = 0. */\nexport function tailLines(text: string, n: number): string {\n if (n === 0) return \"\";\n const lines = text.endsWith(\"\\n\") ? text.slice(0, -1).split(\"\\n\") : text.split(\"\\n\");\n return lines.slice(-n).join(\"\\n\");\n}\n\nexport interface FollowOptions {\n /** The byte offset to start from (what was already shown); default: the end of the file now. */\n from?: number;\n /** How often to look for new bytes. */\n intervalMs?: number;\n signal?: AbortSignal;\n}\n\n/**\n * Hand every byte appended to `path` to `write`, polling, until `signal` aborts. A file that shrinks\n * (truncated, or replaced by a rotation) is read again from its start. Polling rather than fs.watch: it\n * works the same on every filesystem and the file may not exist yet.\n */\nexport async function follow(path: string, write: (chunk: string) => void, opts: FollowOptions = {}): Promise<void> {\n const intervalMs = opts.intervalMs ?? 250;\n let offset = opts.from ?? (await stat(path).then((s) => s.size, () => 0));\n while (!opts.signal?.aborted) {\n const size = await stat(path).then((s) => s.size, () => 0);\n if (size < offset) offset = 0;\n if (size > offset) {\n const fh = await open(path, \"r\");\n try {\n const buf = Buffer.alloc(size - offset);\n const { bytesRead } = await fh.read(buf, 0, buf.length, offset);\n write(buf.subarray(0, bytesRead).toString(\"utf8\"));\n offset += bytesRead;\n } finally {\n await fh.close();\n }\n }\n await sleep(intervalMs, undefined, { signal: opts.signal }).catch(() => undefined);\n }\n}\n","/** kvbox-server net up|down|status — the host network (bridge, forwarding, NAT) through the root helper net-setup.sh. */\nimport { spawnSync } from \"node:child_process\";\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { loadConfig } from \"../core/config.js\";\nimport { netSetupScript } from \"../core/network.js\";\n\nexport const netCommand = new Command(\"net\")\n .description(\"host network: up | down | status (bridge, forwarding, NAT; uses sudo)\")\n .argument(\"<action>\", \"up, down or status\")\n .action(async (action: string) => {\n if (![\"up\", \"down\", \"status\"].includes(action)) throw new KvboxError(\"net: expected up, down or status\");\n const cfg = await loadConfig(paths());\n const res = spawnSync(netSetupScript(), [action], {\n stdio: \"inherit\",\n env: { ...process.env, KVBOX_BRIDGE: cfg.bridge, KVBOX_SUBNET: cfg.subnet, KVBOX_GATEWAY: cfg.gateway },\n });\n process.exit(res.status ?? 1);\n });\n","/**\n * kvbox-server relay <join-string> | off — dial the tunnel to a relay that lends this host a public IP\n * (what `kvbox-relay add` printed there, #50), or take it down. No daemon restart: the HTTPS listener\n * already answers on every address.\n */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { dropRelay, useRelay } from \"../core/relay.js\";\n\nexport const relayCommand = new Command(\"relay\")\n .description(\"reach the internet through a relay (paste what `kvbox-relay add` printed on the relay VM); `off` takes the tunnel down\")\n .argument(\"<join-string>\", \"the line `kvbox-relay add` printed, or `off`\")\n .action(async (joinString: string) => {\n if (joinString === \"off\") {\n const relay = await dropRelay(paths());\n console.log(`tunnel to relay ${relay.name} is down; this host no longer answers at ${relay.publicIp}`);\n return;\n }\n const relay = await useRelay(joinString, paths());\n console.log(`tunnel to relay ${relay.name} (${relay.endpoint}) is up`);\n console.log(`this host is reachable at ${relay.publicIp}; kvbox-server join advertises it by default`);\n });\n","/**\n * kvbox-server rename-realm [name] [--from <old>] [-y] [--json] — the control plane this host joined\n * changed its name (`KVBOX_CLOUD_NAME`): move every cloud box, snapshot and volume on this host from\n * `<user>@<old>` to `<user>@<new>`. Without a name, the control plane is asked what it calls itself now.\n * The daemon is stopped for the few seconds it takes and started again; boxes keep running.\n * --json output: RealmRename {from, to, boxes, snapshots, volumes, keysUpdated: [\"owner/name\"], keysPending: [{box, when, why?}]}\n */\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { loadConfig } from \"../core/config.js\";\nimport { fetchCloudName } from \"../core/controlPlane.js\";\nimport { countRealm, renameRealm, type RealmRename } from \"../core/realm.js\";\nimport { daemonPid, startDetached, stopDaemon } from \"../daemon.js\";\nimport { confirm } from \"./trust-ca.js\";\n\nexport const renameRealmCommand = new Command(\"rename-realm\")\n .description(\"move this host's cloud boxes to the control plane's new name (after KVBOX_CLOUD_NAME changed there)\")\n .argument(\"[name]\", \"the new name; without it the control plane is asked\")\n .option(\"--from <old>\", \"the name the boxes are under now (default: the one this host joined under)\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .option(\"--json\", \"print the report as JSON\")\n .action(async (name: string | undefined, opts: { from?: string; yes?: boolean; json?: boolean }) => {\n const p = paths();\n const cp = (await loadConfig(p)).controlPlane;\n const from = opts.from ?? cp?.name;\n if (from === undefined) throw new KvboxError(\"this host has not joined a control plane; say which name the boxes are under: --from <old>\");\n const to = name ?? (await fetchCloudName(p));\n if (from === to) {\n if (!opts.json) console.log(`nothing to do: the control plane is called ${to} and this host's boxes are already under that name`);\n else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [] } satisfies RealmRename, null, 2));\n return;\n }\n const count = await countRealm(from, to, p);\n if (!opts.json) {\n console.log(`${name === undefined ? `the control plane is now called ${to}; ` : \"\"}this host has ${count.boxes} box(es), ${count.snapshots} snapshot(s) and ${count.volumes} volume(s) under ${from}`);\n }\n if (!(await confirm(`move them to ${to}? (kvbox-server restarts; boxes keep running, a backup in progress is lost)`, opts.yes ?? false))) {\n throw new KvboxError(\"cancelled\", 130);\n }\n\n const pid = await daemonPid(p);\n if (pid !== null) await stopDaemon(pid);\n let report: RealmRename;\n try {\n report = await renameRealm(from, to, p);\n } finally {\n // Whatever happened, a host whose daemon ran is not left without one.\n if (pid !== null) await startDetached(p);\n }\n if (opts.json) console.log(JSON.stringify(report, null, 2));\n else describe(report, pid !== null);\n });\n\nconst WHEN: Record<RealmRename[\"keysPending\"][number][\"when\"], string> = {\n start: \"is stopped: it accepts them from its next start\",\n wake: \"is hibernated: it accepts them from its next wake\",\n resume: \"is in standby: it accepts them from its next resume\",\n later: \"is running but could not take the change now; it accepts them from its next stop and start\",\n};\n\nfunction describe(report: RealmRename, restarted: boolean): void {\n console.log(`moved ${report.boxes} box(es), ${report.snapshots} snapshot(s) and ${report.volumes} volume(s) from ${report.from} to ${report.to}`);\n for (const box of report.keysUpdated) console.log(`box ${box} accepts SSH certificates for ${report.to} now`);\n for (const k of report.keysPending) console.log(`box ${k.box} ${WHEN[k.when]}${k.why ? ` (${k.why})` : \"\"}`);\n console.log(restarted ? \"kvbox-server restarted\" : \"kvbox-server was not running; start it with kvbox-server start -d\");\n}\n","/**\n * `kvbox-server rename-realm`: the control plane this host joined changed its name, so every owner\n * `<slug>@<old>` on this host becomes `<slug>@<new>`. The realm is written in many places (decision\n * \"Owner realms\"): the owner folders under machines/, snapshots/ and volumes/, each meta.json (owner,\n * sources, links, the SSH CA line's principals), env/<owner>.json, the usage ledgers and config.json.\n *\n * Done with the daemon stopped (the command sees to that): its locks, DNS and idle watchers are keyed\n * by owner. Boxes keep running: Firecracker has the box folder as its working directory and every\n * drive by a relative name, and a socket bound in a folder is still reached after the folder moves.\n *\n * Everything is read and checked before anything is written, and config.json is written last, so a\n * run that was cut short is finished by running the command again.\n */\nimport { lstat, readFile, readdir, readlink, rename, rm, symlink, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport type { SshKeysApplied } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { isCaLine } from \"@kvbox/shared/ssh\";\nimport { loadConfig, saveConfig } from \"./config.js\";\nimport { closeDb, renameLedgerRealm } from \"./db.js\";\nimport { pushAuthorizedKeys, statusOf } from \"./machines.js\";\nimport { REALM_RE } from \"./refs.js\";\nimport { MachineMetaSchema, SnapshotMetaSchema, VolumeMetaSchema, type MachineMeta } from \"./state.js\";\n\nexport interface RealmRename {\n from: string;\n to: string;\n boxes: number;\n snapshots: number;\n volumes: number;\n /** Boxes whose guest took the new SSH CA line now, as `owner/name`. */\n keysUpdated: string[];\n /** Boxes whose guest takes it later: at its next start, wake or resume, or (`later`) its next stop and start. */\n keysPending: { box: string; when: Exclude<SshKeysApplied, \"now\">; why?: string }[];\n}\n\n/** What a rename would touch, for the command to show before it asks. */\nexport interface RealmCount {\n boxes: number;\n snapshots: number;\n volumes: number;\n}\n\ninterface Entry<T> {\n oldOwner: string;\n name: string;\n /** The meta.json as it will be written. */\n meta: T;\n}\n\ninterface Plan {\n boxes: (Entry<MachineMeta> & { status: ReturnType<typeof statusOf> })[];\n snapshots: Entry<unknown>[];\n volumes: Entry<unknown>[];\n envOwners: string[];\n}\n\nconst esc = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/** Folders (or `<owner>.json` files) of `root` that name an owner of realm `from`. */\nasync function ownersIn(root: string, from: string, suffix = \"\"): Promise<string[]> {\n const entries = await readdir(root).catch((err: NodeJS.ErrnoException) => {\n if (err.code === \"ENOENT\") return [] as string[];\n throw err;\n });\n const tail = `@${from}${suffix}`;\n return entries.filter((e) => e.endsWith(tail)).map((e) => e.slice(0, e.length - suffix.length));\n}\n\nasync function namesIn(dir: string): Promise<string[]> {\n return (await readdir(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);\n}\n\nasync function plan(from: string, to: string, p: Paths): Promise<Plan> {\n if (!REALM_RE.test(to)) throw new KvboxError(`\"${to}\" cannot name a realm (letters, digits, '.', '-')`);\n if (from === to) throw new KvboxError(`this host's cloud boxes are already under ${to}`);\n const tail = new RegExp(`@${esc(from)}$`);\n const owner = (o: string) => o.replace(tail, `@${to}`);\n // `alice@old/lab1`, `snapshot:alice@old/warm`, `fork:alice@old/lab1`\n const source = (s: string) => s.replace(new RegExp(`^((?:[a-z]+:)?[^/@]+)@${esc(from)}/`), `$1@${to}/`);\n const caLine = (line: string) =>\n isCaLine(line) ? line.replace(/principals=\"([^\"]*)\"/, (_, list: string) => `principals=\"${list.split(\",\").map(owner).join(\",\")}\"`) : line;\n\n const out: Plan = { boxes: [], snapshots: [], volumes: [], envOwners: await ownersIn(p.env, from, \".json\") };\n const clash = async (path: string, what: string) => {\n if (await lstat(path).then(() => true, () => false)) throw new KvboxError(`${what} already exists under ${to} (${path}); nothing was changed`);\n };\n const read = async <T>(file: string, schema: z.ZodType<T>, what: string): Promise<T> => {\n try {\n return schema.parse(JSON.parse(await readFile(file, \"utf8\")));\n } catch (err) {\n throw new KvboxError(`${what} cannot be read (${file}: ${(err as Error).message}); nothing was changed`);\n }\n };\n\n for (const oldOwner of await ownersIn(p.machines, from)) {\n await clash(p.ownerMachines(owner(oldOwner)), `boxes of ${owner(oldOwner)}`);\n for (const name of await namesIn(p.ownerMachines(oldOwner))) {\n const meta = await read(p.machine(oldOwner, name).meta, MachineMetaSchema, `box ${oldOwner}/${name}`);\n const status = statusOf({ ...meta, owner: oldOwner, name }, p);\n const sshKeys = meta.sshKeys?.map(caLine);\n const keysChanged = sshKeys !== undefined && sshKeys.some((l, i) => l !== meta.sshKeys![i]);\n out.boxes.push({\n oldOwner,\n name,\n status,\n meta: {\n ...meta,\n owner: owner(meta.owner),\n source: source(meta.source),\n ...(sshKeys !== undefined ? { sshKeys } : {}),\n // A stopped box reads its lines at boot; any other guest still holds the old ones.\n ...(keysChanged ? { sshKeysStale: status === \"stopped\" ? undefined : true } : {}),\n ...(meta.links !== undefined ? { links: meta.links.map((l) => ({ ...l, owner: owner(l.owner) })) } : {}),\n },\n });\n }\n }\n for (const oldOwner of await ownersIn(p.snapshots, from)) {\n await clash(p.ownerSnapshots(owner(oldOwner)), `snapshots of ${owner(oldOwner)}`);\n // The dot folders a replace works in (#83) hold no finished snapshot: they move with the owner folder.\n for (const name of (await namesIn(p.ownerSnapshots(oldOwner))).filter((n) => !n.startsWith(\".\"))) {\n const meta = await read(p.snapshot(oldOwner, name).meta, SnapshotMetaSchema, `snapshot ${oldOwner}/${name}`);\n out.snapshots.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner), source: source(meta.source) } });\n }\n }\n for (const oldOwner of await ownersIn(p.volumes, from)) {\n await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);\n for (const name of await namesIn(p.ownerVolumes(oldOwner))) {\n // A volume from before #91 has no id yet; the daemon gives it one when it next reads it.\n const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z.string().optional() }), `volume ${oldOwner}/${name}`);\n out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });\n }\n }\n for (const oldOwner of out.envOwners) await clash(p.ownerEnv(owner(oldOwner)), `the variables of ${owner(oldOwner)}`);\n return out;\n}\n\n/** How many boxes, snapshots and volumes are under realm `from`; throws what `renameRealm` would refuse. */\nexport async function countRealm(from: string, to: string, p: Paths = paths()): Promise<RealmCount> {\n const planned = await plan(from, to, p);\n return { boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length };\n}\n\nasync function writeJson(file: string, value: unknown): Promise<void> {\n const tmp = `${file}.tmp`;\n await writeFile(tmp, JSON.stringify(value, null, 2) + \"\\n\");\n await rename(tmp, file);\n}\n\n/** Write each entry's meta.json where it is now, then move every owner folder of the root. */\nasync function move(entries: Entry<unknown>[], metaOf: (owner: string, name: string) => string, ownerDir: (owner: string) => string, owners: string[], to: (o: string) => string) {\n for (const e of entries) await writeJson(metaOf(e.oldOwner, e.name), e.meta);\n for (const o of owners) await rename(ownerDir(o), ownerDir(to(o)));\n}\n\n/**\n * Move every owner of realm `from` on this host to realm `to`. The daemon must not be running. `from`\n * is usually config.json's control plane name, which then becomes `to`; a host that already joined\n * under the new name while its boxes stayed under the old one passes the old name.\n */\nexport async function renameRealm(from: string, to: string, p: Paths = paths()): Promise<RealmRename> {\n const planned = await plan(from, to, p);\n const tail = new RegExp(`@${esc(from)}$`);\n const owner = (o: string) => o.replace(tail, `@${to}`);\n\n await move(planned.volumes, (o, n) => p.volume(o, n).meta, p.ownerVolumes, await ownersIn(p.volumes, from), owner);\n await move(planned.snapshots, (o, n) => p.snapshot(o, n).meta, p.ownerSnapshots, await ownersIn(p.snapshots, from), owner);\n await move(planned.boxes, (o, n) => p.machine(o, n).meta, p.ownerMachines, await ownersIn(p.machines, from), owner);\n\n // A volume's drive is a link in the box folder to the volume's disk by its full path, which just moved.\n // A running Firecracker has the disk open already; a wake or the next boot follows the link.\n for (const box of planned.boxes) {\n const m = p.machine(box.meta.owner, box.name);\n for (const volume of box.meta.volumes ?? []) {\n const link = m.volumeDrive(volume);\n const target = await readlink(link).catch(() => null); // a restore's placeholder is a plain file\n if (target !== p.volume(box.oldOwner, volume).disk) continue;\n await rm(link, { force: true });\n await symlink(p.volume(box.meta.owner, volume).disk, link);\n }\n }\n for (const o of planned.envOwners) await rename(p.ownerEnv(o), p.ownerEnv(owner(o)));\n\n renameLedgerRealm(from, to, p);\n closeDb(p);\n\n const cfg = await loadConfig(p);\n if (cfg.controlPlane?.name === from) await saveConfig({ ...cfg, controlPlane: { ...cfg.controlPlane, name: to } }, p);\n\n const report: RealmRename = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [] };\n for (const box of planned.boxes) {\n const { meta, status } = box;\n if (!(meta.sshKeys ?? []).some(isCaLine)) continue; // a managed service's box: no certificate opens it\n const key = `${meta.owner}/${meta.name}`;\n if (status === \"stopped\") report.keysPending.push({ box: key, when: \"start\" });\n else if (status === \"hibernated\") report.keysPending.push({ box: key, when: \"wake\" });\n else if (status === \"standby\") report.keysPending.push({ box: key, when: \"resume\" });\n else if (!meta.sshKeysStale) report.keysUpdated.push(key); // a run cut short already gave it the line\n else {\n const why = await pushAuthorizedKeys(meta, p.machine(meta.owner, meta.name).vsock, p);\n if (why === undefined) {\n await writeJson(p.machine(meta.owner, meta.name).meta, { ...meta, sshKeysStale: undefined });\n report.keysUpdated.push(key);\n } else report.keysPending.push({ box: key, when: \"later\", why });\n }\n }\n return report;\n}\n","/**\n * kvbox-server trust-ca [public-key] [--from-cloud] [-y] [--json] — every cloud box on this host trusts\n * a new SSH CA (#55), the step after `ca rotate` on the control plane. Through the running daemon's socket\n * (its box locks are in-process): the control plane cannot ask a host to trust a CA, someone on the host does.\n * --json output: TrustCaReport {publicKey, fingerprint, updated: [\"owner/name\"], pending: [{box, when, why?}], failed: [{box, error}], local, skipped: [\"owner/name\"]}\n */\nimport { Command } from \"commander\";\nimport type { SshKeysApplied, TrustCaReport } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { SocketClient } from \"../socketClient.js\";\n\nexport const trustCaCommand = new Command(\"trust-ca\")\n .description(\"make every cloud box on this host trust a new SSH CA (after `ca rotate` on the control plane)\")\n .argument(\"[public-key]\", \"the CA public key (or its cert-authority line); or --from-cloud\")\n .option(\"--from-cloud\", \"ask the control plane this host joined for its current CA, show the fingerprint, then ask\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .option(\"--json\", \"print the report as JSON\")\n .action(async (publicKey: string | undefined, opts: { fromCloud?: boolean; yes?: boolean; json?: boolean }) => {\n if (publicKey === undefined && !opts.fromCloud) throw new KvboxError(\"give the CA public key, or --from-cloud to fetch it from the control plane this host joined\");\n if (publicKey !== undefined && opts.fromCloud) throw new KvboxError(\"either a public key or --from-cloud, not both\");\n const client = new SocketClient(paths().serverSock);\n try {\n let key = publicKey;\n if (key === undefined) {\n const ca = await client.cloudCa();\n console.log(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);\n if (!(await confirm(\"make every cloud box on this host trust it (in place of the CA it trusts now)?\", opts.yes ?? false))) {\n throw new KvboxError(\"cancelled\", 130);\n }\n key = ca.publicKey;\n }\n const report = await client.trustCa({ publicKey: key });\n if (opts.json) console.log(JSON.stringify(report, null, 2));\n else describeReport(report);\n } finally {\n await client.close();\n }\n });\n\n/** y/N on a terminal; without one it refuses unless `yes`, the way a script must say -y. */\nexport async function confirm(question: string, yes: boolean): Promise<boolean> {\n if (yes) return true;\n if (!process.stdin.isTTY) {\n console.error(\"refusing without -y when stdin is not a terminal\");\n return false;\n }\n const { createInterface } = await import(\"node:readline/promises\");\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();\n return answer === \"y\" || answer === \"yes\";\n } finally {\n rl.close();\n }\n}\n\nconst WHEN: Record<Exclude<SshKeysApplied, \"now\">, string> = {\n start: \"is stopped: it trusts the CA from its next start\",\n wake: \"is hibernated: it trusts the CA from its next wake\",\n resume: \"is in standby: it trusts the CA from its next resume\",\n later: \"is running but could not take it now; it trusts the CA from its next stop and start\",\n};\n\nexport function describeReport(report: TrustCaReport): void {\n console.log(`CA ${report.fingerprint}`);\n for (const box of report.updated) console.log(`box ${box} now trusts the CA`);\n for (const p of report.pending) console.log(`box ${p.box} ${WHEN[p.when as Exclude<SshKeysApplied, \"now\">]}${p.why ? ` (${p.why})` : \"\"}`);\n for (const f of report.failed) console.error(`box ${f.box}: ${f.error}`);\n const parts = [`${report.updated.length} box(es) updated now`, `${report.pending.length} pending`, `${report.failed.length} failed`];\n const skipped = report.skipped ?? [];\n if (skipped.length > 0) parts.push(`${skipped.length} cloud box(es) without a CA line untouched (managed services: no certificate opens them)`);\n if (report.local > 0) parts.push(`${report.local} local box(es) untouched (they trust this host's key only)`);\n console.log(parts.join(\", \"));\n}\n","/**\n * kvbox-server status [--json] — is the daemon running, and what it knows: its version and pid, the\n * control plane it answers, its relay, the base image new boxes get, what it brought back at its last\n * start, and whether systemd starts it at boot (#29). Exit 1 when it is not running.\n * --json output: Health (shared/api) plus `running: true` and `startsAtBoot`; `{running: false, startsAtBoot}` when stopped;\n * `{running: true, reachable: false, pid, startsAtBoot}` when the process lives but its socket is gone (#159).\n */\nimport { homedir } from \"node:os\";\nimport { styleText } from \"node:util\";\nimport { Command } from \"commander\";\nimport type { Health } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { startsAtBoot } from \"@kvbox/shared/systemd\";\nimport { answering, daemonPid } from \"../daemon.js\";\nimport { SocketClient } from \"../socketClient.js\";\n\nexport const statusCommand = new Command(\"status\")\n .description(\"show whether the daemon is running, its control plane and which base image new boxes get\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }) => {\n const p = paths();\n const atBoot = startsAtBoot(p);\n const pid = await daemonPid(p);\n if (pid === null) {\n if (opts.json) {\n console.log(JSON.stringify({ running: false, startsAtBoot: atBoot }, null, 2));\n process.exitCode = 1;\n return;\n }\n throw new KvboxError(`kvbox-server is not running (start it with: kvbox-server start -d)${atBoot ? \"; it starts at boot\" : \"\"}`);\n }\n if (!(await answering(p))) {\n if (opts.json) {\n console.log(JSON.stringify({ running: true, reachable: false, pid, startsAtBoot: atBoot }, null, 2));\n process.exitCode = 1;\n return;\n }\n throw new KvboxError(`kvbox-server is running (pid ${pid}) but its socket is gone, so nothing can reach it; restart it: kvbox-server stop, then kvbox-server start -d`);\n }\n const client = new SocketClient(p.serverSock);\n try {\n const health = await client.health();\n if (opts.json) {\n console.log(JSON.stringify({ running: true, ...health, startsAtBoot: atBoot }, null, 2));\n return;\n }\n printStatus(health, atBoot, p.serverLog);\n } finally {\n await client.close();\n }\n });\n\n/**\n * A header line, then one aligned `label value` row per fact, and what the last restart brought back as\n * its own block. Colour only on a terminal (styleText checks stdout and NO_COLOR).\n */\nfunction printStatus(health: Health, atBoot: boolean, logPath: string): void {\n const dim = (t: string) => styleText(\"dim\", t, { stream: process.stdout });\n const rows: [string, string][] = [];\n rows.push([\"starts at boot\", atBoot ? \"yes, and brings back the boxes that were running\" : `no ${dim(\"(install-server.sh sets that up)\")}`]);\n if (health.controlPlane) {\n rows.push([\"control plane\", `${health.controlPlane.name} ${dim(`(${health.controlPlane.url})`)}`]);\n rows.push([\"answers it on\", health.controlPlane.hostUrl]);\n } else {\n rows.push([\"control plane\", `none ${dim(\"(kvbox-server join <url> --token <token>)\")}`]);\n }\n if (health.relay) {\n rows.push([\"relay\", `${health.relay.name} lends this host ${health.relay.publicIp} ${dim(`(tunnel to ${health.relay.endpoint})`)}`]);\n if (health.relay.restarts && health.relay.lastRestartAt) {\n rows.push([\"tunnel redialed\", `${health.relay.restarts} time(s) since the server started, last at ${health.relay.lastRestartAt}`]);\n }\n }\n rows.push([\"base image\", health.base === null ? \"none usable yet (run install-server.sh)\" : `${health.base} ${dim(\"(what kvbox new uses)\")}`]);\n const home = homedir();\n rows.push([\"log\", `${logPath.startsWith(`${home}/`) ? `~${logPath.slice(home.length)}` : logPath} ${dim(\"(kvbox-server logs -f)\")}`]);\n\n const r = health.recovery;\n const after: [string, string][] = [];\n if (r) {\n if (r.booted.length > 0) after.push([\"booted again\", r.booted.join(\", \")]);\n if (r.leftStopped.length > 0) after.push([\"left stopped\", `${r.leftStopped.join(\", \")} ${dim(\"(were in standby, their memory was lost)\")}`]);\n for (const f of r.failed) after.push([\"did not come back\", `${f.box} ${dim(`(${f.error})`)}`]);\n }\n\n const width = Math.max(...rows.map(([k]) => k.length));\n const line = ([k, v]: [string, string]) => console.log(` ${dim(k.padEnd(width))} ${v}`);\n console.log(`${styleText(\"bold\", `kvbox-server ${health.version}`, { stream: process.stdout })} ${styleText(\"green\", \"● running\", { stream: process.stdout })} ${dim(`(pid ${health.pid})`)}`);\n console.log();\n rows.forEach(line);\n if (after.length > 0) {\n console.log();\n console.log(\" after the last restart\");\n const w = Math.max(...after.map(([k]) => k.length));\n for (const [k, v] of after) console.log(` ${dim(k.padEnd(w))} ${v}`);\n }\n}\n","/** kvbox-server stop — SIGTERM the daemon (server.pid, else the systemd unit's, #159) and wait for it to go. Boxes keep running. */\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { daemonPid, stopDaemon } from \"../daemon.js\";\n\nexport const stopCommand = new Command(\"stop\")\n .description(\"stop the daemon (running boxes are not affected)\")\n .action(async () => {\n const pid = await daemonPid(paths());\n if (pid === null) throw new KvboxError(\"kvbox-server is not running\");\n await stopDaemon(pid);\n console.log(`kvbox-server stopped (pid ${pid}); boxes keep running`);\n });\n","/**\n * kvbox-server entry point: parse argv, map KvboxError to an exit code. The foreground daemon\n * (`kvbox-server` / `kvbox-server start`) reports its errors as server.log lines; the operator\n * subcommands (status, logs, stop, join, …) print a plain `error: …` for the terminal.\n */\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { isDaemon } from \"./commands/start.js\";\nimport { log } from \"./core/log.js\";\nimport { buildProgram } from \"./program.js\";\n\ntry {\n await buildProgram().parseAsync(process.argv);\n} catch (err) {\n if (err instanceof KvboxError) {\n if (isDaemon()) log.error(err.message);\n else console.error(`error: ${err.message}`);\n process.exit(err.exitCode);\n }\n if (isDaemon()) {\n log.error((err as Error).stack ?? String(err));\n process.exit(1);\n }\n throw err;\n}\n"],"mappings":";;;AACO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YACE,SACgB,WAAmB,GACnC;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;AAUO,IAAM,gBAAN,cAA4B,WAAW;AAAA,EAC5C,YAAY,MAAc;AACxB,UAAM,GAAG,IAAI,eAAe,CAAC;AAC7B,SAAK,OAAO;AAAA,EACd;AACF;;;ACjBA,SAAS,eAAe;;;ACAxB,SAAS,eAAe;AACxB,SAAS,YAAY;AAEd,SAAS,YAAoB;AAClC,SAAO,QAAQ,IAAI,YAAY,KAAK,KAAK,QAAQ,GAAG,QAAQ;AAC9D;AAEO,SAAS,MAAM,OAAe,UAAU,GAAG;AAChD,SAAO;AAAA,IACL;AAAA,IACA,QAAQ,KAAK,MAAM,aAAa;AAAA;AAAA,IAEhC,IAAI,KAAK,MAAM,UAAU;AAAA,IACzB,YAAY,KAAK,MAAM,aAAa;AAAA,IACpC,WAAW,KAAK,MAAM,YAAY;AAAA,IAClC,WAAW,KAAK,M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B;AACrE,CAAC;;;AdMI,SAAS,eAAwB;AACtC,SAAO,IAAIC,UAAQ,cAAc,EAC9B,YAAY,sFAAsF,EAClG,QAAQ,SAAS,eAAe,EAChC,mBAAmB,EACnB,WAAW,YAAY,EACvB,WAAW,WAAW,EACtB,WAAWC,cAAa,EACxB,WAAW,WAAW,EACtB,WAAW,WAAW,EACtB,WAAW,YAAY,EACvB,WAAW,YAAY,EACvB,WAAW,cAAc,EACzB,WAAW,kBAAkB,EAC7B,WAAW,aAAa,EACxB,WAAW,UAAU;AAC1B;;;AezBA,IAAI;AACF,QAAM,aAAa,EAAE,WAAW,QAAQ,IAAI;AAC9C,SAAS,KAAK;AACZ,MAAI,eAAe,YAAY;AAC7B,QAAI,SAAS,EAAG,KAAI,MAAM,IAAI,OAAO;AAAA,QAChC,SAAQ,MAAM,UAAU,IAAI,OAAO,EAAE;AAC1C,YAAQ,KAAK,IAAI,QAAQ;AAAA,EAC3B;AACA,MAAI,SAAS,GAAG;AACd,QAAI,MAAO,IAAc,SAAS,OAAO,GAAG,CAAC;AAC7C,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,QAAM;AACR;","names":["z","z","readFile","readFile","readFile","rename","writeFile","z","z","z","readFile","writeFile","rename","resolve","spawn","closeSync","existsSync","openSync","statSync","link","mkdir","readFile","rename","rm","truncate","writeFile","sleep","z","z","z","z","z","resolve","mkdir","readFile","readdir","rename","writeFile","z","resolve","z","readFile","writeFile","rename","names","mkdir","readdir","randomBytes","existsSync","readdir","z","openSync","openSync","resolve","existsSync","link","names","readdir","z","randomBytes","connect","shown","existsSync","mkdir","readdir","writeFile","usedBytes","existsSync","mkdir","writeFile","readdir","link","createHash","randomBytes","existsSync","chmod","mkdir","readFile","rename","rm","stat","statfs","writeFile","userInfo","join","stat","existsSync","readFile","createHash","mkdir","writeFile","chmod","rename","join","rm","randomBytes","userInfo","statfs","pid","closeSync","openSync","existsSync","mkdir","readdir","rename","rm","stat","request","request","bootArgs","readdir","stat","existsSync","rm","mkdir","rename","failure","existsSync","existsSync","link","NAME_RE","link","statSync","existsSync","alive","writeFile","truncate","sleep","readFile","rm","openSync","spawn","closeSync","existsSync","size","mkdir","link","forkMachine","statSync","failure","stopMachine","startMachine","setSshKeys","report","pauseMachine","resumeMachine","hibernateMachine","wakeMachine","updateMachine","rescaleMachine","replaceDisk","rename","attachVolume","detachVolume","setMachine","addPorts","open","removePorts","addLink","removeLink","destroyBox","run","randomBytes","existsSync","mkdir","readdir","readFile","rm","stat","statfs","writeFile","basename","join","sleep","randomBytes","promisify","randomBytes","rm","rm","Agent","connect","Agent","statfs","readBox","size","stat","rm","mkdir","meta","envText","existsSync","readFile","writeFile","basename","readdir","join","gb","randomBytes","held","sleep","access","chmod","mkdir","rm","writeFile","z","z","chmod","mkdir","readFile","request","readFile","mkdir","chmod","request","join","mkdir","writeFile","chmod","access","rm","readFile","run","readFile","log","round","log","round","spawn","constants","openSync","readFileSync","statSync","mkdir","readFile","stat","userInfo","sleep","readFileSync","Agent","request","Agent","request","readFile","readFileSync","sleep","stat","mkdir","log","openSync","spawn","constants","statSync","userInfo","readFile","rm","writeFile","createHmac","createHmac","Hono","require","createHash","createHash","mkdir","readFile","writeFile","readFile","mkdir","writeFile","Hono","Hono","connect","Hono","request","resolve","Hono","request","connect","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","Hono","rm","resolve","writeFile","readFile","shutdown","recovery","Command","Command","resolve","Command","Command","resolve","Command","Command","Command","Command","Command","Command","Command","open","readFile","stat","sleep","Command","Command","readFile","stat","size","open","sleep","spawnSync","Command","Command","spawnSync","Command","Command","relay","Command","lstat","readFile","readdir","rename","rm","symlink","writeFile","z","readdir","namesIn","lstat","readFile","z","writeFile","rename","link","rm","symlink","report","Command","Command","report","Command","report","WHEN","homedir","Command","statusCommand","Command","homedir","Command","Command","Command","statusCommand"]}