@tikoci/quickchr 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -136,6 +136,11 @@ quickchr networks sockets
136
136
  # Set up shell completions (bash/zsh/fish)
137
137
  quickchr completions
138
138
 
139
+ # Persist a default so you stop repeating a flag on every add/start
140
+ quickchr settings set default-channel long-term
141
+ quickchr settings set secure-login true
142
+ quickchr settings print
143
+
139
144
  # Reset disk to fresh image
140
145
  quickchr clean my-chr
141
146
 
@@ -251,6 +256,12 @@ quickchr start --name r2 --add-network socket::lab-switch
251
256
  quickchr start --name gw --add-network user --add-network bridged:en0
252
257
  ```
253
258
 
259
+ Not sure which mechanism fits your traffic (host→guest service, host receiving
260
+ guest-originated UDP, L2 broadcasts, VM↔VM links, real LAN)? See the
261
+ [networking recipes guide](./docs/networking-recipes.md) — a "traffic shape →
262
+ mechanism" decision table. The CLI flags map 1:1 to the library:
263
+ `--add-network` ↔ `StartOptions.networks`, `--forward` ↔ `StartOptions.extraPorts`.
264
+
254
265
  ### Port Layout
255
266
 
256
267
  Each instance gets a block of 10 ports. With the default base of 9100, the first instance maps:
@@ -277,28 +288,44 @@ registry when it knows the guest port:
277
288
  quickchr add lab --forward smb # auto host port → guest 445/tcp
278
289
  quickchr add dude-lab --forward winbox:8291 # host 8291 → guest WinBox 8291/tcp
279
290
  quickchr add app-lab --forward myapp:9200:7777/udp
291
+ quickchr add btest-lab --forward btest:9200-9210:2000-2010/udp # UDP port range
280
292
  ```
281
293
 
294
+ A **port range** (`name:hostStart-hostEnd[:guestStart-guestEnd][/proto]`) expands
295
+ to one `hostfwd` per port — handy for L3 peers with dynamic data ports. To
296
+ *receive* UDP a guest sends (no forward at all), see the gateway path in the
297
+ [networking recipes guide](./docs/networking-recipes.md).
298
+
282
299
  Reusing a built-in service name such as `winbox` pins/replaces that service's
283
300
  host port for the machine. Existing machines keep the mapping stored in
284
301
  `machine.json`; recreate the machine to change fixed service ports cleanly.
285
302
 
286
303
  ### Machine Descriptors and Subprocess Environments
287
304
 
288
- `quickchr inspect <name> [--json]` emits a stable JSON descriptor for a
289
- **running** machine: status, ports, URLs, auth, env vars, and the machine
290
- directory. `--json` is accepted for parity; inspect output is always JSON.
305
+ `quickchr inspect <name> [--json]` emits a stable, versioned
306
+ (`descriptorVersion: 1`) JSON descriptor for a **running** machine — the
307
+ quickchr ↔ centrs interface contract
308
+ ([issue #71](https://github.com/tikoci/quickchr/issues/71),
309
+ [`docs/centrs-interface.md`](docs/centrs-interface.md)): status, machine
310
+ identity, and a per-service `services` map (`rest-api`, `native-api`, `ssh`)
311
+ giving host/port/transport/`tls`/availability/auth for each, plus optional
312
+ `customForwards` and `networks`. `--json` is accepted for parity; inspect
313
+ output is always JSON. It has no `env` field — use `quickchr env` for
314
+ subprocess env vars.
291
315
 
292
316
  `quickchr env <name> [--json]` prints the same subprocess environment as
293
317
  `ChrInstance.subprocessEnv()`: shell `KEY=value` lines by default, or a JSON
294
318
  map with `--json`.
295
319
 
296
- > **Credential caveat:** descriptor/env output includes connection secrets
297
- > (`auth.password`, `auth.basic`, `auth.header`, `QUICKCHR_AUTH`, `BASICAUTH`)
298
- > so child processes can connect without reading quickchr's secret store. Treat
299
- > it like a password: do not commit it, paste it into public issues, or leave it
300
- > in CI logs. Stopped machines fail with `MACHINE_STOPPED`; start the machine
301
- > before requesting a descriptor or env map.
320
+ > **Credential caveat:** descriptor/env output includes connection secrets —
321
+ > `subprocessEnv()`/`quickchr env`'s `QUICKCHR_AUTH`/`BASICAUTH`, and each
322
+ > `descriptor()` service's own auth fields (`services["rest-api"].auth.password`/
323
+ > `.basic`/`.header`; `services["native-api"].auth.password`, no basic/header;
324
+ > `services.ssh.auth.privateKeyPath`) — so child processes can connect without
325
+ > reading quickchr's secret store. Treat it like a password: do not commit it,
326
+ > paste it into public issues, or leave it in CI logs. Stopped machines fail
327
+ > with `MACHINE_STOPPED`; start the machine before requesting a descriptor or
328
+ > env map.
302
329
 
303
330
  ### Library Usage
304
331
 
@@ -362,7 +389,7 @@ test("boot CHR and check version", async () => {
362
389
  chr = await QuickCHR.start({ channel: "stable" });
363
390
 
364
391
  const resource = await chr.rest("/system/resource");
365
- expect(resource["board-name"]).toBe("CHR");
392
+ expect(resource["board-name"]).toContain("CHR");
366
393
  }, 120_000);
367
394
 
368
395
  afterAll(async () => {
@@ -376,17 +403,34 @@ afterAll(async () => {
376
403
  |----------|-------------|
377
404
  | `MIKROTIK_WEB_ACCOUNT` | MikroTik.com account email (for license renewal) |
378
405
  | `MIKROTIK_WEB_PASSWORD` | MikroTik.com password (for license renewal) |
406
+ | `QUICKCHR_DEFAULT_CHANNEL`, `QUICKCHR_DEFAULT_ARCH`, `QUICKCHR_CACHE_MAX_SIZE`, `QUICKCHR_TIMEOUT_EXTRA`, `QUICKCHR_SECURE_LOGIN` | Env-tier overrides for the 5 `quickchr settings` keys — see [MANUAL.md §3 `settings`](./MANUAL.md#3-cli-command-reference) |
379
407
  | `QUICKCHR_INTEGRATION` | Set to `1` to run integration tests |
408
+ | `QUICKCHR_TEST_TARGET` | Integration tests only: RouterOS channel (`stable`/`long-term`/`testing`/`development`) or pinned version (e.g. `7.22.1`) to boot. Empty = `stable`. The Integration workflow (`integration.yml`) sets this from its `routeros-target` dispatch input to test a release across platforms |
409
+
410
+ The full list (including `QUICKCHR_DATA_DIR`, `QUICKCHR_NO_PROMPT`, `QUICKCHR_DEBUG`,
411
+ `NO_COLOR`) is in [MANUAL.md §11](./MANUAL.md#11-auth-secrets-environment-variables).
380
412
 
381
413
  ## Documentation
382
414
 
383
415
  - **[MANUAL.md](./MANUAL.md)** — complete reference: every CLI command,
384
416
  every library API, provisioning, channels, networking, storage,
385
417
  errors. Source-checked.
418
+ - **[examples/](./examples/)** — runnable scripts (`bun run`): `quickstart/`
419
+ (boot + query), `grounding/` (apply config → read back — the one `bun:test`),
420
+ `dude/` (install a package), `harness/` (drive an external tool), `rollback/`,
421
+ `service-forward/`, `file-transfer/`, `device-mode/`, plus `mndp`/`udp-gateway`/
422
+ `version-matrix`. See [examples/COVERAGE.md](./examples/COVERAGE.md).
423
+ - **[docs/networking-recipes.md](./docs/networking-recipes.md)** — which
424
+ networking mechanism for which traffic shape.
386
425
  - **[DESIGN.md](./DESIGN.md)** — architecture, layers, design principles.
387
426
  - **[CONTRIBUTING.md](./CONTRIBUTING.md)** — dev setup and `bun run check`.
388
427
  - **[CHANGELOG.md](./CHANGELOG.md)** — release history.
389
428
 
429
+ **Using quickchr with an AI agent?** The **`routeros-quickchr`** skill (in
430
+ [tikoci/routeros-skills](https://github.com/tikoci/routeros-skills)) teaches
431
+ agents the grounding workflow — boot a CHR, apply config, read it back — plus
432
+ the networking recipes and harness patterns.
433
+
390
434
  ## License
391
435
 
392
436
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tikoci/quickchr",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "description": "CLI and library to download, launch, and manage MikroTik CHR virtual machines via QEMU",
5
5
  "module": "src/index.ts",
6
6
  "main": "src/index.ts",
@@ -17,21 +17,24 @@
17
17
  "files": [
18
18
  "src",
19
19
  "README.md",
20
- "DESIGN.md"
20
+ "DESIGN.md",
21
+ "MANUAL.md"
21
22
  ],
22
23
  "scripts": {
23
- "check": "bun run lint:biome && bun run lint:typecheck && bun run lint:markdown && bun run lint:cspell",
24
+ "check": "bun run lint:biome && bun run lint:typecheck && bun run lint:markdown && bun run lint:cspell && bun run lint:examples && bun run lint:shell",
24
25
  "lint": "biome check . && tsc --noEmit",
25
26
  "lint:biome": "biome check .",
26
27
  "lint:typecheck": "tsc --noEmit",
27
28
  "lint:markdown": "bunx markdownlint-cli2 '**/*.md'",
28
29
  "lint:cspell": "cspell lint . --no-progress",
30
+ "lint:examples": "bun run scripts/validate-examples.ts",
31
+ "lint:shell": "sh scripts/lint-shell.sh",
29
32
  "test": "bun test test/unit/",
30
33
  "test:examples": "bun test examples/",
34
+ "smoke:examples": "QUICKCHR_INTEGRATION=1 EXAMPLES_SMOKE=1 bun test test/integration/examples-smoke.test.ts",
31
35
  "test:integration": "QUICKCHR_INTEGRATION=1 bun test test/integration/",
32
36
  "test:all": "QUICKCHR_INTEGRATION=1 bun test test/unit/ test/integration/ examples/",
33
37
  "dev": "bun run src/cli/index.ts",
34
- "release": "bun scripts/release.ts",
35
38
  "install:deps:ubuntu": "sudo apt-get --yes install qemu-system-x86 qemu-system-arm qemu-efi-aarch64 qemu-utils socat && curl -fsSL https://bun.sh/install | bash"
36
39
  },
37
40
  "devDependencies": {
package/src/cli/index.ts CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  import type { StartOptions, Arch, Channel, ServiceName, NetworkSpecifier } from "../lib/types.ts";
7
7
  import { parseNetworkSpecifier } from "../lib/network.ts";
8
- import { parseForwardSpec } from "../lib/forward-spec.ts";
8
+ import { expandForwardSpec } from "../lib/forward-spec.ts";
9
9
  import {
10
10
  MIN_PROVISION_VERSION,
11
11
  PROVISIONING_BOOT_ONLY_SUMMARY,
@@ -116,6 +116,57 @@ function isNoPrompt(): boolean {
116
116
  return !!process.env.QUICKCHR_NO_PROMPT || !process.stdout.isTTY || !process.stdin.isTTY;
117
117
  }
118
118
 
119
+ /** Merge the `-T` short-flag alias for `--timeout-extra` into `flags`, since parseFlags
120
+ * only recognizes `--` flags. Also consumes the `-T <value>` pair from `positional`
121
+ * so `quickchr start -T 15 lab` still targets `lab`. */
122
+ export function applyTimeoutExtraShortFlag(
123
+ argv: readonly string[],
124
+ flags: Record<string, string | boolean | string[]>,
125
+ positional?: string[],
126
+ ): Record<string, string | boolean | string[]> {
127
+ const tIdx = argv.indexOf("-T");
128
+ if (tIdx !== -1) {
129
+ const value = argv[tIdx + 1];
130
+ if (flags["timeout-extra"] === undefined && value !== undefined) {
131
+ flags["timeout-extra"] = value;
132
+ }
133
+ if (positional) {
134
+ const pIdx = positional.indexOf("-T");
135
+ if (pIdx !== -1) {
136
+ positional.splice(pIdx, 1);
137
+ if (value !== undefined && positional[pIdx] === value) {
138
+ positional.splice(pIdx, 1);
139
+ }
140
+ }
141
+ }
142
+ }
143
+ return flags;
144
+ }
145
+
146
+ /** Resolve --timeout-extra into a millisecond boot-timeout addend. Validates an
147
+ * explicit flag with the same non-negative-integer rule the timeout-extra setting
148
+ * itself uses, falling back to the setting (env/file/default) only when the flag
149
+ * is absent. Shared by cmdStart's single-target and --all bulk-restart paths.
150
+ * Callers merge the `-T` short-flag alias into `flags["timeout-extra"]` before
151
+ * calling this — `-T` is single-dash and parseFlags only recognizes `--` flags
152
+ * (same reason cmdLogs scans argv directly for its own `-f`/`-n` aliases). */
153
+ export async function resolveTimeoutExtraMs(flags: Record<string, string | boolean | string[]>): Promise<number | undefined> {
154
+ const { resolveSetting, parseTimeoutExtraSeconds } = await import("../lib/settings.ts");
155
+ const flagRaw = flag(flags, "timeout-extra");
156
+ const seconds = flagRaw !== undefined ? parseTimeoutExtraSeconds(flagRaw) : (resolveSetting("timeout-extra").value as number | undefined);
157
+ return seconds !== undefined ? seconds * 1000 : undefined;
158
+ }
159
+
160
+ /** Resolve --secure-login/--no-secure-login, falling back to the secure-login setting
161
+ * only when neither flag was passed. Shared by cmdAdd, cmdStart, and cmdStart's
162
+ * --all bulk-restart path. */
163
+ export async function resolveSecureLoginFlag(flags: Record<string, string | boolean | string[]>): Promise<boolean | undefined> {
164
+ if (flags["secure-login"] === false) return false;
165
+ if (flagBool(flags, "secure-login")) return true;
166
+ const { resolveSetting } = await import("../lib/settings.ts");
167
+ return resolveSetting("secure-login").value === true ? true : undefined;
168
+ }
169
+
119
170
  async function main() {
120
171
  try {
121
172
  switch (command) {
@@ -191,6 +242,9 @@ async function main() {
191
242
  case "cache":
192
243
  await cmdCache(args.slice(1));
193
244
  break;
245
+ case "settings":
246
+ await cmdSettings(args.slice(1));
247
+ break;
194
248
  case "version":
195
249
  case "--version":
196
250
  case "-v":
@@ -480,11 +534,12 @@ async function cmdAdd(argv: string[]) {
480
534
  const { flags, positional } = parseFlags(argv);
481
535
  const { QuickCHR } = await import("../lib/quickchr.ts");
482
536
  const { bold, formatPorts, formatNetworks, dim } = await import("./format.ts");
537
+ const { resolveSetting } = await import("../lib/settings.ts");
483
538
 
484
539
  const opts: StartOptions = {
485
540
  version: flag(flags, "version"),
486
- channel: flag(flags, "channel") as Channel | undefined,
487
- arch: flag(flags, "arch") as Arch | "auto" | undefined,
541
+ channel: (flag(flags, "channel") as Channel | undefined) ?? (resolveSetting("default-channel").value as Channel | undefined),
542
+ arch: (flag(flags, "arch") as Arch | "auto" | undefined) ?? (resolveSetting("default-arch").value as Arch | "auto" | undefined),
488
543
  name: flag(flags, "name") ?? positional[0],
489
544
  cpu: flag(flags, "cpu") ? Number(flag(flags, "cpu")) : undefined,
490
545
  mem: flag(flags, "mem") ? Number(flag(flags, "mem")) : undefined,
@@ -499,7 +554,7 @@ async function cmdAdd(argv: string[]) {
499
554
  bootDiskFormat: (flag(flags, "boot-disk-format") as StartOptions["bootDiskFormat"] | undefined) ?? "qcow2",
500
555
  bootSize: flag(flags, "boot-size"),
501
556
  extraDisks: flagList(flags, "add-disk").length > 0 ? flagList(flags, "add-disk") : undefined,
502
- extraPorts: flagList(flags, "forward").map(parseForwardSpec),
557
+ extraPorts: flagList(flags, "forward").flatMap(expandForwardSpec),
503
558
  };
504
559
 
505
560
  const deviceModeValue = flag(flags, "device-mode");
@@ -519,13 +574,7 @@ async function cmdAdd(argv: string[]) {
519
574
  opts.user = { name: uname, password: password ?? "" };
520
575
  }
521
576
  opts.disableAdmin = flagBool(flags, "disable-admin");
522
-
523
- // --secure-login / --no-secure-login
524
- if (flags["secure-login"] === false) {
525
- opts.secureLogin = false;
526
- } else if (flagBool(flags, "secure-login")) {
527
- opts.secureLogin = true;
528
- }
577
+ opts.secureLogin = await resolveSecureLoginFlag(flags);
529
578
 
530
579
  const state = await QuickCHR.add(opts);
531
580
 
@@ -1125,11 +1174,14 @@ async function cmdSetup() {
1125
1174
 
1126
1175
  async function cmdStart(argv: string[]) {
1127
1176
  const { flags, positional } = parseFlags(argv);
1177
+ applyTimeoutExtraShortFlag(argv, flags, positional);
1128
1178
 
1129
1179
  // --all: start every stopped machine in background
1130
1180
  if (flagBool(flags, "all")) {
1131
1181
  const { QuickCHR } = await import("../lib/quickchr.ts");
1132
1182
  const { statusIcon, link, bold, resolveDisplayCredentials, formatRestUrl, formatSshCommand } = await import("./format.ts");
1183
+ const timeoutExtra = await resolveTimeoutExtraMs(flags);
1184
+ const secureLogin = await resolveSecureLoginFlag(flags);
1133
1185
  const stopped = QuickCHR.list().filter((m) => m.status !== "running");
1134
1186
  if (stopped.length === 0) {
1135
1187
  console.log("No stopped instances.");
@@ -1137,7 +1189,7 @@ async function cmdStart(argv: string[]) {
1137
1189
  }
1138
1190
  for (const m of stopped) {
1139
1191
  console.log(`Starting ${bold(m.name)}...`);
1140
- const instance = await QuickCHR.start({ name: m.name, background: true });
1192
+ const instance = await QuickCHR.start({ name: m.name, background: true, timeoutExtra, secureLogin });
1141
1193
  const creds = await resolveDisplayCredentials(instance.state);
1142
1194
  console.log(`${statusIcon("running")} ${bold(instance.name)} REST: ${link(formatRestUrl(instance.ports.http, creds.user, creds.password))} SSH: ${formatSshCommand(creds.user, instance.sshPort)}`);
1143
1195
  }
@@ -1162,11 +1214,12 @@ async function cmdStart(argv: string[]) {
1162
1214
  // Build start options from flags
1163
1215
  const { QuickCHR } = await import("../lib/quickchr.ts");
1164
1216
  const { statusIcon, formatPorts, formatNetworks, link, bold, dim, resolveDisplayCredentials, formatRestUrl, formatSshCommand } = await import("./format.ts");
1217
+ const { resolveSetting } = await import("../lib/settings.ts");
1165
1218
 
1166
1219
  const opts: StartOptions = {
1167
1220
  version: flag(flags, "version"),
1168
- channel: flag(flags, "channel") as Channel | undefined,
1169
- arch: flag(flags, "arch") as Arch | "auto" | undefined,
1221
+ channel: (flag(flags, "channel") as Channel | undefined) ?? (resolveSetting("default-channel").value as Channel | undefined),
1222
+ arch: (flag(flags, "arch") as Arch | "auto" | undefined) ?? (resolveSetting("default-arch").value as Arch | "auto" | undefined),
1170
1223
  name: flag(flags, "name") ?? positional[0],
1171
1224
  cpu: flag(flags, "cpu") ? Number(flag(flags, "cpu")) : undefined,
1172
1225
  mem: flag(flags, "mem") ? Number(flag(flags, "mem")) : undefined,
@@ -1181,10 +1234,10 @@ async function cmdStart(argv: string[]) {
1181
1234
  bootDiskFormat: (flag(flags, "boot-disk-format") as StartOptions["bootDiskFormat"] | undefined) ?? "qcow2",
1182
1235
  bootSize: flag(flags, "boot-size"),
1183
1236
  extraDisks: flagList(flags, "add-disk").length > 0 ? flagList(flags, "add-disk") : undefined,
1184
- extraPorts: flagList(flags, "forward").map(parseForwardSpec),
1237
+ extraPorts: flagList(flags, "forward").flatMap(expandForwardSpec),
1185
1238
  installDeps: flagBool(flags, "install-deps"),
1186
1239
  dryRun: flagBool(flags, "dry-run"),
1187
- timeoutExtra: parseInt(flag(flags, "timeout-extra") ?? flag(flags, "T") ?? "0", 10) * 1000 || undefined,
1240
+ timeoutExtra: await resolveTimeoutExtraMs(flags),
1188
1241
  };
1189
1242
 
1190
1243
  const deviceModeValue = flag(flags, "device-mode");
@@ -1227,13 +1280,7 @@ async function cmdStart(argv: string[]) {
1227
1280
  }
1228
1281
 
1229
1282
  opts.disableAdmin = flagBool(flags, "disable-admin");
1230
-
1231
- // --secure-login / --no-secure-login
1232
- if (flags["secure-login"] === false) {
1233
- opts.secureLogin = false;
1234
- } else if (flagBool(flags, "secure-login")) {
1235
- opts.secureLogin = true;
1236
- }
1283
+ opts.secureLogin = await resolveSecureLoginFlag(flags);
1237
1284
 
1238
1285
  // Background default: true. Explicitly foreground only with --fg / --foreground / --no-background / --no-bg.
1239
1286
  const wantFg =
@@ -1443,7 +1490,7 @@ function shellQuoteEnv(value: string): string {
1443
1490
  return `'${value.replaceAll("'", "'\\''")}'`;
1444
1491
  }
1445
1492
 
1446
- async function getRunningDescriptor(name: string) {
1493
+ async function getRunningInstance(name: string) {
1447
1494
  const { QuickCHR } = await import("../lib/quickchr.ts");
1448
1495
  const { machineNotFoundMessage } = await import("./format.ts");
1449
1496
  const instance = QuickCHR.get(name);
@@ -1451,6 +1498,18 @@ async function getRunningDescriptor(name: string) {
1451
1498
  console.error(machineNotFoundMessage(name));
1452
1499
  process.exit(1);
1453
1500
  }
1501
+ if (instance.state.status !== "running") {
1502
+ const { QuickCHRError } = await import("../lib/types.ts");
1503
+ throw new QuickCHRError(
1504
+ "MACHINE_STOPPED",
1505
+ `Machine "${name}" must be running to inspect its connection environment (current status: ${instance.state.status}).`,
1506
+ );
1507
+ }
1508
+ return instance;
1509
+ }
1510
+
1511
+ async function getRunningDescriptor(name: string) {
1512
+ const instance = await getRunningInstance(name);
1454
1513
  return instance.descriptor();
1455
1514
  }
1456
1515
 
@@ -1473,12 +1532,13 @@ async function cmdEnv(argv: string[] = []) {
1473
1532
  console.error("Usage: quickchr env <name> [--json]");
1474
1533
  process.exit(1);
1475
1534
  }
1476
- const descriptor = await getRunningDescriptor(name);
1535
+ const instance = await getRunningInstance(name);
1536
+ const env = await instance.subprocessEnv();
1477
1537
  if (asJson) {
1478
- console.log(JSON.stringify(descriptor.env, null, 2));
1538
+ console.log(JSON.stringify(env, null, 2));
1479
1539
  return;
1480
1540
  }
1481
- for (const [key, value] of Object.entries(descriptor.env)) {
1541
+ for (const [key, value] of Object.entries(env)) {
1482
1542
  console.log(`${key}=${shellQuoteEnv(value)}`);
1483
1543
  }
1484
1544
  }
@@ -2314,7 +2374,7 @@ async function cmdCache(argv: string[]) {
2314
2374
  return;
2315
2375
  }
2316
2376
 
2317
- const { listCacheEntries, pruneCache } = await import("../lib/cache.ts");
2377
+ const { listCacheEntries, pruneCache, parseSizeString, formatSizeBytes } = await import("../lib/cache.ts");
2318
2378
 
2319
2379
  const parseDuration = (s: string): number => {
2320
2380
  const m = s.match(/^(\d+(?:\.\d+)?)([smhdw])$/);
@@ -2324,20 +2384,8 @@ async function cmdCache(argv: string[]) {
2324
2384
  const mult: Record<string, number> = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 };
2325
2385
  return Math.floor(n * (mult[unit ?? ""] ?? 0));
2326
2386
  };
2327
- const parseSize = (s: string): number => {
2328
- const m = s.match(/^(\d+(?:\.\d+)?)([KMGT]?)i?B?$/i);
2329
- if (!m) throw new Error(`Invalid size "${s}" (use NK/NM/NG/NT, e.g. 2G)`);
2330
- const n = Number.parseFloat(m[1] ?? "0");
2331
- const unit = (m[2] ?? "").toUpperCase();
2332
- const mult: Record<string, number> = { "": 1, K: 1024, M: 1024 ** 2, G: 1024 ** 3, T: 1024 ** 4 };
2333
- return Math.floor(n * (mult[unit] ?? 1));
2334
- };
2335
- const formatSize = (b: number): string => {
2336
- if (b >= 1024 ** 3) return `${(b / 1024 ** 3).toFixed(2)} GiB`;
2337
- if (b >= 1024 ** 2) return `${(b / 1024 ** 2).toFixed(1)} MiB`;
2338
- if (b >= 1024) return `${(b / 1024).toFixed(1)} KiB`;
2339
- return `${b} B`;
2340
- };
2387
+ const parseSize = parseSizeString;
2388
+ const formatSize = formatSizeBytes;
2341
2389
  const formatAge = (ms: number): string => {
2342
2390
  const s = Math.floor(ms / 1000);
2343
2391
  if (s < 60) return `${s}s`;
@@ -2429,6 +2477,82 @@ async function cmdCache(argv: string[]) {
2429
2477
  }
2430
2478
  }
2431
2479
 
2480
+ async function cmdSettings(argv: string[]) {
2481
+ const { flags, positional } = parseFlags(argv);
2482
+ const sub = positional[0] ?? "print";
2483
+
2484
+ if (sub === "help" || sub === "--help" || sub === "-h") {
2485
+ printCommandHelp("settings");
2486
+ return;
2487
+ }
2488
+
2489
+ const { settingsFilePath, settingsGet, settingsSet, settingsReset, settingsPrint } = await import("../lib/settings.ts");
2490
+ const { formatSizeBytes } = await import("../lib/cache.ts");
2491
+ const asJson = flags.json === true;
2492
+
2493
+ const displayValue = (key: string, value: unknown): string => {
2494
+ if (value === undefined) return "(unset)";
2495
+ if (key === "cache-max-size" && typeof value === "number") return formatSizeBytes(value);
2496
+ if (key === "timeout-extra" && typeof value === "number") return `${value}s`;
2497
+ return String(value);
2498
+ };
2499
+
2500
+ switch (sub) {
2501
+ case "print": {
2502
+ const key = positional[1];
2503
+ // All-keys print uses the tolerant settingsPrint() — a single malformed
2504
+ // env/file value must not crash the whole table (settingsGet, used for a
2505
+ // single named key below, is intentionally strict).
2506
+ const entries = key ? [settingsGet(key)] : settingsPrint();
2507
+ if (asJson) {
2508
+ console.log(JSON.stringify({ file: settingsFilePath(), settings: entries }, null, 2));
2509
+ return;
2510
+ }
2511
+ console.log(`Settings file: ${settingsFilePath()}\n`);
2512
+ for (const e of entries) {
2513
+ console.log(`${e.key.padEnd(16)} ${displayValue(e.key, e.value).padEnd(12)} [${e.source}]`);
2514
+ }
2515
+ break;
2516
+ }
2517
+ case "get": {
2518
+ const key = positional[1];
2519
+ if (!key) {
2520
+ console.error("Usage: quickchr settings get <key>");
2521
+ process.exit(1);
2522
+ }
2523
+ const entry = settingsGet(key);
2524
+ console.log(asJson ? JSON.stringify(entry, null, 2) : displayValue(entry.key, entry.value));
2525
+ break;
2526
+ }
2527
+ case "set": {
2528
+ const key = positional[1];
2529
+ const value = positional[2];
2530
+ if (!key || value === undefined) {
2531
+ console.error("Usage: quickchr settings set <key> <value>");
2532
+ process.exit(1);
2533
+ }
2534
+ const result = settingsSet(key, value);
2535
+ console.log(`${result.key}: ${displayValue(result.key, result.previous)} -> ${displayValue(result.key, result.value)}`);
2536
+ break;
2537
+ }
2538
+ case "reset": {
2539
+ const key = positional[1];
2540
+ const result = settingsReset(key);
2541
+ console.log(
2542
+ result.cleared.length === 0
2543
+ ? key
2544
+ ? `${key} was not set.`
2545
+ : "Nothing to clear."
2546
+ : `Cleared: ${result.cleared.join(", ")}`,
2547
+ );
2548
+ break;
2549
+ }
2550
+ default:
2551
+ console.error(`Unknown settings subcommand: ${sub}\nRun 'quickchr help settings' for usage.`);
2552
+ process.exit(1);
2553
+ }
2554
+ }
2555
+
2432
2556
  async function cmdDoctor(argv: string[] = []) {
2433
2557
  const { flags } = parseFlags(argv);
2434
2558
  const asJson = flagBool(flags, "json");
@@ -2557,6 +2681,7 @@ Commands:
2557
2681
  snapshot <name> [cmd] Manage snapshots (list/save/load/delete)
2558
2682
  networks Network discovery & socket management
2559
2683
  cache [list|prune|clear] Manage cached CHR images
2684
+ settings [print|get|set|reset] Manage quickchr's own global settings (quickchr.env)
2560
2685
  completions Manage shell completions (Tab completion)
2561
2686
  logs <name> Tail the QEMU log for an instance
2562
2687
  doctor [--json] Check prerequisites
@@ -2600,10 +2725,13 @@ Options:
2600
2725
  --add-disk <size> Add an extra blank qcow2 disk (repeatable, requires qemu-img)
2601
2726
  --add-package <pkg> Extra package to install on first boot (repeatable)
2602
2727
  --forward <spec> Add an extra hostfwd port (repeatable). Spec:
2603
- name[:host[:guest]][/proto]. Examples:
2728
+ name[:host[:guest]][/proto], or a port range
2729
+ name:hostStart-hostEnd[:guestStart-guestEnd][/proto].
2730
+ Examples:
2604
2731
  --forward smb (host auto, guest 445/tcp from registry)
2605
2732
  --forward winbox:9300 (host pinned, guest from registry)
2606
2733
  --forward myapp:9200:7777/udp (fully explicit)
2734
+ --forward btest:9200-9210:2000-2010/udp (range, e.g. dynamic ports)
2607
2735
  --install-all-packages Install all packages on first boot
2608
2736
  --add-user <u:p> Create user on first boot (name:password)
2609
2737
  --disable-admin Disable the default admin account on first boot
@@ -2679,8 +2807,10 @@ Options:
2679
2807
  --add-disk <size> Add an extra blank qcow2 disk (repeatable, requires qemu-img)
2680
2808
  --add-package <pkg> Extra package to install (repeatable)
2681
2809
  --forward <spec> Add an extra hostfwd port (repeatable). Spec:
2682
- name[:host[:guest]][/proto]. Examples: smb,
2683
- winbox:9300, myapp:9200:7777/udp.
2810
+ name[:host[:guest]][/proto], or a range
2811
+ name:hostStart-hostEnd[:guestStart-guestEnd][/proto].
2812
+ Examples: smb, winbox:9300, myapp:9200:7777/udp,
2813
+ btest:9200-9210:2000-2010/udp.
2684
2814
  --add-user <u:p> Create user with name:password
2685
2815
  --disable-admin Disable the default admin account
2686
2816
  --no-secure-login Keep admin with no password (skip managed account)
@@ -2729,8 +2859,9 @@ List all CHR instances or show detailed info for one.
2729
2859
  case "inspect":
2730
2860
  console.log(`quickchr inspect <name> [--json]
2731
2861
 
2732
- Print a stable JSON descriptor for a running CHR instance: ports, URLs,
2733
- credentials, status, and subprocess env vars.
2862
+ Print a stable JSON descriptor for a running CHR instance: status, machine
2863
+ identity, and per-service connection facts (rest-api, native-api, ssh).
2864
+ Use 'quickchr env' for subprocess env vars.
2734
2865
 
2735
2866
  <name> Name of a running CHR instance.
2736
2867
  --json Accepted for parity; output is always JSON.`);
@@ -2912,7 +3043,39 @@ Subcommands:
2912
3043
 
2913
3044
  Duration: <N>(s|m|h|d|w) Size: <N>(K|M|G|T)[i][B] (case-insensitive, IEC binary).
2914
3045
 
2915
- Default auto-prune cap: 2 GiB (applied after each successful start).`);
3046
+ Default auto-prune cap: 2 GiB — override via 'quickchr settings set cache-max-size <size>'
3047
+ or the QUICKCHR_CACHE_MAX_SIZE env var (applied after each successful start).`);
3048
+ break;
3049
+ case "settings":
3050
+ console.log(`quickchr settings [print|get|set|reset] [key] [value] [--json]
3051
+
3052
+ Manage quickchr's own global preferences, stored in
3053
+ ~/.config/quickchr/quickchr.env (dotenv-style: QUICKCHR_KEY=value lines).
3054
+
3055
+ Managed keys:
3056
+ default-channel Default --channel for 'add'/'start' and the setup wizard.
3057
+ stable|long-term|testing|development (default: stable)
3058
+ default-arch Default --arch. arm64|x86|auto (default: auto = host native)
3059
+ cache-max-size Auto-prune cap applied after each successful start.
3060
+ Size string (e.g. 2G, 512M). (default: 2G)
3061
+ timeout-extra Default for 'start's --timeout-extra/-T when omitted.
3062
+ Non-negative integer seconds. (default: 0)
3063
+ secure-login Default for 'add'/'start's --secure-login when neither
3064
+ --secure-login nor --no-secure-login is passed.
3065
+ true|false (default: false — 'settings print' shows this
3066
+ one as "(unset)" rather than "false"; the setup wizard
3067
+ needs to tell "not configured" apart from "explicitly
3068
+ false" to know whether to still recommend managed login)
3069
+
3070
+ Precedence (highest wins): CLI flag > QUICKCHR_<KEY> env var > quickchr.env > built-in default.
3071
+
3072
+ Subcommands:
3073
+ print [key] [--json] Show resolved value + source for one/all keys.
3074
+ get <key> [--json] Print one key's resolved value.
3075
+ set <key> <value> Validate and write a value to quickchr.env.
3076
+ reset [key] Delete one managed line, or all managed lines.
3077
+
3078
+ Credentials (--add-user, MIKROTIK_WEB_ACCOUNT/PASSWORD) are never stored here.`);
2916
3079
  break;
2917
3080
  default:
2918
3081
  console.log(`No detailed help for '${command}'.`);