@xns-cloud/relayer-mcp 0.13.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.
package/PRIVACY.md CHANGED
@@ -17,7 +17,10 @@ conversation, your prompts, or the agent's tool calls.
17
17
  ## The server collects nothing
18
18
 
19
19
  There is no analytics, no telemetry, no crash reporting, and no usage counter in this
20
- package. It does not phone home.
20
+ package. It does not phone home. The one tag it sends is on the default compose download of
21
+ `install_relayer`, fetched as `docker-compose.yml?src=mcp`: `src=mcp` is an anonymous source
22
+ tag, the same fixed word for every user and carrying no identifier, used to count downloads by
23
+ source. The `.env` download and a `compose_url` you pass carry no tag.
21
24
 
22
25
  ## What leaves your machine, and where it goes
23
26
 
@@ -28,7 +31,7 @@ Only through the ordinary, visible operation of the tools you ask the agent to r
28
31
  | Creating an account, signing in | Your credentials, entered by you in your own browser | `auth.xns.tech` (Keycloak) |
29
32
  | Claiming a Relayer to your account | The claim session and the installation's identity | `console.xns.tech` |
30
33
  | Reading or changing settings, host selection, backups | The setting values you ask to read or change | `console.xns.tech` |
31
- | Installing or updating the Relayer | An anonymous download of the Docker Compose bundle and images | `releases.xns.tech`; the `prom/node-exporter` image comes from Docker Hub |
34
+ | Installing or updating the Relayer | An anonymous download of the Docker Compose bundle and images; the default compose URL carries the source tag `?src=mcp`, with no identifier | `releases.xns.tech`; the `prom/node-exporter` image comes from Docker Hub |
32
35
 
33
36
  The agent never handles your password. Sign-in happens in your browser against our identity
34
37
  service; the extension receives only a short-lived access token.
@@ -48,17 +51,20 @@ Both are yours to delete at any time.
48
51
 
49
52
  ## Network boundary
50
53
 
51
- No tool sends your sign-in token to a Relayer on the public internet. The tools that send it
52
- to a Relayer (`verify_storage`, `setup_cli_credentials`) run its host through an allowlist
54
+ No tool sends your sign-in token to a Relayer on the public internet. `setup_cli_credentials`
55
+ takes no address: it sends the token only to the server's own Relayer UI (by default
56
+ `http://localhost:8888`). `verify_storage` runs the Relayer host it is given through an allowlist
53
57
  that permits only `localhost`, loopback, RFC 1918 private ranges (`10/8`, `172.16/12`,
54
- `192.168/16`), and `*.local` (`src/lib/hostAllowlist.js`). Three inputs are not limited to
58
+ `192.168/16`), and `*.local` (`src/lib/hostAllowlist.js`). Two inputs are not limited to
55
59
  private addresses: the `host` of `check_relayer_health`, which gets plain HTTP health probes;
56
- the `compose_url` of `install_relayer`, from which the compose file is downloaded; and the S3
57
- `endpoint` of `verify_storage` (by default port 9000 on the Docker host), which gets the
60
+ and the S3 `endpoint` of `verify_storage` (by default port 9000 on the Docker host), which gets the
58
61
  round-trip test as S3 requests signed with a throwaway key (or the keys you pass). A signed
59
62
  request carries the access key id and a signature, never the secret. The tool deletes a
60
63
  throwaway key after the test, pass or fail; if that deletion fails, the reply carries a
61
- `cleanup_warning` and the key stays until you remove it. Apart from those, the only public hosts contacted are the
64
+ `cleanup_warning` and the key stays until you remove it. The `compose_url` of
65
+ `install_relayer`, which is downloaded and run by Docker as root, is limited the same way
66
+ plus `https://releases.xns.tech` and `file://` URLs; any other host is refused before
67
+ anything is downloaded. Apart from those, the only public hosts contacted are the
62
68
  three XNS services named above and, for the `prom/node-exporter` image that an install
63
69
  pulls, Docker Hub.
64
70
 
package/README.md CHANGED
@@ -6,11 +6,12 @@
6
6
 
7
7
  S3-compatible cloud object storage from XNS, set up and managed by your AI assistant. This is the MCP server for [XNS](https://xns.tech). Provides 15 tools that let an AI agent set up the Relayer, the small gateway that runs on your own machine, and manage it day to day over stdio.
8
8
 
9
- In Claude, use the `xns-storage` plugin: it registers this server and adds the step-by-step skills. In Claude Code, run:
9
+ In Claude, use two plugins: `xns-relayer` registers this server and `xns-storage` adds the step-by-step skills. In Claude Code, run:
10
10
 
11
11
  ```text
12
12
  /plugin marketplace add xns-cloud/xns-storage-plugin
13
13
  /plugin install xns-storage@xns-cloud
14
+ /plugin install xns-relayer@xns-cloud
14
15
  ```
15
16
 
16
17
  then say: set up XNS storage
@@ -28,7 +29,7 @@ npx @xns-cloud/relayer-mcp@latest
28
29
  On Ubuntu 24.04 or Debian 12, one command sets up everything:
29
30
 
30
31
  ```bash
31
- curl -fsSL https://releases.xns.tech/relayer/install.sh | sh
32
+ curl -fsSL 'https://releases.xns.tech/relayer/install.sh?src=github' | sh
32
33
  ```
33
34
 
34
35
  The script installs Docker Engine and the compose plugin, adds you to the `docker` group, starts the Relayer in `/opt/xns-relayer`, and waits for the dashboard at `http://localhost:8888`. If Claude Code is present, it also installs Node.js 24 when Node is missing or older and registers this MCP. Log out and back in afterward so the `docker` group applies. On macOS or Windows it installs nothing and points you to Docker Desktop.
@@ -64,27 +65,28 @@ The Relayer runs as a Docker container and persists its data in a Docker volume.
64
65
  On Ubuntu 24.04 or Debian 12, one command installs the Relayer and registers this MCP when Claude Code is present:
65
66
 
66
67
  ```bash
67
- curl -fsSL https://releases.xns.tech/relayer/install.sh | sh
68
+ curl -fsSL 'https://releases.xns.tech/relayer/install.sh?src=github' | sh
68
69
  ```
69
70
 
70
- If you use Claude Code with the `xns-storage` plugin, remove the `relayer` registration the script made; the plugin registers its own.
71
+ When Claude Code is present, the script also registers this server with it.
71
72
 
72
73
  To set it up yourself instead:
73
74
 
74
- **Claude Code** (with the plugin, which registers this server for you):
75
+ **Claude Code** (with the plugins: `xns-relayer` registers this server, `xns-storage` adds the skills):
75
76
 
76
77
  ```text
77
78
  /plugin marketplace add xns-cloud/xns-storage-plugin
78
79
  /plugin install xns-storage@xns-cloud
80
+ /plugin install xns-relayer@xns-cloud
79
81
  ```
80
82
 
81
- Without the plugin, register it by hand:
83
+ Without the plugins, register it by hand:
82
84
 
83
85
  ```bash
84
86
  claude mcp add --scope user relayer -- npx @xns-cloud/relayer-mcp@latest
85
87
  ```
86
88
 
87
- Do one or the other, not both: with both, the 15 tools load twice.
89
+ Do not add the `xns-relayer` plugin beside a `relayer` registration, whether you or the install script made it: with both, the 15 tools load twice. The `xns-storage` plugin carries no server, so it can go beside either.
88
90
 
89
91
  **Claude Desktop / any MCP client** — add to your `claude_desktop_config.json` (or equivalent):
90
92
 
@@ -118,17 +120,17 @@ No separate install step required — npx fetches the package on demand.
118
120
 
119
121
  | # | Tool | Purpose |
120
122
  |---|------|---------|
121
- | 1 | `check_prerequisites` | Verify Docker (local or remote), the compose plugin, Docker socket access (when it is denied, whether the `docker` group membership is missing or not yet live), ports (8888, 9000, 9443), an existing installation, free disk (10 GB on the Docker root and the install directory), and network connectivity. Each failure names the command that fixes it; ports held by a running `xns-relayer` pass. |
123
+ | 1 | `check_prerequisites` | Verify Docker (local or remote), the compose plugin, Docker socket access (when it is denied, whether the `docker` group membership is missing or not yet live), ports (8888, 9000, 9443), an existing installation, free disk (10 GB on the Docker root and the install directory), the root mount's propagation for the Docker daemon (a private `/`, the WSL2 default, leaves the containers stuck in "Created"), and network connectivity. Each failure names the command that fixes it; ports held by a running `xns-relayer` pass. |
122
124
  | 2 | `start_registration` | Get the browser sign-up URL for creating an XNS account — the agent never handles credentials. |
123
125
  | 3 | `check_email_verified` | Poll email verification status (15s interval, 30-min timeout). |
124
- | 4 | `install_relayer` | Fetch the canonical release channel bundle — relayer + Prometheus/Grafana monitoring stack (`https://releases.xns.tech/relayer/release/docker-compose.yml` and its `.env`, anonymous pull, no `docker login`) — add the ports to that `.env`, and start the containers. 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 fix. **Fresh installs only** — see [Fresh installs vs. existing deployments](#fresh-installs-vs-existing-deployments). The user authors nothing; `compose_url` is an optional override for custom installs. |
126
+ | 4 | `install_relayer` | Fetch the canonical release channel bundle — relayer + Prometheus/Grafana monitoring stack (`https://releases.xns.tech/relayer/release/docker-compose.yml?src=mcp` and its `.env`, anonymous pull, no `docker login`; `?src=mcp` is an anonymous source tag used to count downloads by source, with no identifier, and the `.env` and a `compose_url` override carry no tag) — add the ports to that `.env`, and start the containers. 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 fix. **Fresh installs only** — see [Fresh installs vs. existing deployments](#fresh-installs-vs-existing-deployments). The user authors nothing; `compose_url` is an optional override for custom installs. |
125
127
  | 5 | `check_relayer_health` | Poll UI, S3, HostIO, and the monitoring sidecars (10s interval, 300s timeout). A missing monitoring stack reports as degraded without blocking the flow. Before the owner claims the Relayer and signs in, the S3 gateway is not started yet, so the tool returns `awaiting_claim: true` when the UI answers, the Docker CLI reaches the checked host, and the `xns-relayer` container holds no Muse token yet. When the token cannot be read (no such container, Docker unreachable), S3 down stays unhealthy. Targets the Docker host automatically. |
126
128
  | 6 | `start_claim` | Initiate a claim session — returns a URL for browser confirmation. |
127
129
  | 7 | `check_claim_status` | Poll claim state (STATE_1 / STATE_2 / STATE_3). |
128
130
  | 8 | `get_host_tags` | Retrieve available host tags for VPD configuration, plus the currently applied data/parity selection (read-back with an `is_default` flag). |
129
131
  | 9 | `configure_vpd` | Set data/parity host selection via CEL expressions. `dry_run: true` previews the matched host counts without applying (requires a Relayer build with the HostIO evaluate endpoint; older builds report `preview_supported: false`). |
130
132
  | 10 | `verify_storage` | Round-trip S3 test (create bucket, put object, get object) against the S3 gateway. Provisions a temporary scoped IAM credential automatically from your OIDC session — no manual key management needed. The tool attempts to remove test data and the throwaway credential after the test; a `cleanup_warning` is reported if any resource could not be removed. `relayer_ui_url` must point at a loopback or private-network host. |
131
- | 11 | `setup_cli_credentials` | Provision S3 IAM credentials and write `~/.xns/credentials` so the XNS CLI works without further configuration. |
133
+ | 11 | `setup_cli_credentials` | Provision S3 IAM credentials and save them in `~/.xns/credentials` for the XNS CLI. The Relayer user it makes, `xns-cli`, can read, write and delete in every bucket. Takes an optional `ui_port` (default 8888) for a Relayer installed on another UI port; the host is always this machine. Profiles in the file that hold keys are kept: the new keys go in `default` if it is absent or holds none (a `default` without keys is replaced), otherwise in a new profile that the reply names. |
132
134
  | 12 | `describe_settings` | List the adjustable settings — worker/concurrency tuning, backup schedule, cost center (CCID) — with current values, defaults, and guidance. The MCP deliberately exposes only this curated set, never the full advanced catalog. |
133
135
  | 13 | `update_settings` | Apply a map of setting changes (whitelist-enforced). Returns `require_restart`. **Requires relayer-ui >= 3.43.3** — older servers can clobber the database password on config round-trips. |
134
136
  | 14 | `restart_service` | Restart `hostio`, `gateway`, `s3gateway`, `database`, or all services. Disruptive; pairs with `check_relayer_health` to verify recovery. |
@@ -217,10 +219,10 @@ server is in [PRIVACY.md](./PRIVACY.md).
217
219
 
218
220
  The short version:
219
221
 
220
- - **No telemetry.** No analytics, crash reporting, or usage counters. It does not phone home.
222
+ - **No telemetry.** No analytics, crash reporting, or usage counters. It does not phone home. The one tag it adds: `install_relayer` fetches the default compose file as `docker-compose.yml?src=mcp`, a fixed source tag with no identifier, used to count downloads by source.
221
223
  - **Tokens live in memory only.** OIDC access tokens are never written to disk; they are discarded when the process exits.
222
224
  - **The agent never sees your password.** Sign-in happens in your own browser against `auth.xns.tech`.
223
- - **Credentials stay on your network.** The tools that send a token to a Relayer (`verify_storage`, `setup_cli_credentials`) run its host through an allowlist (`localhost`, loopback, RFC 1918, `*.local`). `check_relayer_health` sends plain HTTP health probes, with no credentials, to the Docker host or the `host` you pass, which is not limited to private addresses, `install_relayer` downloads from any `compose_url` you pass, and the S3 test in `verify_storage` goes to the `endpoint` you pass (requests are signed, so the secret key is never sent). Otherwise the public hosts contacted are the three XNS services `auth.xns.tech`, `console.xns.tech` and `releases.xns.tech`, and Docker Hub for the `prom/node-exporter` image that an install pulls.
225
+ - **Credentials stay on your network.** `verify_storage` runs the Relayer host you pass through an allowlist (`localhost`, loopback, RFC 1918, `*.local`) before sending a token, and `setup_cli_credentials` takes no URL and sends its token only to the server's own Relayer UI. `check_relayer_health` sends plain HTTP health probes, with no credentials, to the Docker host or the `host` you pass, which is not limited to private addresses, `install_relayer` downloads a `compose_url` override only from https on `releases.xns.tech`, a `file://` URL, or a loopback, private-network or `.local` host, and the S3 test in `verify_storage` goes to the `endpoint` you pass (requests are signed, so the secret key is never sent). Otherwise the public hosts contacted are the three XNS services `auth.xns.tech`, `console.xns.tech` and `releases.xns.tech`, and Docker Hub for the `prom/node-exporter` image that an install pulls.
224
226
  - **Your stored objects never pass through it.** The Relayer you host handles your data directly.
225
227
 
226
228
  ## Desktop extension (MCPB)
package/manifest.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "manifest_version": "0.3",
3
3
  "name": "relayer-mcp",
4
4
  "display_name": "XNS Cloud Storage",
5
- "version": "0.13.0",
5
+ "version": "0.14.3",
6
6
  "description": "S3-compatible cloud object storage from XNS, set up and managed by your AI assistant.",
7
7
  "long_description": "XNS is S3-compatible cloud object storage. $6.00 per TB per month. $0 egress, uncapped. 30-day minimum retention, no early-delete fee. You reach it through the Relayer, a small gateway that runs on your own machine, so the S3 endpoint and keys stay on hardware you control. This extension gives Claude 15 tools that walk the whole lifecycle — check prerequisites, register an XNS account, install the Relayer via Docker Compose, claim it to your account, choose which hosts store your data (VPD), verify an S3 round trip, provision CLI credentials, then handle day-2 work: settings, service restarts, and configuration backups.\n\nThe server runs locally on your machine and talks to your Relayer over loopback or your private network only — connections to public addresses are refused by design. Sign-in happens in your browser against XNS's identity service; the agent never sees your password.",
8
8
  "author": {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@xns-cloud/relayer-mcp",
3
3
  "mcpName": "tech.xns/relayer",
4
- "version": "0.13.0",
4
+ "version": "0.14.3",
5
5
  "description": "S3-compatible cloud object storage from XNS, set up and managed by your AI assistant.",
6
6
  "author": "SCP Corp",
7
7
  "license": "Apache-2.0",
@@ -3,6 +3,43 @@
3
3
  const { acquireToken, refreshToken } = require('./oidcAuth');
4
4
  const sharedTokenState = require('./tokenState');
5
5
 
6
+ // One pending browser sign-in per token state, shared by every tool that
7
+ // builds a token manager on that state. Keyed by the state module so
8
+ // injected test state stays isolated from the real one.
9
+ const pendingSignIns = new WeakMap();
10
+
11
+ // Why the last sign-in failed after its link was handed out, per token state.
12
+ // The next link message reports it once, so the person is not sent round new
13
+ // links with no word about why the last one did not work.
14
+ const lastSignInFailures = new WeakMap();
15
+
16
+ // A fixed reason for why a sign-in stopped. The raw error can carry the
17
+ // provider's response body, so only these sentences reach the person; the
18
+ // full text goes to the server log.
19
+ function signInFailureReason(err) {
20
+ const message = err && err.message ? String(err.message) : '';
21
+ if (/^OIDC sign-in timed out/.test(message)) return 'it timed out before the browser came back';
22
+ const oidc = message.match(/^OIDC error: ([a-z_]{1,64})$/);
23
+ if (oidc) return `the sign-in server returned ${oidc[1]}`;
24
+ const exchange = message.match(/^Token exchange failed \(HTTP (\d{3})\)/);
25
+ if (exchange) return `the token exchange failed (HTTP ${exchange[1]})`;
26
+ return 'it stopped with an error (see the server log)';
27
+ }
28
+
29
+ // The sign-in link redirects to 127.0.0.1:<port> on the machine running this
30
+ // server, so the browser has to reach that port.
31
+ function signInLinkMessage(url) {
32
+ const message = `Open this link in a browser on this machine to sign in to XNS (on WSL the Windows browser works), then call this tool again: ${url}`;
33
+ let port = '';
34
+ try {
35
+ port = new URL(new URL(url).searchParams.get('redirect_uri')).port;
36
+ } catch {
37
+ return message;
38
+ }
39
+ if (!port) return message;
40
+ return `${message}\nIf your browser is on another machine, first forward the port with: ssh -L ${port}:127.0.0.1:${port} <this machine>`;
41
+ }
42
+
6
43
  /**
7
44
  * Create an ensureToken function with injectable deps for testing.
8
45
  * Used by getHostTags and configureVpd — both need OIDC token
@@ -51,10 +88,58 @@ function createTokenManager(options = {}) {
51
88
  }
52
89
  }
53
90
 
54
- // Full OIDC sign-in
55
- const newState = await _acquireToken(oidcOpts);
56
- _tokenState.set(newState);
57
- return newState.access_token;
91
+ // Full OIDC sign-in — join one already waiting for the person, if any
92
+ let pending = pendingSignIns.get(_tokenState);
93
+ if (pending) return raceSignInOrLink(pending);
94
+
95
+ pending = startSignIn();
96
+ pendingSignIns.set(_tokenState, pending);
97
+ pending.signIn.then(
98
+ () => { clearPending(pending); },
99
+ (err) => {
100
+ if (pending.linkHandedOut) {
101
+ console.error(`[sign-in] the sign-in did not finish: ${err && err.message ? err.message : String(err)}`);
102
+ lastSignInFailures.set(_tokenState, signInFailureReason(err));
103
+ }
104
+ clearPending(pending);
105
+ },
106
+ );
107
+
108
+ return raceSignInOrLink(pending);
109
+ }
110
+
111
+ // Either the sign-in finishes, or the browser could not be opened and the
112
+ // person needs the link. The sign-in keeps running in that case. A call that
113
+ // joins a pending sign-in gets the same race, so it never waits blind.
114
+ function raceSignInOrLink(pending) {
115
+ return Promise.race([
116
+ pending.signIn,
117
+ pending.link.then((url) => {
118
+ pending.linkHandedOut = true;
119
+ const failure = lastSignInFailures.get(_tokenState);
120
+ lastSignInFailures.delete(_tokenState);
121
+ const prefix = failure ? `The last sign-in did not finish: ${failure}. ` : '';
122
+ const err = new Error(prefix + signInLinkMessage(url));
123
+ err.code = 'SIGNIN_LINK';
124
+ err.authorizeUrl = url;
125
+ throw err;
126
+ }),
127
+ ]);
128
+ }
129
+
130
+ function startSignIn() {
131
+ let reportLink;
132
+ const link = new Promise((resolve) => { reportLink = resolve; });
133
+ const signIn = _acquireToken({ ...oidcOpts, onBrowserOpenFailed: reportLink })
134
+ .then((newState) => {
135
+ _tokenState.set(newState);
136
+ return newState.access_token;
137
+ });
138
+ return { signIn, link };
139
+ }
140
+
141
+ function clearPending(pending) {
142
+ if (pendingSignIns.get(_tokenState) === pending) pendingSignIns.delete(_tokenState);
58
143
  }
59
144
 
60
145
  /**
@@ -29,7 +29,9 @@ const DEFAULT_SIGNIN_TIMEOUT_MS = 1800000; // 30 minutes
29
29
  * @param {object} [opts.httpClient] - Injected HTTP client (testing)
30
30
  * @param {function} [opts.openBrowser] - Injected browser opener (testing)
31
31
  * @param {function} [opts.createServer] - Injected http.createServer (testing)
32
- * @returns {Promise<{access_token: string, expires_at: number, refresh_token: string, authorize_url: string}>}
32
+ * @param {function} [opts.onBrowserOpenFailed] - Called with the authorize URL when the
33
+ * browser cannot be opened; the loopback listener keeps waiting for the callback
34
+ * @returns {Promise<{access_token: string, expires_at: number, refresh_token: string}>}
33
35
  */
34
36
  async function acquireToken(opts = {}) {
35
37
  const clientId = opts.clientId || DEFAULT_CLIENT_ID;
@@ -55,6 +57,7 @@ async function acquireToken(opts = {}) {
55
57
  openBrowser,
56
58
  createServer: _createServer,
57
59
  timeoutMs: opts.timeoutMs,
60
+ onBrowserOpenFailed: opts.onBrowserOpenFailed,
58
61
  });
59
62
 
60
63
  // 5. Exchange code for tokens
@@ -79,7 +82,6 @@ async function acquireToken(opts = {}) {
79
82
  access_token: data.access_token,
80
83
  refresh_token: data.refresh_token,
81
84
  expires_at: Date.now() + (data.expires_in * 1000),
82
- authorize_url: undefined, // already consumed
83
85
  };
84
86
  }
85
87
 
@@ -157,13 +159,25 @@ function captureAuthCode(opts) {
157
159
  const srv = createServer((req, res) => {
158
160
  const url = new URL(req.url, `http://127.0.0.1`);
159
161
 
162
+ // Validate the OIDC state first (CSRF). Any local process or web page can
163
+ // reach this port, so a request with a missing or wrong state is answered
164
+ // with 400 and ignored; it must not end the shared sign-in.
165
+ const returnedState = url.searchParams.get('state');
166
+ if (!returnedState || returnedState !== expectedState) {
167
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
168
+ res.end('<html><body><h1>Invalid state parameter</h1><p>This request does not belong to the current sign-in.</p></body></html>');
169
+ return; // Keep waiting for the real redirect
170
+ }
171
+
160
172
  const error = url.searchParams.get('error');
161
173
  if (error) {
162
174
  res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
163
175
  res.end('<html><body><h1>Authentication failed</h1><p>You can close this window.</p></body></html>');
164
176
  clearTimeout(timeoutHandle);
165
177
  srv.close();
166
- return reject(new Error(`OIDC error: ${error} — ${url.searchParams.get('error_description') || ''}`));
178
+ // Only the error code reaches the caller; error_description is free text.
179
+ const errorCode = /^[a-z_]{1,64}$/.test(error) ? error : 'unknown';
180
+ return reject(new Error(`OIDC error: ${errorCode}`));
167
181
  }
168
182
 
169
183
  const code = url.searchParams.get('code');
@@ -173,16 +187,6 @@ function captureAuthCode(opts) {
173
187
  return; // Don't close server — wait for the real redirect
174
188
  }
175
189
 
176
- // R5-STATE-1: Validate OIDC state parameter to prevent CSRF
177
- const returnedState = url.searchParams.get('state');
178
- if (returnedState !== expectedState) {
179
- res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
180
- res.end('<html><body><h1>Invalid state parameter</h1><p>Possible CSRF attack. Please try again.</p></body></html>');
181
- clearTimeout(timeoutHandle);
182
- srv.close();
183
- return reject(new Error('OIDC callback state mismatch — possible CSRF. Please try again.'));
184
- }
185
-
186
190
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
187
191
  res.end('<html><body><h1>Authentication successful</h1><p>You can close this window and return to the agent.</p></body></html>');
188
192
  clearTimeout(timeoutHandle);
@@ -227,10 +231,17 @@ function captureAuthCode(opts) {
227
231
  reject(new Error(`OIDC sign-in timed out after ${Math.round(timeoutMs / 60000)} minutes. Please try again.`));
228
232
  }, timeoutMs);
229
233
 
230
- // Open browser or return URL for the agent to present
231
- openBrowser(authorizeUrl).catch(() => {
232
- // If browser open fails, the authorize_url is still available
233
- });
234
+ // Open the browser. When that fails (no desktop, SSH, WSL) the person
235
+ // can still sign in by hand, so hand the URL to the caller and keep
236
+ // the listener waiting for the callback.
237
+ const reportOpenFailure = () => {
238
+ if (typeof opts.onBrowserOpenFailed === 'function') opts.onBrowserOpenFailed(authorizeUrl);
239
+ };
240
+ try {
241
+ Promise.resolve(openBrowser(authorizeUrl)).catch(reportOpenFailure);
242
+ } catch {
243
+ reportOpenFailure();
244
+ }
234
245
  });
235
246
  });
236
247
  }
@@ -27,6 +27,13 @@ const DEFAULT_INSTALL_DIR = '/opt/xns-relayer';
27
27
  const MIN_FREE_BYTES = 10 * 10 ** 9;
28
28
  const BYTES_PER_GB = 10 ** 9;
29
29
 
30
+ // Makes / shared in the mount namespace the Docker daemon runs in. The release
31
+ // compose mounts /mnt and / with rslave propagation, which needs a shared or
32
+ // slave root. The daemon runs in systemd's namespace, so a plain
33
+ // `mount --make-rshared /` in the user's shell is not enough.
34
+ // The PID is the daemon the check read, so the fix targets the same process.
35
+ const makeRootSharedCommand = (pid) => `sudo nsenter -t ${pid} -m mount --make-rshared /`;
36
+
30
37
  const GROUP_NOTE = 'the Docker socket refuses this user until the docker group applies (see docker_group)';
31
38
 
32
39
  /**
@@ -99,6 +106,31 @@ async function isInDockerGroup(readFile, username) {
99
106
  }
100
107
  }
101
108
 
109
+ /**
110
+ * Propagation state of the "/" mount in a mountinfo file: 'shared', 'slave'
111
+ * (a master: tag) or 'private'; null when no "/" entry is found. When "/" is
112
+ * mounted over more than once, the top mount is the "/" entry that no other
113
+ * "/" entry names as its parent; line order says nothing about stacking.
114
+ */
115
+ function rootPropagation(mountinfo) {
116
+ const roots = [];
117
+ for (const line of String(mountinfo).split('\n')) {
118
+ const fields = line.trim().split(' ');
119
+ if (fields.length < 7 || fields[4] !== '/') continue;
120
+ const separator = fields.indexOf('-');
121
+ const optional = separator === -1 ? fields.slice(6) : fields.slice(6, separator);
122
+ let state = 'private';
123
+ if (optional.some((f) => f.startsWith('shared:'))) state = 'shared';
124
+ else if (optional.some((f) => f.startsWith('master:'))) state = 'slave';
125
+ roots.push({ id: fields[0], parent: fields[1], state });
126
+ }
127
+ if (roots.length === 0) return null;
128
+ const parents = new Set(roots.map((r) => r.parent));
129
+ const top = roots.filter((r) => !parents.has(r.id));
130
+ // A cycle or several unrelated tops cannot be told apart; read it as unknown.
131
+ return top.length === 1 ? top[0].state : null;
132
+ }
133
+
102
134
  module.exports = function registerCheckPrerequisites(server, options = {}) {
103
135
  const docker = options.dockerUtil || createDockerUtil(options);
104
136
  const http = options.httpClient || createHttpClient(options);
@@ -107,6 +139,84 @@ module.exports = function registerCheckPrerequisites(server, options = {}) {
107
139
  const _statfs = options.statfs || require('fs').promises.statfs;
108
140
  const _readFile = options.fs?.readFile || require('fs').promises.readFile;
109
141
  const _userInfo = options.userInfo || os.userInfo;
142
+ // Reads of /proc go through these so tests use fixtures, not the real /proc.
143
+ const _platform = options.platform || process.platform;
144
+ const _env = options.env || process.env;
145
+ const _readdir = options.procFs?.readdir || require('fs').promises.readdir;
146
+ const _procRead = options.procFs?.readFile || require('fs').promises.readFile;
147
+
148
+ /** PIDs of every dockerd running on this machine, lowest first. */
149
+ async function findLocalDockerds() {
150
+ const entries = await _readdir('/proc');
151
+ const pids = entries.map(String).filter((e) => /^\d+$/.test(e)).sort((a, b) => Number(a) - Number(b));
152
+ const found = [];
153
+ for (const pid of pids) {
154
+ try {
155
+ const comm = await _procRead(`/proc/${pid}/comm`, 'utf8');
156
+ if (String(comm).trim() === 'dockerd') found.push(pid);
157
+ } catch {
158
+ // the process ended or is not readable; keep looking
159
+ }
160
+ }
161
+ return found;
162
+ }
163
+
164
+ async function isWsl() {
165
+ if (_env.WSL_DISTRO_NAME) return true;
166
+ try {
167
+ return /microsoft/i.test(String(await _procRead('/proc/version', 'utf8')));
168
+ } catch {
169
+ return false;
170
+ }
171
+ }
172
+
173
+ /**
174
+ * The release compose mounts / and /mnt with rslave propagation, which needs
175
+ * "/" to be shared or slave in the Docker daemon's mount namespace. A private
176
+ * root (WSL2 default) leaves the containers stuck in Created. Only a dockerd
177
+ * on this machine can be checked; Docker Desktop, a remote daemon, macOS and
178
+ * Windows skip it and never fail.
179
+ */
180
+ async function checkRootMountPropagation(dockerHost) {
181
+ const name = 'root_mount_propagation';
182
+ const skipped = (why) => ({ name, passed: true, skipped: true, detail: `Root mount check skipped — ${why}.` });
183
+ if (_platform !== 'linux') return skipped('only Linux hosts are checked');
184
+ if (dockerHost.remote) return skipped(`the Docker daemon runs on ${dockerHost.host}`);
185
+ let pids;
186
+ try {
187
+ pids = await findLocalDockerds();
188
+ } catch (err) {
189
+ console.error(`[check_prerequisites] could not scan /proc: ${err.message}`);
190
+ return skipped('the process list could not be read');
191
+ }
192
+ // With several daemons (for example a system one and a rootless one) the
193
+ // one behind the Docker endpoint cannot be told from the process list.
194
+ if (pids.length > 1) return skipped(`${pids.length} Docker daemon processes run on this machine (PIDs ${pids.join(', ')}), so the one this install uses cannot be picked`);
195
+ const pid = pids.length === 1 ? pids[0] : null;
196
+ if (pid === null) return skipped('no Docker daemon process runs on this machine (Docker Desktop or a remote daemon keeps its own mounts)');
197
+ // Only the daemon's own mountinfo says what its mount namespace looks like;
198
+ // another process (PID 1) can sit in a different namespace.
199
+ let mountinfo = null;
200
+ try {
201
+ mountinfo = await _procRead(`/proc/${pid}/mountinfo`, 'utf8');
202
+ } catch (err) {
203
+ console.error(`[check_prerequisites] could not read /proc/${pid}/mountinfo: ${err.message}`);
204
+ }
205
+ const state = mountinfo === null ? null : rootPropagation(mountinfo);
206
+ if (state === null) return skipped('the root mount could not be read');
207
+ if (state !== 'private') {
208
+ return { name, passed: true, detail: `The root mount is ${state} for the Docker daemon, as the Relayer compose needs` };
209
+ }
210
+ const wslNote = (await isWsl())
211
+ ? ' WSL resets this on every restart, so run it again after wsl --shutdown or a reboot, before each docker compose up.'
212
+ : '';
213
+ return {
214
+ name,
215
+ passed: false,
216
+ detail: 'The root mount (/) is private for the Docker daemon, so the Relayer containers would stay stuck in "Created" and the install would never become healthy',
217
+ remediation: `Make / shared in the Docker daemon's mount namespace: ${makeRootSharedCommand(pid)} — then run the install again.${wslNote}`,
218
+ };
219
+ }
110
220
 
111
221
  /**
112
222
  * install_relayer is fresh-install only; an existing xns-relayer container
@@ -463,6 +573,11 @@ module.exports = function registerCheckPrerequisites(server, options = {}) {
463
573
  if (!fixedNames.passed) allPassed = false;
464
574
  checks.push(fixedNames);
465
575
 
576
+ // 3a-2. A private root mount leaves the containers stuck in Created.
577
+ const rootMount = await checkRootMountPropagation(dockerHost);
578
+ if (!rootMount.passed) allPassed = false;
579
+ checks.push(rootMount);
580
+
466
581
  // 3b. Existing installation — warn early, here.
467
582
  checks.push(await checkExistingInstall(dockerState));
468
583
 
@@ -5,6 +5,7 @@ const os = require('os');
5
5
  const path = require('path');
6
6
  const net = require('net');
7
7
  const { createDockerUtil, redactEndpoint, classifyDockerFailure } = require('../lib/dockerUtil');
8
+ const { validateHostAllowlist } = require('../lib/hostAllowlist');
8
9
 
9
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';
10
11
 
@@ -109,9 +110,68 @@ function isValidBindAddress(value) {
109
110
  // monitoring stack), published on the XNS releases registry and served
110
111
  // login-free. THE default install source. Its .env (COMPOSE_PROFILES and the
111
112
  // rest of the release settings) sits beside it and is fetched on every run.
112
- const CHANNEL_COMPOSE_URL = 'https://releases.xns.tech/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';
113
115
  const CHANNEL_ENV_FILE = '.env';
114
116
 
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
+ }
166
+
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
+
115
175
  // Where a release .env that stops short is reported.
116
176
  const BUGS_URL = require('../../package.json').bugs.url;
117
177
 
@@ -280,12 +340,12 @@ module.exports = function registerInstallRelayer(server, options = {}) {
280
340
  'install_relayer',
281
341
  {
282
342
  title: 'Install the Relayer',
283
- 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.\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.',
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.',
284
344
  inputSchema: {
285
345
  install_path: z.string().optional().default('/opt/xns-relayer').describe('Directory to install the compose file into'),
286
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.'),
287
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.'),
288
- 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.'),
289
349
  // R5 input boundary — see isValidBindAddress above for why each
290
350
  // documented address form is validated whole rather than by charset.
291
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.'),
@@ -302,6 +362,12 @@ module.exports = function registerInstallRelayer(server, options = {}) {
302
362
  try {
303
363
  const { execFile: nodeExecFile } = require('child_process');
304
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
+ }
305
371
  const composePath = path.join(install_path, 'docker-compose.yml');
306
372
  const envPath = path.join(install_path, '.env');
307
373
 
@@ -358,15 +424,30 @@ module.exports = function registerInstallRelayer(server, options = {}) {
358
424
  });
359
425
  });
360
426
 
361
- // curl -fsSL -o <outPath> <url> (execFile, no shell). Rejects
362
- // with curl's own error; each caller chooses the message.
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.
363
431
  const curlTo = (url, outPath) => new Promise((resolve, reject) => {
364
- execFileFn('curl', ['-fsSL', '-o', outPath, url], { timeout: 60000 }, (err) => {
432
+ execFileFn('curl', ['-q', '-fsSL', '-g', '-o', outPath, url], { timeout: 60000 }, (err) => {
365
433
  if (err) return reject(err);
366
434
  resolve();
367
435
  });
368
436
  });
369
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
+
370
451
  // Download the release compose and .env into an owner-only
371
452
  // temporary folder, read them and run the two checks. The folder
372
453
  // is removed whatever happens; a failed removal is logged and
@@ -418,9 +499,15 @@ module.exports = function registerInstallRelayer(server, options = {}) {
418
499
  let source;
419
500
  if (compose_url) {
420
501
  // Override path: make the folder, then download a custom
421
- // compose straight into it.
502
+ // compose and write it into it.
422
503
  await mkdirInstallPath();
423
- await curlTo(compose_url, composePath).catch((err) => {
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
+ }
424
511
  throw safeError('Failed to download compose file', err);
425
512
  });
426
513
  source = 'compose_url';
@@ -462,6 +549,7 @@ module.exports = function registerInstallRelayer(server, options = {}) {
462
549
  compose_path: composePath,
463
550
  install_path,
464
551
  source,
552
+ compose_host: composeCheck ? composeCheck.host : new URL(channelComposeUrl).host,
465
553
  // D5/W5: state the binding at install time, out-of-band, so a
466
554
  // refused connection is explainable later. Two statements, never
467
555
  // merged (PRD §7): `composed_from` is what this installer asserts
@@ -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,
@@ -1,11 +1,169 @@
1
1
  'use strict';
2
2
 
3
+ const crypto = require('crypto');
3
4
  const fs = require('fs');
4
5
  const path = require('path');
5
6
  const os = require('os');
7
+ const { isDeepStrictEqual } = require('util');
6
8
  const { z } = require('zod');
7
9
  const { createHttpClient } = require('../lib/httpClient');
8
- const { validateHostAllowlist, NO_REDIRECT_TOKEN_CONFIG } = require('../lib/hostAllowlist');
10
+ const { createTokenManager } = require('../lib/ensureToken');
11
+ const { NO_REDIRECT_TOKEN_CONFIG } = require('../lib/hostAllowlist');
12
+
13
+ const DEFAULT_UI_PORT = 8888;
14
+ const RELAYER_UI_BASE = `http://localhost:${DEFAULT_UI_PORT}`;
15
+
16
+ // The Relayer user, its policy, and the profile used when `default` already holds keys.
17
+ const CLI_NAME = 'xns-cli';
18
+
19
+ /**
20
+ * DECISION: the key is the account owner's own, so it gets the gateway's ReadWrite actions
21
+ * plus s3:DeleteBucket, on every bucket. The actions are spelled out in a policy of its own
22
+ * because a Relayer already installed may not have a built-in set by that name.
23
+ */
24
+ const CLI_POLICY = {
25
+ Version: '2012-10-17',
26
+ Statement: [{
27
+ Effect: 'Allow',
28
+ Action: [
29
+ 's3:GetObject',
30
+ 's3:GetObjectVersion',
31
+ 's3:HeadObject',
32
+ 's3:ListBucket',
33
+ 's3:ListBucketVersions',
34
+ 's3:ListAllMyBuckets',
35
+ 's3:GetBucketLocation',
36
+ 's3:GetBucketPolicy',
37
+ 's3:GetBucketTagging',
38
+ 's3:GetBucketVersioning',
39
+ 's3:GetObjectTagging',
40
+ 's3:GetObjectAttributes',
41
+ 's3:ListBucketMultipartUploads',
42
+ 's3:ListMultipartUploadParts',
43
+ 's3:PutObject',
44
+ 's3:DeleteObject',
45
+ 's3:CreateMultipartUpload',
46
+ 's3:UploadPart',
47
+ 's3:CompleteMultipartUpload',
48
+ 's3:AbortMultipartUpload',
49
+ 's3:PutObjectTagging',
50
+ 's3:DeleteObjectTagging',
51
+ 's3:CreateBucket',
52
+ 's3:DeleteBucket',
53
+ ],
54
+ Resource: ['arn:aws:s3:::*', 'arn:aws:s3:::*/*'],
55
+ }],
56
+ };
57
+
58
+ // How many policy names to try when earlier ones hold other rules.
59
+ const MAX_POLICY_NAMES = 10;
60
+
61
+ const BAD_FILE_ERROR = '~/.xns/credentials exists but could not be read as an XNS credentials file, so it was left as it is. Ask the user to fix it or move it aside, then call setup_cli_credentials again.';
62
+
63
+ const NOT_SAVED_ERROR = 'The Relayer created the user xns-cli, but its keys could not be saved to ~/.xns/credentials. See the server log for detail. Ask the user to delete the user xns-cli in the Relayer UI and make sure that file can be written, then call setup_cli_credentials again.';
64
+
65
+ const NO_POLICY_ERROR = 'The Relayer did not give the new user xns-cli its permissions, so that user was deleted and nothing was saved to ~/.xns/credentials. See the server log for detail, then call setup_cli_credentials again.';
66
+
67
+ const USER_LEFT_ERROR = 'The Relayer created the user xns-cli but did not give it its permissions, and that user could not be deleted. Nothing was saved to ~/.xns/credentials. See the server log for detail. Ask the user to delete the user xns-cli in the Relayer UI, then call setup_cli_credentials again.';
68
+
69
+ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
70
+
71
+ /**
72
+ * Read the credentials file the xns CLI uses. Absent file: an empty set. A file that is
73
+ * there but is not one the CLI would load throws CREDS_UNREADABLE, because writing over
74
+ * it would drop keys a Relayer shows only once.
75
+ */
76
+ function readCredentials(credsPath) {
77
+ let creds;
78
+ try {
79
+ creds = JSON.parse(fs.readFileSync(credsPath, 'utf8'));
80
+ } catch (err) {
81
+ if (err.code === 'ENOENT') return { version: 1, profiles: {} };
82
+ // JSON.parse quotes the text it failed on, which may be a key: never pass it on.
83
+ throw Object.assign(new Error(`credentials file unreadable (${err.code || 'not JSON'})`), { code: 'CREDS_UNREADABLE' });
84
+ }
85
+ if (!isPlainObject(creds) || creds.version !== 1 || !isPlainObject(creds.profiles)) {
86
+ throw Object.assign(new Error('credentials file is not XNS version 1'), { code: 'CREDS_UNREADABLE' });
87
+ }
88
+ return creds;
89
+ }
90
+
91
+ /**
92
+ * DECISION: a profile that holds a secret key is never replaced, `default` included. The
93
+ * new keys go to `default` when it is absent or keyless (`xns register` writes it keyless),
94
+ * otherwise to the first free xns-cli, xns-cli-2, ... name.
95
+ */
96
+ function pickProfileName(profiles) {
97
+ if (!Object.hasOwn(profiles, 'default') || !profiles.default?.secret_access_key) return 'default';
98
+ let name = CLI_NAME;
99
+ for (let n = 2; Object.hasOwn(profiles, name); n += 1) name = `${CLI_NAME}-${n}`;
100
+ return name;
101
+ }
102
+
103
+ /**
104
+ * Replace the file in one step, so a failed write cannot cut short the profiles in it.
105
+ * The temporary file is this write's own: the xns CLI or a second server may be saving at
106
+ * the same moment, and must not take it. 'wx' creates it fresh, which makes mode 0600 hold
107
+ * whatever the old file's mode was.
108
+ */
109
+ function writeCredentials(credsPath, creds) {
110
+ fs.mkdirSync(path.dirname(credsPath), { recursive: true, mode: 0o700 });
111
+ const tmp = `${credsPath}.${crypto.randomUUID()}.tmp`;
112
+ try {
113
+ fs.writeFileSync(tmp, JSON.stringify(creds, null, 2), { mode: 0o600, flag: 'wx' });
114
+ fs.renameSync(tmp, credsPath);
115
+ } catch (err) {
116
+ fs.rmSync(tmp, { force: true });
117
+ throw err;
118
+ }
119
+ }
120
+
121
+ // For the server log only: the Relayer UI answers a gateway refusal as HTTP 200 and a message.
122
+ const describeAnswer = ({ status, data }) => `HTTP ${status}${data?.message ? `: ${data.message}` : ''}`;
123
+
124
+ /**
125
+ * Create the policy and return its name. The gateway refuses a name that is taken and keeps
126
+ * the rules stored under it, and deleting a user leaves its policy behind, so an earlier run
127
+ * may have made this one. DECISION: a policy with these same rules is used as it is; one with
128
+ * other rules is somebody else's, so it is neither used nor changed and the next name is tried.
129
+ */
130
+ async function createCliPolicy(http, mcBase, config) {
131
+ for (let n = 1; n <= MAX_POLICY_NAMES; n += 1) {
132
+ const name = n === 1 ? CLI_NAME : `${CLI_NAME}-${n}`;
133
+ const created = await http.post(
134
+ `${mcBase}/policy-create`,
135
+ { name, type: 'json', json: JSON.stringify(CLI_POLICY) },
136
+ config
137
+ );
138
+ if (created.status === 200 && created.data?.success === true) return name;
139
+
140
+ const existing = await http.get(`${mcBase}/policy/${name}`, config);
141
+ if (existing.status !== 200 || !isPlainObject(existing.data?.policy_json)) {
142
+ throw new Error(`policy create failed (${describeAnswer(created)}); reading ${name}: ${describeAnswer(existing)}`);
143
+ }
144
+ if (isDeepStrictEqual(existing.data.policy_json, CLI_POLICY)) return name;
145
+ }
146
+ throw new Error(`policy create failed: ${MAX_POLICY_NAMES} names are taken`);
147
+ }
148
+
149
+ async function attachCliPolicy(http, mcBase, policy, config) {
150
+ const answer = await http.post(`${mcBase}/policy`, { name: CLI_NAME, policy }, config);
151
+ if (answer.status !== 200 || answer.data?.status !== 'attached') {
152
+ throw new Error(`policy attach failed (${describeAnswer(answer)})`);
153
+ }
154
+ }
155
+
156
+ /** Delete the user this run made. Returns whether the Relayer says it is gone. */
157
+ async function deleteCliUser(http, mcBase, config) {
158
+ try {
159
+ const answer = await http.del(`${mcBase}/user/${CLI_NAME}`, config);
160
+ if (answer.status === 200 && answer.data?.status === 'deleted') return true;
161
+ console.error(`[setup_cli_credentials] user delete failed (${describeAnswer(answer)})`);
162
+ } catch (err) {
163
+ console.error(`[setup_cli_credentials] user delete failed: ${err && err.message ? err.message : String(err)}`);
164
+ }
165
+ return false;
166
+ }
9
167
 
10
168
  /**
11
169
  * Tool 11: setup_cli_credentials
@@ -14,23 +172,28 @@ const { validateHostAllowlist, NO_REDIRECT_TOKEN_CONFIG } = require('../lib/host
14
172
  * but no CLI credentials. This tool:
15
173
  * 1. Creates an IAM user "xns-cli" via the Relayer UI MC proxy
16
174
  * 2. Receives the one-time {access_key, secret_key} response
17
- * 3. Writes ~/.xns/credentials (AC-11 JSON schema, mode 0600)
175
+ * 3. Creates a policy and attaches it to the user: the gateway denies every request
176
+ * from a user that has none. If that fails, the user is deleted again
177
+ * 4. Adds the keys to ~/.xns/credentials as one profile (mode 0600),
178
+ * keeping every profile already there
18
179
  *
19
- * The muse_token is the Keycloak JWT already held by the agent from the
20
- * configure_vpd / get_host_tags calls — no new auth step required.
180
+ * The sign-in token comes from the server's own token manager, the same one
181
+ * get_host_tags and configure_vpd use (one browser sign-in per session); the
182
+ * caller never passes a token.
21
183
  */
22
184
  module.exports = function registerSetupCliCredentials(server, options = {}) {
23
185
  const http = options.httpClient || createHttpClient(options);
186
+ const relayerUiBase = (options.relayerUiBase || RELAYER_UI_BASE).replace(/\/+$/, '');
187
+ const tokenMgr = createTokenManager(options);
24
188
 
25
189
  server.registerTool(
26
190
  'setup_cli_credentials',
27
191
  {
28
192
  title: 'Set up CLI credentials',
29
- description: 'Provision S3 IAM credentials for the XNS CLI. Creates an IAM user in the Relayer and writes ~/.xns/credentials so that `xns ls` and other S3 verbs work without further configuration. Call once after check_claim_status reaches STATE_3.',
193
+ description: 'Provision S3 IAM credentials for the XNS CLI. Creates an IAM user in the Relayer that can read, write and delete in every bucket, and saves its keys in ~/.xns/credentials, where `xns ls` and the other S3 verbs read them. Profiles in that file that hold keys are kept: if its default profile is one of them, the new keys go in a new profile, and the reply names it and the command that uses it. Call once after check_claim_status reaches STATE_3.',
30
194
  inputSchema: {
31
- muse_token: z.string().describe('Keycloak/Muse token — the same token used for get_host_tags and configure_vpd'),
32
195
  installation_id: z.string().optional().default('').describe('Installation ID from check_claim_status STATE_3 result — used as cost_center_id in credentials'),
33
- relayer_ui_url: z.string().url().optional().default('http://localhost:8888').describe('Relayer UI base URL (default: http://localhost:8888). Must be a loopback, private-network, or .local address — this tool sends your Muse token to it.'),
196
+ ui_port: z.number().int().min(1).max(65535).optional().default(DEFAULT_UI_PORT).describe('Relayer UI port, if install_relayer was run with a ui_port other than 8888. Only the port is chosen; the host is always this machine.'),
34
197
  },
35
198
  annotations: {
36
199
  readOnlyHint: false,
@@ -38,31 +201,34 @@ module.exports = function registerSetupCliCredentials(server, options = {}) {
38
201
  openWorldHint: true,
39
202
  },
40
203
  },
41
- async ({ muse_token, installation_id, relayer_ui_url }) => {
42
- // This request carries the caller's Muse token. Check the destination BEFORE
43
- // sending anything, or a caller can name any host and collect the token
44
- // (MR !33). Same allowlist verify_storage has always applied.
45
- const allow = validateHostAllowlist(relayer_ui_url);
46
- if (!allow.allowed) {
47
- console.error(`[setup_cli_credentials] relayer_ui_url rejected: ${allow.reason}`);
48
- return {
49
- content: [{
50
- type: 'text',
51
- text: JSON.stringify({
52
- success: false,
53
- error: `relayer_ui_url rejected: ${allow.reason}`,
54
- }),
55
- }],
56
- };
57
- }
58
-
204
+ async ({ installation_id, ui_port = DEFAULT_UI_PORT }) => {
205
+ // DECISION: the server's own sign-in token is never sent to a caller-chosen
206
+ // host. The request goes only to the server-owned Relayer UI base, the same
207
+ // base get_host_tags uses; the tool takes no URL input. The caller picks
208
+ // only the UI port, never the host.
209
+ let keysIssued = false;
59
210
  try {
211
+ const uiUrl = new URL(relayerUiBase);
212
+ uiUrl.port = String(ui_port);
213
+ const mcBase = `${uiUrl.toString().replace(/\/+$/, '')}/api/v1/mc`;
214
+ const credsPath = path.join(os.homedir(), '.xns', 'credentials');
215
+ let token = await tokenMgr.ensureToken();
216
+
217
+ // Checked before the user is created: the Relayer shows the secret key
218
+ // once, so a file that cannot take it has to stop the tool here.
219
+ readCredentials(credsPath);
220
+
221
+ const tokenConfig = () => ({ headers: { keycloaktoken: token }, ...NO_REDIRECT_TOKEN_CONFIG });
222
+ const createUser = () => http.post(`${mcBase}/user`, { user: CLI_NAME }, tokenConfig());
223
+
60
224
  // Step 1: create IAM user "xns-cli" via MC proxy
61
- const { status, data } = await http.post(
62
- `${relayer_ui_url}/api/v1/mc/user`,
63
- { user: 'xns-cli' },
64
- { headers: { keycloaktoken: muse_token }, ...NO_REDIRECT_TOKEN_CONFIG }
65
- );
225
+ let { status, data } = await createUser();
226
+
227
+ // A rejected token gets one re-auth and retry.
228
+ if (status === 401) {
229
+ token = await tokenMgr.reauth();
230
+ ({ status, data } = await createUser());
231
+ }
66
232
 
67
233
  if (status !== 200) {
68
234
  return {
@@ -88,18 +254,35 @@ module.exports = function registerSetupCliCredentials(server, options = {}) {
88
254
  text: JSON.stringify({
89
255
  success: false,
90
256
  error: `Relayer: ${msg}`,
91
- hint: 'CLI credentials may already exist. Run `xns ls` — if it works, credentials are valid.',
257
+ hint: 'CLI credentials may already exist in one of the profiles in ~/.xns/credentials. Run `xns ls`, or `xns --profile <name> ls` for a profile that is not active — if it works, those credentials are valid. If it is denied, the user xns-cli may have no permissions: ask the user to delete xns-cli in the Relayer UI, then call setup_cli_credentials again.',
92
258
  }),
93
259
  }],
94
260
  };
95
261
  }
96
262
 
97
- // Step 2: derive S3 endpoint (same host, port 9000).
263
+ // Step 2: give the user its permissions. Nothing is saved unless this works.
264
+ try {
265
+ const policy = await createCliPolicy(http, mcBase, tokenConfig());
266
+ await attachCliPolicy(http, mcBase, policy, tokenConfig());
267
+ } catch (err) {
268
+ console.error(`[setup_cli_credentials] ${err && err.message ? err.message : String(err)}`);
269
+ const deleted = await deleteCliUser(http, mcBase, tokenConfig());
270
+ return {
271
+ content: [{
272
+ type: 'text',
273
+ text: JSON.stringify({ success: false, error: deleted ? NO_POLICY_ERROR : USER_LEFT_ERROR }),
274
+ }],
275
+ };
276
+ }
277
+
278
+ keysIssued = true;
279
+
280
+ // Step 3: derive S3 endpoint (same host, port 9000).
98
281
  // Parse rather than regex-replace: the old `.replace(/:(\d+)(\/|$)/, ...)`
99
282
  // only rewrote an EXISTING :port slot, so a portless URL kept 80/443, a
100
283
  // query or fragment survived into the persisted endpoint, and a ':digits'
101
284
  // sequence in the PATH could be rewritten instead of the port (MR !33).
102
- const s3Url = new URL(relayer_ui_url);
285
+ const s3Url = new URL(relayerUiBase);
103
286
  s3Url.port = '9000';
104
287
  s3Url.username = '';
105
288
  s3Url.password = '';
@@ -107,59 +290,68 @@ module.exports = function registerSetupCliCredentials(server, options = {}) {
107
290
  s3Url.hash = '';
108
291
  const s3Endpoint = s3Url.toString().replace(/\/$/, '');
109
292
 
110
- // Step 3: write ~/.xns/credentials (AC-11 JSON schema, mode 0600)
111
- const credsPath = path.join(os.homedir(), '.xns', 'credentials');
112
- fs.mkdirSync(path.dirname(credsPath), { recursive: true });
113
-
114
- const creds = {
115
- version: 1,
116
- profiles: {
117
- default: {
118
- endpoint: s3Endpoint,
119
- access_key_id: ak,
120
- secret_access_key: sk,
121
- cost_center_id: installation_id,
122
- // Deliberately empty. The 5-key schema requires the key to be
123
- // PRESENT, but the xns CLI never reads its value — the only
124
- // reference in that codebase is `_ = p.MuseToken` in
125
- // validateProfile, whose comment states "muse_token may be
126
- // empty", and its round-trip test asserts the field IS empty.
127
- // Writing the JWT here bought nothing and cost real exposure:
128
- // it expires in minutes so the copy goes stale, there is no
129
- // refresh token to renew it, and until expiry a read of this
130
- // file grants Muse-API reach well beyond S3. The access and
131
- // secret keys below do belong here — S3 request signing needs
132
- // them in plaintext, same as ~/.aws/credentials.
133
- muse_token: '',
134
- },
135
- },
136
- active_profile: 'default',
293
+ // Step 4: add the profile to ~/.xns/credentials (mode 0600).
294
+ // Read again: another program may have saved a profile in the meantime.
295
+ const creds = readCredentials(credsPath);
296
+ const profileName = pickProfileName(creds.profiles);
297
+ creds.profiles[profileName] = {
298
+ endpoint: s3Endpoint,
299
+ access_key_id: ak,
300
+ secret_access_key: sk,
301
+ cost_center_id: installation_id,
302
+ // Deliberately empty. The 5-key schema requires the key to be
303
+ // PRESENT, but the xns CLI never reads its value — the only
304
+ // reference in that codebase is `_ = p.MuseToken` in
305
+ // validateProfile, whose comment states "muse_token may be
306
+ // empty", and its round-trip test asserts the field IS empty.
307
+ // Writing the JWT here bought nothing and cost real exposure:
308
+ // it expires in minutes so the copy goes stale, there is no
309
+ // refresh token to renew it, and until expiry a read of this
310
+ // file grants Muse-API reach well beyond S3. The access and
311
+ // secret keys below do belong here — S3 request signing needs
312
+ // them in plaintext, same as ~/.aws/credentials.
313
+ muse_token: '',
137
314
  };
138
-
139
- fs.writeFileSync(credsPath, JSON.stringify(creds, null, 2), { mode: 0o600 });
140
- // writeFileSync's mode only applies when the file is CREATED. This file is
141
- // overwritten unconditionally, so an existing loose-permission file would
142
- // keep those permissions and hold secret keys (MR !33).
143
- fs.chmodSync(credsPath, 0o600);
315
+ // DECISION: the active profile stays the user's. Moving it would point
316
+ // every later `xns` command at another Relayer. The CLI refuses a file
317
+ // whose active_profile names no profile, so only that case is set.
318
+ if (typeof creds.active_profile !== 'string' || !Object.hasOwn(creds.profiles, creds.active_profile)) {
319
+ creds.active_profile = profileName;
320
+ }
321
+ writeCredentials(credsPath, creds);
144
322
 
145
323
  return {
146
324
  content: [{
147
325
  type: 'text',
148
326
  text: JSON.stringify({
149
327
  success: true,
150
- message: 'CLI credentials written to ~/.xns/credentials. The user can now run `xns ls` to list their storage.',
328
+ message: creds.active_profile === profileName
329
+ ? 'CLI credentials written to ~/.xns/credentials. The user can now run `xns ls` to list their storage.'
330
+ : `CLI credentials written to ~/.xns/credentials as the profile ${profileName}. Profiles that already hold keys are unchanged, and plain \`xns\` commands still use ${creds.active_profile}. The user can now run \`xns --profile ${profileName} ls\` to list the storage on this Relayer.`,
331
+ profile: profileName,
332
+ active_profile: creds.active_profile,
151
333
  s3_endpoint: s3Endpoint,
152
334
  }),
153
335
  }],
154
336
  };
155
337
  } catch (err) {
338
+ // Caught error text stays in the server log. The sign-in link message
339
+ // is the one exception: this server builds it from fixed text and the
340
+ // link, and the person needs it to sign in.
341
+ let error = 'Setting up CLI credentials failed. See the server log for detail, then call setup_cli_credentials again.';
342
+ if (err && err.code === 'SIGNIN_LINK') {
343
+ error = err.message;
344
+ } else {
345
+ console.error(`[setup_cli_credentials] ${err && err.message ? err.message : String(err)}`);
346
+ // Calling again would not help once the user exists: the Relayer
347
+ // refuses a second xns-cli and does not show the first one's key again.
348
+ if (keysIssued) error = NOT_SAVED_ERROR;
349
+ else if (err && err.code === 'CREDS_UNREADABLE') error = BAD_FILE_ERROR;
350
+ }
156
351
  return {
157
352
  content: [{
158
353
  type: 'text',
159
- text: JSON.stringify({
160
- success: false,
161
- error: err.message,
162
- }),
354
+ text: JSON.stringify({ success: false, error }),
163
355
  }],
164
356
  };
165
357
  }
@@ -115,6 +115,7 @@ module.exports = function registerVerifyStorage(server, options = {}) {
115
115
  try {
116
116
  muse_token = await tokenMgr.ensureToken();
117
117
  } catch (signInErr) {
118
+ if (signInErr.code === 'SIGNIN_LINK') throw safeError(signInErr.message);
118
119
  console.error(`[verify_storage] SignIn: ${signInErr.message}`);
119
120
  throw safeError('OIDC sign-in did not complete. Run get_host_tags first to sign in, or pass muse_token or access_key_id/secret_access_key.');
120
121
  }