hopwire 0.1.3 → 0.1.5

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.
@@ -22,7 +22,10 @@ export function isRedactedHeader(name) {
22
22
  export function isRedactedField(name) {
23
23
  return SENSITIVE_FIELD.test(name);
24
24
  }
25
- /** The headers as shown: a redacted value keeps the scheme of an authorization header (`Bearer [redacted, 40 chars]`). */
25
+ /**
26
+ * The headers as shown: a redacted value keeps the scheme of an authorization header (`Bearer [redacted, 40 chars]`)
27
+ * and the structure of a signature header (`t=1764490817,v1=[redacted, 64 chars]`, `sha256=[redacted, 64 chars]`).
28
+ */
26
29
  export function redactHeaders(headers) {
27
30
  return headers.map(([name, value]) => {
28
31
  if (!isRedactedHeader(name)) {
@@ -35,9 +38,33 @@ export function redactHeaders(headers) {
35
38
  return [name, `${scheme[1]} ${redacted(scheme[2])}`];
36
39
  }
37
40
  }
41
+ if (lower.includes('signature')) {
42
+ return [name, redactSignature(value) ?? redacted(value)];
43
+ }
38
44
  return [name, redacted(value)];
39
45
  });
40
46
  }
47
+ /** Names of the parts of a signature header that carry its time, shown when they are digits only */
48
+ const SIGNATURE_TIME_PARTS = new Set(['t', 'ts', 'timestamp']);
49
+ /**
50
+ * A signature header of `name=value` parts separated by commas (Stripe's `t=…,v1=…`, GitHub's `sha256=…`) with every
51
+ * value redacted but a timestamp, so an agent can tell whether a provider's tolerance has passed before it replays.
52
+ * Null when the value has another form; the caller then redacts it as a whole.
53
+ */
54
+ function redactSignature(value) {
55
+ const parts = value.split(',');
56
+ const shown = [];
57
+ for (const part of parts) {
58
+ const match = /^(\s*)([A-Za-z0-9_-]{1,32})=(.*)$/s.exec(part);
59
+ if (match?.[1] === undefined || match[2] === undefined || match[3] === undefined) {
60
+ return null;
61
+ }
62
+ const [, space, key, inner] = match;
63
+ const isTime = SIGNATURE_TIME_PARTS.has(key.toLowerCase()) && /^\d{1,13}$/.test(inner);
64
+ shown.push(`${space}${key}=${isTime ? inner : redacted(inner)}`);
65
+ }
66
+ return shown.join(',');
67
+ }
41
68
  /** A path with the values of sensitive query parameters redacted; the rest is kept as it was written. */
42
69
  export function redactPath(requestPath) {
43
70
  const at = requestPath.indexOf('?');
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import { HopwireError, errorCode } from './errors.js';
6
6
  import { ApiError, sendError } from './inspector-api.js';
7
7
  /**
8
- * The agent socket of a tunnel started with --agent: the inspector API on a Unix socket that only this user can
8
+ * The agent socket of a tunnel (on by default, decision 139; --no-agent turns it off): the inspector API on a Unix socket that only this user can
9
9
  * reach (`<dataDir>/run/agent.sock`, the directory 0700, the socket 0600), for `hopwire mcp`. It needs no access
10
10
  * key, Host or Origin check: a browser cannot reach a Unix socket, and the file system decides who can.
11
11
  */
@@ -30,14 +30,14 @@ export async function checkRunDirectory(dir, repair) {
30
30
  }
31
31
  if ((stats.mode & 0o077) !== 0) {
32
32
  if (!repair) {
33
- throw new HopwireError(`${dir} can be entered by other users; restart the tunnel with --agent to fix it.`);
33
+ throw new HopwireError(`${dir} can be entered by other users; restart the tunnel to fix it.`);
34
34
  }
35
35
  await chmod(dir, 0o700);
36
36
  }
37
37
  }
38
38
  export async function startAgentSocket(api, dataDir) {
39
39
  if (process.platform === 'win32') {
40
- throw new HopwireError('--agent needs a Unix socket and is not available on Windows.');
40
+ throw new HopwireError('The agent socket needs a Unix socket and is not available on Windows; start without --agent.');
41
41
  }
42
42
  const socketPath = agentSocketPath(dataDir);
43
43
  if (Buffer.byteLength(socketPath) > AGENT_SOCKET_PATH_MAX_BYTES) {
package/dist/cli.js CHANGED
@@ -51,7 +51,7 @@ Commands:
51
51
  hopwire doctor Print a report about this installation (versions, data directory, account,
52
52
  hopwire.yaml) to read or to paste into a bug report. It is sent nowhere
53
53
  hopwire mcp An MCP server for a coding agent on this machine (stdio): it reads and replays
54
- the traffic of a tunnel started with --agent on the same data directory
54
+ the traffic of a tunnel running on the same data directory
55
55
 
56
56
  Options for http:
57
57
  --listen <port> Loopback port of the entry point (default ${LOCAL_ENTRY_DEFAULT_PORT}, 0 picks a free one)
@@ -74,16 +74,22 @@ Options for http:
74
74
  it the fixed t-... URL of your organisation is used (a random one with a dev token)
75
75
  --force When another tunnel holds the data directory, stop it (as Ctrl+C does) and start
76
76
  this one in its place
77
- --agent Let a coding agent on this machine read the traffic and replay it (hopwire mcp),
78
- through a socket only this user can open. What the agent reads goes to its model
79
- provider
77
+ --no-agent Do not let a coding agent on this machine read the traffic and replay it. By
78
+ default it can, through hopwire mcp and a socket only this user can open; what the
79
+ agent reads goes to its model provider. Nothing reaches an agent until you register
80
+ hopwire mcp with one
81
+ --agent Require that socket: fail when it cannot open (by default the tunnel then runs
82
+ without it)
83
+ --allow-agents With --share: the coding agents of teammates who watch the log (hopwire watch
84
+ --agent) may read the exchanges captured from now on. What an agent reads goes to its
85
+ model provider; exchanges captured without it stay closed to agents
80
86
 
81
87
  Options for up:
82
88
  --config <path> The config file (default ${HOPWIRE_YAML_FILE} in the working directory). A public service
83
89
  takes the URL of the edge from edge.url in the file. With controlPlane.url in the file
84
90
  it uses your account (hopwire login), without it the dev token in HOPWIRE_DEV_TOKEN.
85
91
  p2p.team in the file is --team of http
86
- --agent As for http: the traffic of every service for hopwire mcp
92
+ --no-agent, --agent As for http, for every service; agent: false in the file turns it off too
87
93
  --force As for http: stop the tunnel that holds the data directory first
88
94
 
89
95
  Options for login:
@@ -118,6 +124,9 @@ Options for watch:
118
124
  --inspect <port> Loopback port of the inspector (default ${INSPECTOR_DEFAULT_PORT}, 0 picks a free one)
119
125
  --team For a teammate who shares with --team: registers the key of this machine with your
120
126
  organisation (hopwire login first), so the sharer lets it in
127
+ --agent Let a coding agent on this machine read the exchanges your teammate allowed for
128
+ agents (they share with --allow-agents) through hopwire mcp; never on without it.
129
+ What the agent reads goes to its model provider
121
130
  --force As for http: stop the tunnel that holds the data directory first
122
131
 
123
132
  Global options:
@@ -131,8 +140,8 @@ export const MCP_TERMINAL_HINT = [
131
140
  'hopwire mcp is an MCP server for coding agents. It is started by the agent, not by hand,',
132
141
  'and is now waiting for one on standard input.',
133
142
  '',
134
- ' 1. Start a tunnel with --agent: hopwire http 3000 --agent',
135
- ' 2. Register it with your agent: claude mcp add hopwire -- hopwire mcp',
143
+ ' 1. Start a tunnel: hopwire http 3000',
144
+ ' 2. Register it with your agent: claude mcp add hopwire -- hopwire mcp',
136
145
  '',
137
146
  `Cursor, Codex and other agents: ${DOCS_URL}/coding-agents`,
138
147
  'Press Ctrl+C to stop.',
@@ -148,16 +157,18 @@ const COMMAND_OPTIONS = {
148
157
  'share',
149
158
  'allow',
150
159
  'team',
160
+ 'allow-agents',
151
161
  'public',
152
162
  'subdomain',
153
163
  'agent',
164
+ 'no-agent',
154
165
  'force',
155
166
  ],
156
- up: ['config', 'agent', 'force'],
167
+ up: ['config', 'agent', 'no-agent', 'force'],
157
168
  id: [],
158
169
  rotate: [],
159
170
  connect: ['port', 'service', 'allow-host', 'team'],
160
- watch: ['replay-target', 'inspect', 'team', 'force'],
171
+ watch: ['replay-target', 'inspect', 'team', 'agent', 'force'],
161
172
  login: ['api', 'token', 'no-browser'],
162
173
  logout: [],
163
174
  mcp: ['read-only'],
@@ -298,11 +309,13 @@ export async function run(argv, io) {
298
309
  dataDir,
299
310
  print: io.print,
300
311
  bootstrap: parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP),
312
+ agent: values.agent ?? false,
301
313
  signal: io.signal,
302
314
  });
303
315
  }
304
316
  if (command === 'up') {
305
317
  noMoreArguments(rest, 0, 'hopwire up [--config <path>]');
318
+ const agent = agentChoice(values);
306
319
  if (values.config === '') {
307
320
  throw new UsageError('--config needs the path of a config file');
308
321
  }
@@ -326,7 +339,7 @@ export async function run(argv, io) {
326
339
  // The account is only read for p2p.team: without it private mode never looks at it
327
340
  team: config.team ? await teamAccessOfFile(shown, config, dataDir) : undefined,
328
341
  bootstrap: config.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
329
- agent: values.agent ?? false,
342
+ agent: agent ?? config.agent ?? undefined,
330
343
  signal: io.signal,
331
344
  });
332
345
  // After the lines of the start, so the mode stays the first line of every tunnel
@@ -344,6 +357,9 @@ export async function run(argv, io) {
344
357
  if (values.team && !values.share) {
345
358
  throw new UsageError('--team only works together with --share');
346
359
  }
360
+ if (values['allow-agents'] && !values.share) {
361
+ throw new UsageError('--allow-agents only works together with --share');
362
+ }
347
363
  if (values.team && allow.length > 0) {
348
364
  throw new UsageError('--team and --allow cannot be combined: with --team the team is the list');
349
365
  }
@@ -367,19 +383,27 @@ export async function run(argv, io) {
367
383
  serviceName: values.name ?? 'default',
368
384
  print: io.print,
369
385
  share: values.share ?? false,
386
+ allowAgents: values['allow-agents'] ?? false,
370
387
  allow,
371
388
  // The account is only read for --team: without it private mode never looks at it
372
389
  team: values.team ? await teamAccess('--team', dataDir) : undefined,
373
390
  bootstrap: values.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
374
391
  // Edge URL, token and account are only read for --public: private mode never looks at them
375
392
  public: values.public ? update.watch(await parsePublic(values.subdomain, io.env, dataDir)) : undefined,
376
- agent: values.agent ?? false,
393
+ agent: agentChoice(values),
377
394
  signal: io.signal,
378
395
  });
379
396
  // After the lines of the start, so the mode stays the first line of every tunnel
380
397
  update.print(io.print);
381
398
  return running;
382
399
  }
400
+ /** --agent or --no-agent; undefined leaves the choice to hopwire.yaml or the default (on, decision 139). */
401
+ function agentChoice(values) {
402
+ if (values.agent && values['no-agent']) {
403
+ throw new UsageError('--agent and --no-agent cannot be combined');
404
+ }
405
+ return values.agent ? true : values['no-agent'] ? false : undefined;
406
+ }
383
407
  function parse(argv) {
384
408
  try {
385
409
  return parseArgs({
@@ -400,12 +424,14 @@ function parse(argv) {
400
424
  share: { type: 'boolean' },
401
425
  allow: { type: 'string', multiple: true },
402
426
  team: { type: 'boolean' },
427
+ 'allow-agents': { type: 'boolean' },
403
428
  'allow-host': { type: 'string', multiple: true },
404
429
  port: { type: 'string' },
405
430
  service: { type: 'string' },
406
431
  'replay-target': { type: 'string' },
407
432
  config: { type: 'string' },
408
433
  agent: { type: 'boolean' },
434
+ 'no-agent': { type: 'boolean' },
409
435
  'read-only': { type: 'boolean' },
410
436
  api: { type: 'string' },
411
437
  token: { type: 'boolean' },
@@ -5,6 +5,7 @@ import { HOPWIRE_YAML_FILE } from '@hopwire/protocol';
5
5
  import { accountFile, boundEdge, readAccount } from '../account.js';
6
6
  import { loadConfig } from '../config.js';
7
7
  import { errorCode } from '../errors.js';
8
+ import { describeProxy, proxyFor } from '../outbound-proxy.js';
8
9
  import { printable } from '../output.js';
9
10
  /**
10
11
  * `hopwire doctor`: a report about this installation, for the user to read and, when they choose, to paste into a
@@ -26,6 +27,7 @@ export async function doctor(options) {
26
27
  print(`Traffic log ${await entry(path.join(dataDir, 'store'), 0o700, 'none yet; the first tunnel creates it')}`);
27
28
  print(`Account ${await account(dataDir)}`);
28
29
  print(`Config ${await config(options.cwd)}`);
30
+ print(`Proxy ${proxy(options.env ?? process.env)}`);
29
31
  print(`Network ${options.network ? await network(options) : NOT_CHECKED}`);
30
32
  print('');
31
33
  print(options.network
@@ -33,6 +35,24 @@ export async function doctor(options) {
33
35
  : 'Nothing was sent anywhere: this report was put together on this machine without a network connection.');
34
36
  print('It holds no keys, no tokens and no traffic. If you paste it into a bug report, read it first: the paths can name your user.');
35
37
  }
38
+ /**
39
+ * The HTTP proxy public mode uses for the edge and the control plane, as HTTPS_PROXY and NO_PROXY name it. Read from
40
+ * the environment only: nothing is sent to the proxy. Its credentials are never printed, the entries of NO_PROXY
41
+ * neither (they can name internal hosts).
42
+ */
43
+ function proxy(env) {
44
+ const noProxy = (env.no_proxy ?? env.NO_PROXY ?? '').trim() === '' ? '' : '; NO_PROXY is set and exempts the hosts it names';
45
+ try {
46
+ // Any public https host stands for the edge and the control plane; loopback ones are always reached directly
47
+ const found = proxyFor(new URL('https://proxy-check.invalid'), { ...env, no_proxy: '', NO_PROXY: '' });
48
+ return found === null
49
+ ? `none (HTTPS_PROXY is not set): public mode connects directly${noProxy}`
50
+ : `${describeProxy(found)}: public mode reaches the edge and the control plane through it; private mode is UDP and does not use it${noProxy}`;
51
+ }
52
+ catch (error) {
53
+ return error instanceof Error ? error.message : String(error);
54
+ }
55
+ }
36
56
  const NOT_CHECKED = 'not checked. hopwire doctor --network tests whether this network allows direct P2P connections; for that it joins the public DHT, whose nodes see your IP address';
37
57
  /** Whether a file or directory is there, and whether others than its owner can get at it. */
38
58
  async function entry(file, expected, missing = 'missing') {
@@ -1,4 +1,4 @@
1
- import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, agentLine, formatExchange, formatLimitReached, formatMeteredUsage, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, } from '../output.js';
1
+ import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, AGENTS_ALLOWED_LINE, agentLine, agentOffLine, formatExchange, formatLimitReached, formatMeteredUsage, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, } from '../output.js';
2
2
  import { startServing } from '../serve.js';
3
3
  export { INSPECTOR_FILES } from '../serve.js';
4
4
  /**
@@ -18,12 +18,13 @@ export async function startHttpTunnel(options) {
18
18
  force: options.force ?? false,
19
19
  onHolderStopped: (line) => stopped.push(line),
20
20
  share: options.share ?? false,
21
+ allowAgents: options.allowAgents ?? false,
21
22
  allow,
22
23
  team: options.team,
23
24
  onTeamEvent: (event, organisation) => options.print(formatTeamEvent(event, organisation)),
24
25
  bootstrap: options.bootstrap,
25
26
  inspectorFiles: options.inspectorFiles,
26
- agent: options.agent ?? false,
27
+ agent: options.agent,
27
28
  signal: options.signal,
28
29
  listenOption: '--listen <port>',
29
30
  inspectOption: '--inspect <port> or run with --no-inspect',
@@ -58,12 +59,18 @@ export async function startHttpTunnel(options) {
58
59
  if (peerKey !== null) {
59
60
  options.print(`Peer key ${peerKey}`);
60
61
  options.print(shareNotice(access));
62
+ if (options.allowAgents === true) {
63
+ options.print(AGENTS_ALLOWED_LINE);
64
+ }
61
65
  }
62
66
  if (inspectorUrl !== null) {
63
67
  options.print(`Inspector ${inspectorUrl}`);
64
68
  }
65
69
  if (agentSocket !== null) {
66
- options.print(agentLine(agentSocket, target.origin));
70
+ options.print(agentLine(agentSocket, target.origin, '--no-agent'));
71
+ }
72
+ else if (serving.agentProblem !== null) {
73
+ options.print(agentOffLine(serving.agentProblem));
67
74
  }
68
75
  for (const line of tunnelGuide({
69
76
  services: [
@@ -1,7 +1,7 @@
1
1
  import { createAgentClient } from '../mcp/client.js';
2
2
  import { MESSAGE_LIMIT_BYTES, createMcpServer } from '../mcp/jsonrpc.js';
3
3
  /**
4
- * `hopwire mcp`: a stdio MCP server for coding agents on this machine. It reaches a tunnel started with --agent
4
+ * `hopwire mcp`: a stdio MCP server for coding agents on this machine. It reaches a tunnel with the agent socket (on by default)
5
5
  * through the agent socket of the data directory. It opens no TCP connection, never opens the traffic log and writes
6
6
  * no file; standard output carries JSON-RPC and nothing else.
7
7
  */
@@ -1,7 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { LOCAL_ENTRY_DEFAULT_PORT, RANDOM_SUBDOMAIN_BYTES, randomSubdomain } from '@hopwire/protocol';
3
3
  import { HopwireError } from '../errors.js';
4
- import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, agentLine, formatExchange, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, } from '../output.js';
4
+ import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, AGENTS_ALLOWED_LINE, agentLine, agentOffLine, formatExchange, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, } from '../output.js';
5
5
  import { startServing } from '../serve.js';
6
6
  import { formatBridgeEvent } from './http.js';
7
7
  /**
@@ -41,12 +41,13 @@ export async function startUp(options) {
41
41
  force: options.force ?? false,
42
42
  onHolderStopped: (line) => stopped.push(line),
43
43
  share: config.share,
44
+ allowAgents: config.allowAgents,
44
45
  allow: config.allow ?? [],
45
46
  team: options.team,
46
47
  onTeamEvent: (event, organisation) => options.print(formatTeamEvent(event, organisation)),
47
48
  bootstrap: options.bootstrap,
48
49
  inspectorFiles: options.inspectorFiles,
49
- agent: options.agent ?? false,
50
+ agent: options.agent,
50
51
  signal: options.signal,
51
52
  listenOption: 'a free port',
52
53
  inspectOption: 'inspector.port in hopwire.yaml',
@@ -83,11 +84,17 @@ export async function startUp(options) {
83
84
  if (serving.peerKey !== null) {
84
85
  options.print(`Peer key ${serving.peerKey}`);
85
86
  options.print(shareNotice(access, 'p2p.allow in hopwire.yaml'));
87
+ if (config.allowAgents) {
88
+ options.print(AGENTS_ALLOWED_LINE);
89
+ }
86
90
  }
87
91
  options.print(`Inspector ${serving.inspectorUrl ?? ''}`);
88
92
  if (serving.agentSocket !== null) {
89
93
  const [first, ...rest] = serving.services;
90
- options.print(agentLine(serving.agentSocket, first !== undefined && rest.length === 0 ? first.target : 'the local service of each exchange'));
94
+ options.print(agentLine(serving.agentSocket, first !== undefined && rest.length === 0 ? first.target : 'the local service of each exchange', '--no-agent or agent: false in hopwire.yaml'));
95
+ }
96
+ else if (serving.agentProblem !== null) {
97
+ options.print(agentOffLine(serving.agentProblem));
91
98
  }
92
99
  for (const line of tunnelGuide({
93
100
  services: serving.services.map((service, index) => ({
@@ -1,10 +1,12 @@
1
1
  import { openOwnLog } from '../data-dir-holder.js';
2
+ import { startAgentSocket } from '../agent-socket.js';
2
3
  import { HopwireError, listenError } from '../errors.js';
3
4
  import { loadOrCreateIdentity } from '../identity.js';
5
+ import { agentsOnly, createInspectorApi } from '../inspector-api.js';
4
6
  import { startInspectorServer } from '../inspector-server.js';
5
7
  import { createInterceptor } from '../interceptor.js';
6
8
  import { REMOTE_LOG_BUDGET_BYTES } from '../log.js';
7
- import { MODE_P2P, MODE_P2P_TEAM, formatExchange, printable, shortKey, watchGuide } from '../output.js';
9
+ import { MODE_P2P, MODE_P2P_TEAM, formatExchange, printable, shortKey, watchAgentLine, watchGuide } from '../output.js';
8
10
  import { INSPECTOR_FILES } from '../serve.js';
9
11
  import { Supervisor, unlessAborted } from '../supervisor.js';
10
12
  /**
@@ -107,6 +109,23 @@ export async function startWatch(options) {
107
109
  throw listenError(error, options.inspectPort, 'inspector', '--inspect <port>');
108
110
  });
109
111
  supervisor.add('servers', () => inspector.close());
112
+ let agentSocket = null;
113
+ if (options.agent === true) {
114
+ proceed();
115
+ // Its own API: the browser inspector above shows the whole log, the agent only what the sharer allowed
116
+ const api = createInspectorApi({
117
+ sources: [
118
+ { origin: 'remote', log: agentsOnly(remote) },
119
+ { origin: 'own', log: own },
120
+ ],
121
+ status: () => status,
122
+ replayThrough: (exchange) => replayThrough(exchange.serviceName),
123
+ });
124
+ supervisor.add('servers', async () => api.close());
125
+ const socket = await startAgentSocket(api, options.dataDir);
126
+ supervisor.add('servers', () => socket.close());
127
+ agentSocket = socket.path;
128
+ }
110
129
  // Stopped at the last step: nothing is reported as running
111
130
  proceed();
112
131
  const stopPrinting = remote.subscribe((_index, exchange) => options.print(formatExchange(exchange)));
@@ -122,13 +141,16 @@ export async function startWatch(options) {
122
141
  ? 'Replay off; start hopwire watch with --replay-target <url> to replay to a local service'
123
142
  : `Replay to ${options.replayTarget.origin}`);
124
143
  options.print(`Inspector ${inspector.url}`);
144
+ if (agentSocket !== null) {
145
+ options.print(watchAgentLine(agentSocket, options.replayTarget?.origin ?? null));
146
+ }
125
147
  for (const line of watchGuide(options.replayTarget?.origin ?? null)) {
126
148
  options.print(line);
127
149
  }
128
150
  for (const line of stopped) {
129
151
  options.print(line);
130
152
  }
131
- return { kind: 'watch', inspectorUrl: inspector.url, logKey, peerKey, close };
153
+ return { kind: 'watch', inspectorUrl: inspector.url, agentSocket, logKey, peerKey, close };
132
154
  }
133
155
  catch (error) {
134
156
  await close().catch(() => { });
package/dist/config.js CHANGED
@@ -23,7 +23,7 @@ class Problem {
23
23
  this.problem = problem;
24
24
  }
25
25
  }
26
- const ROOT_KEYS = ['version', 'inspector', 'edge', 'controlPlane', 'p2p', 'services'];
26
+ const ROOT_KEYS = ['version', 'inspector', 'agent', 'edge', 'controlPlane', 'p2p', 'services'];
27
27
  const SERVICE_KEYS = ['local', 'public', 'subdomain', 'auth'];
28
28
  const LOCAL_RULE = 'must be an http URL on this machine without a path, for example http://127.0.0.1:3000; Hopwire only forwards to loopback addresses.';
29
29
  const SUBDOMAIN_RULE = 'must be 3 to 63 lowercase letters, digits or hyphens, must not start or end with a hyphen, must not start with t- and must not be a reserved name such as www or api.';
@@ -142,10 +142,15 @@ function validate(value, ordered) {
142
142
  let share = false;
143
143
  let allow = null;
144
144
  let team = false;
145
+ let allowAgents = false;
145
146
  if (root.p2p !== undefined) {
146
- const p2p = mapping(root.p2p, ['p2p'], ['share', 'allow', 'team'], 'p2p');
147
+ const p2p = mapping(root.p2p, ['p2p'], ['share', 'allow', 'team', 'allowAgents'], 'p2p');
147
148
  share = boolean(p2p.share, ['p2p', 'share']);
148
149
  team = boolean(p2p.team, ['p2p', 'team']);
150
+ allowAgents = boolean(p2p.allowAgents, ['p2p', 'allowAgents']);
151
+ if (allowAgents && !share) {
152
+ throw new Problem(['p2p', 'allowAgents'], 'needs p2p.share: true; it lets the coding agents of teammates who watch the shared log read it.');
153
+ }
149
154
  if (team && !share) {
150
155
  throw new Problem(['p2p', 'team'], 'only works together with p2p.share: true; it decides who the shared services and the shared log are for.');
151
156
  }
@@ -191,7 +196,8 @@ function validate(value, ordered) {
191
196
  if (edgeUrl === null && services.some((service) => service.public)) {
192
197
  throw new Problem(['edge', 'url'], 'is missing, and a service is public; add the URL of the edge, for example ws://127.0.0.1:8787 for a local edge.');
193
198
  }
194
- return { inspectorPort, edgeUrl, controlPlaneUrl, share, allow, team, services };
199
+ const agent = root.agent === undefined ? null : boolean(root.agent, ['agent']);
200
+ return { inspectorPort, edgeUrl, controlPlaneUrl, share, allow, team, allowAgents, agent, services };
195
201
  }
196
202
  /**
197
203
  * The names of the services in the order of the file. The plain object cannot say: JavaScript lists keys that look
@@ -1,5 +1,8 @@
1
1
  import { RANDOM_SUBDOMAIN_PREFIX, isPlanName, isPublicKeyHex, isSubdomain } from '@hopwire/protocol';
2
+ import http from 'node:http';
3
+ import https from 'node:https';
2
4
  import { TemporaryError, HopwireError } from './errors.js';
5
+ import { proxiedConnection, proxyFor, throughProxy } from './outbound-proxy.js';
3
6
  import { printable } from './output.js';
4
7
  import { parseEdgeUrl } from './urls.js';
5
8
  /**
@@ -189,6 +192,8 @@ function seconds(value, fallback, min, max) {
189
192
  function connect(options) {
190
193
  const where = options.url.origin;
191
194
  const timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
195
+ // HTTPS_PROXY / HTTP_PROXY and NO_PROXY; a proxy URL that cannot be used is refused before any request
196
+ const proxy = proxyFor(options.url);
192
197
  /** One request; resolves with the status and the answer as JSON (null when it is none). */
193
198
  const request = async (method, path, body, signal, maxAnswerBytes = MAX_ANSWER_BYTES) => {
194
199
  signal?.throwIfAborted();
@@ -196,15 +201,20 @@ function connect(options) {
196
201
  const timer = setTimeout(() => timeout.abort(), timeoutMs);
197
202
  const stop = () => timeout.abort();
198
203
  signal?.addEventListener('abort', stop, { once: true });
204
+ const headers = {
205
+ accept: 'application/json',
206
+ ...(options.apiToken === undefined ? {} : { authorization: `Bearer ${options.apiToken}` }),
207
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
208
+ };
209
+ const payload = body === undefined ? undefined : JSON.stringify(body);
199
210
  try {
211
+ if (proxy !== null) {
212
+ return await requestThroughProxy(proxy, new URL(path, options.url), method, headers, payload, timeout.signal, maxAnswerBytes);
213
+ }
200
214
  const response = await fetch(new URL(path, options.url), {
201
215
  method,
202
- headers: {
203
- accept: 'application/json',
204
- ...(options.apiToken === undefined ? {} : { authorization: `Bearer ${options.apiToken}` }),
205
- ...(body === undefined ? {} : { 'content-type': 'application/json' }),
206
- },
207
- body: body === undefined ? undefined : JSON.stringify(body),
216
+ headers,
217
+ body: payload,
208
218
  // The API token is never carried on to another address
209
219
  redirect: 'manual',
210
220
  signal: timeout.signal,
@@ -214,7 +224,7 @@ function connect(options) {
214
224
  catch (error) {
215
225
  // Stopped by the caller: that is its own reason, not a failure of the control plane
216
226
  signal?.throwIfAborted();
217
- throw new TemporaryError(`The control plane at ${where} cannot be reached (${timeout.signal.aborted ? 'TIMEOUT' : networkCode(error)}); check its URL, your connection and that it is running.`);
227
+ throw new TemporaryError(`The control plane at ${where} cannot be reached${throughProxy(proxy)} (${timeout.signal.aborted ? 'TIMEOUT' : networkCode(error)}); check its URL, your connection${proxy === null ? '' : ', the proxy'} and that it is running.`);
218
228
  }
219
229
  finally {
220
230
  clearTimeout(timer);
@@ -240,6 +250,54 @@ function connect(options) {
240
250
  const malformed = (what) => new HopwireError(`The control plane at ${where} did not answer with ${what}; check that the URL is the one of a Hopwire control plane and that it matches this version of the CLI.`);
241
251
  return { where, request, failure, malformed };
242
252
  }
253
+ /**
254
+ * One request through an HTTP proxy (CONNECT, then TLS to the control plane), answered like the fetch path: the
255
+ * status and the answer as JSON, null when it is not JSON or longer than maxBytes. Redirects are not followed, so
256
+ * the API token never goes to another address.
257
+ */
258
+ function requestThroughProxy(proxy, url, method, headers, payload, signal, maxBytes) {
259
+ return new Promise((resolve, reject) => {
260
+ const send = url.protocol === 'https:' ? https.request : http.request;
261
+ const request = send(url, {
262
+ method,
263
+ headers: payload === undefined ? headers : { ...headers, 'content-length': String(Buffer.byteLength(payload)) },
264
+ createConnection: proxiedConnection(proxy, url),
265
+ signal,
266
+ });
267
+ request.once('error', reject);
268
+ request.once('response', (response) => {
269
+ const chunks = [];
270
+ let length = 0;
271
+ let tooLong = false;
272
+ response.on('data', (chunk) => {
273
+ length += chunk.length;
274
+ if (length > maxBytes) {
275
+ tooLong = true;
276
+ response.destroy();
277
+ resolve({ status: response.statusCode ?? 0, json: null });
278
+ return;
279
+ }
280
+ chunks.push(chunk);
281
+ });
282
+ response.once('error', (error) => {
283
+ if (!tooLong) {
284
+ reject(error);
285
+ }
286
+ });
287
+ response.once('end', () => {
288
+ let json;
289
+ try {
290
+ json = JSON.parse(Buffer.concat(chunks).toString('utf8'));
291
+ }
292
+ catch {
293
+ json = null;
294
+ }
295
+ resolve({ status: response.statusCode ?? 0, json });
296
+ });
297
+ });
298
+ request.end(payload);
299
+ });
300
+ }
243
301
  /** The answer as JSON, null when it is not JSON or longer than anything the control plane sends. */
244
302
  async function readJson(response, maxBytes) {
245
303
  if (response.body === null) {
@@ -1,4 +1,5 @@
1
1
  import { WebSocket } from 'ws';
2
+ import { proxiedConnection, proxyFor, throughProxy } from './outbound-proxy.js';
2
3
  import { BASIC_AUTH_HEADER, CHUNK_SIZE_BYTES, CLOSE_CODE_IDLE, CLOSE_CODE_REPLACED, CLOSE_CODE_TOKEN_EXPIRED, EDGE_CONNECT_PATH, FLOW_ACK_BYTES, FLOW_WINDOW_BYTES, KEEPALIVE_HEADER, KEEPALIVE_INTERVAL_MS, KEEPALIVE_MISSED_PONGS, PUBLIC_URL_HEADER, ProtocolError, RECONNECT_BACKOFF_MS, TOKEN_EXPIRES_IN_HEADER, USAGE_HEADER, WS_CLOSE, WS_MESSAGE_MAX_BYTES, closeReason, decodeEdgeToCliMessage, decodeUsageSnapshot, encodeMessage, getHeader, isBase64, keepaliveTexts, webSocketMessageCost, } from '@hopwire/protocol';
3
4
  import { TemporaryError, HopwireError } from './errors.js';
4
5
  import { printable } from './output.js';
@@ -63,6 +64,8 @@ export async function startEdgeBridge(options) {
63
64
  };
64
65
  const { subdomain, interceptor } = options;
65
66
  const edge = options.edgeUrl.origin;
67
+ // HTTPS_PROXY / HTTP_PROXY and NO_PROXY, read once per tunnel; a proxy URL that cannot be used ends the start here
68
+ const proxy = proxyFor(options.edgeUrl);
66
69
  const proto = forwardedProto(options.edgeUrl);
67
70
  let token = options.token;
68
71
  /**
@@ -127,6 +130,11 @@ export async function startEdgeBridge(options) {
127
130
  closeTimeout: CLOSE_HANDSHAKE_TIMEOUT_MS,
128
131
  maxPayload: MAX_FRAME_BYTES,
129
132
  followRedirects: false,
133
+ // Node's http client and ws take a createConnection that answers through its callback; the ws types
134
+ // only know the synchronous form
135
+ ...(proxy === null
136
+ ? {}
137
+ : { createConnection: proxiedConnection(proxy, url) }),
130
138
  };
131
139
  const candidate = new WebSocket(url, socketOptions);
132
140
  pending = candidate;
@@ -821,7 +829,9 @@ export async function startEdgeBridge(options) {
821
829
  throw withoutToken(first.error);
822
830
  }
823
831
  if (first.kind === 'unreachable') {
824
- throw new HopwireError(`The edge at ${edge} cannot be reached (${first.code}); check the edge URL and that the edge is running.`);
832
+ throw new HopwireError(proxy !== null && first.code.startsWith('PROXY_')
833
+ ? `The edge at ${edge} cannot be reached${throughProxy(proxy)}: ${proxyHint(first.code)}`
834
+ : `The edge at ${edge} cannot be reached${throughProxy(proxy)} (${first.code}); check the edge URL and that the edge is running.`);
825
835
  }
826
836
  return {
827
837
  publicUrl: first.publicUrl,
@@ -1029,3 +1039,19 @@ function errorCode(error) {
1029
1039
  }
1030
1040
  return 'UNKNOWN';
1031
1041
  }
1042
+ /** What to check when the proxy step failed, by its code (outbound-proxy.ts). */
1043
+ export function proxyHint(code) {
1044
+ if (code === 'PROXY_407') {
1045
+ return 'the proxy asks for credentials (407); put them into the proxy URL (http://user:password@host:port).';
1046
+ }
1047
+ if (code === 'PROXY_403' || code === 'PROXY_405') {
1048
+ return `the proxy refused the tunnel (${code.slice(6)}); ask whoever runs it to allow CONNECT to the edge on port 443.`;
1049
+ }
1050
+ if (code === 'PROXY_TIMEOUT') {
1051
+ return 'the proxy did not open a tunnel in time; check the proxy URL and your connection.';
1052
+ }
1053
+ if (/^PROXY_\d+$/.test(code)) {
1054
+ return `the proxy answered ${code.slice(6)} instead of opening a tunnel; check the proxy URL, or set NO_PROXY for the edge if it is reached directly.`;
1055
+ }
1056
+ return `the proxy cannot be reached (${code.slice(6)}); check the proxy URL and that the proxy is running.`;
1057
+ }