@spurtest/cli 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.js CHANGED
@@ -45,7 +45,7 @@ export class SpurApi {
45
45
  requestInit: { headers: { Authorization: `Bearer ${await accessToken(this.server)}` } },
46
46
  fetch: proxiedFetch,
47
47
  });
48
- const client = new Client({ name: "spur-cli", version: "0.1.5" });
48
+ const client = new Client({ name: "spur-cli", version: "0.1.6" });
49
49
  await client.connect(transport);
50
50
  try {
51
51
  const result = await client.callTool({ name, arguments: args });
package/dist/auth.js CHANGED
@@ -64,6 +64,8 @@ class FileProvider {
64
64
  // A refresh that fell back to a fresh authorization: only `spur login` can open a browser.
65
65
  throw new NotLoggedInError();
66
66
  }
67
+ if (!isWebUrl(url))
68
+ throw new Error(`Refusing to open the login page at ${url.protocol}: it must be an https:// URL.`);
67
69
  console.log(`Opening your browser to log in. If it does not open, visit:\n ${url.href}\n`);
68
70
  openBrowser(url.href);
69
71
  }
@@ -89,9 +91,27 @@ class FileProvider {
89
91
  await writeLogin(this.login);
90
92
  }
91
93
  }
94
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
95
+ /**
96
+ * The OS opener runs whatever it's handed (a file:, UNC or program path included), and the login page comes from the
97
+ * server's metadata, so only https:// pages (or http:// on this machine, for a local Spur) are opened.
98
+ */
99
+ export function isWebUrl(url) {
100
+ return url.protocol === "https:" || (url.protocol === "http:" && LOOPBACK.has(url.hostname));
101
+ }
102
+ /**
103
+ * The command that opens `url` in the default browser. Windows skips `cmd /c start`: cmd reads `&` in the login URL
104
+ * as a command separator, which cuts the URL short and would run whatever follows it.
105
+ */
106
+ export function browserCommand(platform, url) {
107
+ if (platform === "darwin")
108
+ return ["open", [url]];
109
+ if (platform === "win32")
110
+ return ["rundll32", ["url.dll,FileProtocolHandler", url]];
111
+ return ["xdg-open", [url]];
112
+ }
92
113
  function openBrowser(url) {
93
- const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
94
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
114
+ const [command, args] = browserCommand(process.platform, url);
95
115
  try {
96
116
  spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => { }).unref();
97
117
  }
@@ -107,31 +127,35 @@ export async function login(server) {
107
127
  // A fresh registration each time: the loopback port is part of the registered redirect URI.
108
128
  const saved = { server };
109
129
  const provider = new FileProvider(saved, port);
110
- try {
111
- const code = new Promise((resolve, reject) => {
112
- const timer = setTimeout(() => reject(new Error("Timed out waiting for the browser login.")), LOGIN_TIMEOUT_MS);
113
- callback.on("request", (request, response) => {
114
- const url = new URL(request.url ?? "/", `http://127.0.0.1:${port}`);
115
- if (url.pathname !== "/callback") {
116
- response.writeHead(404).end();
117
- return;
118
- }
119
- const received = url.searchParams.get("code");
120
- const ok = received && provider.checkState(url.searchParams.get("state"));
121
- response.writeHead(ok ? 200 : 400, { "Content-Type": "text/html; charset=utf-8" });
122
- response.end(ok ? "<p>Logged in to Spur. You can close this tab.</p>" : "<p>Login failed. Run <code>spur login</code> again.</p>");
123
- clearTimeout(timer);
124
- if (ok)
125
- resolve(received);
126
- else
127
- reject(new Error(url.searchParams.get("error_description") || url.searchParams.get("error") || "Login failed."));
128
- });
130
+ let timer;
131
+ const code = new Promise((resolve, reject) => {
132
+ timer = setTimeout(() => reject(new Error("Timed out waiting for the browser login.")), LOGIN_TIMEOUT_MS);
133
+ callback.on("request", (request, response) => {
134
+ const url = new URL(request.url ?? "/", `http://127.0.0.1:${port}`);
135
+ if (url.pathname !== "/callback") {
136
+ response.writeHead(404).end();
137
+ return;
138
+ }
139
+ const received = url.searchParams.get("code");
140
+ const ok = received && provider.checkState(url.searchParams.get("state"));
141
+ response.writeHead(ok ? 200 : 400, { "Content-Type": "text/html; charset=utf-8" });
142
+ response.end(ok ? "<p>Logged in to Spur. You can close this tab.</p>" : "<p>Login failed. Run <code>spur login</code> again.</p>");
143
+ clearTimeout(timer);
144
+ if (ok)
145
+ resolve(received);
146
+ else
147
+ reject(new Error(url.searchParams.get("error_description") || url.searchParams.get("error") || "Login failed."));
129
148
  });
149
+ });
150
+ // When the first step throws, nothing awaits `code`; its later rejection must not surface as unhandled.
151
+ code.catch(() => undefined);
152
+ try {
130
153
  if ((await auth(provider, { serverUrl: mcpUrl(server), fetchFn: proxiedFetch })) === "AUTHORIZED")
131
154
  return;
132
155
  await auth(provider, { serverUrl: mcpUrl(server), authorizationCode: await code, fetchFn: proxiedFetch });
133
156
  }
134
157
  finally {
158
+ clearTimeout(timer);
135
159
  callback.close();
136
160
  }
137
161
  }
package/dist/connector.js CHANGED
@@ -12,6 +12,8 @@ const RETRY_MS = [1_000, 2_000, 5_000, 10_000, 30_000];
12
12
  const START_ATTEMPTS = 3;
13
13
  // How long a relay may take to answer the hello before the attempt counts as failed.
14
14
  const READY_TIMEOUT_MS = 15_000;
15
+ // How long a shared host may leave its socket full before its stream is closed.
16
+ const STALL_MS = 30_000;
15
17
  // Once one relay is ready, how long start waits for the others before reporting them as retrying.
16
18
  const OTHERS_GRACE_MS = 1_000;
17
19
  export function encodeFrame(type, stream, payload = Buffer.alloc(0)) {
@@ -61,6 +63,24 @@ function splitHostPort(target) {
61
63
  const host = target.slice(0, colon);
62
64
  return { host: host.startsWith("[") ? host.slice(1, -1) : host, port: Number(target.slice(colon + 1)) };
63
65
  }
66
+ // The relay receives the tunnel token and can open streams to every shared host, so the connector only dials Spur's
67
+ // relays over TLS. A relay run locally (including on the Docker host) may use plain ws://.
68
+ const RELAY_DOMAINS = ["spurtest.com"];
69
+ export function checkRelayUrl(relay) {
70
+ let url;
71
+ try {
72
+ url = new URL(relay);
73
+ }
74
+ catch {
75
+ throw new Error(`"${relay}" isn't a relay URL.`);
76
+ }
77
+ const host = url.hostname.toLowerCase();
78
+ const spur = RELAY_DOMAINS.some((domain) => host === domain || host.endsWith(`.${domain}`));
79
+ const local = isLocalHost(host) || host === "host.docker.internal";
80
+ if ((url.protocol === "wss:" && spur) || (url.protocol === "ws:" && local))
81
+ return relay;
82
+ throw new Error(`${url.origin} isn't a Spur relay. The connector only connects to wss:// relays on ${RELAY_DOMAINS.join(", ")}.`);
83
+ }
64
84
  export class Connector {
65
85
  tunnel;
66
86
  hosts;
@@ -68,8 +88,11 @@ export class Connector {
68
88
  relayUrl;
69
89
  retryMs;
70
90
  readyTimeoutMs;
91
+ stallMs;
71
92
  socket = null;
72
93
  streams = new Map();
94
+ // Local sockets whose write buffer is full; the relay socket stays paused while any are.
95
+ blocked = new Set();
73
96
  stopped = false;
74
97
  attempt = 0;
75
98
  endWith = () => { };
@@ -77,13 +100,15 @@ export class Connector {
77
100
  ended = new Promise((resolve) => {
78
101
  this.endWith = resolve;
79
102
  });
80
- constructor(tunnel, hosts, log, relayUrl = process.env.SPUR_RELAY_URL || tunnel.relay_url, retryMs = RETRY_MS, readyTimeoutMs = READY_TIMEOUT_MS) {
103
+ constructor(tunnel, hosts, log, relayUrl = process.env.SPUR_RELAY_URL || tunnel.relay_url, retryMs = RETRY_MS, readyTimeoutMs = READY_TIMEOUT_MS, stallMs = STALL_MS) {
81
104
  this.tunnel = tunnel;
82
105
  this.hosts = hosts;
83
106
  this.log = log;
84
107
  this.relayUrl = relayUrl;
85
108
  this.retryMs = retryMs;
86
109
  this.readyTimeoutMs = readyTimeoutMs;
110
+ this.stallMs = stallMs;
111
+ checkRelayUrl(relayUrl);
87
112
  }
88
113
  /**
89
114
  * Resolves once the relay accepts the tunnel and keeps reconnecting after that until stop(). Rejects after
@@ -110,6 +135,8 @@ export class Connector {
110
135
  let lastError = "";
111
136
  let readyTimer;
112
137
  let readyHere = false;
138
+ // A relay that keeps sending junk shouldn't flood the log: one line per connection is enough.
139
+ let reportedMalformed = false;
113
140
  ws.on("open", () => {
114
141
  ws.send(JSON.stringify({ type: "hello", version: 1, tunnel_id: this.tunnel.id, token: this.tunnel.token, hosts: this.hosts }));
115
142
  // A relay that accepts the socket but never answers the hello counts as a failed attempt.
@@ -120,7 +147,17 @@ export class Connector {
120
147
  });
121
148
  ws.on("message", (data, isBinary) => {
122
149
  if (!isBinary) {
123
- const message = JSON.parse(data.toString());
150
+ let message = null;
151
+ try {
152
+ message = JSON.parse(data.toString());
153
+ }
154
+ catch { }
155
+ if (!message || typeof message !== "object") {
156
+ if (!reportedMalformed)
157
+ this.log("Ignored a malformed message from the relay.");
158
+ reportedMalformed = true;
159
+ return;
160
+ }
124
161
  if (message.type === "ready") {
125
162
  clearTimeout(readyTimer);
126
163
  readyHere = true;
@@ -138,7 +175,7 @@ export class Connector {
138
175
  }
139
176
  }
140
177
  else if (message.type === "error") {
141
- end(`Spur refused the tunnel: ${message.message ?? "unknown error"}`);
178
+ end(`Spur refused the tunnel: ${typeof message.message === "string" ? message.message : "unknown error"}`);
142
179
  }
143
180
  return;
144
181
  }
@@ -197,21 +234,53 @@ export class Connector {
197
234
  if (type === FRAME.OPEN)
198
235
  this.open(stream, payload.toString("utf8").toLowerCase());
199
236
  else if (type === FRAME.DATA)
200
- this.streams.get(stream)?.write(payload);
237
+ this.writeLocal(stream, payload);
201
238
  else if (type === FRAME.CLOSE) {
202
239
  this.streams.get(stream)?.end();
203
240
  this.streams.delete(stream);
204
241
  }
205
242
  }
243
+ /**
244
+ * Writes relay data to a local socket. When a shared host reads slower than the relay sends, its socket stops
245
+ * accepting writes and the connector stops reading the relay until it drains, so memory can't grow without bound.
246
+ * Every stream shares the one WebSocket, so a slow host briefly holds back the others too.
247
+ */
248
+ writeLocal(stream, payload) {
249
+ const local = this.streams.get(stream);
250
+ if (!local || local.write(payload) || this.blocked.has(local))
251
+ return;
252
+ this.blocked.add(local);
253
+ this.socket?.pause();
254
+ // A host that stops reading altogether would hold every stream (and the relay's own frames) back for good,
255
+ // so a stream still blocked after stallMs is closed instead.
256
+ const stall = setTimeout(() => {
257
+ if (!this.blocked.has(local))
258
+ return;
259
+ this.log(`Closed a stream to a shared host that stopped reading for ${this.stallMs / 1000}s.`);
260
+ local.destroy();
261
+ }, this.stallMs);
262
+ local.once("drain", () => {
263
+ clearTimeout(stall);
264
+ this.unblock(local);
265
+ });
266
+ local.once("close", () => clearTimeout(stall));
267
+ }
268
+ unblock(local) {
269
+ if (this.blocked.delete(local) && !this.blocked.size)
270
+ this.socket?.resume();
271
+ }
206
272
  open(stream, target) {
207
273
  if (!this.hosts.includes(target)) {
208
274
  this.log(`Refused ${target}: not shared.`);
209
275
  this.send(FRAME.OPEN_FAIL, stream, Buffer.from("host not shared"));
210
276
  return;
211
277
  }
278
+ // A repeated OPEN for a live stream id replaces it; the earlier socket would otherwise stay open, unreachable.
279
+ this.streams.get(stream)?.destroy();
212
280
  const { host, port } = splitHostPort(target);
213
281
  const local = net.connect({ host, port, autoSelectFamily: true });
214
282
  this.streams.set(stream, local);
283
+ const current = () => this.streams.get(stream) === local;
215
284
  let opened = false;
216
285
  local.on("connect", () => {
217
286
  opened = true;
@@ -232,13 +301,18 @@ export class Connector {
232
301
  }
233
302
  });
234
303
  local.on("error", (error) => {
235
- if (opened)
304
+ // A socket the relay already closed or replaced must not fail the stream id's new owner.
305
+ if (opened || !current())
236
306
  return;
237
307
  this.log(`Could not reach ${target}: ${error.message}`);
238
308
  this.send(FRAME.OPEN_FAIL, stream, Buffer.from(`${target}: ${error.message}`));
239
309
  });
240
310
  local.on("close", () => {
241
- if (opened && this.streams.has(stream))
311
+ this.unblock(local);
312
+ // A socket replaced by a repeated OPEN no longer owns the stream id.
313
+ if (!current())
314
+ return;
315
+ if (opened)
242
316
  this.send(FRAME.CLOSE, stream);
243
317
  this.streams.delete(stream);
244
318
  });
@@ -247,6 +321,11 @@ export class Connector {
247
321
  for (const local of this.streams.values())
248
322
  local.destroy();
249
323
  this.streams.clear();
324
+ // A paused relay socket can't read the close handshake, so stop() would wait out ws's close timeout.
325
+ if (this.blocked.size) {
326
+ this.blocked.clear();
327
+ this.socket?.resume();
328
+ }
250
329
  }
251
330
  }
252
331
  /** Every relay the connector should reach: SPUR_RELAY_URL wins, then the server's list, then its single relay_url. */
@@ -272,6 +351,9 @@ export function regionStatus(handle) {
272
351
  */
273
352
  export async function startTunnel(api, specs, name, log, options = {}) {
274
353
  const hosts = [...new Set(specs.flatMap(parseHostSpec))];
354
+ // Checked before the tunnel exists, so a bad override can't leave a named tunnel registered with no connector.
355
+ if (process.env.SPUR_RELAY_URL)
356
+ checkRelayUrl(process.env.SPUR_RELAY_URL);
275
357
  const tunnel = await api.request("POST", "/api/cli/tunnels", { hosts, ...(name ? { name } : {}) });
276
358
  const relays = relaysFor(tunnel);
277
359
  // A connector key's tunnel is named and outlives this process; only an unnamed tunnel is revoked on close.
@@ -284,6 +366,14 @@ export async function startTunnel(api, specs, name, log, options = {}) {
284
366
  await revoke();
285
367
  throw new Error("Spur returned no relay for this tunnel.");
286
368
  }
369
+ try {
370
+ for (const relay of relays)
371
+ checkRelayUrl(relay.url);
372
+ }
373
+ catch (error) {
374
+ await revoke();
375
+ throw error;
376
+ }
287
377
  const many = relays.length > 1;
288
378
  const connectors = relays.map((relay) => new Connector(tunnel, hosts, many ? (message) => log(`${relay.region}: ${message}`) : log, relay.url, options.retryMs, options.readyTimeoutMs));
289
379
  const outcomes = relays.map(() => ({ status: "pending" }));
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { EXIT, run } from "./run.js";
8
8
  const program = new Command()
9
9
  .name("spur")
10
10
  .description("Run Spur tests from your terminal and CI, including against localhost.")
11
- .version("0.1.5")
11
+ .version("0.1.6")
12
12
  .option("--server <url>", "Spur app URL (or SPUR_SERVER)");
13
13
  const api = async () => new SpurApi(await resolveServer(program.opts().server));
14
14
  program
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spurtest/cli",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Run Spur tests from your terminal and CI, including against localhost.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -21,8 +21,8 @@
21
21
  "commander": "15.1.0",
22
22
  "https-proxy-agent": "^7.0.6",
23
23
  "proxy-from-env": "^1.1.0",
24
- "undici": "^6.21.3",
25
- "ws": "^8.18.3"
24
+ "undici": "^6.29.1",
25
+ "ws": "^8.23.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^22",