@termix-ssh/cli 1.1.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -29307,7 +29307,7 @@ function unavailableFor(pluginId, reason) {
29307
29307
  }
29308
29308
 
29309
29309
  // src/version.ts
29310
- var CLI_VERSION = true ? "1.1.2" : "0.0.0-dev";
29310
+ var CLI_VERSION = true ? "1.3.0" : "0.0.0-dev";
29311
29311
 
29312
29312
  // src/core/http.ts
29313
29313
  var MAX_ATTEMPTS = 3;
@@ -31332,6 +31332,224 @@ function resolveLocalTarget(localPath, remotePath) {
31332
31332
 
31333
31333
  // src/commands/tunnel.ts
31334
31334
  import { setTimeout as sleep2 } from "timers/promises";
31335
+
31336
+ // src/commands/gateway.ts
31337
+ var GATEWAY_COLUMNS = [
31338
+ { header: "id", value: (g) => g.id, align: "right" },
31339
+ { header: "name", value: (g) => g.name },
31340
+ { header: "state", value: (g) => g.status.state },
31341
+ { header: "private host", value: (g) => g.privateHostId, align: "right" },
31342
+ { header: "public host", value: (g) => g.publicHostId, align: "right" },
31343
+ {
31344
+ header: "ports on",
31345
+ value: (g) => g.ports.filter((p) => p.enabled).length,
31346
+ align: "right"
31347
+ }
31348
+ ];
31349
+ var PORT_COLUMNS = [
31350
+ { header: "id", value: (p) => p.id, align: "right" },
31351
+ { header: "public", value: (p) => `${p.proto} ${p.publicPort}` },
31352
+ { header: "target", value: (p) => `${p.targetHost || "-"}:${p.targetPort}` },
31353
+ { header: "on", value: (p) => p.enabled ? "yes" : "no" },
31354
+ { header: "from", value: (p) => p.source },
31355
+ { header: "label", value: (p) => p.label }
31356
+ ];
31357
+ function gatewayPath(id, sub = "") {
31358
+ return pluginPath("tunnels", `/gateways/${id}${sub}`);
31359
+ }
31360
+ function parsePort2(value, flag) {
31361
+ const port = Number(value);
31362
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
31363
+ throw new UsageError(`Invalid ${flag}: "${value}" (expected 1-65535).`);
31364
+ }
31365
+ return port;
31366
+ }
31367
+ function buildPortBody(opts) {
31368
+ if (opts.publicPort === void 0) {
31369
+ throw new UsageError("A port needs --public-port.");
31370
+ }
31371
+ const publicPort = parsePort2(opts.publicPort, "--public-port");
31372
+ const proto = opts.proto ?? "tcp";
31373
+ if (!["tcp", "udp", "both"].includes(proto)) {
31374
+ throw new UsageError(
31375
+ `Invalid --proto: "${proto}" (expected tcp, udp or both).`
31376
+ );
31377
+ }
31378
+ return {
31379
+ proto,
31380
+ publicPort,
31381
+ targetPort: opts.targetPort === void 0 ? publicPort : parsePort2(opts.targetPort, "--target-port"),
31382
+ targetHost: opts.targetHost ?? "",
31383
+ label: opts.label ?? "",
31384
+ force: opts.force === true ? true : void 0
31385
+ };
31386
+ }
31387
+ function registerGatewayCommands(tunnel) {
31388
+ const gateway = tunnel.command("gateway").description(
31389
+ "Publish services on a private host through a public host over WireGuard."
31390
+ );
31391
+ gateway.command("list", { isDefault: true }).description("List gateways.").action(async function() {
31392
+ await run(async () => {
31393
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31394
+ await requireFeature2("tunnels");
31395
+ const rows = await client.request({
31396
+ method: "GET",
31397
+ path: pluginPath("tunnels", "/gateways")
31398
+ });
31399
+ printList(rows ?? [], GATEWAY_COLUMNS, {
31400
+ quietField: "id",
31401
+ jsonWrapper: (list) => ({ count: list.length, gateways: list })
31402
+ });
31403
+ });
31404
+ });
31405
+ gateway.command("show <gatewayId>").description("Show a gateway's state and ports.").action(async function(idArg) {
31406
+ await run(async () => {
31407
+ const id = parseId(idArg);
31408
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31409
+ await requireFeature2("tunnels");
31410
+ const found = await client.request({
31411
+ method: "GET",
31412
+ path: gatewayPath(id)
31413
+ });
31414
+ printList(found.ports ?? [], PORT_COLUMNS, {
31415
+ quietField: "id",
31416
+ jsonWrapper: () => found
31417
+ });
31418
+ });
31419
+ });
31420
+ gateway.command("create").description("Create a gateway and set it up on both hosts.").requiredOption("--name <name>", "Gateway name").requiredOption("--private-host <id>", "Host with the services").requiredOption("--public-host <id>", "Host with a public address").requiredOption(
31421
+ "--endpoint <address>",
31422
+ "Public address of the public host (an IP or domain)"
31423
+ ).option("--port <port>", "WireGuard UDP port (picked for you by default)").action(async function(opts) {
31424
+ await run(async () => {
31425
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31426
+ await requireFeature2("tunnels");
31427
+ const created = await client.request({
31428
+ method: "POST",
31429
+ path: pluginPath("tunnels", "/gateways"),
31430
+ data: {
31431
+ name: opts.name,
31432
+ privateHostId: parseId(opts.privateHost),
31433
+ publicHostId: parseId(opts.publicHost),
31434
+ endpoint: opts.endpoint,
31435
+ listenPort: opts.port === void 0 ? void 0 : parsePort2(opts.port, "--port")
31436
+ }
31437
+ });
31438
+ printResult(`Created gateway ${created.id}.`, {
31439
+ id: created.id,
31440
+ name: created.name
31441
+ });
31442
+ });
31443
+ });
31444
+ for (const [name, sub, verb] of [
31445
+ ["apply", "/apply", "Applied"],
31446
+ ["check", "/check", "Checked"]
31447
+ ]) {
31448
+ gateway.command(`${name} <gatewayId>`).description(
31449
+ name === "apply" ? "Write the tunnel and rules to both hosts again." : "Read the tunnel and rule state from both hosts."
31450
+ ).action(async function(idArg) {
31451
+ await run(async () => {
31452
+ const id = parseId(idArg);
31453
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31454
+ await requireFeature2("tunnels");
31455
+ const result = await client.request({
31456
+ method: "POST",
31457
+ path: gatewayPath(id, sub)
31458
+ });
31459
+ printResult(`${verb} gateway ${id}: ${result.status.state}.`, {
31460
+ id,
31461
+ state: result.status.state,
31462
+ message: result.status.message
31463
+ });
31464
+ });
31465
+ });
31466
+ }
31467
+ gateway.command("scan <gatewayId>").description("Look for new listening ports now.").action(async function(idArg) {
31468
+ await run(async () => {
31469
+ const id = parseId(idArg);
31470
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31471
+ await requireFeature2("tunnels");
31472
+ const result = await client.request({
31473
+ method: "POST",
31474
+ path: gatewayPath(id, "/scan")
31475
+ });
31476
+ printResult(`Found ${result.found} new port(s).`, {
31477
+ id,
31478
+ found: result.found
31479
+ });
31480
+ });
31481
+ });
31482
+ gateway.command("remove <gatewayId>").description("Take a gateway off both hosts and delete it.").action(async function(idArg) {
31483
+ await run(async () => {
31484
+ const id = parseId(idArg);
31485
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31486
+ await requireFeature2("tunnels");
31487
+ await client.request({ method: "DELETE", path: gatewayPath(id) });
31488
+ printResult(`Removed gateway ${id}.`, { id });
31489
+ });
31490
+ });
31491
+ const port = gateway.command("port").description("Manage a gateway's ports.");
31492
+ port.command("add <gatewayId>").description("Forward a public port. It starts on.").option("--public-port <port>", "Port on the public host").option("--target-port <port>", "Port on the target (default: same)").option("--proto <proto>", "tcp, udp or both (default: tcp)").option(
31493
+ "--target-host <ip>",
31494
+ "IPv4 address of the target (default: the private host)"
31495
+ ).option("--label <text>", "A note for the port").option("--force", "Use the port even if the public host listens on it").action(async function(idArg, opts) {
31496
+ await run(async () => {
31497
+ const id = parseId(idArg);
31498
+ const body = buildPortBody(opts);
31499
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31500
+ await requireFeature2("tunnels");
31501
+ const created = await client.request({
31502
+ method: "POST",
31503
+ path: gatewayPath(id, "/ports"),
31504
+ data: body
31505
+ });
31506
+ printResult(`Added port ${created.id} to gateway ${id}.`, {
31507
+ id: created.id,
31508
+ gatewayId: id
31509
+ });
31510
+ });
31511
+ });
31512
+ for (const [name, enabled] of [
31513
+ ["enable", true],
31514
+ ["disable", false]
31515
+ ]) {
31516
+ port.command(`${name} <gatewayId> <portId>`).description(`Turn a forwarded port ${enabled ? "on" : "off"}.`).option("--force", "Use the port even if the public host listens on it").action(async function(idArg, portArg, opts) {
31517
+ await run(async () => {
31518
+ const id = parseId(idArg);
31519
+ const portId = parseId(portArg);
31520
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31521
+ await requireFeature2("tunnels");
31522
+ await client.request({
31523
+ method: "PATCH",
31524
+ path: gatewayPath(id, `/ports/${portId}`),
31525
+ data: { enabled, force: opts.force === true ? true : void 0 }
31526
+ });
31527
+ printResult(
31528
+ `Turned port ${portId} ${enabled ? "on" : "off"} on gateway ${id}.`,
31529
+ { id: portId, gatewayId: id, enabled }
31530
+ );
31531
+ });
31532
+ });
31533
+ }
31534
+ port.command("remove <gatewayId> <portId>").description("Delete a forwarded port.").action(async function(idArg, portArg) {
31535
+ await run(async () => {
31536
+ const id = parseId(idArg);
31537
+ const portId = parseId(portArg);
31538
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31539
+ await requireFeature2("tunnels");
31540
+ await client.request({
31541
+ method: "DELETE",
31542
+ path: gatewayPath(id, `/ports/${portId}`)
31543
+ });
31544
+ printResult(`Removed port ${portId} from gateway ${id}.`, {
31545
+ id: portId,
31546
+ gatewayId: id
31547
+ });
31548
+ });
31549
+ });
31550
+ }
31551
+
31552
+ // src/commands/tunnel.ts
31335
31553
  var TUNNEL_COLUMNS = [
31336
31554
  { header: "name", value: (t) => t.displayName ?? t.name },
31337
31555
  { header: "status", value: (t) => t.status },
@@ -31379,6 +31597,15 @@ function parseConnections(host) {
31379
31597
  }
31380
31598
  return [];
31381
31599
  }
31600
+ function parseIndex(value) {
31601
+ const index = Number(value);
31602
+ if (!Number.isInteger(index) || index < 0) {
31603
+ throw new UsageError(
31604
+ `Invalid tunnel index: "${value}" (expected a non-negative integer).`
31605
+ );
31606
+ }
31607
+ return index;
31608
+ }
31382
31609
  function tunnelMode(connection) {
31383
31610
  return connection.mode ?? connection.tunnelType ?? "local";
31384
31611
  }
@@ -31429,6 +31656,95 @@ async function loadHost(client, hostId) {
31429
31656
  });
31430
31657
  return { ...host, id: hostId };
31431
31658
  }
31659
+ async function loadConnections(client, host) {
31660
+ try {
31661
+ const saved = await client.request({ method: "GET", path: pluginPath("tunnels", "/saved") });
31662
+ if (Array.isArray(saved)) {
31663
+ return saved.find((entry) => entry.hostId === host.id)?.connections ?? [];
31664
+ }
31665
+ } catch (error) {
31666
+ if (!(error instanceof TermixApiError && error.status === 404)) throw error;
31667
+ }
31668
+ return parseConnections(host);
31669
+ }
31670
+ async function saveConnections(client, hostId, connections) {
31671
+ try {
31672
+ await client.request({
31673
+ method: "PUT",
31674
+ path: pluginPath("tunnels", `/saved/${hostId}`),
31675
+ data: { connections }
31676
+ });
31677
+ } catch (error) {
31678
+ if (error instanceof TermixApiError && error.status === 404) {
31679
+ throw new Error(
31680
+ "This server's Tunnels plugin is older than 1.2.0, so tunnels can't be changed from the CLI. Update the plugin."
31681
+ );
31682
+ }
31683
+ throw error;
31684
+ }
31685
+ }
31686
+ function parsePort3(value, flag) {
31687
+ const port = Number(value);
31688
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
31689
+ throw new UsageError(`Invalid ${flag}: "${value}" (expected 1-65535).`);
31690
+ }
31691
+ return port;
31692
+ }
31693
+ function parseCount(value, flag) {
31694
+ const count = Number(value);
31695
+ if (!Number.isInteger(count) || count < 0) {
31696
+ throw new UsageError(
31697
+ `Invalid ${flag}: "${value}" (expected a whole number).`
31698
+ );
31699
+ }
31700
+ return count;
31701
+ }
31702
+ function buildConnection(opts, base) {
31703
+ const next = base ? { ...base } : {
31704
+ scope: "s2s",
31705
+ mode: "local",
31706
+ bindHost: "127.0.0.1",
31707
+ maxRetries: 3,
31708
+ retryInterval: 10,
31709
+ autoStart: false
31710
+ };
31711
+ if (opts.mode !== void 0) {
31712
+ if (!["local", "remote", "dynamic"].includes(opts.mode)) {
31713
+ throw new UsageError(
31714
+ `Invalid --mode: "${opts.mode}" (expected local, remote or dynamic).`
31715
+ );
31716
+ }
31717
+ next.mode = opts.mode;
31718
+ next.tunnelType = opts.mode === "remote" ? "remote" : "local";
31719
+ }
31720
+ if (opts.sourcePort !== void 0) {
31721
+ next.sourcePort = parsePort3(opts.sourcePort, "--source-port");
31722
+ }
31723
+ if (opts.endpointHost !== void 0) next.endpointHost = opts.endpointHost;
31724
+ if (opts.endpointPort !== void 0) {
31725
+ next.endpointPort = parsePort3(opts.endpointPort, "--endpoint-port");
31726
+ }
31727
+ if (opts.bindHost !== void 0) next.bindHost = opts.bindHost;
31728
+ if (opts.maxRetries !== void 0) {
31729
+ next.maxRetries = parseCount(opts.maxRetries, "--max-retries");
31730
+ }
31731
+ if (opts.retryInterval !== void 0) {
31732
+ next.retryInterval = parseCount(opts.retryInterval, "--retry-interval");
31733
+ }
31734
+ if (opts.autoStart !== void 0) next.autoStart = opts.autoStart;
31735
+ if (next.sourcePort === void 0) {
31736
+ throw new UsageError("A tunnel needs --source-port.");
31737
+ }
31738
+ if (tunnelMode(next) !== "dynamic" && next.endpointPort === void 0) {
31739
+ throw new UsageError(
31740
+ "A tunnel needs --endpoint-port unless it is dynamic."
31741
+ );
31742
+ }
31743
+ return next;
31744
+ }
31745
+ function withTunnelOptions(command) {
31746
+ return command.option("--mode <mode>", "local, remote or dynamic").option("--source-port <port>", "Port the tunnel listens on").option("--endpoint-host <host>", "Where the tunnel goes").option("--endpoint-port <port>", "Port on the endpoint").option("--bind-host <address>", "Address the tunnel listens on").option("--max-retries <count>", "How many times to retry").option("--retry-interval <seconds>", "Seconds between retries").option("--auto-start", "Start the tunnel when Termix starts").option("--no-auto-start", "Do not start it when Termix starts");
31747
+ }
31432
31748
  function registerTunnelCommands(program3) {
31433
31749
  const tunnel = program3.command("tunnel").description("Manage SSH tunnels configured on your hosts.");
31434
31750
  tunnel.command("list", { isDefault: true }).description("Show the status of every tunnel.").action(async function() {
@@ -31453,14 +31769,16 @@ function registerTunnelCommands(program3) {
31453
31769
  const { client, requireFeature: requireFeature2 } = await createContext(this);
31454
31770
  await requireFeature2("tunnels");
31455
31771
  const host = await loadHost(client, hostId);
31456
- const rows = parseConnections(host).map((connection, index) => ({
31457
- index,
31458
- name: buildTunnelName(host, index, connection),
31459
- mode: tunnelMode(connection),
31460
- sourcePort: connection.sourcePort,
31461
- endpointHost: endpointHostOf(connection),
31462
- endpointPort: connection.endpointPort
31463
- }));
31772
+ const rows = (await loadConnections(client, host)).map(
31773
+ (connection, index) => ({
31774
+ index,
31775
+ name: buildTunnelName(host, index, connection),
31776
+ mode: tunnelMode(connection),
31777
+ sourcePort: connection.sourcePort,
31778
+ endpointHost: endpointHostOf(connection),
31779
+ endpointPort: connection.endpointPort
31780
+ })
31781
+ );
31464
31782
  printList(
31465
31783
  rows,
31466
31784
  [
@@ -31492,7 +31810,7 @@ function registerTunnelCommands(program3) {
31492
31810
  const { client, requireFeature: requireFeature2 } = await createContext(this);
31493
31811
  await requireFeature2("tunnels");
31494
31812
  const host = await loadHost(client, hostId);
31495
- const connection = parseConnections(host)[index];
31813
+ const connection = (await loadConnections(client, host))[index];
31496
31814
  if (!connection) {
31497
31815
  throw new UsageError(
31498
31816
  `Host ${hostId} has no tunnel at index ${index}. Run \`termix tunnel show ${hostId}\`.`
@@ -31517,6 +31835,82 @@ function registerTunnelCommands(program3) {
31517
31835
  );
31518
31836
  });
31519
31837
  });
31838
+ withTunnelOptions(
31839
+ tunnel.command("add <hostId>").description(
31840
+ "Add a tunnel to a host. Tunnels must be turned on for the host."
31841
+ )
31842
+ ).action(async function(hostIdArg, opts) {
31843
+ await run(async () => {
31844
+ const hostId = parseId(hostIdArg);
31845
+ const connection = buildConnection(opts);
31846
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31847
+ await requireFeature2("tunnels");
31848
+ const host = await loadHost(client, hostId);
31849
+ if (host.pluginSettings?.tunnels?.enableTunnel !== true) {
31850
+ throw new UsageError(
31851
+ `Tunnels are off for host ${hostId}. Turn on Enable Tunneling for it first.`
31852
+ );
31853
+ }
31854
+ const connections = await loadConnections(client, host);
31855
+ await saveConnections(client, hostId, [...connections, connection]);
31856
+ const index = connections.length;
31857
+ printResult(`Added tunnel ${index} to host ${hostId}.`, {
31858
+ hostId,
31859
+ index
31860
+ });
31861
+ });
31862
+ });
31863
+ withTunnelOptions(
31864
+ tunnel.command("edit <hostId> <index>").description("Change a tunnel. Only the options you give are changed.")
31865
+ ).action(async function(hostIdArg, indexArg, opts) {
31866
+ await run(async () => {
31867
+ const hostId = parseId(hostIdArg);
31868
+ const index = parseIndex(indexArg);
31869
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31870
+ await requireFeature2("tunnels");
31871
+ const host = await loadHost(client, hostId);
31872
+ const connections = await loadConnections(client, host);
31873
+ const current = connections[index];
31874
+ if (!current) {
31875
+ throw new UsageError(
31876
+ `Host ${hostId} has no tunnel at index ${index}. Run \`termix tunnel show ${hostId}\`.`
31877
+ );
31878
+ }
31879
+ const next = connections.map(
31880
+ (c, i) => i === index ? buildConnection(opts, current) : c
31881
+ );
31882
+ await saveConnections(client, hostId, next);
31883
+ printResult(`Changed tunnel ${index} on host ${hostId}.`, {
31884
+ hostId,
31885
+ index
31886
+ });
31887
+ });
31888
+ });
31889
+ tunnel.command("remove <hostId> <index>").description("Delete a tunnel from a host.").action(async function(hostIdArg, indexArg) {
31890
+ await run(async () => {
31891
+ const hostId = parseId(hostIdArg);
31892
+ const index = parseIndex(indexArg);
31893
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31894
+ await requireFeature2("tunnels");
31895
+ const host = await loadHost(client, hostId);
31896
+ const connections = await loadConnections(client, host);
31897
+ if (!connections[index]) {
31898
+ throw new UsageError(
31899
+ `Host ${hostId} has no tunnel at index ${index}. Run \`termix tunnel show ${hostId}\`.`
31900
+ );
31901
+ }
31902
+ await saveConnections(
31903
+ client,
31904
+ hostId,
31905
+ connections.filter((_, i) => i !== index)
31906
+ );
31907
+ printResult(`Removed tunnel ${index} from host ${hostId}.`, {
31908
+ hostId,
31909
+ index
31910
+ });
31911
+ });
31912
+ });
31913
+ registerGatewayCommands(tunnel);
31520
31914
  tunnel.command("stop <name>").description("Stop a running tunnel by its full name (see `tunnel list`).").action(async function(name) {
31521
31915
  await run(async () => {
31522
31916
  const { client, requireFeature: requireFeature2 } = await createContext(this);
@@ -32335,13 +32729,17 @@ function registerApiKeyCommands(program3) {
32335
32729
  });
32336
32730
  keys.command("create").description(
32337
32731
  "Create an API key for a user. The token is shown once and cannot be retrieved again."
32338
- ).requiredOption("--name <name>", "Human-readable name for the key").requiredOption("--user <userId>", "Id of the user the key acts as").option("--expires-at <date>", "Expiry as an ISO date; omit for no expiry").action(async function(opts) {
32732
+ ).requiredOption("--name <name>", "Human-readable name for the key").requiredOption("--user <userId>", "Id of the user the key acts as").option("--expires-at <date>", "Expiry as an ISO date; omit for no expiry").option(
32733
+ "--scope <scope>",
32734
+ "Limit the key to actions: actions-read or actions-run. Omit for full access"
32735
+ ).action(async function(opts) {
32339
32736
  await run(async () => {
32340
32737
  if (opts.expiresAt && Number.isNaN(Date.parse(opts.expiresAt))) {
32341
32738
  throw new UsageError(
32342
32739
  `Invalid --expires-at: "${opts.expiresAt}" (expected an ISO date).`
32343
32740
  );
32344
32741
  }
32742
+ const scopes = opts.scope ? [scopeOf(opts.scope)] : void 0;
32345
32743
  const { client } = await createContext(this);
32346
32744
  const created = await client.request({
32347
32745
  method: "POST",
@@ -32349,7 +32747,8 @@ function registerApiKeyCommands(program3) {
32349
32747
  data: {
32350
32748
  name: opts.name,
32351
32749
  userId: opts.user,
32352
- ...opts.expiresAt ? { expiresAt: opts.expiresAt } : {}
32750
+ ...opts.expiresAt ? { expiresAt: opts.expiresAt } : {},
32751
+ ...scopes ? { scopes } : {}
32353
32752
  }
32354
32753
  });
32355
32754
  if (isJsonMode()) {
@@ -32373,6 +32772,21 @@ function registerApiKeyCommands(program3) {
32373
32772
  });
32374
32773
  });
32375
32774
  }
32775
+ function scopeOf(value) {
32776
+ const scopes = {
32777
+ "actions-read": "operations:read",
32778
+ "actions-run": "operations:run",
32779
+ "operations:read": "operations:read",
32780
+ "operations:run": "operations:run"
32781
+ };
32782
+ const scope = scopes[value];
32783
+ if (!scope) {
32784
+ throw new UsageError(
32785
+ `Invalid --scope "${value}" (expected actions-read or actions-run).`
32786
+ );
32787
+ }
32788
+ return scope;
32789
+ }
32376
32790
 
32377
32791
  // src/commands/misc.ts
32378
32792
  var STATUS_COLUMNS = [
@@ -32552,6 +32966,242 @@ function registerApiCommands(program3) {
32552
32966
  });
32553
32967
  }
32554
32968
 
32969
+ // src/commands/ops.ts
32970
+ var OPS_EXIT = {
32971
+ FAILED: 1,
32972
+ NEEDS_APPROVAL: 9,
32973
+ PARTIAL: 10
32974
+ };
32975
+ function collectInput2(value, previous) {
32976
+ const index = value.indexOf("=");
32977
+ if (index <= 0) {
32978
+ throw new UsageError(`Invalid --input "${value}" (expected KEY=VALUE).`);
32979
+ }
32980
+ const raw = value.slice(index + 1);
32981
+ let parsed = raw;
32982
+ if (/^(true|false|null|-?\d+(\.\d+)?|\{.*\}|\[.*\])$/s.test(raw)) {
32983
+ try {
32984
+ parsed = JSON.parse(raw);
32985
+ } catch {
32986
+ parsed = raw;
32987
+ }
32988
+ }
32989
+ return { ...previous, [value.slice(0, index)]: parsed };
32990
+ }
32991
+ function collectHosts(value, previous) {
32992
+ return [
32993
+ ...previous,
32994
+ ...value.split(",").map((part) => parseId(part.trim(), "host id"))
32995
+ ];
32996
+ }
32997
+ function exitFor(outcomes) {
32998
+ if (outcomes.length === 0) return 0;
32999
+ const failed = outcomes.filter(
33000
+ (outcome) => outcome.status !== "success" && outcome.status !== "pending_approval"
33001
+ ).length;
33002
+ const waiting = outcomes.filter(
33003
+ (outcome) => outcome.status === "pending_approval"
33004
+ ).length;
33005
+ if (failed === outcomes.length) return OPS_EXIT.FAILED;
33006
+ if (failed > 0) return OPS_EXIT.PARTIAL;
33007
+ if (waiting > 0) return OPS_EXIT.NEEDS_APPROVAL;
33008
+ return 0;
33009
+ }
33010
+ var ACTION_COLUMNS = [
33011
+ { header: "id", value: (a) => a.id },
33012
+ { header: "title", value: (a) => a.title },
33013
+ { header: "plugin", value: (a) => a.pluginName },
33014
+ { header: "on", value: (a) => a.scope },
33015
+ { header: "risk", value: (a) => a.risk }
33016
+ ];
33017
+ var RUN_COLUMNS = [
33018
+ { header: "id", value: (r) => String(r.id).slice(0, 8) },
33019
+ { header: "action", value: (r) => r.actionId },
33020
+ { header: "host", value: (r) => r.hostName },
33021
+ { header: "status", value: (r) => r.status },
33022
+ { header: "by", value: (r) => r.username },
33023
+ { header: "when", value: (r) => r.createdAt }
33024
+ ];
33025
+ var POLL_MS = 1500;
33026
+ function registerOpsCommands(program3) {
33027
+ const ops = program3.command("ops").alias("actions").description(
33028
+ "Run and track the actions plugins offer, such as restarting a container, on one host or many."
33029
+ );
33030
+ ops.command("list").description("List the actions you can run").option("--search <text>", "Only actions whose id, title or plugin match").action(async function(opts) {
33031
+ await run(async () => {
33032
+ const { client } = await createContext(this);
33033
+ const catalog = await client.request({
33034
+ method: "GET",
33035
+ path: "/operations/catalog",
33036
+ params: { surface: "cli" }
33037
+ });
33038
+ const text = opts.search?.toLowerCase() ?? "";
33039
+ const rows = catalog.actions.filter(
33040
+ (action) => action.available && (!text || `${action.id} ${action.title} ${action.pluginName}`.toLowerCase().includes(text))
33041
+ );
33042
+ printList(
33043
+ rows,
33044
+ ACTION_COLUMNS,
33045
+ {
33046
+ quietField: "id",
33047
+ jsonWrapper: (actions) => ({ actions })
33048
+ }
33049
+ );
33050
+ });
33051
+ });
33052
+ ops.command("describe <id>").description("Show what an action needs").action(async function(id) {
33053
+ await run(async () => {
33054
+ const { client } = await createContext(this);
33055
+ const action = await client.request({
33056
+ method: "GET",
33057
+ path: `/operations/catalog/${encodeURIComponent(id)}`
33058
+ });
33059
+ printRecord(action);
33060
+ });
33061
+ });
33062
+ ops.command("run <id>").description(
33063
+ "Run an action. Pick hosts with --host. Changes may wait for approval, which exits 9."
33064
+ ).option(
33065
+ "--host <ids>",
33066
+ "Host id, or several separated by commas; repeatable",
33067
+ collectHosts,
33068
+ []
33069
+ ).option("--target <key>", "The item on each host, such as a container name").option(
33070
+ "--input <KEY=VALUE>",
33071
+ "An input value; repeatable",
33072
+ collectInput2,
33073
+ {}
33074
+ ).option("-d, --data <json>", "All inputs as a JSON object").option("--data-file <path>", "Read the inputs from a file, or - for stdin").option("--dry-run", "Report what would happen without changing anything").option("--yes", "Confirm a destructive action").action(async function(id, opts) {
33075
+ await run(async () => {
33076
+ const body = parseApiBody(opts);
33077
+ if (body !== void 0 && (typeof body !== "object" || Array.isArray(body))) {
33078
+ throw new UsageError("The inputs must be a JSON object.");
33079
+ }
33080
+ const input = {
33081
+ ...body ?? {},
33082
+ ...opts.input
33083
+ };
33084
+ const { client } = await createContext(this);
33085
+ const hosts = opts.host.length > 0 ? opts.host : [void 0];
33086
+ const outcomes = [];
33087
+ for (const hostId of hosts) {
33088
+ const outcome = await client.request({
33089
+ method: "POST",
33090
+ path: `/operations/${encodeURIComponent(id)}/run`,
33091
+ data: {
33092
+ hostId,
33093
+ resourceKey: opts.target,
33094
+ input,
33095
+ dryRun: opts.dryRun === true,
33096
+ confirmed: opts.yes === true
33097
+ }
33098
+ });
33099
+ outcomes.push({ ...outcome, hostId });
33100
+ }
33101
+ if (hosts.length === 1) {
33102
+ printRecord(outcomes[0], {
33103
+ quietField: "runId"
33104
+ });
33105
+ } else {
33106
+ printList(
33107
+ outcomes,
33108
+ [
33109
+ { header: "host", value: (o) => o.hostId },
33110
+ { header: "status", value: (o) => o.status },
33111
+ { header: "result", value: (o) => o.summary ?? o.error }
33112
+ ],
33113
+ { jsonWrapper: (results) => ({ results }) }
33114
+ );
33115
+ }
33116
+ process.exitCode = exitFor(outcomes);
33117
+ });
33118
+ });
33119
+ ops.command("runs").description("List recent runs").option("--host <id>", "Only runs on this host").option("--status <status>", "Only runs with this status").option("--limit <n>", "How many", "50").action(async function(opts) {
33120
+ await run(async () => {
33121
+ const { client } = await createContext(this);
33122
+ const { runs } = await client.request({
33123
+ method: "GET",
33124
+ path: "/operations/runs",
33125
+ params: {
33126
+ hostId: opts.host ? parseId(opts.host, "host id") : void 0,
33127
+ status: opts.status,
33128
+ limit: opts.limit
33129
+ }
33130
+ });
33131
+ printList(runs, RUN_COLUMNS, {
33132
+ quietField: "id",
33133
+ jsonWrapper: (rows) => ({ runs: rows })
33134
+ });
33135
+ });
33136
+ });
33137
+ ops.command("status <runId>").description("Show one run. --wait waits until it finishes.").option("--wait", "Wait for the run to finish").action(async function(runId, opts) {
33138
+ await run(async () => {
33139
+ const { client } = await createContext(this);
33140
+ const get = () => client.request({
33141
+ method: "GET",
33142
+ path: `/operations/runs/${encodeURIComponent(runId)}`
33143
+ });
33144
+ let current = await get();
33145
+ while (opts.wait && (current.status === "running" || current.status === "pending_approval")) {
33146
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
33147
+ current = await get();
33148
+ }
33149
+ printRecord(current);
33150
+ process.exitCode = exitFor([current]);
33151
+ });
33152
+ });
33153
+ ops.command("approvals").description("List requests waiting for approval").action(async function() {
33154
+ await run(async () => {
33155
+ const { client } = await createContext(this);
33156
+ const { approvals } = await client.request({ method: "GET", path: "/operations/approvals" });
33157
+ printList(
33158
+ approvals.map(
33159
+ (approval) => ({ ...approval.run, approvalId: approval.id })
33160
+ ),
33161
+ [
33162
+ { header: "approval", value: (r) => r.approvalId },
33163
+ { header: "action", value: (r) => r.actionId },
33164
+ { header: "host", value: (r) => r.hostName },
33165
+ { header: "by", value: (r) => r.username }
33166
+ ],
33167
+ {
33168
+ quietField: "approvalId",
33169
+ jsonWrapper: (rows) => ({ approvals: rows })
33170
+ }
33171
+ );
33172
+ });
33173
+ });
33174
+ for (const [name, approve] of [
33175
+ ["approve", true],
33176
+ ["reject", false]
33177
+ ]) {
33178
+ ops.command(`${name} <approvalId>`).description(
33179
+ approve ? "Approve a waiting request and run it. Needs a signed in session, not an API key." : "Reject a waiting request"
33180
+ ).option("--comment <text>", "A note kept with the decision").action(async function(approvalId, opts) {
33181
+ await run(async () => {
33182
+ const { client } = await createContext(this);
33183
+ const outcome = await client.request({
33184
+ method: "POST",
33185
+ path: `/operations/approvals/${encodeURIComponent(approvalId)}`,
33186
+ data: { approve, comment: opts.comment }
33187
+ });
33188
+ printRecord(outcome);
33189
+ if (approve) process.exitCode = exitFor([outcome]);
33190
+ });
33191
+ });
33192
+ }
33193
+ ops.command("cancel <runId>").description("Stop a running action, or withdraw one waiting for approval").action(async function(runId) {
33194
+ await run(async () => {
33195
+ const { client } = await createContext(this);
33196
+ const result = await client.request({
33197
+ method: "POST",
33198
+ path: `/operations/runs/${encodeURIComponent(runId)}/cancel`
33199
+ });
33200
+ printJson(result);
33201
+ });
33202
+ });
33203
+ }
33204
+
32555
33205
  // src/index.ts
32556
33206
  var program2 = new Command();
32557
33207
  program2.name("termix").description(
@@ -32576,6 +33226,7 @@ registerAdminCommands(program2);
32576
33226
  registerApiKeyCommands(program2);
32577
33227
  registerMiscCommands(program2);
32578
33228
  registerPluginCommands(program2);
33229
+ registerOpsCommands(program2);
32579
33230
  registerApiCommands(program2);
32580
33231
  program2.exitOverride((error) => {
32581
33232
  if (error.code === "commander.help" || error.code === "commander.helpDisplayed" || error.code === "commander.version") {