@termix-ssh/cli 1.0.2 → 1.1.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
@@ -1207,7 +1207,7 @@ var require_command = __commonJS({
1207
1207
  var EventEmitter2 = __require("events").EventEmitter;
1208
1208
  var childProcess = __require("child_process");
1209
1209
  var path3 = __require("path");
1210
- var fs7 = __require("fs");
1210
+ var fs8 = __require("fs");
1211
1211
  var process2 = __require("process");
1212
1212
  var { Argument: Argument2, humanReadableArgName } = require_argument();
1213
1213
  var { CommanderError: CommanderError2 } = require_error();
@@ -2201,7 +2201,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2201
2201
  * @param {string} subcommandName
2202
2202
  */
2203
2203
  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2204
- if (fs7.existsSync(executableFile)) return;
2204
+ if (fs8.existsSync(executableFile)) return;
2205
2205
  const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
2206
2206
  const executableMissing = `'${executableFile}' does not exist
2207
2207
  - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
@@ -2220,10 +2220,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2220
2220
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2221
2221
  function findFile(baseDir, baseName) {
2222
2222
  const localBin = path3.resolve(baseDir, baseName);
2223
- if (fs7.existsSync(localBin)) return localBin;
2223
+ if (fs8.existsSync(localBin)) return localBin;
2224
2224
  if (sourceExt.includes(path3.extname(baseName))) return void 0;
2225
2225
  const foundExt = sourceExt.find(
2226
- (ext) => fs7.existsSync(`${localBin}${ext}`)
2226
+ (ext) => fs8.existsSync(`${localBin}${ext}`)
2227
2227
  );
2228
2228
  if (foundExt) return `${localBin}${foundExt}`;
2229
2229
  return void 0;
@@ -2235,7 +2235,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2235
2235
  if (this._scriptPath) {
2236
2236
  let resolvedScriptPath;
2237
2237
  try {
2238
- resolvedScriptPath = fs7.realpathSync(this._scriptPath);
2238
+ resolvedScriptPath = fs8.realpathSync(this._scriptPath);
2239
2239
  } catch {
2240
2240
  resolvedScriptPath = this._scriptPath;
2241
2241
  }
@@ -13443,7 +13443,7 @@ var require_form_data = __commonJS({
13443
13443
  var http3 = __require("http");
13444
13444
  var https3 = __require("https");
13445
13445
  var parseUrl2 = __require("url").parse;
13446
- var fs7 = __require("fs");
13446
+ var fs8 = __require("fs");
13447
13447
  var Stream = __require("stream").Stream;
13448
13448
  var crypto2 = __require("crypto");
13449
13449
  var mime = require_mime_types();
@@ -13513,7 +13513,7 @@ var require_form_data = __commonJS({
13513
13513
  if (value.end != void 0 && value.end != Infinity && value.start != void 0) {
13514
13514
  callback(null, value.end + 1 - (value.start ? value.start : 0));
13515
13515
  } else {
13516
- fs7.stat(value.path, function(err, stat) {
13516
+ fs8.stat(value.path, function(err, stat) {
13517
13517
  if (err) {
13518
13518
  callback(err);
13519
13519
  return;
@@ -16041,7 +16041,7 @@ var require_permessage_deflate = __commonJS({
16041
16041
  var require_validation = __commonJS({
16042
16042
  "node_modules/ws/lib/validation.js"(exports, module) {
16043
16043
  "use strict";
16044
- var { isUtf8 } = __require("buffer");
16044
+ var { isUtf8: isUtf82 } = __require("buffer");
16045
16045
  var { hasBlob } = require_constants();
16046
16046
  var tokenChars = [
16047
16047
  0,
@@ -16222,9 +16222,9 @@ var require_validation = __commonJS({
16222
16222
  isValidUTF8: _isValidUTF8,
16223
16223
  tokenChars
16224
16224
  };
16225
- if (isUtf8) {
16225
+ if (isUtf82) {
16226
16226
  module.exports.isValidUTF8 = function(buf) {
16227
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
16227
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf82(buf);
16228
16228
  };
16229
16229
  } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
16230
16230
  try {
@@ -23240,6 +23240,24 @@ var coerce = {
23240
23240
  var NEVER = INVALID;
23241
23241
 
23242
23242
  // src/core/config.ts
23243
+ var RETIRED_SERVICE_URL_VARS = [
23244
+ "TERMIX_METRICS_URL",
23245
+ "TERMIX_DOCKER_URL",
23246
+ "TERMIX_FILES_URL",
23247
+ "TERMIX_TUNNEL_URL",
23248
+ "TERMIX_TERMINAL_URL"
23249
+ ];
23250
+ var warnedRetiredVars = false;
23251
+ function warnRetiredServiceUrls(env) {
23252
+ if (warnedRetiredVars) return;
23253
+ const set = RETIRED_SERVICE_URL_VARS.filter((name) => env[name]?.trim());
23254
+ if (set.length === 0) return;
23255
+ warnedRetiredVars = true;
23256
+ process.stderr.write(
23257
+ `termix: ignoring ${set.join(", ")}: Termix 2.9 and later serve everything at TERMIX_URL
23258
+ `
23259
+ );
23260
+ }
23243
23261
  var storedConfigSchema = external_exports.object({
23244
23262
  url: external_exports.string().url(),
23245
23263
  token: external_exports.string().optional(),
@@ -23324,6 +23342,7 @@ function deleteStoredConfig(env = process.env) {
23324
23342
  }
23325
23343
  function resolveConfig(env = process.env, opts = {}) {
23326
23344
  const stored = loadStoredConfig(env);
23345
+ warnRetiredServiceUrls(env);
23327
23346
  const url2 = opts.url || env.TERMIX_URL || stored?.url;
23328
23347
  if (!url2) {
23329
23348
  throw new Error(
@@ -23345,14 +23364,7 @@ function resolveConfig(env = process.env, opts = {}) {
23345
23364
  apiKey,
23346
23365
  username: stored?.username,
23347
23366
  insecureTls: env.TERMIX_INSECURE_TLS === "true",
23348
- requestTimeoutMs: timeoutMs,
23349
- serviceUrls: {
23350
- metrics: normaliseOptionalUrl(env.TERMIX_METRICS_URL),
23351
- docker: normaliseOptionalUrl(env.TERMIX_DOCKER_URL),
23352
- files: normaliseOptionalUrl(env.TERMIX_FILES_URL),
23353
- tunnel: normaliseOptionalUrl(env.TERMIX_TUNNEL_URL),
23354
- terminal: normaliseOptionalUrl(env.TERMIX_TERMINAL_URL)
23355
- }
23367
+ requestTimeoutMs: timeoutMs
23356
23368
  };
23357
23369
  }
23358
23370
  function normaliseUrl(value) {
@@ -23364,10 +23376,6 @@ function normaliseUrl(value) {
23364
23376
  }
23365
23377
  return trimmed;
23366
23378
  }
23367
- function normaliseOptionalUrl(value) {
23368
- const trimmed = value?.trim();
23369
- return trimmed ? normaliseUrl(trimmed) : void 0;
23370
- }
23371
23379
 
23372
23380
  // src/core/credentials-store.ts
23373
23381
  var SERVICE = "termix-cli";
@@ -23452,9 +23460,9 @@ var hasOwnInPrototypeChain = (thing, prop) => {
23452
23460
  return false;
23453
23461
  };
23454
23462
  var getSafeProp = (obj, prop) => obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : void 0;
23455
- var kindOf = /* @__PURE__ */ ((cache) => (thing) => {
23463
+ var kindOf = /* @__PURE__ */ ((cache2) => (thing) => {
23456
23464
  const str = toString.call(thing);
23457
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
23465
+ return cache2[str] || (cache2[str] = str.slice(8, -1).toLowerCase());
23458
23466
  })(/* @__PURE__ */ Object.create(null));
23459
23467
  var kindOfTest = (type) => {
23460
23468
  type = type.toLowerCase();
@@ -26146,8 +26154,8 @@ function getProxyEnvAgent(options2, configHttpAgent, configHttpsAgent) {
26146
26154
  }
26147
26155
  function getTunnelingAgent(agentOptions, userHttpsAgent) {
26148
26156
  const key = agentOptions.protocol + "//" + agentOptions.hostname + ":" + (agentOptions.port || "") + "#" + (agentOptions.auth || "");
26149
- const cache = userHttpsAgent ? tunnelingAgentCacheUser.get(userHttpsAgent) || tunnelingAgentCacheUser.set(userHttpsAgent, /* @__PURE__ */ new Map()).get(userHttpsAgent) : tunnelingAgentCache;
26150
- let agent = cache.get(key);
26157
+ const cache2 = userHttpsAgent ? tunnelingAgentCacheUser.get(userHttpsAgent) || tunnelingAgentCacheUser.set(userHttpsAgent, /* @__PURE__ */ new Map()).get(userHttpsAgent) : tunnelingAgentCache;
26158
+ let agent = cache2.get(key);
26151
26159
  if (agent) return agent;
26152
26160
  const merged = userHttpsAgent && userHttpsAgent.options ? { ...userHttpsAgent.options, ...agentOptions } : agentOptions;
26153
26161
  agent = new import_https_proxy_agent.default(merged);
@@ -26159,7 +26167,7 @@ function getTunnelingAgent(agentOptions, userHttpsAgent) {
26159
26167
  };
26160
26168
  }
26161
26169
  agent[kAxiosInstalledTunnel] = true;
26162
- cache.set(key, agent);
26170
+ cache2.set(key, agent);
26163
26171
  return agent;
26164
26172
  }
26165
26173
  var supportedProtocols = platform_default.protocols.map((protocol) => {
@@ -28684,6 +28692,7 @@ var ExitCode = {
28684
28692
  NOT_FOUND: 5,
28685
28693
  UNREACHABLE: 6,
28686
28694
  DATA_LOCKED: 7,
28695
+ FEATURE_UNAVAILABLE: 8,
28687
28696
  INTERNAL: 255
28688
28697
  };
28689
28698
  var TermixApiError = class extends Error {
@@ -28728,6 +28737,19 @@ var TermixConnectionError = class extends Error {
28728
28737
  return ExitCode.UNREACHABLE;
28729
28738
  }
28730
28739
  };
28740
+ var FeatureUnavailableError = class extends Error {
28741
+ constructor(message, pluginId, reason) {
28742
+ super(message);
28743
+ this.pluginId = pluginId;
28744
+ this.reason = reason;
28745
+ this.name = "FeatureUnavailableError";
28746
+ }
28747
+ pluginId;
28748
+ reason;
28749
+ get exitCode() {
28750
+ return ExitCode.FEATURE_UNAVAILABLE;
28751
+ }
28752
+ };
28731
28753
  var UsageError = class extends Error {
28732
28754
  constructor(message) {
28733
28755
  super(message);
@@ -28738,6 +28760,9 @@ var UsageError = class extends Error {
28738
28760
  }
28739
28761
  };
28740
28762
  function remediationFor(error) {
28763
+ if (error instanceof FeatureUnavailableError) {
28764
+ return error.reason === "missing" ? "An admin can install it in Settings > Plugins. Run `termix plugins` to see what this server has." : "An admin can turn it on in Settings > Plugins. Run `termix plugins` to see what this server has.";
28765
+ }
28741
28766
  if (!(error instanceof TermixApiError)) return void 0;
28742
28767
  switch (error.code) {
28743
28768
  case "TOTP_REQUIRED":
@@ -28764,7 +28789,7 @@ function remediationFor(error) {
28764
28789
  return void 0;
28765
28790
  }
28766
28791
  function exitCodeFor(error) {
28767
- if (error instanceof TermixApiError || error instanceof TermixConnectionError || error instanceof UsageError) {
28792
+ if (error instanceof TermixApiError || error instanceof TermixConnectionError || error instanceof FeatureUnavailableError || error instanceof UsageError) {
28768
28793
  return error.exitCode;
28769
28794
  }
28770
28795
  return ExitCode.FAILURE;
@@ -28776,26 +28801,108 @@ function messageFor(error) {
28776
28801
  return error instanceof Error ? error.message : String(error);
28777
28802
  }
28778
28803
 
28779
- // src/core/services.ts
28780
- function resolveServiceUrl(config, service) {
28781
- if (service === "api") return config.url;
28782
- return config.serviceUrls?.[service] ?? config.url;
28804
+ // src/api/features.ts
28805
+ var FEATURES = {
28806
+ terminal: {
28807
+ pluginId: "ssh-terminal",
28808
+ label: "The SSH terminal",
28809
+ commands: ["ssh"]
28810
+ },
28811
+ files: {
28812
+ pluginId: "file-manager",
28813
+ label: "The file manager",
28814
+ commands: ["files"]
28815
+ },
28816
+ docker: { pluginId: "docker", label: "Docker", commands: ["docker"] },
28817
+ tunnels: { pluginId: "tunnels", label: "Tunnels", commands: ["tunnel"] },
28818
+ fleets: { pluginId: "fleets", label: "Fleets", commands: ["fleets"] },
28819
+ snippets: {
28820
+ pluginId: "snippets",
28821
+ label: "Snippets",
28822
+ commands: ["snippets", "exec"]
28823
+ },
28824
+ alerts: { pluginId: "alerts", label: "Alerts", commands: ["alerts"] }
28825
+ };
28826
+ function commandsForPlugin(pluginId) {
28827
+ return Object.values(FEATURES).filter((feature) => feature.pluginId === pluginId).flatMap((feature) => [...feature.commands]);
28783
28828
  }
28784
- function resolveWebSocketUrl(config, path3) {
28785
- const base = resolveServiceUrl(config, "terminal");
28786
- const url2 = new URL(base);
28787
- url2.protocol = url2.protocol === "https:" ? "wss:" : "ws:";
28788
- url2.pathname = joinPath(url2.pathname, path3);
28789
- return url2.toString();
28829
+ function pluginPath(feature, sub = "") {
28830
+ const tail = !sub || sub.startsWith("/") ? sub : `/${sub}`;
28831
+ return `/plugin-api/${FEATURES[feature].pluginId}${tail}`;
28790
28832
  }
28791
- function joinPath(base, path3) {
28792
- const left = base.replace(/\/+$/, "");
28793
- const right = path3.replace(/^\/+/, "");
28794
- return `${left}/${right}`;
28833
+
28834
+ // src/core/plugins.ts
28835
+ var OLD_SERVER = "This server runs a Termix version older than 2.9, which this CLI no longer supports. Use @termix-ssh/cli 1.0.x with it, or upgrade Termix.";
28836
+ var cache = /* @__PURE__ */ new WeakMap();
28837
+ function getServerPlugins(client) {
28838
+ let pending = cache.get(client);
28839
+ if (!pending) {
28840
+ pending = fetchPlugins(client);
28841
+ cache.set(client, pending);
28842
+ pending.catch(() => cache.delete(client));
28843
+ }
28844
+ return pending;
28845
+ }
28846
+ async function fetchPlugins(client) {
28847
+ let data;
28848
+ try {
28849
+ data = await client.request({ method: "GET", path: "/plugins" });
28850
+ } catch (error) {
28851
+ if (error instanceof TermixApiError && error.status === 404) {
28852
+ throw new Error(OLD_SERVER);
28853
+ }
28854
+ throw error;
28855
+ }
28856
+ if (!Array.isArray(data)) throw new Error(OLD_SERVER);
28857
+ return data.filter(
28858
+ (entry) => !!entry && typeof entry.id === "string"
28859
+ );
28860
+ }
28861
+ function isPluginActive(plugin) {
28862
+ if (plugin.state) return plugin.state === "active";
28863
+ return plugin.enabled === true;
28864
+ }
28865
+ async function requireFeature(client, feature) {
28866
+ const { pluginId } = FEATURES[feature];
28867
+ const plugin = (await getServerPlugins(client)).find(
28868
+ (p) => p.id === pluginId
28869
+ );
28870
+ if (!plugin) throw featureMissing(feature);
28871
+ if (!isPluginActive(plugin)) throw featureDisabled(feature);
28872
+ }
28873
+ function featureMissing(feature) {
28874
+ const { label, pluginId } = FEATURES[feature];
28875
+ return new FeatureUnavailableError(
28876
+ `${label} is not installed on this server (plugin "${pluginId}").`,
28877
+ pluginId,
28878
+ "missing"
28879
+ );
28880
+ }
28881
+ function featureDisabled(feature) {
28882
+ const { label, pluginId } = FEATURES[feature];
28883
+ return new FeatureUnavailableError(
28884
+ `${label} is turned off on this server (plugin "${pluginId}").`,
28885
+ pluginId,
28886
+ "disabled"
28887
+ );
28888
+ }
28889
+ function unavailableFor(pluginId, reason) {
28890
+ const entry = Object.entries(FEATURES).find(
28891
+ ([, value]) => value.pluginId === pluginId
28892
+ );
28893
+ if (entry) {
28894
+ const feature = entry[0];
28895
+ return reason === "missing" ? featureMissing(feature) : featureDisabled(feature);
28896
+ }
28897
+ return new FeatureUnavailableError(
28898
+ reason === "missing" ? `The "${pluginId}" plugin is not installed on this server.` : `The "${pluginId}" plugin is turned off on this server.`,
28899
+ pluginId,
28900
+ reason
28901
+ );
28795
28902
  }
28796
28903
 
28797
28904
  // src/version.ts
28798
- var CLI_VERSION = true ? "1.0.2" : "0.0.0-dev";
28905
+ var CLI_VERSION = true ? "1.1.0" : "0.0.0-dev";
28799
28906
 
28800
28907
  // src/core/http.ts
28801
28908
  var MAX_ATTEMPTS = 3;
@@ -28816,24 +28923,20 @@ var TermixClient = class {
28816
28923
  }
28817
28924
  }
28818
28925
  config;
28819
- instances = /* @__PURE__ */ new Map();
28820
- clientFor(service) {
28821
- const baseURL = resolveServiceUrl(this.config, service);
28822
- const existing = this.instances.get(baseURL);
28823
- if (existing) return existing;
28824
- const instance = axios_default.create({
28825
- baseURL,
28926
+ instance;
28927
+ axios() {
28928
+ if (this.instance) return this.instance;
28929
+ this.instance = axios_default.create({
28930
+ baseURL: this.config.url,
28826
28931
  timeout: this.config.requestTimeoutMs,
28827
28932
  httpsAgent: this.config.insecureTls ? new https2.Agent({ rejectUnauthorized: false }) : void 0,
28828
28933
  maxRedirects: 0,
28829
28934
  // We handle non-2xx ourselves for uniform error mapping.
28830
28935
  validateStatus: () => true
28831
28936
  });
28832
- this.instances.set(baseURL, instance);
28833
- return instance;
28937
+ return this.instance;
28834
28938
  }
28835
28939
  async request(opts) {
28836
- const service = opts.service ?? "api";
28837
28940
  const method = String(opts.method).toUpperCase();
28838
28941
  const retryable = opts.retry ?? IDEMPOTENT.has(method);
28839
28942
  const headers = {
@@ -28847,7 +28950,7 @@ var TermixClient = class {
28847
28950
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
28848
28951
  let res;
28849
28952
  try {
28850
- res = await this.clientFor(service).request({
28953
+ res = await this.axios().request({
28851
28954
  method: opts.method,
28852
28955
  url: opts.path,
28853
28956
  params: opts.params,
@@ -28858,7 +28961,7 @@ var TermixClient = class {
28858
28961
  } catch (error) {
28859
28962
  lastError = new TermixConnectionError(
28860
28963
  connectionMessage(error),
28861
- resolveServiceUrl(this.config, service)
28964
+ this.config.url
28862
28965
  );
28863
28966
  if (retryable && attempt < MAX_ATTEMPTS) {
28864
28967
  await sleep(backoffMs(attempt));
@@ -28867,6 +28970,13 @@ var TermixClient = class {
28867
28970
  throw lastError;
28868
28971
  }
28869
28972
  if (res.status >= 200 && res.status < 300) {
28973
+ if (isUnexpectedHtml(res.headers, opts.responseType)) {
28974
+ throw new TermixApiError(
28975
+ "The server answered with a web page instead of the API. This route does not exist on this Termix version.",
28976
+ 404,
28977
+ opts.path
28978
+ );
28979
+ }
28870
28980
  return res.data;
28871
28981
  }
28872
28982
  if (retryable && RETRYABLE_STATUS.has(res.status) && attempt < MAX_ATTEMPTS) {
@@ -28875,7 +28985,7 @@ var TermixClient = class {
28875
28985
  );
28876
28986
  continue;
28877
28987
  }
28878
- throw toApiError(res.status, res.data, opts.path, service);
28988
+ throw toApiError(res.status, res.data, opts.path);
28879
28989
  }
28880
28990
  throw lastError ?? new Error("Request failed");
28881
28991
  }
@@ -28892,13 +29002,26 @@ function retryAfterMs(header) {
28892
29002
  if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
28893
29003
  return void 0;
28894
29004
  }
28895
- function toApiError(status, data, path3, service) {
28896
- const { error, code } = extractError(data);
28897
- let message = error ?? `HTTP ${status}`;
28898
- if (status === 404 && service !== "api") {
28899
- message += ` - "${path3}" is served by the ${service} service, which is not reachable at this URL. Point TERMIX_${service.toUpperCase()}_URL at it, or use the address your reverse proxy serves.`;
29005
+ function isUnexpectedHtml(headers, responseType) {
29006
+ if (responseType && responseType !== "json") return false;
29007
+ const type = headers?.["content-type"];
29008
+ return typeof type === "string" && type.includes("text/html");
29009
+ }
29010
+ var PLUGIN_PATH = /^\/plugin-api\/([^/?#]+)/;
29011
+ var NOT_AVAILABLE = "This feature is not available";
29012
+ function toApiError(status, data, path3) {
29013
+ const pluginId = PLUGIN_PATH.exec(path3)?.[1];
29014
+ if (pluginId && data && typeof data === "object") {
29015
+ const body = data;
29016
+ if (status === 503 && body.pluginId === pluginId) {
29017
+ return unavailableFor(pluginId, "disabled");
29018
+ }
29019
+ if (status === 404 && body.error === NOT_AVAILABLE && !body.pluginId) {
29020
+ return unavailableFor(pluginId, "missing");
29021
+ }
28900
29022
  }
28901
- return new TermixApiError(message, status, path3, code);
29023
+ const { error, code } = extractError(data);
29024
+ return new TermixApiError(error ?? `HTTP ${status}`, status, path3, code);
28902
29025
  }
28903
29026
  function extractError(data) {
28904
29027
  if (!data || typeof data !== "object") return {};
@@ -29146,7 +29269,12 @@ async function createContext(command) {
29146
29269
  config.token = session.token;
29147
29270
  }
29148
29271
  }
29149
- return { config, client: new TermixClient(config) };
29272
+ const client = new TermixClient(config);
29273
+ return {
29274
+ config,
29275
+ client,
29276
+ requireFeature: (feature) => requireFeature(client, feature)
29277
+ };
29150
29278
  }
29151
29279
 
29152
29280
  // src/core/prompt.ts
@@ -29196,6 +29324,10 @@ async function readSecretFromStdin() {
29196
29324
  }
29197
29325
  return value;
29198
29326
  }
29327
+ async function confirm(question) {
29328
+ const answer = await prompt(`${question} [y/N] `);
29329
+ return /^y(es)?$/i.test(answer);
29330
+ }
29199
29331
  function requireTty(question) {
29200
29332
  if (process.stdin.isTTY) return;
29201
29333
  throw new UsageError(
@@ -29208,8 +29340,7 @@ function bareClient(url2, insecure) {
29208
29340
  const config = {
29209
29341
  url: url2.replace(/\/+$/, ""),
29210
29342
  insecureTls: insecure || process.env.TERMIX_INSECURE_TLS === "true",
29211
- requestTimeoutMs: 6e4,
29212
- serviceUrls: {}
29343
+ requestTimeoutMs: 6e4
29213
29344
  };
29214
29345
  return new TermixClient(config);
29215
29346
  }
@@ -29242,6 +29373,13 @@ function registerAuthCommands(program3) {
29242
29373
  noAuth: true
29243
29374
  });
29244
29375
  if (res.requires_totp && res.temp_token) {
29376
+ const factors = res.second_factors ?? [];
29377
+ const hasTotp = factors.length === 0 || factors.some((f) => f.id === "totp");
29378
+ if (!hasTotp) {
29379
+ throw new UsageError(
29380
+ "This account signs in with a second factor the CLI cannot complete, such as a passkey. Create an API key in Termix and pass it with --api-key or TERMIX_API_KEY."
29381
+ );
29382
+ }
29245
29383
  const totpCode = opts.totp || await promptHidden("Two-factor code: ");
29246
29384
  if (!totpCode) {
29247
29385
  throw new UsageError("A two-factor code is required.");
@@ -29252,6 +29390,7 @@ function registerAuthCommands(program3) {
29252
29390
  data: {
29253
29391
  temp_token: res.temp_token,
29254
29392
  totp_code: totpCode,
29393
+ ...factors.length ? { factor: "totp" } : {},
29255
29394
  rememberMe: true
29256
29395
  },
29257
29396
  headers: { "X-Electron-App": "true" },
@@ -29380,6 +29519,39 @@ function buildHostPayload(opts) {
29380
29519
  if (opts.enableTunnel !== void 0) body.enableTunnel = opts.enableTunnel;
29381
29520
  return body;
29382
29521
  }
29522
+ var HOST_TOGGLES = [
29523
+ { flag: "enableTerminal", feature: "terminal" },
29524
+ { flag: "enableFileManager", feature: "files" },
29525
+ { flag: "enableDocker", feature: "docker" },
29526
+ { flag: "enableTunnel", feature: "tunnels" }
29527
+ ];
29528
+ function hostToggleSettings(opts) {
29529
+ return HOST_TOGGLES.filter(({ flag }) => opts[flag] !== void 0).map(
29530
+ ({ flag, feature }) => ({
29531
+ pluginId: FEATURES[feature].pluginId,
29532
+ settings: { [flag]: opts[flag] }
29533
+ })
29534
+ );
29535
+ }
29536
+ async function applyHostToggles(client, hostId, opts) {
29537
+ for (const { pluginId, settings } of hostToggleSettings(opts)) {
29538
+ try {
29539
+ await client.request({
29540
+ method: "PUT",
29541
+ path: `/plugins/${pluginId}/settings/host/${hostId}`,
29542
+ data: settings
29543
+ });
29544
+ } catch (error) {
29545
+ if (error instanceof TermixApiError && error.status === 404) {
29546
+ printWarning(
29547
+ `Skipped ${Object.keys(settings)[0]}: the "${pluginId}" plugin is not installed on this server.`
29548
+ );
29549
+ continue;
29550
+ }
29551
+ throw error;
29552
+ }
29553
+ }
29554
+ }
29383
29555
  function parsePort(value) {
29384
29556
  const port = Number(value);
29385
29557
  if (!Number.isInteger(port) || port <= 0 || port > 65535) {
@@ -29503,6 +29675,7 @@ function registerHostCommands(program3) {
29503
29675
  path: "/host/db/host",
29504
29676
  data: payload
29505
29677
  });
29678
+ await applyHostToggles(client, Number(created.id), opts);
29506
29679
  printResult(`Created host ${created.id}.`, {
29507
29680
  id: created.id,
29508
29681
  name: created.name
@@ -29531,6 +29704,7 @@ function registerHostCommands(program3) {
29531
29704
  path: `/host/db/host/${id}`,
29532
29705
  data: merged
29533
29706
  });
29707
+ await applyHostToggles(client, id, opts);
29534
29708
  const saved = await client.request({
29535
29709
  method: "GET",
29536
29710
  path: `/host/db/host/${id}`
@@ -29690,7 +29864,7 @@ function parseExecOutput(raw) {
29690
29864
  async function executeOnHost(client, hostId, content, name) {
29691
29865
  const created = await client.request({
29692
29866
  method: "POST",
29693
- path: "/snippets",
29867
+ path: pluginPath("snippets"),
29694
29868
  data: {
29695
29869
  name,
29696
29870
  content,
@@ -29701,7 +29875,7 @@ async function executeOnHost(client, hostId, content, name) {
29701
29875
  try {
29702
29876
  await client.request({
29703
29877
  method: "DELETE",
29704
- path: `/snippets/${created.id}`
29878
+ path: pluginPath("snippets", `/${created.id}`)
29705
29879
  });
29706
29880
  } catch {
29707
29881
  process.stderr.write(
@@ -29718,7 +29892,7 @@ async function executeOnHost(client, hostId, content, name) {
29718
29892
  try {
29719
29893
  return await client.request({
29720
29894
  method: "POST",
29721
- path: "/snippets/execute",
29895
+ path: pluginPath("snippets", "/execute"),
29722
29896
  data: { snippetId: created.id, hostId }
29723
29897
  });
29724
29898
  } finally {
@@ -29734,7 +29908,8 @@ function registerExecCommands(program3) {
29734
29908
  try {
29735
29909
  const hostId = parseId(hostIdArg);
29736
29910
  const command = commandParts.join(" ");
29737
- const { client } = await createContext(this);
29911
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
29912
+ await requireFeature2("snippets");
29738
29913
  const result = await executeOnHost(
29739
29914
  client,
29740
29915
  hostId,
@@ -29762,11 +29937,21 @@ var import_websocket = __toESM(require_websocket(), 1);
29762
29937
  var import_websocket_server = __toESM(require_websocket_server(), 1);
29763
29938
  var wrapper_default = import_websocket.default;
29764
29939
 
29940
+ // src/core/services.ts
29941
+ function resolveWebSocketUrl(config, path3) {
29942
+ const url2 = new URL(config.url);
29943
+ url2.protocol = url2.protocol === "https:" ? "wss:" : "ws:";
29944
+ url2.pathname = joinPath(url2.pathname, path3);
29945
+ return url2.toString();
29946
+ }
29947
+ function joinPath(base, path3) {
29948
+ const left = base.replace(/\/+$/, "");
29949
+ const right = path3.replace(/^\/+/, "");
29950
+ return `${left}/${right}`;
29951
+ }
29952
+
29765
29953
  // src/terminal/ws-client.ts
29766
- var TERMINAL_WEBSOCKET_PATHS = [
29767
- "/plugin-ws/ssh-terminal/terminal",
29768
- "/ssh/websocket/"
29769
- ];
29954
+ var TERMINAL_WEBSOCKET_PATH = "/plugin-ws/ssh-terminal/terminal";
29770
29955
  var LOGIN_HINT = "The server rejected the connection. Your session may have expired: run `termix login`.";
29771
29956
  var TerminalSocket = class {
29772
29957
  constructor(config, token) {
@@ -29787,20 +29972,11 @@ var TerminalSocket = class {
29787
29972
  */
29788
29973
  pending = [];
29789
29974
  async open() {
29790
- let unanswered;
29791
- for (const path3 of TERMINAL_WEBSOCKET_PATHS) {
29792
- const url2 = resolveWebSocketUrl(this.config, path3);
29793
- try {
29794
- this.ws = await this.handshake(url2);
29795
- break;
29796
- } catch (caught) {
29797
- const error = caught;
29798
- if (!isWrongPath(error)) throw new Error(handshakeMessage(error, url2));
29799
- unanswered ??= { error, url: url2 };
29800
- }
29801
- }
29802
- if (!this.ws) {
29803
- throw new Error(handshakeMessage(unanswered.error, unanswered.url));
29975
+ const url2 = resolveWebSocketUrl(this.config, TERMINAL_WEBSOCKET_PATH);
29976
+ try {
29977
+ this.ws = await this.handshake(url2);
29978
+ } catch (caught) {
29979
+ throw handshakeError(caught, url2);
29804
29980
  }
29805
29981
  this.pingTimer = setInterval(() => this.send("ping"), 3e4);
29806
29982
  this.pingTimer.unref();
@@ -29841,8 +30017,14 @@ var TerminalSocket = class {
29841
30017
  }
29842
30018
  return () => this.handlers.delete(handler);
29843
30019
  }
29844
- /** Wait for one of `types`, rejecting on `error` or an early close. */
30020
+ /**
30021
+ * Wait for one of `types`, rejecting on `error` or an early close. A type
30022
+ * starting with `*` matches by suffix, e.g. `*_auth_required`.
30023
+ */
29845
30024
  waitFor(types, timeoutMs = 6e4) {
30025
+ const matches = (type) => types.some(
30026
+ (wanted) => wanted.startsWith("*") ? type.endsWith(wanted.slice(1)) : wanted === type
30027
+ );
29846
30028
  return new Promise((resolve, reject) => {
29847
30029
  const state = { settled: false };
29848
30030
  const cleanup = () => {
@@ -29858,7 +30040,7 @@ var TerminalSocket = class {
29858
30040
  };
29859
30041
  state.unsubscribe = this.onMessage((message) => {
29860
30042
  if (state.settled) return;
29861
- if (types.includes(message.type)) {
30043
+ if (matches(message.type)) {
29862
30044
  cleanup();
29863
30045
  resolve(message);
29864
30046
  } else if (message.type === "error") {
@@ -29927,22 +30109,15 @@ function parseMessage(raw) {
29927
30109
  return null;
29928
30110
  }
29929
30111
  }
29930
- function isWrongPath(error) {
29931
- const match = /Unexpected server response: (\d{3})/.exec(error.message);
29932
- return match !== null && match[1] !== "401" && match[1] !== "403";
29933
- }
29934
- function handshakeMessage(error, url2) {
29935
- const text = error.message;
29936
- if (text.includes("401") || text.includes("403")) {
29937
- return LOGIN_HINT;
29938
- }
29939
- if (text.includes("ECONNREFUSED")) {
29940
- return `Could not reach the terminal service at ${url2}. If you are connecting straight to a backend older than Termix 2.9 rather than through a proxy, set TERMIX_TERMINAL_URL.`;
29941
- }
29942
- if (text.includes("404")) {
29943
- return `The terminal endpoint was not found at ${url2}. If you are connecting straight to a backend older than Termix 2.9, set TERMIX_TERMINAL_URL (default port 30002).`;
29944
- }
29945
- return `Could not open the terminal connection: ${text}`;
30112
+ function handshakeError(error, url2) {
30113
+ const status = /Unexpected server response: (\d{3})/.exec(error.message)?.[1];
30114
+ if (status === "401" || status === "403") return new Error(LOGIN_HINT);
30115
+ if (status === "404") return featureMissing("terminal");
30116
+ if (status === "503") return featureDisabled("terminal");
30117
+ if (error.message.includes("ECONNREFUSED")) {
30118
+ return new Error(`Could not reach the Termix server at ${url2}.`);
30119
+ }
30120
+ return new Error(`Could not open the terminal connection: ${error.message}`);
29946
30121
  }
29947
30122
  function closeMessage(code, reason) {
29948
30123
  if (code === 1008 && reason === "Authentication required") return LOGIN_HINT;
@@ -30011,12 +30186,16 @@ function registerSshCommands(program3) {
30011
30186
  ).option(
30012
30187
  "--command <command>",
30013
30188
  "Run a command instead of an interactive shell"
30014
- ).option("--path <path>", "Directory to start in").option("--tmux <session>", "Attach to a tmux session by name").action(async function(hostIdArg, opts) {
30189
+ ).option("--path <path>", "Directory to start in").option("--tmux <session>", "Attach to a tmux session by name").option(
30190
+ "--trust-host-key",
30191
+ "Trust a host key seen for the first time without asking. A changed key is never trusted this way"
30192
+ ).action(async function(hostIdArg, opts) {
30015
30193
  let tty;
30016
30194
  try {
30017
30195
  const id = parseId(hostIdArg);
30018
- const { config, client } = await createContext(this);
30196
+ const { config, client, requireFeature: requireFeature2 } = await createContext(this);
30019
30197
  const token = requireSessionToken(config, "`termix ssh`");
30198
+ await requireFeature2("terminal");
30020
30199
  const host = await client.request({
30021
30200
  method: "GET",
30022
30201
  path: `/host/db/host/${id}`
@@ -30037,6 +30216,7 @@ function registerSshCommands(program3) {
30037
30216
  command: opts.command,
30038
30217
  path: opts.path,
30039
30218
  tmux: opts.tmux,
30219
+ trustHostKey: opts.trustHostKey === true,
30040
30220
  onTty: (session) => {
30041
30221
  tty = session;
30042
30222
  }
@@ -30048,6 +30228,83 @@ function registerSshCommands(program3) {
30048
30228
  }
30049
30229
  });
30050
30230
  }
30231
+ var READY = ["connected", "sessionAttached"];
30232
+ var AUTH_STEPS = [
30233
+ "host_key_verification_required",
30234
+ "host_key_changed",
30235
+ "passphrase_required",
30236
+ "totp_required",
30237
+ "totp_retry",
30238
+ "password_required",
30239
+ "*_auth_required"
30240
+ ];
30241
+ var MAX_AUTH_ROUNDS = 10;
30242
+ async function decideHostKey(changed, data, hostLabel, trustNew) {
30243
+ if (!changed && trustNew) return true;
30244
+ if (changed) {
30245
+ process.stderr.write(
30246
+ `WARNING: the host key for ${hostLabel} has changed. Someone may be intercepting the connection.
30247
+ Old: ${data.oldKeyType ?? "?"} ${data.oldFingerprint ?? "?"}
30248
+ New: ${data.keyType ?? "?"} ${data.fingerprint ?? "?"}
30249
+ `
30250
+ );
30251
+ } else {
30252
+ process.stderr.write(
30253
+ `The host key for ${hostLabel} has not been seen before.
30254
+ ${data.keyType ?? "?"} ${data.fingerprint ?? "?"}
30255
+ `
30256
+ );
30257
+ }
30258
+ return confirm(changed ? "Trust the new key anyway?" : "Trust this key?");
30259
+ }
30260
+ async function completeAuth(socket, connect, trustHostKey) {
30261
+ const label = `${connect.hostConfig.username}@${connect.hostConfig.ip}:${connect.hostConfig.port}`;
30262
+ for (let round = 0; round < MAX_AUTH_ROUNDS; round++) {
30263
+ const message = await socket.waitFor([...READY, ...AUTH_STEPS]);
30264
+ if (READY.includes(message.type)) return;
30265
+ switch (message.type) {
30266
+ case "host_key_verification_required":
30267
+ case "host_key_changed": {
30268
+ const accept = await decideHostKey(
30269
+ message.type === "host_key_changed",
30270
+ message.data ?? {},
30271
+ label,
30272
+ trustHostKey
30273
+ );
30274
+ socket.send("host_key_verification_response", {
30275
+ action: accept ? "accept" : "reject"
30276
+ });
30277
+ if (!accept)
30278
+ throw new Error(
30279
+ "Host key not trusted, so the connection was closed."
30280
+ );
30281
+ break;
30282
+ }
30283
+ case "passphrase_required": {
30284
+ const keyPassword = await promptHidden("Key passphrase: ");
30285
+ socket.send("reconnect_with_credentials", { ...connect, keyPassword });
30286
+ break;
30287
+ }
30288
+ case "totp_required":
30289
+ case "totp_retry": {
30290
+ const label2 = message.type === "totp_retry" ? "That code did not work. Verification code:" : message.prompt?.trim() || "Verification code:";
30291
+ socket.send("totp_response", { code: await promptHidden(`${label2} `) });
30292
+ break;
30293
+ }
30294
+ case "password_required": {
30295
+ const label2 = message.isPush ? "Approve the sign-in on your device, then press Enter:" : message.prompt?.trim() || "Password:";
30296
+ const code = message.echo || message.isPush ? await prompt(`${label2} `) : await promptHidden(`${label2} `);
30297
+ socket.send("password_response", { code });
30298
+ break;
30299
+ }
30300
+ default:
30301
+ throw new Error(
30302
+ `Host ${connect.hostConfig.id} needs a browser sign-in, which the CLI cannot do. Use the web UI.`
30303
+ );
30304
+ }
30305
+ }
30306
+ throw new Error("The host kept asking for more sign-in steps.");
30307
+ }
30051
30308
  async function runSession(socket, opts) {
30052
30309
  const { cols, rows } = currentSize();
30053
30310
  socket.connectToHost({
@@ -30058,16 +30315,11 @@ async function runSession(socket, opts) {
30058
30315
  executeCommand: opts.command,
30059
30316
  tmuxAttachSession: opts.tmux
30060
30317
  });
30061
- let ready = await socket.waitFor([
30062
- "connected",
30063
- "passphrase_required",
30064
- "sessionAttached"
30065
- ]);
30066
- if (ready.type === "passphrase_required") {
30067
- const passphrase = await promptHidden("Key passphrase: ");
30068
- socket.send("password_response", { password: passphrase });
30069
- ready = await socket.waitFor(["connected", "sessionAttached"]);
30070
- }
30318
+ await completeAuth(
30319
+ socket,
30320
+ { cols, rows, hostConfig: opts.hostConfig },
30321
+ opts.trustHostKey
30322
+ );
30071
30323
  return new Promise((resolve) => {
30072
30324
  let tty;
30073
30325
  let settled = false;
@@ -30125,6 +30377,55 @@ async function runSession(socket, opts) {
30125
30377
  import fs4 from "fs";
30126
30378
  import path2 from "path";
30127
30379
  import { randomUUID as randomUUID2 } from "crypto";
30380
+ import { isUtf8 } from "buffer";
30381
+
30382
+ // src/core/ssh-connect.ts
30383
+ var MAX_ROUNDS = 5;
30384
+ async function openSshSession(opts) {
30385
+ const { client, hostId, sessionId } = opts;
30386
+ const connect = (extra = {}) => client.request({
30387
+ method: "POST",
30388
+ path: opts.connectPath,
30389
+ data: { ...opts.body, ...extra }
30390
+ });
30391
+ let reply = await connect();
30392
+ let askedPassphrase = false;
30393
+ for (let round = 0; round < MAX_ROUNDS; round++) {
30394
+ if (!reply || typeof reply !== "object") return;
30395
+ if (reply.requires_totp || reply.requiresTOTP) {
30396
+ const label = reply.prompt?.trim() || (reply.isPassword ? "Password:" : "Verification code:");
30397
+ const code = await promptHidden(`${label} `);
30398
+ reply = await client.request({
30399
+ method: "POST",
30400
+ path: opts.totpPath,
30401
+ data: { sessionId, totpCode: code }
30402
+ });
30403
+ continue;
30404
+ }
30405
+ if (reply.requires_browser_sign_in) {
30406
+ throw new Error(
30407
+ `Host ${hostId} needs a browser sign-in, which the CLI cannot do. Use the web UI.`
30408
+ );
30409
+ }
30410
+ if (reply.status === "passphrase_required") {
30411
+ if (askedPassphrase)
30412
+ throw new Error("The key passphrase was not accepted.");
30413
+ askedPassphrase = true;
30414
+ const passphrase = await promptHidden("Key passphrase: ");
30415
+ reply = await connect({ [opts.passphraseField]: passphrase });
30416
+ continue;
30417
+ }
30418
+ if (reply.status === "auth_required") {
30419
+ throw new Error(
30420
+ `Host ${hostId} has no saved login the server can use. Add a password, key or credential to the host.`
30421
+ );
30422
+ }
30423
+ return;
30424
+ }
30425
+ throw new Error(`Host ${hostId} kept asking for more sign-in steps.`);
30426
+ }
30427
+
30428
+ // src/commands/files.ts
30128
30429
  var FILE_COLUMNS = [
30129
30430
  { header: "name", value: (f) => f.name },
30130
30431
  { header: "type", value: (f) => f.type },
@@ -30132,6 +30433,16 @@ var FILE_COLUMNS = [
30132
30433
  { header: "modified", value: (f) => f.modified },
30133
30434
  { header: "permissions", value: (f) => f.permissions }
30134
30435
  ];
30436
+ function encodeUpload(data) {
30437
+ if (isUtf8(data) && !data.includes(0))
30438
+ return { content: data.toString("utf8") };
30439
+ return { content: data.toString("base64"), encoding: "base64" };
30440
+ }
30441
+ function decodeDownload(data) {
30442
+ if (typeof data === "string") return Buffer.from(data, "utf8");
30443
+ const content = data?.content ?? "";
30444
+ return data?.encoding === "base64" ? Buffer.from(content, "base64") : Buffer.from(content, "utf8");
30445
+ }
30135
30446
  var SftpSession = class _SftpSession {
30136
30447
  constructor(client, sessionId) {
30137
30448
  this.client = client;
@@ -30150,11 +30461,14 @@ var SftpSession = class _SftpSession {
30150
30461
  );
30151
30462
  }
30152
30463
  const sessionId = `cli-${randomUUID2()}`;
30153
- const result = await client.request({
30154
- method: "POST",
30155
- path: "/ssh/file_manager/ssh/connect",
30156
- service: "files",
30157
- data: {
30464
+ await openSshSession({
30465
+ client,
30466
+ hostId,
30467
+ sessionId,
30468
+ connectPath: pluginPath("files", "/connect"),
30469
+ totpPath: pluginPath("files", "/connect-totp"),
30470
+ passphraseField: "keyPassword",
30471
+ body: {
30158
30472
  sessionId,
30159
30473
  hostId,
30160
30474
  ip: host.ip,
@@ -30164,18 +30478,12 @@ var SftpSession = class _SftpSession {
30164
30478
  credentialId: host.credentialId
30165
30479
  }
30166
30480
  });
30167
- if (result?.requiresTOTP) {
30168
- throw new UsageError(
30169
- "This host needs two-factor confirmation, which the file commands cannot prompt for. Use the web UI or `termix ssh`."
30170
- );
30171
- }
30172
30481
  return new _SftpSession(client, sessionId);
30173
30482
  }
30174
30483
  async list(remotePath) {
30175
30484
  const data = await this.client.request({
30176
30485
  method: "GET",
30177
- path: "/ssh/file_manager/ssh/listFiles",
30178
- service: "files",
30486
+ path: pluginPath("files", "/listFiles"),
30179
30487
  params: { sessionId: this.sessionId, path: remotePath }
30180
30488
  });
30181
30489
  if (Array.isArray(data)) return data;
@@ -30184,26 +30492,26 @@ var SftpSession = class _SftpSession {
30184
30492
  async read(remotePath) {
30185
30493
  const data = await this.client.request({
30186
30494
  method: "GET",
30187
- path: "/ssh/file_manager/ssh/readFile",
30188
- service: "files",
30495
+ path: pluginPath("files", "/readFile"),
30189
30496
  params: { sessionId: this.sessionId, path: remotePath }
30190
30497
  });
30191
- if (typeof data === "string") return data;
30192
- return data?.content ?? "";
30498
+ return decodeDownload(data);
30193
30499
  }
30194
- async write(remotePath, content) {
30500
+ async write(remotePath, data) {
30195
30501
  await this.client.request({
30196
30502
  method: "POST",
30197
- path: "/ssh/file_manager/ssh/writeFile",
30198
- service: "files",
30199
- data: { sessionId: this.sessionId, path: remotePath, content }
30503
+ path: pluginPath("files", "/writeFile"),
30504
+ data: {
30505
+ sessionId: this.sessionId,
30506
+ path: remotePath,
30507
+ ...encodeUpload(data)
30508
+ }
30200
30509
  });
30201
30510
  }
30202
30511
  async mkdir(remotePath) {
30203
30512
  await this.client.request({
30204
30513
  method: "POST",
30205
- path: "/ssh/file_manager/ssh/createFolder",
30206
- service: "files",
30514
+ path: pluginPath("files", "/createFolder"),
30207
30515
  data: {
30208
30516
  sessionId: this.sessionId,
30209
30517
  path: path2.posix.dirname(remotePath),
@@ -30211,24 +30519,32 @@ var SftpSession = class _SftpSession {
30211
30519
  }
30212
30520
  });
30213
30521
  }
30214
- async remove(remotePath, isDirectory) {
30215
- await this.client.request({
30216
- method: "DELETE",
30217
- path: "/ssh/file_manager/ssh/deleteItem",
30218
- service: "files",
30219
- data: {
30220
- sessionId: this.sessionId,
30221
- path: remotePath,
30222
- isDirectory
30522
+ async remove(remotePath, isDirectory, toTrash) {
30523
+ try {
30524
+ await this.client.request({
30525
+ method: "DELETE",
30526
+ path: pluginPath("files", "/deleteItem"),
30527
+ data: {
30528
+ sessionId: this.sessionId,
30529
+ path: remotePath,
30530
+ isDirectory,
30531
+ permanent: !toTrash
30532
+ }
30533
+ });
30534
+ } catch (error) {
30535
+ if (toTrash && error instanceof TermixApiError && error.status === 409) {
30536
+ throw new Error(
30537
+ `Could not move ${remotePath} to the trash (${error.message}), so it was not deleted. Run without --trash to delete it for good.`
30538
+ );
30223
30539
  }
30224
- });
30540
+ throw error;
30541
+ }
30225
30542
  }
30226
30543
  async close() {
30227
30544
  try {
30228
30545
  await this.client.request({
30229
30546
  method: "POST",
30230
- path: "/ssh/file_manager/ssh/disconnect",
30231
- service: "files",
30547
+ path: pluginPath("files", "/disconnect"),
30232
30548
  data: { sessionId: this.sessionId }
30233
30549
  });
30234
30550
  } catch {
@@ -30271,7 +30587,8 @@ function registerFileCommands(program3) {
30271
30587
  files.command("ls <remote>").description("List a remote directory, given as HOST_ID:/path.").action(async function(remote) {
30272
30588
  await run(async () => {
30273
30589
  const { hostId, path: remotePath } = parseRemote(remote);
30274
- const { client } = await createContext(this);
30590
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30591
+ await requireFeature2("files");
30275
30592
  const entries = await withSession(
30276
30593
  client,
30277
30594
  hostId,
@@ -30283,7 +30600,8 @@ function registerFileCommands(program3) {
30283
30600
  files.command("cat <remote>").description("Print a remote file, given as HOST_ID:/path.").action(async function(remote) {
30284
30601
  await run(async () => {
30285
30602
  const { hostId, path: remotePath } = parseRemote(remote);
30286
- const { client } = await createContext(this);
30603
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30604
+ await requireFeature2("files");
30287
30605
  const content = await withSession(
30288
30606
  client,
30289
30607
  hostId,
@@ -30295,14 +30613,15 @@ function registerFileCommands(program3) {
30295
30613
  files.command("get <remote> [localPath]").description("Download a remote file. Defaults to the basename in the CWD.").action(async function(remote, localPath) {
30296
30614
  await run(async () => {
30297
30615
  const { hostId, path: remotePath } = parseRemote(remote);
30298
- const { client } = await createContext(this);
30616
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30617
+ await requireFeature2("files");
30299
30618
  const content = await withSession(
30300
30619
  client,
30301
30620
  hostId,
30302
30621
  (session) => session.read(remotePath)
30303
30622
  );
30304
30623
  const target = resolveLocalTarget(localPath, remotePath);
30305
- fs4.writeFileSync(target, content, "utf8");
30624
+ fs4.writeFileSync(target, content);
30306
30625
  printResult(`Downloaded ${remotePath} to ${target}.`, { path: target });
30307
30626
  });
30308
30627
  });
@@ -30311,11 +30630,12 @@ function registerFileCommands(program3) {
30311
30630
  const { hostId, path: remotePath } = parseRemote(remote);
30312
30631
  let content;
30313
30632
  try {
30314
- content = fs4.readFileSync(localPath, "utf8");
30633
+ content = fs4.readFileSync(localPath);
30315
30634
  } catch {
30316
30635
  throw new UsageError(`Could not read local file: ${localPath}`);
30317
30636
  }
30318
- const { client } = await createContext(this);
30637
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30638
+ await requireFeature2("files");
30319
30639
  await withSession(
30320
30640
  client,
30321
30641
  hostId,
@@ -30329,7 +30649,8 @@ function registerFileCommands(program3) {
30329
30649
  files.command("mkdir <remote>").description("Create a remote directory.").action(async function(remote) {
30330
30650
  await run(async () => {
30331
30651
  const { hostId, path: remotePath } = parseRemote(remote);
30332
- const { client } = await createContext(this);
30652
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30653
+ await requireFeature2("files");
30333
30654
  await withSession(
30334
30655
  client,
30335
30656
  hostId,
@@ -30338,16 +30659,24 @@ function registerFileCommands(program3) {
30338
30659
  printResult(`Created ${remotePath}.`, { path: remotePath });
30339
30660
  });
30340
30661
  });
30341
- files.command("rm <remote>").description("Delete a remote file, or a directory with --recursive.").option("-r, --recursive", "Delete a directory and its contents").action(async function(remote, opts) {
30662
+ files.command("rm <remote>").description("Delete a remote file, or a directory with --recursive.").option("-r, --recursive", "Delete a directory and its contents").option("--trash", "Move it to the server's trash instead of deleting it").action(async function(remote, opts) {
30342
30663
  await run(async () => {
30343
30664
  const { hostId, path: remotePath } = parseRemote(remote);
30344
- const { client } = await createContext(this);
30665
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30666
+ await requireFeature2("files");
30345
30667
  await withSession(
30346
30668
  client,
30347
30669
  hostId,
30348
- (session) => session.remove(remotePath, opts.recursive === true)
30670
+ (session) => session.remove(
30671
+ remotePath,
30672
+ opts.recursive === true,
30673
+ opts.trash === true
30674
+ )
30675
+ );
30676
+ printResult(
30677
+ opts.trash ? `Moved ${remotePath} to the trash.` : `Deleted ${remotePath}.`,
30678
+ { path: remotePath, trashed: opts.trash === true }
30349
30679
  );
30350
- printResult(`Deleted ${remotePath}.`, { path: remotePath });
30351
30680
  });
30352
30681
  });
30353
30682
  }
@@ -30364,6 +30693,7 @@ function resolveLocalTarget(localPath, remotePath) {
30364
30693
  }
30365
30694
 
30366
30695
  // src/commands/tunnel.ts
30696
+ import { setTimeout as sleep2 } from "timers/promises";
30367
30697
  var TUNNEL_COLUMNS = [
30368
30698
  { header: "name", value: (t) => t.displayName ?? t.name },
30369
30699
  { header: "status", value: (t) => t.status },
@@ -30371,18 +30701,35 @@ var TUNNEL_COLUMNS = [
30371
30701
  { header: "endpoint", value: (t) => joinEndpoint(t) },
30372
30702
  { header: "host", value: (t) => t.sourceHostId, align: "right" }
30373
30703
  ];
30374
- function buildTunnelName(hostId, index, displayName, sourcePort, endpointHost, endpointPort) {
30704
+ function buildTunnelName(host, index, connection) {
30705
+ const label = host.name || `${host.username ?? ""}@${host.ip ?? ""}`;
30375
30706
  return [
30376
- hostId,
30707
+ host.id,
30377
30708
  index,
30378
- displayName,
30709
+ label,
30710
+ connection.sourcePort ?? "",
30711
+ endpointHostOf(connection),
30712
+ connection.endpointPort ?? 0
30713
+ ].join("::");
30714
+ }
30715
+ function parseTunnelName(name) {
30716
+ const parts = name.split("::");
30717
+ if (parts.length !== 6) return {};
30718
+ const [hostId, index, label, sourcePort, endpointHost, endpointPort] = parts;
30719
+ return {
30720
+ sourceHostId: Number(hostId),
30721
+ tunnelIndex: Number(index),
30722
+ hostLabel: label,
30379
30723
  sourcePort,
30380
30724
  endpointHost,
30381
30725
  endpointPort
30382
- ].join("::");
30726
+ };
30727
+ }
30728
+ function endpointHostOf(connection) {
30729
+ return (connection.endpointHost ?? connection.endpointIP ?? "").trim();
30383
30730
  }
30384
30731
  function parseConnections(host) {
30385
- const raw = host.tunnelConnections;
30732
+ const raw = host.pluginSettings?.tunnels?.tunnelConnections ?? host.tunnelConnections;
30386
30733
  if (Array.isArray(raw)) return raw;
30387
30734
  if (typeof raw === "string" && raw.trim()) {
30388
30735
  try {
@@ -30394,18 +30741,69 @@ function parseConnections(host) {
30394
30741
  }
30395
30742
  return [];
30396
30743
  }
30744
+ function tunnelMode(connection) {
30745
+ return connection.mode ?? connection.tunnelType ?? "local";
30746
+ }
30747
+ function connectRequestFor(host, index, connection) {
30748
+ const mode = tunnelMode(connection);
30749
+ return {
30750
+ name: buildTunnelName(host, index, connection),
30751
+ sourceHostId: host.id,
30752
+ tunnelIndex: index,
30753
+ scope: connection.scope ?? "s2s",
30754
+ mode,
30755
+ tunnelType: mode === "remote" ? "remote" : "local",
30756
+ bindHost: connection.bindHost,
30757
+ targetHost: connection.targetHost,
30758
+ endpointHost: endpointHostOf(connection),
30759
+ sourcePort: connection.sourcePort,
30760
+ endpointPort: connection.endpointPort ?? 0,
30761
+ maxRetries: connection.maxRetries,
30762
+ retryInterval: connection.retryInterval,
30763
+ autoStart: connection.autoStart
30764
+ };
30765
+ }
30766
+ var SETTLED = /* @__PURE__ */ new Set(["connected", "failed", "disconnected"]);
30767
+ var START_WAIT_MS = 15e3;
30768
+ async function waitForTunnel(client, name) {
30769
+ const deadline = Date.now() + START_WAIT_MS;
30770
+ let last = null;
30771
+ while (Date.now() < deadline) {
30772
+ await sleep2(500);
30773
+ try {
30774
+ const data = await client.request({
30775
+ method: "GET",
30776
+ path: pluginPath("tunnels", `/status/${encodeURIComponent(name)}`)
30777
+ });
30778
+ last = data?.status ?? null;
30779
+ } catch (error) {
30780
+ if (error instanceof TermixApiError && error.status === 404) continue;
30781
+ throw error;
30782
+ }
30783
+ if (last && SETTLED.has(String(last.status))) return last;
30784
+ }
30785
+ return last;
30786
+ }
30787
+ async function loadHost(client, hostId) {
30788
+ const host = await client.request({
30789
+ method: "GET",
30790
+ path: `/host/db/host/${hostId}`
30791
+ });
30792
+ return { ...host, id: hostId };
30793
+ }
30397
30794
  function registerTunnelCommands(program3) {
30398
30795
  const tunnel = program3.command("tunnel").description("Manage SSH tunnels configured on your hosts.");
30399
30796
  tunnel.command("list", { isDefault: true }).description("Show the status of every tunnel.").action(async function() {
30400
30797
  await run(async () => {
30401
- const { client } = await createContext(this);
30798
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30799
+ await requireFeature2("tunnels");
30402
30800
  const data = await client.request({
30403
30801
  method: "GET",
30404
- path: "/ssh/tunnel/status",
30405
- service: "tunnel"
30802
+ path: pluginPath("tunnels", "/status")
30406
30803
  });
30407
30804
  const rows = Object.entries(data ?? {}).map(([name, value]) => ({
30408
30805
  name,
30806
+ ...parseTunnelName(name),
30409
30807
  ...value
30410
30808
  }));
30411
30809
  printList(rows, TUNNEL_COLUMNS, { quietField: "name" });
@@ -30414,23 +30812,22 @@ function registerTunnelCommands(program3) {
30414
30812
  tunnel.command("show <hostId>").description("List the tunnels configured on a host, with their indexes.").action(async function(hostIdArg) {
30415
30813
  await run(async () => {
30416
30814
  const hostId = parseId(hostIdArg);
30417
- const { client } = await createContext(this);
30418
- const host = await client.request({
30419
- method: "GET",
30420
- path: `/host/db/host/${hostId}`
30421
- });
30815
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30816
+ await requireFeature2("tunnels");
30817
+ const host = await loadHost(client, hostId);
30422
30818
  const rows = parseConnections(host).map((connection, index) => ({
30423
30819
  index,
30424
- name: connection.name ?? `tunnel-${index}`,
30820
+ name: buildTunnelName(host, index, connection),
30821
+ mode: tunnelMode(connection),
30425
30822
  sourcePort: connection.sourcePort,
30426
- endpointHost: connection.endpointHost ?? connection.endpointIP,
30823
+ endpointHost: endpointHostOf(connection),
30427
30824
  endpointPort: connection.endpointPort
30428
30825
  }));
30429
30826
  printList(
30430
30827
  rows,
30431
30828
  [
30432
30829
  { header: "index", value: (r) => r.index, align: "right" },
30433
- { header: "name", value: (r) => r.name },
30830
+ { header: "mode", value: (r) => r.mode },
30434
30831
  { header: "source", value: (r) => r.sourcePort, align: "right" },
30435
30832
  { header: "endpoint host", value: (r) => r.endpointHost },
30436
30833
  {
@@ -30454,61 +30851,41 @@ function registerTunnelCommands(program3) {
30454
30851
  `Invalid tunnel index: "${indexArg}" (expected a non-negative integer).`
30455
30852
  );
30456
30853
  }
30457
- const { client } = await createContext(this);
30458
- const host = await client.request({
30459
- method: "GET",
30460
- path: `/host/db/host/${hostId}`
30461
- });
30462
- const connections = parseConnections(host);
30463
- const connection = connections[index];
30854
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30855
+ await requireFeature2("tunnels");
30856
+ const host = await loadHost(client, hostId);
30857
+ const connection = parseConnections(host)[index];
30464
30858
  if (!connection) {
30465
30859
  throw new UsageError(
30466
30860
  `Host ${hostId} has no tunnel at index ${index}. Run \`termix tunnel show ${hostId}\`.`
30467
30861
  );
30468
30862
  }
30469
- if (!host.ip || !host.username) {
30470
- throw new UsageError(
30471
- `Host ${hostId} is missing an address or username.`
30472
- );
30473
- }
30474
- const endpointHost = connection.endpointHost ?? connection.endpointIP ?? "";
30475
- const displayName = connection.name ?? `tunnel-${index}`;
30476
- const name = buildTunnelName(
30477
- hostId,
30478
- index,
30479
- displayName,
30480
- connection.sourcePort ?? "",
30481
- endpointHost,
30482
- connection.endpointPort ?? ""
30483
- );
30863
+ const request = connectRequestFor(host, index, connection);
30864
+ const name = String(request.name);
30484
30865
  await client.request({
30485
30866
  method: "POST",
30486
- path: "/ssh/tunnel/connect",
30487
- service: "tunnel",
30488
- data: {
30489
- ...connection,
30490
- name,
30491
- sourceHostId: hostId,
30492
- tunnelIndex: index,
30493
- hostName: host.name,
30494
- sourceIP: host.ip,
30495
- sourceSSHPort: host.port ?? 22,
30496
- sourceUsername: host.username,
30497
- sourceAuthMethod: host.authType,
30498
- sourceCredentialId: host.credentialId,
30499
- endpointHost
30500
- }
30867
+ path: pluginPath("tunnels", "/connect"),
30868
+ data: request
30501
30869
  });
30502
- printResult(`Started tunnel ${displayName}.`, { name, index });
30870
+ const status = await waitForTunnel(client, name);
30871
+ const state = status?.status ? String(status.status) : "connecting";
30872
+ if (state === "failed") {
30873
+ const reason = status?.reason ? `: ${String(status.reason)}` : ".";
30874
+ throw new Error(`Tunnel ${name} failed to start${reason}`);
30875
+ }
30876
+ printResult(
30877
+ state === "connected" ? `Started tunnel ${name}.` : `Tunnel ${name} is ${state}. Check \`termix tunnel list\`.`,
30878
+ { name, index, status: state }
30879
+ );
30503
30880
  });
30504
30881
  });
30505
30882
  tunnel.command("stop <name>").description("Stop a running tunnel by its full name (see `tunnel list`).").action(async function(name) {
30506
30883
  await run(async () => {
30507
- const { client } = await createContext(this);
30884
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30885
+ await requireFeature2("tunnels");
30508
30886
  await client.request({
30509
30887
  method: "POST",
30510
- path: "/ssh/tunnel/disconnect",
30511
- service: "tunnel",
30888
+ path: pluginPath("tunnels", "/disconnect"),
30512
30889
  data: { tunnelName: name }
30513
30890
  });
30514
30891
  printResult(`Stopped tunnel ${name}.`, { name });
@@ -30533,18 +30910,29 @@ var CONTAINER_COLUMNS = [
30533
30910
  ];
30534
30911
  async function withDockerSession(client, hostId, fn) {
30535
30912
  const sessionId = `cli-${randomUUID3()}`;
30536
- await client.request({
30537
- method: "POST",
30538
- path: "/docker/ssh/connect",
30539
- service: "docker",
30540
- data: { sessionId, hostId }
30541
- });
30913
+ try {
30914
+ await openSshSession({
30915
+ client,
30916
+ hostId,
30917
+ sessionId,
30918
+ connectPath: pluginPath("docker", "/ssh/connect"),
30919
+ totpPath: pluginPath("docker", "/ssh/connect-totp"),
30920
+ passphraseField: "userProvidedKeyPassword",
30921
+ body: { sessionId, hostId }
30922
+ });
30923
+ } catch (error) {
30924
+ if (error instanceof TermixApiError && error.code === "DOCKER_DISABLED") {
30925
+ throw new Error(
30926
+ `Docker is turned off for host ${hostId}. Turn it on in the host's Docker settings.`
30927
+ );
30928
+ }
30929
+ throw error;
30930
+ }
30542
30931
  const disconnect = async () => {
30543
30932
  try {
30544
30933
  await client.request({
30545
30934
  method: "POST",
30546
- path: "/docker/ssh/disconnect",
30547
- service: "docker",
30935
+ path: pluginPath("docker", "/ssh/disconnect"),
30548
30936
  data: { sessionId }
30549
30937
  });
30550
30938
  } catch {
@@ -30568,14 +30956,14 @@ function registerDockerCommands(program3) {
30568
30956
  docker.command("ps <hostId>").description("List containers on a host.").action(async function(hostIdArg) {
30569
30957
  await run(async () => {
30570
30958
  const hostId = parseId(hostIdArg);
30571
- const { client } = await createContext(this);
30959
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30960
+ await requireFeature2("docker");
30572
30961
  const containers = await withDockerSession(
30573
30962
  client,
30574
30963
  hostId,
30575
30964
  (sessionId) => client.request({
30576
30965
  method: "GET",
30577
- path: `/docker/containers/${sessionId}`,
30578
- service: "docker"
30966
+ path: pluginPath("docker", `/containers/${sessionId}`)
30579
30967
  })
30580
30968
  );
30581
30969
  const rows = Array.isArray(containers) ? containers : containers?.containers ?? [];
@@ -30585,14 +30973,17 @@ function registerDockerCommands(program3) {
30585
30973
  docker.command("logs <hostId> <containerId>").description("Print a container's logs.").option("--tail <n>", "Number of lines from the end").action(async function(hostIdArg, containerId, opts) {
30586
30974
  await run(async () => {
30587
30975
  const hostId = parseId(hostIdArg);
30588
- const { client } = await createContext(this);
30976
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
30977
+ await requireFeature2("docker");
30589
30978
  const logs = await withDockerSession(
30590
30979
  client,
30591
30980
  hostId,
30592
30981
  (sessionId) => client.request({
30593
30982
  method: "GET",
30594
- path: `/docker/containers/${sessionId}/${encodeURIComponent(containerId)}/logs`,
30595
- service: "docker",
30983
+ path: pluginPath(
30984
+ "docker",
30985
+ `/containers/${sessionId}/${encodeURIComponent(containerId)}/logs`
30986
+ ),
30596
30987
  params: opts.tail ? { tail: opts.tail } : void 0
30597
30988
  })
30598
30989
  );
@@ -30605,14 +30996,17 @@ function registerDockerCommands(program3) {
30605
30996
  docker.command(`${action} <hostId> <containerId>`).description(`${capitalise(action)} a container.`).action(async function(hostIdArg, containerId) {
30606
30997
  await run(async () => {
30607
30998
  const hostId = parseId(hostIdArg);
30608
- const { client } = await createContext(this);
30999
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31000
+ await requireFeature2("docker");
30609
31001
  await withDockerSession(
30610
31002
  client,
30611
31003
  hostId,
30612
31004
  (sessionId) => client.request({
30613
31005
  method: "POST",
30614
- path: `/docker/containers/${sessionId}/${encodeURIComponent(containerId)}/${action}`,
30615
- service: "docker"
31006
+ path: pluginPath(
31007
+ "docker",
31008
+ `/containers/${sessionId}/${encodeURIComponent(containerId)}/${action}`
31009
+ )
30616
31010
  })
30617
31011
  );
30618
31012
  printResult(`Sent ${action} to ${containerId}.`, {
@@ -30651,10 +31045,11 @@ function registerFleetCommands(program3) {
30651
31045
  const fleets = program3.command("fleets").description("Manage fleets, and run a command across every host in one.");
30652
31046
  fleets.command("list", { isDefault: true }).description("List fleets.").action(async function() {
30653
31047
  await run(async () => {
30654
- const { client } = await createContext(this);
31048
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31049
+ await requireFeature2("fleets");
30655
31050
  const data = await client.request({
30656
31051
  method: "GET",
30657
- path: "/fleets"
31052
+ path: pluginPath("fleets")
30658
31053
  });
30659
31054
  printList(toRows(data, "fleets"), FLEET_COLUMNS);
30660
31055
  });
@@ -30662,20 +31057,22 @@ function registerFleetCommands(program3) {
30662
31057
  fleets.command("members <fleetId>").description("List the hosts in a fleet.").action(async function(fleetId) {
30663
31058
  await run(async () => {
30664
31059
  const id = parseId(fleetId, "fleet id");
30665
- const { client } = await createContext(this);
31060
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31061
+ await requireFeature2("fleets");
30666
31062
  const data = await client.request({
30667
31063
  method: "GET",
30668
- path: `/fleets/${id}/members`
31064
+ path: pluginPath("fleets", `/${id}/members`)
30669
31065
  });
30670
31066
  printList(toRows(data, "members"), MEMBER_COLUMNS);
30671
31067
  });
30672
31068
  });
30673
31069
  fleets.command("create").description("Create a fleet.").requiredOption("--name <name>", "Fleet name").option("--description <text>", "Description").action(async function(opts) {
30674
31070
  await run(async () => {
30675
- const { client } = await createContext(this);
31071
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31072
+ await requireFeature2("fleets");
30676
31073
  const created = await client.request({
30677
31074
  method: "POST",
30678
- path: "/fleets",
31075
+ path: pluginPath("fleets"),
30679
31076
  data: { name: opts.name, description: opts.description }
30680
31077
  });
30681
31078
  printResult(`Created fleet ${created.id}.`, {
@@ -30687,8 +31084,12 @@ function registerFleetCommands(program3) {
30687
31084
  fleets.command("delete <fleetId>").description("Delete a fleet.").action(async function(fleetId) {
30688
31085
  await run(async () => {
30689
31086
  const id = parseId(fleetId, "fleet id");
30690
- const { client } = await createContext(this);
30691
- await client.request({ method: "DELETE", path: `/fleets/${id}` });
31087
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31088
+ await requireFeature2("fleets");
31089
+ await client.request({
31090
+ method: "DELETE",
31091
+ path: pluginPath("fleets", `/${id}`)
31092
+ });
30692
31093
  printResult(`Deleted fleet ${id}.`, { id });
30693
31094
  });
30694
31095
  });
@@ -30696,10 +31097,11 @@ function registerFleetCommands(program3) {
30696
31097
  await run(async () => {
30697
31098
  const fleet = parseId(fleetId, "fleet id");
30698
31099
  const host = parseId(hostId, "host id");
30699
- const { client } = await createContext(this);
31100
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31101
+ await requireFeature2("fleets");
30700
31102
  await client.request({
30701
31103
  method: "POST",
30702
- path: `/fleets/${fleet}/members`,
31104
+ path: pluginPath("fleets", `/${fleet}/members`),
30703
31105
  data: { hostId: host }
30704
31106
  });
30705
31107
  printResult(`Added host ${host} to fleet ${fleet}.`, { id: host });
@@ -30709,10 +31111,11 @@ function registerFleetCommands(program3) {
30709
31111
  await run(async () => {
30710
31112
  const fleet = parseId(fleetId, "fleet id");
30711
31113
  const host = parseId(hostId, "host id");
30712
- const { client } = await createContext(this);
31114
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31115
+ await requireFeature2("fleets");
30713
31116
  await client.request({
30714
31117
  method: "DELETE",
30715
- path: `/fleets/${fleet}/members/${host}`
31118
+ path: pluginPath("fleets", `/${fleet}/members/${host}`)
30716
31119
  });
30717
31120
  printResult(`Removed host ${host} from fleet ${fleet}.`, { id: host });
30718
31121
  });
@@ -30726,10 +31129,11 @@ function registerFleetCommands(program3) {
30726
31129
  if (!command.trim()) {
30727
31130
  throw new UsageError("A command is required.");
30728
31131
  }
30729
- const { client } = await createContext(this);
31132
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31133
+ await requireFeature2("fleets");
30730
31134
  const data = await client.request({
30731
31135
  method: "POST",
30732
- path: `/fleets/${id}/execute`,
31136
+ path: pluginPath("fleets", `/${id}/execute`),
30733
31137
  data: { command }
30734
31138
  });
30735
31139
  const results = data?.results ?? [];
@@ -30843,10 +31247,11 @@ function registerSnippetCommands(program3) {
30843
31247
  const snippets = program3.command("snippets").description("Manage and run the command snippets saved in Termix.");
30844
31248
  snippets.command("list", { isDefault: true }).description("List saved snippets.").action(async function() {
30845
31249
  await run(async () => {
30846
- const { client } = await createContext(this);
31250
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31251
+ await requireFeature2("snippets");
30847
31252
  const all3 = await client.request({
30848
31253
  method: "GET",
30849
- path: "/snippets"
31254
+ path: pluginPath("snippets")
30850
31255
  });
30851
31256
  printList(all3, SNIPPET_COLUMNS, {
30852
31257
  jsonWrapper: (rows) => ({ count: rows.length, snippets: rows })
@@ -30859,10 +31264,11 @@ function registerSnippetCommands(program3) {
30859
31264
  if (!content) {
30860
31265
  throw new UsageError("Provide --content or --content-file.");
30861
31266
  }
30862
- const { client } = await createContext(this);
31267
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31268
+ await requireFeature2("snippets");
30863
31269
  const created = await client.request({
30864
31270
  method: "POST",
30865
- path: "/snippets",
31271
+ path: pluginPath("snippets"),
30866
31272
  data: {
30867
31273
  name: opts.name,
30868
31274
  content,
@@ -30890,10 +31296,11 @@ function registerSnippetCommands(program3) {
30890
31296
  );
30891
31297
  }
30892
31298
  const id = parseId(snippetId);
30893
- const { client } = await createContext(this);
31299
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31300
+ await requireFeature2("snippets");
30894
31301
  await client.request({
30895
31302
  method: "PUT",
30896
- path: `/snippets/${id}`,
31303
+ path: pluginPath("snippets", `/${id}`),
30897
31304
  data: body
30898
31305
  });
30899
31306
  printResult(`Updated snippet ${id}.`, { id });
@@ -30902,8 +31309,12 @@ function registerSnippetCommands(program3) {
30902
31309
  snippets.command("delete <snippetId>").description("Delete a saved snippet.").action(async function(snippetId) {
30903
31310
  await run(async () => {
30904
31311
  const id = parseId(snippetId);
30905
- const { client } = await createContext(this);
30906
- await client.request({ method: "DELETE", path: `/snippets/${id}` });
31312
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31313
+ await requireFeature2("snippets");
31314
+ await client.request({
31315
+ method: "DELETE",
31316
+ path: pluginPath("snippets", `/${id}`)
31317
+ });
30907
31318
  printResult(`Deleted snippet ${id}.`, { id });
30908
31319
  });
30909
31320
  });
@@ -30918,10 +31329,11 @@ function registerSnippetCommands(program3) {
30918
31329
  try {
30919
31330
  const snippetId = parseId(snippetIdArg);
30920
31331
  const hostId = parseId(opts.host, "--host");
30921
- const { client } = await createContext(this);
31332
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31333
+ await requireFeature2("snippets");
30922
31334
  const result = await client.request({
30923
31335
  method: "POST",
30924
- path: "/snippets/execute",
31336
+ path: pluginPath("snippets", "/execute"),
30925
31337
  data: {
30926
31338
  snippetId,
30927
31339
  hostId,
@@ -31117,53 +31529,81 @@ function registerCredentialCommands(program3) {
31117
31529
 
31118
31530
  // src/commands/alerts.ts
31119
31531
  var ALERT_COLUMNS = [
31120
- { header: "id", value: (a) => a.id },
31532
+ { header: "id", value: (a) => a.id, align: "right" },
31121
31533
  { header: "severity", value: (a) => a.severity ?? a.level },
31534
+ { header: "source", value: (a) => a.source },
31122
31535
  { header: "title", value: (a) => a.title ?? a.message },
31123
- { header: "created", value: (a) => a.createdAt }
31536
+ { header: "created", value: (a) => a.createdAt },
31537
+ { header: "read", value: (a) => Boolean(a.readAt) }
31124
31538
  ];
31125
31539
  function toAlertRows(data) {
31126
- const unwrapped = Array.isArray(data) ? data[0] : data;
31127
- if (!unwrapped || typeof unwrapped !== "object") return [];
31128
- const alerts = unwrapped.alerts;
31129
- if (Array.isArray(alerts)) return alerts;
31130
- if (Array.isArray(data) && data.every((d) => d && !("alerts" in d))) {
31131
- return data;
31132
- }
31540
+ if (Array.isArray(data)) return data;
31541
+ if (!data || typeof data !== "object") return [];
31542
+ const record = data;
31543
+ if (Array.isArray(record.items)) return record.items;
31544
+ if (Array.isArray(record.alerts)) return record.alerts;
31133
31545
  return [];
31134
31546
  }
31547
+ function parseAlertId(value) {
31548
+ const id = Number(value);
31549
+ if (!Number.isInteger(id) || id <= 0) {
31550
+ throw new UsageError(
31551
+ `Invalid alert id: "${value}" (expected a positive integer).`
31552
+ );
31553
+ }
31554
+ return id;
31555
+ }
31556
+ function parseLimit(value) {
31557
+ const limit = Number(value);
31558
+ if (!Number.isInteger(limit) || limit <= 0) {
31559
+ throw new UsageError(`Invalid --limit: "${value}".`);
31560
+ }
31561
+ return limit;
31562
+ }
31135
31563
  function registerAlertCommands(program3) {
31136
31564
  const alerts = program3.command("alerts").description("List and dismiss Termix alerts.");
31137
- alerts.command("list", { isDefault: true }).description("List active alerts and notifications.").action(async function() {
31565
+ alerts.command("list", { isDefault: true }).description("List alerts in your inbox, newest first.").option("--unread", "Only unread alerts").option("--limit <n>", "How many to show (server default 50)", parseLimit).action(async function(opts) {
31138
31566
  await run(async () => {
31139
- const { client } = await createContext(this);
31567
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31568
+ await requireFeature2("alerts");
31140
31569
  const data = await client.request({
31141
31570
  method: "GET",
31142
- path: "/alerts"
31571
+ path: pluginPath("alerts", "/items"),
31572
+ params: {
31573
+ ...opts.unread ? { unread: true } : {},
31574
+ ...opts.limit ? { limit: opts.limit } : {}
31575
+ }
31143
31576
  });
31144
31577
  printList(toAlertRows(data), ALERT_COLUMNS);
31145
31578
  });
31146
31579
  });
31147
- alerts.command("dismiss <alertId>").description("Dismiss an alert.").allowUnknownOption().action(async function(alertId) {
31580
+ const markRead = (read) => async function(alertId) {
31148
31581
  await run(async () => {
31149
- const { client } = await createContext(this);
31582
+ const id = parseAlertId(alertId);
31583
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31584
+ await requireFeature2("alerts");
31150
31585
  await client.request({
31151
31586
  method: "POST",
31152
- path: "/alerts/dismiss",
31153
- data: { alertId }
31587
+ path: pluginPath("alerts", "/items/read"),
31588
+ data: { ids: [id], read }
31589
+ });
31590
+ printResult(read ? `Dismissed alert ${id}.` : `Restored alert ${id}.`, {
31591
+ id
31154
31592
  });
31155
- printResult(`Dismissed alert ${alertId}.`, { id: alertId });
31156
31593
  });
31157
- });
31158
- alerts.command("undismiss <alertId>").description("Restore a previously dismissed alert.").allowUnknownOption().action(async function(alertId) {
31594
+ };
31595
+ alerts.command("dismiss <alertId>").description("Mark an alert as read.").action(markRead(true));
31596
+ alerts.command("undismiss <alertId>").description("Mark an alert as unread again.").action(markRead(false));
31597
+ alerts.command("delete <alertId>").description("Delete an alert from your inbox for good.").action(async function(alertId) {
31159
31598
  await run(async () => {
31160
- const { client } = await createContext(this);
31599
+ const id = parseAlertId(alertId);
31600
+ const { client, requireFeature: requireFeature2 } = await createContext(this);
31601
+ await requireFeature2("alerts");
31161
31602
  await client.request({
31162
31603
  method: "DELETE",
31163
- path: "/alerts/dismiss",
31164
- params: { alertId }
31604
+ path: pluginPath("alerts", `/items/${id}`)
31165
31605
  });
31166
- printResult(`Restored alert ${alertId}.`, { id: alertId });
31606
+ printResult(`Deleted alert ${id}.`, { id });
31167
31607
  });
31168
31608
  });
31169
31609
  }
@@ -31325,26 +31765,22 @@ function registerMiscCommands(program3) {
31325
31765
  path: "/version",
31326
31766
  params: { checkRemote: false }
31327
31767
  }).catch(() => null);
31768
+ const plugins = server ? await getServerPlugins(client).catch(() => null) : null;
31328
31769
  printRecord({
31329
31770
  cli: CLI_VERSION,
31330
31771
  url: config.url,
31331
31772
  health: health?.status ?? "unknown",
31332
31773
  server: server?.localVersion ?? null,
31333
- serverStatus: server?.status ?? null
31774
+ serverStatus: server?.status ?? null,
31775
+ plugins: plugins ? plugins.filter(isPluginActive).length : null
31334
31776
  });
31335
31777
  });
31336
31778
  });
31337
31779
  program3.command("status [hostId]").description("Show online/offline status for all hosts, or one host.").action(async function(hostId) {
31338
31780
  await run(async () => {
31339
31781
  const { client } = await createContext(this);
31340
- const path3 = hostId ? `/status/${parseId(hostId)}` : "/status";
31341
- const data = await client.request({
31342
- method: "GET",
31343
- path: path3,
31344
- // Host status is served by the metrics app, which sits behind the
31345
- // same origin in a normal deployment but on its own port otherwise.
31346
- service: "metrics"
31347
- });
31782
+ const path3 = hostId ? `/host/status/${parseId(hostId)}` : "/host/status";
31783
+ const data = await client.request({ method: "GET", path: path3 });
31348
31784
  if (hostId) {
31349
31785
  printRecord({ id: Number(hostId), ...data });
31350
31786
  return;
@@ -31362,6 +31798,122 @@ function registerMiscCommands(program3) {
31362
31798
  });
31363
31799
  }
31364
31800
 
31801
+ // src/commands/plugins.ts
31802
+ var PLUGIN_COLUMNS = [
31803
+ { header: "id", value: (p) => p.id },
31804
+ { header: "name", value: (p) => p.name },
31805
+ { header: "version", value: (p) => p.version },
31806
+ { header: "state", value: (p) => p.state },
31807
+ { header: "commands", value: (p) => p.commands }
31808
+ ];
31809
+ function registerPluginCommands(program3) {
31810
+ const plugins = program3.command("plugins").description(
31811
+ "Show the plugins on the server, and which CLI commands each one enables."
31812
+ );
31813
+ plugins.command("list", { isDefault: true }).description("List the server's plugins.").action(async function() {
31814
+ await run(async () => {
31815
+ const { client } = await createContext(this);
31816
+ const rows = (await getServerPlugins(client)).map((plugin) => ({
31817
+ id: plugin.id,
31818
+ name: plugin.name,
31819
+ version: plugin.version,
31820
+ enabled: plugin.enabled,
31821
+ state: plugin.state,
31822
+ commands: commandsForPlugin(plugin.id)
31823
+ }));
31824
+ printList(rows, PLUGIN_COLUMNS, {
31825
+ jsonWrapper: (all3) => ({ count: all3.length, plugins: all3 })
31826
+ });
31827
+ });
31828
+ });
31829
+ }
31830
+
31831
+ // src/commands/api.ts
31832
+ import fs7 from "fs";
31833
+ var METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
31834
+ function parseApiMethod(value) {
31835
+ const method = value.toUpperCase();
31836
+ if (!METHODS.includes(method)) {
31837
+ throw new UsageError(
31838
+ `Unknown method "${value}" (expected one of ${METHODS.join(", ")}).`
31839
+ );
31840
+ }
31841
+ return method;
31842
+ }
31843
+ function parseApiPath(value) {
31844
+ if (/^[A-Za-z]:[\\/]/.test(value)) {
31845
+ throw new UsageError(
31846
+ `"${value}" is a local file path. Git Bash rewrites arguments that start with "/", so leave the slash off (plugins, not /plugins) or set MSYS_NO_PATHCONV=1.`
31847
+ );
31848
+ }
31849
+ if (/^[a-z]+:\/\//i.test(value) || value.startsWith("//")) {
31850
+ throw new UsageError(
31851
+ `Pass a path on the server, like /plugins, not a full URL. Use --url to pick the server.`
31852
+ );
31853
+ }
31854
+ return value.startsWith("/") ? value : `/${value}`;
31855
+ }
31856
+ function collectQuery(value, previous) {
31857
+ const index = value.indexOf("=");
31858
+ if (index <= 0) {
31859
+ throw new UsageError(`Invalid --query "${value}" (expected NAME=VALUE).`);
31860
+ }
31861
+ return { ...previous, [value.slice(0, index)]: value.slice(index + 1) };
31862
+ }
31863
+ function parseApiBody(opts) {
31864
+ if (opts.data !== void 0 && opts.dataFile !== void 0) {
31865
+ throw new UsageError("Pass only one of --data or --data-file.");
31866
+ }
31867
+ let raw = opts.data;
31868
+ if (opts.dataFile !== void 0) {
31869
+ try {
31870
+ raw = fs7.readFileSync(opts.dataFile === "-" ? 0 : opts.dataFile, "utf8");
31871
+ } catch {
31872
+ throw new UsageError(`Could not read --data-file: ${opts.dataFile}`);
31873
+ }
31874
+ }
31875
+ if (raw === void 0) return void 0;
31876
+ try {
31877
+ return JSON.parse(raw);
31878
+ } catch {
31879
+ throw new UsageError("The request body is not valid JSON.");
31880
+ }
31881
+ }
31882
+ function registerApiCommands(program3) {
31883
+ program3.command("api <method> <path>").description(
31884
+ "Send an authenticated request to any Termix route, including plugin routes under /plugin-api/<id>/. Prints the JSON response."
31885
+ ).option("-d, --data <json>", "JSON request body").option(
31886
+ "--data-file <path>",
31887
+ "Read the JSON request body from a file, or - for stdin"
31888
+ ).option(
31889
+ "--query <NAME=VALUE>",
31890
+ "Query string parameter; repeatable",
31891
+ collectQuery,
31892
+ {}
31893
+ ).option("--raw", "Print the response body as-is instead of as JSON").action(async function(methodArg, pathArg, opts) {
31894
+ await run(async () => {
31895
+ const method = parseApiMethod(methodArg);
31896
+ const path3 = parseApiPath(pathArg);
31897
+ const data = parseApiBody(opts);
31898
+ const { client } = await createContext(this);
31899
+ const response = await client.request({
31900
+ method,
31901
+ path: path3,
31902
+ data,
31903
+ params: Object.keys(opts.query).length ? opts.query : void 0,
31904
+ responseType: opts.raw ? "text" : "json"
31905
+ });
31906
+ if (opts.raw) {
31907
+ process.stdout.write(
31908
+ typeof response === "string" ? response : JSON.stringify(response)
31909
+ );
31910
+ return;
31911
+ }
31912
+ printJson(response ?? null);
31913
+ });
31914
+ });
31915
+ }
31916
+
31365
31917
  // src/index.ts
31366
31918
  var program2 = new Command();
31367
31919
  program2.name("termix").description(
@@ -31385,6 +31937,8 @@ registerAlertCommands(program2);
31385
31937
  registerAdminCommands(program2);
31386
31938
  registerApiKeyCommands(program2);
31387
31939
  registerMiscCommands(program2);
31940
+ registerPluginCommands(program2);
31941
+ registerApiCommands(program2);
31388
31942
  program2.exitOverride((error) => {
31389
31943
  if (error.code === "commander.help" || error.code === "commander.helpDisplayed" || error.code === "commander.version") {
31390
31944
  process.exit(ExitCode.OK);