hopwire 0.1.2 → 0.1.4

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('?');
package/dist/cli.js CHANGED
@@ -127,9 +127,16 @@ Global options:
127
127
  --version Show the version
128
128
  `;
129
129
  /** What `hopwire mcp` says on standard error when a person starts it on a terminal. */
130
- export const MCP_TERMINAL_HINT = 'hopwire mcp is running and waits for a coding agent on standard input. It is meant to be started by the ' +
131
- 'agent, not by hand, for example: claude mcp add hopwire -- hopwire mcp\n' +
132
- 'Press Ctrl+C to stop.';
130
+ export const MCP_TERMINAL_HINT = [
131
+ 'hopwire mcp is an MCP server for coding agents. It is started by the agent, not by hand,',
132
+ 'and is now waiting for one on standard input.',
133
+ '',
134
+ ' 1. Start a tunnel with --agent: hopwire http 3000 --agent',
135
+ ' 2. Register it with your agent: claude mcp add hopwire -- hopwire mcp',
136
+ '',
137
+ `Cursor, Codex and other agents: ${DOCS_URL}/coding-agents`,
138
+ 'Press Ctrl+C to stop.',
139
+ ].join('\n');
133
140
  /** Options every command takes, and the ones of each command. Anything else is a usage error. */
134
141
  const GLOBAL_OPTIONS = ['help', 'version', 'data-dir'];
135
142
  const COMMAND_OPTIONS = {
@@ -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,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
+ }
package/dist/mcp/body.js CHANGED
@@ -99,11 +99,14 @@ export function showBody(part, offset, maxChars) {
99
99
  truncatedAtCapture: part.bodyTruncated,
100
100
  };
101
101
  }
102
- const shown = safeText(redactText(text, contentType));
102
+ const display = redactText(text, contentType);
103
+ const shown = safeText(display.text);
103
104
  const page = shown.slice(offset, offset + maxChars);
104
105
  return {
105
106
  kind: 'text',
106
107
  decodedFrom: decoded.decodedFrom,
108
+ capturedBytes: raw.byteLength,
109
+ display: display.display,
107
110
  text: page,
108
111
  offset,
109
112
  totalChars: shown.length,
@@ -111,22 +114,29 @@ export function showBody(part, offset, maxChars) {
111
114
  truncatedAtCapture: part.bodyTruncated,
112
115
  };
113
116
  }
117
+ /** The whole text of a body as the model is shown it (decoded and redacted, not paged), or null for a binary body. */
118
+ export function shownText(part) {
119
+ const contentType = getHeader(part.headers, 'content-type') ?? null;
120
+ const decoded = decodedBytes(part);
121
+ const text = decoded === null ? null : bodyText(decoded.bytes, contentType, part.bodyTruncated);
122
+ return text === null || text === '' ? null : { text: redactText(text, contentType).text, contentType };
123
+ }
114
124
  /** JSON is shown pretty-printed with sensitive keys redacted, a form with sensitive fields redacted. */
115
125
  function redactText(text, contentType) {
116
126
  const type = (contentType ?? '').toLowerCase();
117
127
  if (type.includes('x-www-form-urlencoded')) {
118
- return redactUrlEncoded(text);
128
+ return { text: redactUrlEncoded(text), display: 'as-captured' };
119
129
  }
120
130
  if (type === '' || type.includes('json')) {
121
131
  try {
122
- return JSON.stringify(redactJson(JSON.parse(text)), null, 2);
132
+ return { text: JSON.stringify(redactJson(JSON.parse(text)), null, 2), display: 'json-pretty-printed' };
123
133
  }
124
134
  catch {
125
135
  // Not JSON after all, or cut at the capture limit: what looks like a sensitive field is still redacted
126
- return redactJsonText(text);
136
+ return { text: redactJsonText(text), display: 'as-captured' };
127
137
  }
128
138
  }
129
- return text;
139
+ return { text, display: 'as-captured' };
130
140
  }
131
141
  /** Text with control and invisible format characters escaped; tabs and line breaks stay. */
132
142
  export function safeText(text) {
@@ -0,0 +1,278 @@
1
+ import { safeText } from './body.js';
2
+ const MAX_MESSAGE_CHARS = 600;
3
+ const MAX_FRAMES = 5;
4
+ /** How far into a page the summary looks for the error */
5
+ const SCAN_CHARS = 64 * 1024;
6
+ /** How far into a page the text fallback reads: error pages carry kilobytes of inline CSS before the first word */
7
+ const TEXT_SCAN_CHARS = 512 * 1024;
8
+ /** The summary of an error response, or null when the text holds nothing recognisable. */
9
+ export function summarizeError(text, contentType) {
10
+ const head = text.slice(0, SCAN_CHARS);
11
+ const type = (contentType ?? '').toLowerCase();
12
+ const summary = type.includes('json') ? fromJson(text) : (fromJson(text) ?? fromHtml(head, text));
13
+ if (summary === null) {
14
+ return null;
15
+ }
16
+ return {
17
+ ...summary,
18
+ exception: clean(summary.exception, 200),
19
+ message: clean(summary.message, MAX_MESSAGE_CHARS),
20
+ location: clean(summary.location, 300),
21
+ appFrames: summary.appFrames.map((frame) => clean(frame, 300) ?? ''),
22
+ };
23
+ }
24
+ function clean(value, max) {
25
+ if (value === null) {
26
+ return null;
27
+ }
28
+ const text = safeText(value.trim());
29
+ return text.length > max ? `${text.slice(0, max)}…` : text;
30
+ }
31
+ // ---- JSON: Laravel and Symfony debug output, RFC 9457 problem details, { error } and { message } ----
32
+ function fromJson(text) {
33
+ let body;
34
+ try {
35
+ body = JSON.parse(text);
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ if (!isObject(body)) {
41
+ return null;
42
+ }
43
+ const nested = isObject(body.error) ? body.error : null;
44
+ const exception = string(body.exception) ?? string(body.class) ?? string(nested?.type) ?? string(body.title);
45
+ const message = string(body.message) ??
46
+ string(body.detail) ??
47
+ string(nested?.message) ??
48
+ string(body.error) ??
49
+ string(body.error_description);
50
+ if (exception === null && message === null) {
51
+ return null;
52
+ }
53
+ const file = string(body.file);
54
+ const line = typeof body.line === 'number' || typeof body.line === 'string' ? String(body.line) : null;
55
+ const frames = jsonFrames(body.trace ?? nested?.trace ?? body.stack ?? nested?.stack);
56
+ return {
57
+ format: 'json',
58
+ exception,
59
+ message,
60
+ location: file === null ? null : line === null ? file : `${file}:${line}`,
61
+ appFrames: pickFrames(frames),
62
+ totalFrames: frames.length,
63
+ };
64
+ }
65
+ function jsonFrames(trace) {
66
+ if (typeof trace === 'string') {
67
+ return stackLines(trace);
68
+ }
69
+ if (!Array.isArray(trace)) {
70
+ return [];
71
+ }
72
+ return trace.flatMap((frame) => {
73
+ if (typeof frame === 'string') {
74
+ return [frame];
75
+ }
76
+ if (!isObject(frame)) {
77
+ return [];
78
+ }
79
+ const where = string(frame.file) === null ? '[internal]' : `${string(frame.file)}:${String(frame.line ?? '?')}`;
80
+ const call = `${string(frame.class) ?? ''}${string(frame.type) ?? ''}${string(frame.function) ?? ''}`;
81
+ return [call === '' ? where : `${where} ${call}()`];
82
+ });
83
+ }
84
+ // ---- HTML ----
85
+ /**
86
+ * The known page formats first, then what any framework's page shows a reader (the exception name and the
87
+ * file:line locations in its visible text), then the title.
88
+ */
89
+ function fromHtml(head, text) {
90
+ return (fromPhpComment(head) ??
91
+ fromExpress(head) ??
92
+ fromDjango(head) ??
93
+ fromVisibleText(text.slice(0, TEXT_SCAN_CHARS)) ??
94
+ fromTitle(head));
95
+ }
96
+ /** Laravel's and Symfony's HTML error pages begin with a comment that holds the exception and its trace. */
97
+ function fromPhpComment(html) {
98
+ const comment = /<!--\s*([\s\S]*?)-->/.exec(html)?.[1];
99
+ if (comment === undefined) {
100
+ return null;
101
+ }
102
+ const text = decodeEntities(comment);
103
+ const head = /^([A-Za-z_\\][\w\\]*): ([\s\S]*?) in file (\S+) on line (\d+)/.exec(text);
104
+ if (head === null) {
105
+ return null;
106
+ }
107
+ const frames = text
108
+ .split('\n')
109
+ .map((line) => /^#\d+ (.+)$/.exec(line.trim())?.[1])
110
+ .filter((line) => line !== undefined);
111
+ return {
112
+ format: 'php-comment',
113
+ exception: head[1] ?? null,
114
+ message: head[2] ?? null,
115
+ location: `${head[3]}:${head[4]}`,
116
+ appFrames: pickFrames(frames),
117
+ totalFrames: frames.length,
118
+ };
119
+ }
120
+ /** Express's default error handler: the stack in a <pre>, lines joined with <br>. */
121
+ function fromExpress(html) {
122
+ const pre = /<pre>([\s\S]*?)<\/pre>/i.exec(html)?.[1];
123
+ if (pre === undefined) {
124
+ return null;
125
+ }
126
+ const text = decodeEntities(pre.replace(/<br\s*\/?>/gi, '\n'));
127
+ const first = /^([A-Za-z_$][\w$.]*(?:Error|Exception)): ?(.*)$/m.exec(text.trim());
128
+ if (first === null) {
129
+ return null;
130
+ }
131
+ const frames = stackLines(text);
132
+ return {
133
+ format: 'express',
134
+ exception: first[1] ?? null,
135
+ message: first[2] ?? null,
136
+ location: frames[0] ?? null,
137
+ appFrames: pickFrames(frames),
138
+ totalFrames: frames.length,
139
+ };
140
+ }
141
+ /** Django's debug page. */
142
+ function fromDjango(html) {
143
+ const value = /<pre class="exception_value">([\s\S]*?)<\/pre>/i.exec(html)?.[1];
144
+ if (value === undefined) {
145
+ return null;
146
+ }
147
+ const title = titleOf(html);
148
+ const where = /<th[^>]*>Exception Location:<\/th>\s*<td>([\s\S]*?)<\/td>/i.exec(html)?.[1];
149
+ return {
150
+ format: 'django',
151
+ exception: title === null ? null : (/^(\S+) at /.exec(title)?.[1] ?? null),
152
+ message: decodeEntities(value),
153
+ location: where === undefined ? null : stripTags(where),
154
+ appFrames: [],
155
+ totalFrames: 0,
156
+ };
157
+ }
158
+ /**
159
+ * Any page or plain text, whatever the framework: the visible text (scripts, styles and tags removed) read for the
160
+ * first exception or error name (TypeError, ErrorException, java.lang.NullPointerException, KeyError) and for source
161
+ * locations in the forms stack traces print them (file.php:25, file.js:26:28, File "app.py", line 12, Foo.cs:line 42,
162
+ * Foo.java:42). Null when the text names neither, so a page without an error falls through to its title.
163
+ */
164
+ function fromVisibleText(page) {
165
+ const text = visibleText(page);
166
+ const exception = EXCEPTION_NAME.exec(text);
167
+ const frames = locations(text);
168
+ if (exception === null && frames.length === 0) {
169
+ return null;
170
+ }
171
+ const start = exception?.index ?? 0;
172
+ return {
173
+ format: 'text',
174
+ exception: exception?.[1] ?? null,
175
+ message: text.slice(start, start + MAX_MESSAGE_CHARS * 2),
176
+ location: frames[0] ?? null,
177
+ appFrames: pickFrames(frames),
178
+ totalFrames: frames.length,
179
+ };
180
+ }
181
+ /** A class name ending in Exception or Error, optionally qualified (App\\Foo, java.lang.Foo, Foo::Bar) */
182
+ const EXCEPTION_NAME = /(?<![\w$\\.:])((?:[A-Za-z_][\w$]*(?:\\|\.|::))*[A-Z][\w$]*(?:Exception|Error))\b/;
183
+ const SOURCE_EXTENSION = 'php|phtml|m?js|cjs|tsx?|jsx|mts|cts|py|rb|erb|go|java|kt|scala|groovy|cs|cshtml|razor|fs|vb|ex|exs|erl|rs|swift|dart|c|cc|cpp|h|hpp|lua|pl|pm|twig|vue|svelte|astro';
184
+ /** file.ext followed by a line number: ":25" (also " :25", as separate HTML elements leave it), "(25)", '", line 25', ", line 25", ":line 25" */
185
+ const LOCATION = new RegExp(`((?:[A-Za-z]:)?[\\w@~.\\-/\\\\]*[\\w-]\\.(?:${SOURCE_EXTENSION}))(?:\\s?:(\\d+)|\\((\\d+)\\)|"?, line (\\d+)|:line (\\d+))`, 'g');
186
+ /** The source locations of a text in order of appearance, each once, as "file:line". */
187
+ function locations(text) {
188
+ const seen = new Set();
189
+ for (const match of text.matchAll(LOCATION)) {
190
+ const line = match[2] ?? match[3] ?? match[4] ?? match[5];
191
+ if (match[1] !== undefined && line !== undefined) {
192
+ seen.add(`${match[1]}:${line}`);
193
+ }
194
+ }
195
+ return [...seen];
196
+ }
197
+ /**
198
+ * What a reader of the page sees: no scripts, styles, comments or head, tags removed with their quoted attributes.
199
+ * Text that is not HTML (a plain stack trace, where "<anonymous>" is not a tag) is only folded onto one line.
200
+ */
201
+ function visibleText(html) {
202
+ if (!/<(!doctype|html|body|div|p|pre|h1)\b/i.test(html.slice(0, SCAN_CHARS))) {
203
+ return html.replace(/\s+/g, ' ').trim();
204
+ }
205
+ return decodeEntities(html
206
+ .replace(/<!--[\s\S]*?-->/g, ' ')
207
+ .replace(/<(script|style|svg|template|noscript|head)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, ' ')
208
+ // a quoted attribute may hold ">" (Alpine's x-data, inline handlers)
209
+ .replace(/<\/?[A-Za-z!][^>"']*(?:(?:"[^"]*"|'[^']*')[^>"']*)*>/g, ' '))
210
+ .replace(/\s+/g, ' ')
211
+ .trim();
212
+ }
213
+ /** Any other page: its title and first heading. */
214
+ function fromTitle(html) {
215
+ const title = titleOf(html);
216
+ const h1 = /<h1[^>]*>([\s\S]*?)<\/h1>/i.exec(html)?.[1];
217
+ const heading = h1 === undefined ? null : stripTags(h1);
218
+ if (title === null && (heading === null || heading === '')) {
219
+ return null;
220
+ }
221
+ return {
222
+ format: 'html',
223
+ exception: null,
224
+ message: heading !== null && heading !== '' && heading !== title
225
+ ? `${title ?? ''}${title ? ': ' : ''}${heading}`
226
+ : title,
227
+ location: null,
228
+ appFrames: [],
229
+ totalFrames: 0,
230
+ };
231
+ }
232
+ function titleOf(html) {
233
+ const title = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1];
234
+ if (title === undefined) {
235
+ return null;
236
+ }
237
+ const text = stripTags(title);
238
+ return text === '' ? null : text;
239
+ }
240
+ // ---- helpers ----
241
+ /** The "at ..." lines of a JavaScript stack. */
242
+ function stackLines(stack) {
243
+ return stack
244
+ .split('\n')
245
+ .map((line) => /^\s*at (.+)$/.exec(line)?.[1]?.trim())
246
+ .filter((line) => line !== undefined);
247
+ }
248
+ const LIBRARY_FRAME = /(^|[\s(\\/])(vendor|node_modules|site-packages|dist-packages|gems)[\\/]|[\\/]go[\\/]pkg[\\/]mod[\\/]|^node:|\(node:|\[internal\]/;
249
+ function pickFrames(frames) {
250
+ const own = frames.filter((frame) => !LIBRARY_FRAME.test(frame));
251
+ return (own.length > 0 ? own : frames).slice(0, MAX_FRAMES);
252
+ }
253
+ function stripTags(html) {
254
+ return decodeEntities(html.replace(/<[^>]*>/g, ' '))
255
+ .replace(/\s+/g, ' ')
256
+ .trim();
257
+ }
258
+ const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
259
+ function decodeEntities(text) {
260
+ return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, name) => {
261
+ if (name.startsWith('#x') || name.startsWith('#X')) {
262
+ return codePoint(Number.parseInt(name.slice(2), 16)) ?? entity;
263
+ }
264
+ if (name.startsWith('#')) {
265
+ return codePoint(Number.parseInt(name.slice(1), 10)) ?? entity;
266
+ }
267
+ return ENTITIES[name.toLowerCase()] ?? entity;
268
+ });
269
+ }
270
+ function codePoint(value) {
271
+ return Number.isInteger(value) && value >= 0 && value <= 0x10ffff ? String.fromCodePoint(value) : null;
272
+ }
273
+ function isObject(value) {
274
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
275
+ }
276
+ function string(value) {
277
+ return typeof value === 'string' && value.trim() !== '' ? value : null;
278
+ }
package/dist/mcp/tools.js CHANGED
@@ -2,8 +2,9 @@ import { getHeader, isBase64, isWebSocketHandshake, } from '@hopwire/protocol';
2
2
  import { REDACTION_MARKER, isRedactedHeader, redactHeaders } from '../agent/redact.js';
3
3
  import { summarize } from '../agent/summary.js';
4
4
  import { printable } from '../output.js';
5
- import { contentEncoding, decodedBytes, encode, showBody } from './body.js';
5
+ import { contentEncoding, decodedBytes, encode, showBody, shownText } from './body.js';
6
6
  import { START_HINT, ToolError } from './client.js';
7
+ import { summarizeError } from './error-summary.js';
7
8
  /**
8
9
  * The tools of `hopwire mcp` (spec phase 10). Everything they return is captured traffic of third parties, so every
9
10
  * result carries NOTE and every description repeats it; values a model reads are escaped and redacted, and a replay
@@ -231,6 +232,13 @@ function show(summary) {
231
232
  response: printableContentType(summary.response),
232
233
  };
233
234
  }
235
+ /** The summary without its part summaries, for a result that shows the parts themselves. */
236
+ function showHead(summary) {
237
+ const head = show(summary);
238
+ delete head.request;
239
+ delete head.response;
240
+ return head;
241
+ }
234
242
  function printableContentType(part) {
235
243
  return { ...part, contentType: part.contentType === null ? null : printable(part.contentType) };
236
244
  }
@@ -240,6 +248,18 @@ function shownHeaders(headers) {
240
248
  function shownPart(part, offset, max) {
241
249
  return { headers: shownHeaders(part.headers), body: showBody(part, offset, max) };
242
250
  }
251
+ /** The response of a server error with a summary of its error page first, so the exception is read before the page. */
252
+ function shownResponse(exchange, offset, max) {
253
+ const { headers, body } = shownPart(exchange.response, offset, max);
254
+ if (exchange.response.status < 500) {
255
+ return { headers, body };
256
+ }
257
+ return { headers, errorSummary: errorSummaryOf(exchange.response), body };
258
+ }
259
+ function errorSummaryOf(part) {
260
+ const shown = shownText(part);
261
+ return shown === null ? null : summarizeError(shown.text, shown.contentType);
262
+ }
243
263
  /** Why an exchange cannot be replayed as it is, or null. */
244
264
  function notReplayable(exchange) {
245
265
  if (isWebSocketHandshake(exchange)) {
@@ -340,7 +360,7 @@ const listTool = {
340
360
  const getTool = {
341
361
  name: 'hopwire_get_exchange',
342
362
  title: 'Show a captured request',
343
- description: `One captured exchange by id: request and response headers (credentials and signatures redacted) and bodies, decompressed and decoded as text in pages of maxChars (JSON pretty-printed, fields such as password, token or card redacted; continue with bodyOffset); a binary body is given as size and sha256 only. ${NOTE}`,
363
+ description: `One captured exchange by id: request and response headers (credentials and signatures redacted) and bodies, decompressed and decoded as text in pages of maxChars (JSON pretty-printed, fields such as password, token or card redacted; continue with bodyOffset); a binary body is given as size and sha256 only. A text body names capturedBytes and display: json-pretty-printed means the JSON was printed again for reading, so the text is not the bytes that were sent (a signature over the body covers those bytes, and bodyOffset, maxBodyChars and totalChars count characters of the text shown); as-captured is the text as sent, decompressed when decodedFrom is set. Signature headers keep their timestamp (Stripe's t=) and show the rest redacted. A response with status 500 or above also has errorSummary: exception, message, location and the first stack frames outside library folders (vendor, node_modules, site-packages), read from the error page: the known formats of Laravel and Symfony, Express, Django and JSON error bodies, otherwise from any framework's page or plain-text stack trace the first exception name and the file:line locations it shows, otherwise the page title, or null when the page names no error. Read it before paging through the body. ${NOTE}`,
344
364
  inputSchema: schema({
345
365
  id: { type: 'string' },
346
366
  part: { type: 'string', enum: ['request', 'response', 'both'], default: 'both' },
@@ -360,9 +380,9 @@ const getTool = {
360
380
  const found = await record(context, id);
361
381
  const reason = notReplayable(found.exchange);
362
382
  return {
363
- exchange: show(summarize(found)),
383
+ exchange: showHead(summarize(found)),
364
384
  ...(part === 'response' ? {} : { request: shownPart(found.exchange.request, offset, max) }),
365
- ...(part === 'request' ? {} : { response: shownPart(found.exchange.response, offset, max) }),
385
+ ...(part === 'request' ? {} : { response: shownResponse(found.exchange, offset, max) }),
366
386
  replayable: reason === null,
367
387
  notReplayableReason: reason,
368
388
  };
@@ -630,7 +650,7 @@ export function applyEdit(stored, edit) {
630
650
  const replayTool = {
631
651
  name: 'hopwire_replay',
632
652
  title: 'Replay a captured request',
633
- description: `Sends a captured request again to the tunnel's local service (and nowhere else) and returns the new response; the replay is logged with source replay. Without edit the stored request is sent byte for byte, credentials and signatures included. edit changes it: method, path, setHeaders, removeHeaders, and one of body (text), bodyBase64 or jsonSet (RFC 6901 pointers patched into the stored JSON body). Redacted placeholders are refused: leave a field out to keep its stored value. Side effects on the local service are real (database writes, mails). Signed webhooks (Stripe's timestamp tolerance, GitHub's HMAC) may reject an old or edited replay; use the handler's test signing mode. One replay at a time, at most ${REPLAYS_PER_MINUTE} a minute. ${NOTE}`,
653
+ description: `Sends a captured request again to the tunnel's local service (and nowhere else) and returns the new response; the replay is logged with source replay. Without edit the stored request is sent byte for byte, credentials and signatures included, and the result says sentAsCaptured: true; with edit it is false. edit changes it: method, path, setHeaders, removeHeaders, and one of body (text), bodyBase64 or jsonSet (RFC 6901 pointers patched into the stored JSON body). Redacted placeholders are refused: leave a field out to keep its stored value. Side effects on the local service are real (database writes, mails). Signed webhooks (Stripe's timestamp tolerance, GitHub's HMAC) may reject an old or edited replay; use the handler's test signing mode. One replay at a time, at most ${REPLAYS_PER_MINUTE} a minute. ${NOTE}`,
634
654
  inputSchema: schema({
635
655
  id: { type: 'string' },
636
656
  responseBodyChars: {
@@ -695,6 +715,8 @@ const replayTool = {
695
715
  const body = showBody(exchange.response, 0, chars);
696
716
  return {
697
717
  original: { id: original.exchange.id, status: original.exchange.response.status },
718
+ // Without an edit the tunnel sends the stored method, path, headers and body bytes of that block
719
+ sentAsCaptured: edit === null,
698
720
  replay: show(summarize(stored)),
699
721
  response: {
700
722
  status: exchange.response.status,
@@ -0,0 +1,206 @@
1
+ import http from 'node:http';
2
+ import net from 'node:net';
3
+ import tls from 'node:tls';
4
+ import { HopwireError } from './errors.js';
5
+ /** How long the proxy may take to open the tunnel to the target; the handshake timeout of the caller starts after it. */
6
+ const CONNECT_TIMEOUT_MS = 10_000;
7
+ /** The variables a proxy for a target of this scheme is read from, in this order (lower case first, as curl does). */
8
+ function variablesFor(protocol) {
9
+ if (protocol === 'https:' || protocol === 'wss:') {
10
+ return ['https_proxy', 'HTTPS_PROXY'];
11
+ }
12
+ if (protocol === 'http:' || protocol === 'ws:') {
13
+ return ['http_proxy', 'HTTP_PROXY'];
14
+ }
15
+ return null;
16
+ }
17
+ /** The default port of a scheme, for NO_PROXY entries with a port. */
18
+ function portOf(target) {
19
+ if (target.port !== '') {
20
+ return target.port;
21
+ }
22
+ return target.protocol === 'https:' || target.protocol === 'wss:' ? '443' : '80';
23
+ }
24
+ /** The host of a URL without the brackets of an IPv6 address, in lower case. */
25
+ function hostOf(target) {
26
+ return target.hostname.replace(/^\[(.*)\]$/, '$1').toLowerCase();
27
+ }
28
+ function isLoopback(host) {
29
+ return host === 'localhost' || host.endsWith('.localhost') || host === '::1' || /^127\.\d+\.\d+\.\d+$/.test(host);
30
+ }
31
+ /**
32
+ * Whether NO_PROXY exempts the target: `*` exempts everything; an entry exempts its host and every subdomain of it
33
+ * (a leading dot or `*.` changes nothing); an entry with a port only that port. IP addresses match exactly.
34
+ */
35
+ function exempted(target, noProxy) {
36
+ const host = hostOf(target);
37
+ const port = portOf(target);
38
+ for (const raw of noProxy.split(/[\s,]+/)) {
39
+ let entry = raw.trim().toLowerCase();
40
+ if (entry === '') {
41
+ continue;
42
+ }
43
+ if (entry === '*') {
44
+ return true;
45
+ }
46
+ let entryPort = null;
47
+ const bracketed = /^\[([^\]]+)\](?::(\d+))?$/.exec(entry);
48
+ if (bracketed !== null) {
49
+ entry = bracketed[1] ?? '';
50
+ entryPort = bracketed[2] ?? null;
51
+ }
52
+ else if (net.isIP(entry) === 0) {
53
+ const withPort = /^(.*):(\d+)$/.exec(entry);
54
+ if (withPort !== null) {
55
+ entry = withPort[1] ?? '';
56
+ entryPort = withPort[2] ?? null;
57
+ }
58
+ }
59
+ if (entryPort !== null && entryPort !== port) {
60
+ continue;
61
+ }
62
+ entry = entry.replace(/^\*?\./, '');
63
+ if (host === entry || (net.isIP(host) === 0 && host.endsWith(`.${entry}`))) {
64
+ return true;
65
+ }
66
+ }
67
+ return false;
68
+ }
69
+ /**
70
+ * The proxy for a connection to `target`, or null for a direct connection: without a proxy variable, for a loopback
71
+ * target (a local edge or control plane is never reached through a proxy) and for a target NO_PROXY exempts.
72
+ * A proxy URL that is not http:// is refused with the variable named.
73
+ */
74
+ export function proxyFor(target, env = process.env) {
75
+ const variables = variablesFor(target.protocol);
76
+ if (variables === null || isLoopback(hostOf(target))) {
77
+ return null;
78
+ }
79
+ let source = null;
80
+ let value = '';
81
+ for (const name of variables) {
82
+ const candidate = env[name]?.trim() ?? '';
83
+ if (candidate !== '') {
84
+ source = name;
85
+ value = candidate;
86
+ break;
87
+ }
88
+ }
89
+ if (source === null) {
90
+ return null;
91
+ }
92
+ if (exempted(target, env.no_proxy ?? env.NO_PROXY ?? '')) {
93
+ return null;
94
+ }
95
+ let url;
96
+ try {
97
+ // A bare host:port, as some systems set it, means http://
98
+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? value : `http://${value}`);
99
+ }
100
+ catch {
101
+ throw new HopwireError(`${source} is not a proxy URL; set it to http://<host>:<port> or unset it.`);
102
+ }
103
+ if (url.protocol !== 'http:') {
104
+ throw new HopwireError(`${source} names a ${url.protocol.replace(/:$/, '')} proxy; Hopwire supports HTTP proxies only (http://<host>:<port>).`);
105
+ }
106
+ const authorization = url.username === '' && url.password === ''
107
+ ? null
108
+ : `Basic ${Buffer.from(`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`, 'utf8').toString('base64')}`;
109
+ url.username = '';
110
+ url.password = '';
111
+ return { url, source, authorization };
112
+ }
113
+ /** The proxy as it may be printed: its origin, never its credentials. */
114
+ export function describeProxy(proxy) {
115
+ return `${proxy.url.origin} (${proxy.source}${proxy.authorization === null ? '' : ', with credentials'})`;
116
+ }
117
+ /** An error of the proxy step, with a code that says it happened there (PROXY_407, PROXY_ECONNREFUSED, PROXY_TIMEOUT). */
118
+ function proxyError(code, message) {
119
+ return Object.assign(new Error(message), { code: `PROXY_${code}` });
120
+ }
121
+ /**
122
+ * Opens a tunnel to host:port through the proxy (HTTP CONNECT) and, for a secure target, TLS to the target over it;
123
+ * calls back with the socket. The TLS options are those of the caller (servername, ca, rejectUnauthorized), so
124
+ * certificate checks are the same as for a direct connection, NODE_EXTRA_CA_CERTS included.
125
+ */
126
+ function tunnel(proxy, secure, options, callback) {
127
+ const host = (options.hostname ?? options.host ?? '').replace(/^\[(.*)\]$/, '$1');
128
+ const port = Number(options.port ?? (secure ? 443 : 80));
129
+ const authority = net.isIPv6(host) ? `[${host}]:${port}` : `${host}:${port}`;
130
+ let done = false;
131
+ const finish = (error, socket) => {
132
+ if (done) {
133
+ socket?.destroy();
134
+ return;
135
+ }
136
+ done = true;
137
+ clearTimeout(timer);
138
+ callback(error, socket);
139
+ };
140
+ const request = http.request({
141
+ host: proxy.url.hostname.replace(/^\[(.*)\]$/, '$1'),
142
+ port: Number(proxy.url.port === '' ? 80 : proxy.url.port),
143
+ method: 'CONNECT',
144
+ path: authority,
145
+ headers: {
146
+ host: authority,
147
+ ...(proxy.authorization === null ? {} : { 'proxy-authorization': proxy.authorization }),
148
+ },
149
+ agent: false,
150
+ });
151
+ const timer = setTimeout(() => {
152
+ request.destroy();
153
+ finish(proxyError('TIMEOUT', `the proxy did not open a tunnel to ${authority} in time`));
154
+ }, CONNECT_TIMEOUT_MS);
155
+ request.once('connect', (response, socket, head) => {
156
+ const status = response.statusCode ?? 0;
157
+ if (status < 200 || status > 299) {
158
+ socket.destroy();
159
+ finish(proxyError(String(status), `the proxy answered ${status} to CONNECT ${authority}`));
160
+ return;
161
+ }
162
+ if (head.length > 0) {
163
+ // Bytes of the target before it was asked anything: not a tunnel this client can use
164
+ socket.destroy();
165
+ finish(proxyError('PROTOCOL', `the proxy sent data before the tunnel to ${authority} was used`));
166
+ return;
167
+ }
168
+ if (!secure) {
169
+ finish(null, socket);
170
+ return;
171
+ }
172
+ const servername = options.servername ?? (net.isIP(host) === 0 ? host : undefined);
173
+ const secured = tls.connect({
174
+ ...options,
175
+ socket,
176
+ servername,
177
+ host: undefined,
178
+ port: undefined,
179
+ path: undefined,
180
+ });
181
+ // Errors of the TLS handshake reach the caller through the socket, as on a direct connection
182
+ finish(null, secured);
183
+ });
184
+ request.once('response', (response) => {
185
+ // A proxy that answers CONNECT with a body instead of switching
186
+ response.resume();
187
+ finish(proxyError(String(response.statusCode ?? 0), `the proxy answered ${response.statusCode ?? 0} to CONNECT ${authority}`));
188
+ });
189
+ request.once('error', (error) => {
190
+ const code = 'code' in error && typeof error.code === 'string' ? error.code : 'UNKNOWN';
191
+ finish(proxyError(code, `the proxy at ${proxy.url.origin} cannot be reached`));
192
+ });
193
+ request.end();
194
+ }
195
+ /** A `createConnection` that opens every connection to `target`'s scheme through the proxy. */
196
+ export function proxiedConnection(proxy, target) {
197
+ const secure = target.protocol === 'https:' || target.protocol === 'wss:';
198
+ return (options, callback) => {
199
+ tunnel(proxy, secure, options, callback);
200
+ return undefined;
201
+ };
202
+ }
203
+ /** The sentence that names the proxy in a message about a connection that failed, or nothing for a direct one. */
204
+ export function throughProxy(proxy) {
205
+ return proxy === null ? '' : ` through the proxy ${describeProxy(proxy)}`;
206
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hopwire",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Record, share and replay the HTTP traffic of your local services: private P2P sharing with teammates, and public HTTPS URLs.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://hopwire.to",