@xns-cloud/relayer-mcp 0.12.0 → 0.14.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,80 @@
1
1
  'use strict';
2
2
 
3
3
  const { z } = require('zod');
4
+ const os = require('os');
4
5
  const path = require('path');
5
6
  const net = require('net');
6
7
  const { createDockerUtil, redactEndpoint, classifyDockerFailure } = require('../lib/dockerUtil');
8
+ const { validateHostAllowlist } = require('../lib/hostAllowlist');
7
9
 
8
10
  const BIND_ADDRESS_HELP = 'bind_address must be empty (all interfaces), an IPv4 address (e.g. "127.0.0.1"), or a bracketed IPv6 address (e.g. "[::1]") — the Compose ports host component is an IP address, not a hostname';
9
11
 
10
- // A ports list item that uses ${BIND_ADDRESS...}; a comment naming it does not count.
11
- const PORTS_USE_BIND_ADDRESS = /^[ \t]*-[^#\n]*\$\{BIND_ADDRESS\b/m;
12
+ const USES_BIND_ADDRESS = /\$\{BIND_ADDRESS\b/;
13
+
14
+ /** A YAML line with its comment cut off ('#' starts no ${...} expansion). */
15
+ function stripComment(line) {
16
+ const at = line.search(/(^|\s)#/);
17
+ return at === -1 ? line : line.slice(0, at);
18
+ }
19
+
20
+ /**
21
+ * Whether every port a compose file publishes uses ${BIND_ADDRESS...} in the
22
+ * short syntax, so a bind_address narrows all of them. Reads each `ports:`
23
+ * block, block or flow form. A port without it, a long-syntax item (the .env
24
+ * value carries a trailing colon, which is no valid host_ip), or a file with no
25
+ * published port at all gives false: the caller stops before writing anything.
26
+ * Comments and other keys (environment) never count.
27
+ *
28
+ * @param {string} text - compose file text
29
+ * @returns {boolean}
30
+ */
31
+ function everyPortUsesBindAddress(text) {
32
+ const lines = text.split(/\r?\n/);
33
+ const items = [];
34
+ for (let i = 0; i < lines.length; i++) {
35
+ const key = /^([ \t]*)(?:-[ \t]+)?ports:(.*)$/.exec(stripComment(lines[i]));
36
+ if (!key) continue;
37
+ const keyIndent = key[1].length;
38
+ const rest = key[2].trim();
39
+ if (rest) {
40
+ // Flow form: ports: ["a", "b"]. Anything else is unreadable here.
41
+ const flow = /^\[(.*)\]$/.exec(rest);
42
+ if (!flow) return false;
43
+ items.push(...flow[1].split(',').map((item) => item.trim()).filter(Boolean));
44
+ continue;
45
+ }
46
+ let itemIndent = null;
47
+ let current = null;
48
+ for (let j = i + 1; j < lines.length; j++) {
49
+ const line = stripComment(lines[j]);
50
+ if (!line.trim()) continue;
51
+ const indent = /^[ \t]*/.exec(line)[0].length;
52
+ const dash = /^[ \t]*-(\s|$)/.test(line);
53
+ if (itemIndent === null) {
54
+ if (!dash || indent < keyIndent) break;
55
+ itemIndent = indent;
56
+ }
57
+ if (indent < itemIndent || (indent === itemIndent && !dash)) break;
58
+ if (indent === itemIndent) {
59
+ current = { text: line };
60
+ items.push(current);
61
+ } else {
62
+ current.text += `\n${line}`;
63
+ }
64
+ i = j;
65
+ }
66
+ }
67
+ const LONG_SYNTAX = /^[ \t]*-[ \t]+[A-Za-z_]+:(\s|$)/;
68
+ return items.length > 0 && items.every((item) => {
69
+ const text = typeof item === 'string' ? item : item.text;
70
+ return USES_BIND_ADDRESS.test(text) && (typeof item === 'string' || !LONG_SYNTAX.test(text));
71
+ });
72
+ }
12
73
 
13
74
  /** What the response says about bind_address, per compose source. */
14
75
  function bindAddressApplied(source, bindAddress) {
15
- if (source === 'bundled-fallback') {
16
- return 'yes — the bundled fallback compose references BIND_ADDRESS in its port declarations';
17
- }
18
76
  if (source === 'channel' && bindAddress) {
19
- return 'yes — the channel compose references BIND_ADDRESS in its port declarations (checked before install)';
77
+ return 'yes — the channel compose uses BIND_ADDRESS on every published port (checked before install)';
20
78
  }
21
79
  if (source === 'channel') {
22
80
  return 'not needed — no bind_address was set, so ports are published on all interfaces';
@@ -52,16 +110,72 @@ function isValidBindAddress(value) {
52
110
  // monitoring stack), published on the XNS releases registry and served
53
111
  // login-free. THE default install source. Its .env (COMPOSE_PROFILES and the
54
112
  // rest of the release settings) sits beside it and is fetched on every run.
55
- const CHANNEL_COMPOSE_URL = 'https://releases.scpri.me/relayer/release/docker-compose.yml';
113
+ // src=mcp counts this download by source; the .env URL built from it drops the query.
114
+ const CHANNEL_COMPOSE_URL = 'https://releases.xns.tech/relayer/release/docker-compose.yml?src=mcp';
56
115
  const CHANNEL_ENV_FILE = '.env';
57
116
 
58
- // Bundled OFFLINE FALLBACK template (ships in the npm package; package.json
59
- // `files: ["src/"]` covers it). Written only when the channel compose or .env
60
- // fetch fails;
61
- // kept service-parity with the channel bundle by the jest contract tests.
62
- const TEMPLATE_PATH = path.join(__dirname, '..', 'templates', 'docker-compose.yml');
117
+ const RELEASES_HOST = 'releases.xns.tech';
118
+ const MAX_OVERRIDE_BYTES = 1048576;
119
+
120
+ /**
121
+ * Decide whether a compose_url override may be downloaded and run.
122
+ * Allowed: https on releases.xns.tech, a file:// URL (a file on this machine), or
123
+ * a loopback / private-network / .local host over http or https.
124
+ *
125
+ * DECISION: no opt-in flag for other hosts. The compose file runs as root through
126
+ * docker compose, and a flag is one more input a planted instruction could set.
127
+ *
128
+ * @param {string} url
129
+ * @returns {{ allowed: boolean, host: string }}
130
+ */
131
+ function isComposeFilePath(pathname) {
132
+ let decoded;
133
+ try {
134
+ decoded = decodeURIComponent(pathname);
135
+ } catch {
136
+ return false;
137
+ }
138
+ return /\.ya?ml$/i.test(decoded);
139
+ }
140
+
141
+ function checkComposeUrl(url) {
142
+ let parsed;
143
+ try {
144
+ parsed = new URL(url);
145
+ } catch {
146
+ return { allowed: false, host: '(unreadable URL)' };
147
+ }
148
+ const hostname = parsed.hostname.toLowerCase();
149
+ if (parsed.protocol === 'file:') {
150
+ const local = hostname === '' || hostname === 'localhost';
151
+ if (!local) return { allowed: false, host: hostname };
152
+ // curl would copy any readable file (or read /dev/zero without end) into the
153
+ // install folder, so only a compose file by name is accepted.
154
+ if (!isComposeFilePath(parsed.pathname)) {
155
+ return { allowed: false, host: 'this machine', reason: 'file-extension' };
156
+ }
157
+ return { allowed: true, host: 'this machine' };
158
+ }
159
+ if (parsed.protocol === 'https:' && hostname === RELEASES_HOST) return { allowed: true, host: hostname };
160
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return { allowed: false, host: hostname || parsed.protocol };
161
+ // Only plain DNS names and IP literals. Node accepts characters such as "{" in a
162
+ // hostname that curl reads as syntax, so the host curl contacts could differ.
163
+ if (!/^([a-z0-9-]+\.)*[a-z0-9-]+$|^\[[0-9a-f:.]+\]$/.test(hostname)) return { allowed: false, host: hostname };
164
+ return { allowed: validateHostAllowlist(url).allowed, host: hostname };
165
+ }
63
166
 
64
- // container_name in the bundled compose. Docker container names are unique
167
+ function composeFileRefusedMessage() {
168
+ return 'compose_url file:// path must be a .yml or .yaml file, so nothing was written and nothing was downloaded. Pass the path of your docker-compose.yml, for example file:///home/you/docker-compose.yml.';
169
+ }
170
+
171
+ function composeHostRefusedMessage(host) {
172
+ return `compose_url host ${host} is not allowed, so nothing was written and nothing was downloaded. A custom compose runs as root through Docker, so it may only come from https://${RELEASES_HOST}, a file:// URL, or a loopback, private-network or .local host. To use your own compose file, download it to this machine and pass a file:// URL (for example file:///home/you/docker-compose.yml), or serve it from your private network.`;
173
+ }
174
+
175
+ // Where a release .env that stops short is reported.
176
+ const BUGS_URL = require('../../package.json').bugs.url;
177
+
178
+ // container_name in the release compose. Docker container names are unique
65
179
  // per daemon, so ANY existing container with this name — running or stopped,
66
180
  // any channel — makes `docker compose up` fail with a name conflict.
67
181
  const CONTAINER_NAME = 'xns-relayer';
@@ -107,6 +221,25 @@ function safeError(message, cause) {
107
221
  return Object.assign(new Error(message, { cause }), { userSafe: true });
108
222
  }
109
223
 
224
+ // The four reasons a default install stops before it touches the install
225
+ // folder. Each names the cause and what to do; curl and OS text go to the
226
+ // server log only.
227
+ function downloadFailedMessage(host, file) {
228
+ return `The Relayer release files could not be downloaded from ${host} (the ${file} download failed), so nothing was installed. Check that this machine reaches https://${host}, then run install_relayer again.`;
229
+ }
230
+
231
+ function incompleteEnvMessage(host) {
232
+ return `The release .env downloaded from ${host} has no COMPOSE_PROFILES line, so the download was cut short or the published release is incomplete, and nothing was installed. Run install_relayer again; if it stops here again, report it at ${BUGS_URL}.`;
233
+ }
234
+
235
+ function bindUnsupportedMessage(bindAddress) {
236
+ return `bind_address ${bindAddress} was requested, but the release compose file does not use BIND_ADDRESS on every published port, so the ports would be published on all interfaces. Nothing was installed. Run install_relayer again without bind_address, or pass compose_url pointing at a compose file whose ports use \${BIND_ADDRESS}.`;
237
+ }
238
+
239
+ function tempFolderMessage(tmpDir) {
240
+ return `The release files could not be prepared on this machine: the temporary folder under ${tmpDir} could not be created or read. Nothing was installed. Check that the folder is writable and the disk is not full, then run install_relayer again.`;
241
+ }
242
+
110
243
  const DOCKER_GROUP_SENTENCE = 'The Docker socket refused this user, so nothing was written and nothing was started. Add the user to the docker group (sudo usermod -aG docker $USER), then log out and back in (or reboot) and run install_relayer again.';
111
244
 
112
245
  // Fixed sentences per classified Docker failure (dockerUtil FAILURE_PATTERNS).
@@ -116,7 +249,7 @@ const FAILURE_SENTENCES = {
116
249
  permission_denied: DOCKER_GROUP_SENTENCE,
117
250
  daemon_stopped: 'Docker is not running on this machine. Start it with sudo systemctl start docker, then run install_relayer again.',
118
251
  out_of_disk: 'Docker ran out of disk space while pulling the Relayer images. Free disk space on the filesystem holding the Docker root (docker info --format {{.DockerRootDir}} shows where it is), then run install_relayer again.',
119
- pull_refused: 'The Relayer images could not be pulled from releases.scpri.me. Check that this machine reaches https://releases.scpri.me and that no stale registry login is stored (docker logout releases.scpri.me), then run install_relayer again.',
252
+ pull_refused: 'The Relayer images could not be pulled from releases.xns.tech. Check that this machine reaches https://releases.xns.tech and that no stale registry login is stored (docker logout releases.xns.tech), then run install_relayer again.',
120
253
  };
121
254
 
122
255
  // The release compose also publishes the S3 HTTPS port. No install_relayer
@@ -184,12 +317,13 @@ function withPortLines(fetchedEnv, portLines) {
184
317
  *
185
318
  * A first-time user has never heard of a Relayer and cannot supply a compose
186
319
  * file or a .env. So by default this tool authors both for them: it fetches
187
- * the CANONICAL release channel bundle (relayer + Prometheus + Grafana +
188
- * node-exporter — the monitoring stack powers the dashboards under Monitoring
189
- * in the web UI) and its .env, then appends the two ports and the bind address
190
- * to that .env. If either fetch fails (offline, registry hiccup), the bundled
191
- * service-parity template and a .env of just those lines are the fallback —
192
- * the install still completes and the response says it fell back.
320
+ * the CANONICAL release channel bundle (relayer, the Prometheus + Grafana +
321
+ * node-exporter monitoring stack that powers the dashboards under Monitoring in
322
+ * the web UI, Alertmanager, and the Loki + Alloy + audit-logrotate audit-log
323
+ * pipeline) and its .env, then appends the two ports and the bind address to
324
+ * that .env. Both files are downloaded into a temporary folder and checked
325
+ * there first. If either cannot be downloaded or used, the tool stops with the
326
+ * cause and the fix, and the install folder is left exactly as it was.
193
327
  *
194
328
  * `compose_url` stays as an optional override for internal/custom installs;
195
329
  * when given, the old download-a-URL behavior is preserved.
@@ -205,16 +339,16 @@ module.exports = function registerInstallRelayer(server, options = {}) {
205
339
  server.registerTool(
206
340
  'install_relayer',
207
341
  {
208
- title: 'install_relayer',
209
- description: 'Install and start the XNS Relayer. By default fetches the canonical release channel bundle — relayer + the Prometheus/Grafana monitoring stack — and its .env from releases.scpri.me (anonymous pull), appends the ports to that .env, then runs docker compose up -d — the user does NOT need to author any file. Falls back to a bundled copy of the bundle if either fetch fails. A failure names its cause (port in use, image pull refused, Docker stopped, out of disk, Docker socket permission) and the command that fixes it. Pass compose_url only to override with a custom compose.\n\nIMPORTANT — two machines: this tool writes docker-compose.yml and .env on the machine running the MCP, then starts the containers on whichever machine the Docker daemon is on. When DOCKER_HOST or an ssh:// Docker context points at a daemon on another machine, the tool refuses: it writes nothing and starts nothing, and returns an error naming the Docker host. Run the MCP on the Docker host (Node.js 20 there) and install from there.\n\nExposure decisions on this surface:\n\n1. BINDING — bind_address controls which host network interface Docker publishes ports on. Default: empty (all interfaces — the dashboard answers from any machine on the LAN with zero configuration). Set to "127.0.0.1" for loopback-only, or a specific interface IP. The value is passed to docker compose via env as BIND_ADDRESS; it takes effect only if the compose file used for the install references BIND_ADDRESS in its port declarations. When bind_address is set and the channel compose does not reference BIND_ADDRESS, the tool installs the bundled compose instead (source bundled-fallback, with a reason), because the bundled one honors it. A compose_url override is fetched remotely and may not honor it. The prerequisite check (check_prerequisites) probes port availability by binding 0.0.0.0 regardless of this setting.\n\n2. UI TLS — ui_tls_enabled describes whether the admin UI listens on HTTPS in addition to HTTP. Default: false (off). This switch is described here for decision visibility; it is NOT wired to behavior in this version — setting it to true is accepted but has no effect until a future release ships the listener. Cost when enabled: requires a TLS certificate and key provisioned on the host.\n\n3. S3 TLS — s3_tls_enabled describes whether the S3 gateway listens on HTTPS in addition to HTTP. Default: false (off). This switch is described here for decision visibility; it is NOT wired to behavior in this version — setting it to true is accepted but has no effect until a future release ships the listener. Cost when enabled: requires a TLS certificate and key provisioned on the host; S3 clients must be configured to use the HTTPS endpoint.',
342
+ title: 'Install the Relayer',
343
+ description: 'Install and start the XNS Relayer. By default fetches the canonical release channel bundle — relayer + the Prometheus/Grafana monitoring stack — and its .env from releases.xns.tech (anonymous pull), appends the ports to that .env, then runs docker compose up -d — the user does NOT need to author any file. If the release files cannot be downloaded or used, it stops, says why and what to do, and installs nothing. A failure names its cause (port in use, image pull refused, Docker stopped, out of disk, Docker socket permission) and the command that fixes it. Pass compose_url only to override with a custom compose; it must be https on releases.xns.tech, a file:// URL, or a loopback, private-network or .local host (any other host is refused before anything is downloaded).\n\nIMPORTANT — two machines: this tool writes docker-compose.yml and .env on the machine running the MCP, then starts the containers on whichever machine the Docker daemon is on. When DOCKER_HOST or an ssh:// Docker context points at a daemon on another machine, the tool refuses: it writes nothing and starts nothing, and returns an error naming the Docker host. Run the MCP on the Docker host (Node.js 24 there) and install from there.\n\nExposure decisions on this surface:\n\n1. BINDING — bind_address controls which host network interface Docker publishes ports on. Default: empty (all interfaces — the dashboard answers from any machine on the LAN with zero configuration). Set to "127.0.0.1" for loopback-only, or a specific interface IP. The value is passed to docker compose via env as BIND_ADDRESS; it takes effect only if the compose file used for the install references BIND_ADDRESS in its port declarations. When bind_address is set and the release compose does not use BIND_ADDRESS on every published port, the tool stops before installing anything and says so. A compose_url override is fetched remotely and may not honor it. The prerequisite check (check_prerequisites) probes port availability by binding 0.0.0.0 regardless of this setting.\n\n2. UI TLS — ui_tls_enabled describes whether the admin UI listens on HTTPS in addition to HTTP. Default: false (off). This switch is described here for decision visibility; it is NOT wired to behavior in this version — setting it to true is accepted but has no effect until a future release ships the listener. Cost when enabled: requires a TLS certificate and key provisioned on the host.\n\n3. S3 TLS — s3_tls_enabled describes whether the S3 gateway listens on HTTPS in addition to HTTP. Default: false (off). This switch is described here for decision visibility; it is NOT wired to behavior in this version — setting it to true is accepted but has no effect until a future release ships the listener. Cost when enabled: requires a TLS certificate and key provisioned on the host; S3 clients must be configured to use the HTTPS endpoint.',
210
344
  inputSchema: {
211
345
  install_path: z.string().optional().default('/opt/xns-relayer').describe('Directory to install the compose file into'),
212
346
  ui_port: z.number().int().min(1).max(65535).optional().default(8888).describe('Host port for the Relayer admin/customer UI (container 8888). Docker publishes this port on the interface chosen by bind_address.'),
213
347
  s3_port: z.number().int().min(1).max(65535).optional().default(9000).describe('Host port for the S3 API (container 9000). Docker publishes this port on the interface chosen by bind_address.'),
214
- compose_url: z.string().url().optional().describe('OPTIONAL override: URL to a custom docker-compose.yml. Omit for the normal released install. When provided, bind_address is passed to docker compose via env but the downloaded compose must use the BIND_ADDRESS variable in its port declarations for it to take effect.'),
348
+ compose_url: z.string().url().optional().describe('OPTIONAL override: URL to a custom docker-compose.yml. Allowed: https on releases.xns.tech, a file:// URL (a .yml or .yaml compose file on this machine), or a loopback, private-network or .local host; any other host is refused. Omit for the normal released install. When provided, bind_address is passed to docker compose via env but the downloaded compose must use the BIND_ADDRESS variable in its port declarations for it to take effect.'),
215
349
  // R5 input boundary — see isValidBindAddress above for why each
216
350
  // documented address form is validated whole rather than by charset.
217
- bind_address: z.string().max(255).refine(isValidBindAddress, BIND_ADDRESS_HELP).optional().default('').describe('Host network interface for Docker port publication. Default: empty string (all interfaces — reachable from any machine on the LAN). Set to "127.0.0.1" for loopback-only access, or a specific interface IP to restrict reachability. Accepted forms: empty, an IPv4 address, or a bracketed IPv6 address (e.g. "[::1]"). Hostnames are rejected — the Compose ports host component is an IP address. This value is passed to docker compose via env, and on the channel and bundled-fallback paths it is also written into the .env this installer authors (the compose_url override path writes no .env). It is honored in the bundled fallback compose (which uses BIND_ADDRESS in its port declarations). On the default path the installer checks the fetched channel compose for BIND_ADDRESS and uses the bundled fallback compose when it is absent. On the compose_url path the fetched compose must reference the BIND_ADDRESS variable in its port declarations for the setting to take effect — this installer cannot verify that.'),
351
+ bind_address: z.string().max(255).refine(isValidBindAddress, BIND_ADDRESS_HELP).optional().default('').describe('Host network interface for Docker port publication. Default: empty string (all interfaces — reachable from any machine on the LAN). Set to "127.0.0.1" for loopback-only access, or a specific interface IP to restrict reachability. Accepted forms: empty, an IPv4 address, or a bracketed IPv6 address (e.g. "[::1]"). Hostnames are rejected — the Compose ports host component is an IP address. This value is passed to docker compose via env, and on the default path it is also written into the .env this installer authors (the compose_url override path writes no .env). On the default path the installer checks the fetched channel compose for BIND_ADDRESS and stops, installing nothing, when it is absent. On the compose_url path the fetched compose must reference the BIND_ADDRESS variable in its port declarations for the setting to take effect — this installer cannot verify that.'),
218
352
  ui_tls_enabled: z.boolean().optional().default(false).describe('Whether the admin UI should listen on HTTPS in addition to HTTP. Default: false (off — HTTP only). NOT WIRED in this version: accepted but has no effect until a future release ships the TLS listener. Cost when enabled: requires a TLS certificate and key provisioned on the host.'),
219
353
  s3_tls_enabled: z.boolean().optional().default(false).describe('Whether the S3 gateway should listen on HTTPS in addition to HTTP. Default: false (off — HTTP only). NOT WIRED in this version: accepted but has no effect until a future release ships the TLS listener. Cost when enabled: requires a TLS certificate and key provisioned on the host; S3 clients must be configured to use the HTTPS endpoint.'),
220
354
  },
@@ -228,6 +362,12 @@ module.exports = function registerInstallRelayer(server, options = {}) {
228
362
  try {
229
363
  const { execFile: nodeExecFile } = require('child_process');
230
364
  const execFileFn = _execFile || nodeExecFile;
365
+ // Before any lookup, mkdir or download: the override compose runs
366
+ // as root, so its host is checked first.
367
+ const composeCheck = compose_url ? checkComposeUrl(compose_url) : null;
368
+ if (composeCheck && !composeCheck.allowed) {
369
+ return errorResponse(`Relayer installation failed: ${composeCheck.reason === 'file-extension' ? composeFileRefusedMessage() : composeHostRefusedMessage(composeCheck.host)}`);
370
+ }
231
371
  const composePath = path.join(install_path, 'docker-compose.yml');
232
372
  const envPath = path.join(install_path, '.env');
233
373
 
@@ -243,7 +383,7 @@ module.exports = function registerInstallRelayer(server, options = {}) {
243
383
  error: `The Docker daemon is on ${dockerHost.host}, not this machine. install_relayer would write docker-compose.yml and .env on this machine instead of on ${dockerHost.host}, so nothing was written and nothing was started.`,
244
384
  docker_host: dockerHost.host,
245
385
  docker_endpoint: redactEndpoint(dockerHost.endpoint),
246
- remediation: `Run the MCP on ${dockerHost.host} (install Node.js 20 there and point your MCP client at it), then run install_relayer again. Or, to install on this machine, unset DOCKER_HOST or switch to the default Docker context.`,
386
+ remediation: `Run the MCP on ${dockerHost.host} (install Node.js 24 there and point your MCP client at it), then run install_relayer again. Or, to install on this machine, unset DOCKER_HOST or switch to the default Docker context.`,
247
387
  }, null, 2),
248
388
  }],
249
389
  isError: true,
@@ -277,79 +417,127 @@ module.exports = function registerInstallRelayer(server, options = {}) {
277
417
  };
278
418
  }
279
419
 
280
- // Create install directory (execFile, no shell)
281
- await new Promise((resolve, reject) => {
420
+ const mkdirInstallPath = () => new Promise((resolve, reject) => {
282
421
  execFileFn('mkdir', ['-p', install_path], {}, (err) => {
283
422
  if (err) return reject(safeError(`Failed to create directory ${install_path} — check that the path is writable on this machine and no file sits at or along it`, err));
284
423
  resolve();
285
424
  });
286
425
  });
287
426
 
288
- const download = (url, outPath, what) => new Promise((resolve, reject) => {
289
- execFileFn('curl', ['-fsSL', '-o', outPath, url], { timeout: 60000 }, (err) => {
290
- if (err) return reject(safeError(`Failed to download ${what}`, err));
427
+ // curl -fsSL -o <outPath> <url> (execFile, no shell) for the release
428
+ // channel. Rejects with curl's own error; each caller chooses the message.
429
+ // -q must be the first argument: it keeps curl from reading ~/.curlrc.
430
+ // -g: curl must not expand {a,b} or [1-9] patterns into other URLs.
431
+ const curlTo = (url, outPath) => new Promise((resolve, reject) => {
432
+ execFileFn('curl', ['-q', '-fsSL', '-g', '-o', outPath, url], { timeout: 60000 }, (err) => {
433
+ if (err) return reject(err);
291
434
  resolve();
292
435
  });
293
436
  });
294
- const fetchCompose = (url) => download(url, composePath, 'compose file');
437
+
438
+ // The override download: no redirects (a redirect would reach a host the
439
+ // check never saw), http, https or a local file only, and at most
440
+ // MAX_OVERRIDE_BYTES. curl writes to stdout and Node stops it past the
441
+ // cap, because --max-filesize does not stop a transfer of unknown length
442
+ // before curl 8.4.0. Only then is the file written.
443
+ const curlOverrideTo = (url, outPath) => new Promise((resolve, reject) => {
444
+ const args = ['-q', '-fsS', '-g', '--proto', '=http,https,file', '--max-filesize', String(MAX_OVERRIDE_BYTES), url];
445
+ execFileFn('curl', args, { timeout: 60000, maxBuffer: MAX_OVERRIDE_BYTES, encoding: 'buffer' }, (err, stdout) => {
446
+ if (err) return reject(err);
447
+ resolve(stdout);
448
+ });
449
+ }).then((body) => fsp.writeFile(outPath, body ?? ''));
450
+
451
+ // Download the release compose and .env into an owner-only
452
+ // temporary folder, read them and run the two checks. The folder
453
+ // is removed whatever happens; a failed removal is logged and
454
+ // never replaces the result.
455
+ const stageReleaseFiles = async (bindAddress) => {
456
+ const host = new URL(channelComposeUrl).host;
457
+ const tmpDir = os.tmpdir();
458
+ const readStaged = (file) => fsp.readFile(file, 'utf8').catch((err) => {
459
+ throw safeError(tempFolderMessage(tmpDir), err);
460
+ });
461
+ let stage;
462
+ try {
463
+ stage = await fsp.mkdtemp(path.join(tmpDir, 'xns-relayer-install-'));
464
+ } catch (err) {
465
+ throw safeError(tempFolderMessage(tmpDir), err);
466
+ }
467
+ try {
468
+ const stagedCompose = path.join(stage, 'docker-compose.yml');
469
+ await curlTo(channelComposeUrl, stagedCompose).catch((err) => {
470
+ throw safeError(downloadFailedMessage(host, 'docker-compose.yml'), err);
471
+ });
472
+ const composeText = await readStaged(stagedCompose);
473
+ // A bind_address the release compose ignores would publish
474
+ // the ports on every interface.
475
+ if (bindAddress && !everyPortUsesBindAddress(composeText)) {
476
+ throw safeError(bindUnsupportedMessage(bindAddress));
477
+ }
478
+ const stagedEnv = path.join(stage, CHANNEL_ENV_FILE);
479
+ await curlTo(channelEnvUrl, stagedEnv).catch((err) => {
480
+ throw safeError(downloadFailedMessage(host, CHANNEL_ENV_FILE), err);
481
+ });
482
+ const fetchedEnv = await readStaged(stagedEnv);
483
+ // The publisher always ships this line, so its absence means a
484
+ // truncated or empty download. Without it no audit sidecar starts.
485
+ if (!/^COMPOSE_PROFILES=/m.test(fetchedEnv)) {
486
+ throw safeError(incompleteEnvMessage(host));
487
+ }
488
+ return { composeText, fetchedEnv };
489
+ } finally {
490
+ try {
491
+ await fsp.rm(stage, { recursive: true, force: true });
492
+ } catch (rmErr) {
493
+ console.error(`[install_relayer] could not remove ${stage}: ${rmErr.message}`);
494
+ }
495
+ }
496
+ };
295
497
 
296
498
  const bindPrefix = bind_address ? `${bind_address}:` : '';
297
- let envContents = null;
298
499
  let source;
299
- let note;
300
- let reason;
301
500
  if (compose_url) {
302
- // Override path: download a custom compose (execFile, no shell).
303
- await fetchCompose(compose_url);
501
+ // Override path: make the folder, then download a custom
502
+ // compose and write it into it.
503
+ await mkdirInstallPath();
504
+ // DECISION: curl gets the serialized URL that was checked, not the
505
+ // raw string. Node and curl parse a backslash before "@" differently,
506
+ // so the raw string could name another host than the one allowed.
507
+ await curlOverrideTo(new URL(compose_url).href, composePath).catch((err) => {
508
+ if (err && err.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
509
+ throw safeError(`Failed to download compose file: it is larger than ${MAX_OVERRIDE_BYTES} bytes, so nothing was written`, err);
510
+ }
511
+ throw safeError('Failed to download compose file', err);
512
+ });
304
513
  source = 'compose_url';
305
514
  } else {
306
- // Default path: fetch the canonical release bundle (relayer +
307
- // monitoring stack) and its .env fresh on every run, then
308
- // append the port lines to the fetched .env. Fall back to the
309
- // bundled service-parity template and a .env of just the port
310
- // lines when either fetch (or reading the fetched .env) fails.
311
- // Either way the user never writes a file.
515
+ // Default path: download the release compose and its .env
516
+ // into a temporary folder and check them there. Only when
517
+ // every check passes is the install folder made and written,
518
+ // so a stop leaves it exactly as it was.
312
519
  const portLines = `UI_PORT=${ui_port}\nS3_PORT=${s3_port}\nBIND_ADDRESS=${bindPrefix}\n`;
313
- try {
314
- await fetchCompose(channelComposeUrl);
315
- // DECISION: the release compose has no BIND_ADDRESS in its
316
- // ports, so a bind_address would be silently ignored and the
317
- // ports published on all interfaces. Use the bundled compose,
318
- // which honors it, and say so.
319
- if (bind_address && !PORTS_USE_BIND_ADDRESS.test(await fsp.readFile(composePath, 'utf8'))) {
320
- throw Object.assign(new Error('channel compose does not reference BIND_ADDRESS'), { bindUnsupported: true });
321
- }
322
- await download(channelEnvUrl, envPath, 'release .env');
323
- // curl creates the file with the default umask; close it before
324
- // any later step can throw and leave it world-readable.
325
- await fsp.chmod(envPath, ENV_FILE_MODE);
326
- envContents = withPortLines(await fsp.readFile(envPath, 'utf8'), portLines);
327
- source = 'channel';
328
- } catch (fetchErr) {
329
- const template = await fsp.readFile(TEMPLATE_PATH, 'utf8');
330
- await fsp.writeFile(composePath, template);
331
- envContents = portLines;
332
- source = 'bundled-fallback';
333
- console.error(`[install_relayer] channel bundle fetch failed: ${fetchErr.message}${fetchErr.cause ? `: ${fetchErr.cause.message}` : ''}`);
334
- if (fetchErr.bindUnsupported) {
335
- reason = 'The release channel compose does not support bind_address, so the bundled compose, which does, was used. Same services.';
336
- } else {
337
- reason = 'Channel bundle fetch failed.';
338
- note = 'Channel bundle fetch failed — fell back to the bundled compose. Same services; re-running install later is not required.';
339
- }
340
- }
520
+ const { composeText, fetchedEnv } = await stageReleaseFiles(bind_address);
521
+ await mkdirInstallPath();
522
+ await fsp.writeFile(composePath, composeText);
341
523
  // The .env holds webhook/SMTP secrets: owner-only. The mode on
342
- // writeFile covers a new file; chmod covers the one curl made.
343
- await fsp.writeFile(envPath, envContents, { mode: ENV_FILE_MODE });
524
+ // writeFile covers a new file; chmod covers one that existed.
525
+ await fsp.writeFile(envPath, withPortLines(fetchedEnv, portLines), { mode: ENV_FILE_MODE });
344
526
  await fsp.chmod(envPath, ENV_FILE_MODE);
527
+ source = 'channel';
345
528
  }
346
529
 
347
530
  // Run docker compose up -d. cwd + env so ${UI_PORT}/${S3_PORT}
348
531
  // interpolation and the ./data bind resolve in the install dir,
349
532
  // regardless of where the MCP process was launched.
533
+ // The .env written above owns COMPOSE_PROFILES, aliased to RELAYER_AUDIT_MODE.
534
+ // Compose lets the process environment beat .env, so an inherited value
535
+ // would leave the audit sink on with no sidecars to tail and rotate it.
536
+ // compose_url writes no .env, so there the caller's value stands.
537
+ const { COMPOSE_PROFILES: _inheritedProfiles, ...withoutProfiles } = process.env;
350
538
  await docker.composeUp(composePath, {
351
539
  cwd: install_path,
352
- env: { ...process.env, UI_PORT: String(ui_port), S3_PORT: String(s3_port), BIND_ADDRESS: bindPrefix },
540
+ env: { ...(compose_url ? process.env : withoutProfiles), UI_PORT: String(ui_port), S3_PORT: String(s3_port), BIND_ADDRESS: bindPrefix },
353
541
  });
354
542
 
355
543
  return {
@@ -361,7 +549,7 @@ module.exports = function registerInstallRelayer(server, options = {}) {
361
549
  compose_path: composePath,
362
550
  install_path,
363
551
  source,
364
- ...(reason ? { reason } : {}),
552
+ compose_host: composeCheck ? composeCheck.host : new URL(channelComposeUrl).host,
365
553
  // D5/W5: state the binding at install time, out-of-band, so a
366
554
  // refused connection is explainable later. Two statements, never
367
555
  // merged (PRD §7): `composed_from` is what this installer asserts
@@ -388,7 +576,6 @@ module.exports = function registerInstallRelayer(server, options = {}) {
388
576
  ui_tls_enabled: { requested: ui_tls_enabled, effective: false, note: ui_tls_enabled ? 'Accepted but not wired in this version — no effect until a future release ships the TLS listener.' : 'Off (HTTP only).' },
389
577
  s3_tls_enabled: { requested: s3_tls_enabled, effective: false, note: s3_tls_enabled ? 'Accepted but not wired in this version — no effect until a future release ships the TLS listener.' : 'Off (HTTP only).' },
390
578
  },
391
- ...(note ? { note } : {}),
392
579
  }, null, 2),
393
580
  }],
394
581
  };
@@ -31,7 +31,7 @@ module.exports = function registerManageBackups(server, options = {}) {
31
31
  server.registerTool(
32
32
  'manage_backups',
33
33
  {
34
- title: 'manage_backups',
34
+ title: 'Manage backups',
35
35
  description: 'Manage Relayer configuration backups: list archives, start a backup, restore from an archive, or delete one. Restore OVERWRITES current state and restarts services — always confirm with the operator and state which archive and components first. Backups must be enabled (BACKUP_ENABLED) for list/start.',
36
36
  inputSchema: {
37
37
  action: z.enum(['list', 'start', 'restore', 'delete'])
@@ -146,7 +146,9 @@ module.exports = function registerManageBackups(server, options = {}) {
146
146
  type: 'text',
147
147
  text: JSON.stringify({
148
148
  success: false,
149
- error: `Backup ${action} failed. See server log for detail.`,
149
+ error: err.code === 'SIGNIN_LINK'
150
+ ? err.message
151
+ : `Backup ${action} failed. See server log for detail.`,
150
152
  }),
151
153
  }],
152
154
  isError: true,
@@ -26,7 +26,7 @@ module.exports = function registerRestartService(server, options = {}) {
26
26
  server.registerTool(
27
27
  'restart_service',
28
28
  {
29
- title: 'restart_service',
29
+ title: 'Restart service',
30
30
  description: 'Restart a Relayer service (hostio, gateway, s3gateway, database) or all services. Disruptive: in-flight S3 requests will fail during the restart — confirm with the operator before calling. Verify recovery afterwards with check_relayer_health.',
31
31
  inputSchema: {
32
32
  service: z.enum(SERVICES).optional()