hopwire 0.4.0 → 0.5.1

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/bin.js CHANGED
@@ -8,14 +8,19 @@ import { wantsColor } from './style.js';
8
8
  import { LiveFeed } from './live.js';
9
9
  import { STARTING, Spinner, TerminalScreen, hopFrames, terminalLook } from './terminal.js';
10
10
  import { readVersion } from './version.js';
11
+ import { App } from './tui/app.js';
12
+ import { Facts, tunnelInfo } from './tui/model.js';
13
+ import { Screen } from './tui/screen.js';
11
14
  const argv = process.argv.slice(2);
12
15
  const look = terminalLook(process.env);
13
- const color = wantsColor(process.stdout, process.env);
14
- const colorErrors = wantsColor(process.stderr, process.env);
16
+ // --plain: the lines a pipe gets, on a terminal too. No colour, no keys, nothing redrawn
17
+ const plain = argv.includes('--plain');
18
+ const color = !plain && wantsColor(process.stdout, process.env);
19
+ const colorErrors = !plain && wantsColor(process.stderr, process.env);
15
20
  // A command that runs a tunnel, not its help: only these get the spinner and the keys
16
21
  const command = argv[0] ?? '';
17
22
  const tunnel = command in STARTING && !argv.some((arg) => arg === '--help' || arg === '-h' || arg === '--version');
18
- const keys = tunnel && process.stdin.isTTY === true && command !== 'connect';
23
+ const keys = tunnel && !plain && process.stdin.isTTY === true && command !== 'connect';
19
24
  // hopwire --version on a terminal shows the mark beside the version; a script reading it gets the bare version
20
25
  const versionOnly = argv.length === 1 && argv[0] === '--version';
21
26
  const screen = color || colorErrors
@@ -30,8 +35,28 @@ const screen = color || colorErrors
30
35
  const spinner = tunnel && colorErrors && screen !== null ? new Spinner(process.stderr, look, `${STARTING[command] ?? ''}...`) : null;
31
36
  spinner?.start();
32
37
  const quiet = () => spinner?.stop();
33
- // A tunnel's feed on a colour terminal: rows scroll above a status line that stays put
34
- const live = tunnel && color && screen !== null
38
+ // On a terminal with a keyboard http, up and watch take the whole window once they run: the full-screen view.
39
+ // Until then their lines are kept, not shown; a start that fails prints them as before
40
+ const fullScreen = keys && color && process.stdout.isTTY === true;
41
+ const facts = fullScreen ? new Facts() : null;
42
+ let app = null;
43
+ let held = fullScreen ? [] : null;
44
+ /** What was written to standard error while the view ran, with its time: shown again after it is gone */
45
+ const problems = [];
46
+ const release = () => {
47
+ if (held !== null) {
48
+ const lines = held;
49
+ held = null;
50
+ for (const { error, line } of lines) {
51
+ ;
52
+ (error ? process.stderr : process.stdout).write(`${line}\n`);
53
+ }
54
+ }
55
+ };
56
+ // A start that was stopped or failed never opened the view: its lines are shown as they would have been
57
+ process.once('exit', release);
58
+ // A tunnel's feed on a colour terminal without a keyboard: rows scroll above a status line that stays put
59
+ const live = tunnel && color && !fullScreen && screen !== null
35
60
  ? new LiveFeed(screen, process.stdout, () => process.stdout.columns ?? 100)
36
61
  : null;
37
62
  process.once('exit', () => live?.stop());
@@ -61,6 +86,87 @@ const hop = () => {
61
86
  process.stdout.write(`\u001b[${height}A\r\u001b[J`);
62
87
  }
63
88
  };
89
+ /**
90
+ * Opens the full-screen view for a tunnel that runs: the terminal goes into raw mode and the alternate screen, and
91
+ * both are given back when the process exits, however it does.
92
+ */
93
+ function openView(info, known, running) {
94
+ let rowWidth = 100;
95
+ const rows = new TerminalScreen({ look, width: () => rowWidth, version: readVersion(), shortcuts: false });
96
+ if ((running.kind === 'http' || running.kind === 'up') && running.webhookSecrets !== undefined) {
97
+ rows.checkSignatures(running.webhookSecrets);
98
+ }
99
+ const dataDir = argv.findIndex((arg) => arg === '--data-dir' || arg.startsWith('--data-dir='));
100
+ const dataDirValue = dataDir < 0
101
+ ? null
102
+ : (argv[dataDir] ?? '').includes('=')
103
+ ? (argv[dataDir] ?? '').split('=')[1]
104
+ : argv[dataDir + 1];
105
+ const view = new Screen(process.stdout, () => opened.draw());
106
+ const opened = new App(view, {
107
+ version: readVersion(),
108
+ info,
109
+ facts: known,
110
+ extraArgs: dataDirValue === null || dataDirValue === undefined ? '' : ` --data-dir ${dataDirValue}`,
111
+ ui: {
112
+ look,
113
+ row: (entry, width) => {
114
+ rowWidth = width;
115
+ return rows.row(entry.exchange, entry.label);
116
+ },
117
+ signature: (entry) => rows.signatureOf(entry.exchange),
118
+ now: Date.now,
119
+ },
120
+ actions: {
121
+ openBrowser: (url) => openBrowser(url),
122
+ copy: (text) => copyToClipboard(text, (escape) => view.control(escape)),
123
+ replay: replayThroughInspector,
124
+ fetchJson: async (url) => {
125
+ const response = await fetch(url);
126
+ if (!response.ok) {
127
+ throw new Error(`the inspector answered ${response.status}`);
128
+ }
129
+ return response.json();
130
+ },
131
+ interrupt: () => process.kill(process.pid, 'SIGINT'),
132
+ },
133
+ });
134
+ known.start();
135
+ held = null;
136
+ const input = process.stdin;
137
+ const onData = (chunk) => opened.input(chunk);
138
+ input.setRawMode(true);
139
+ input.setEncoding('utf8');
140
+ input.resume();
141
+ input.on('data', onData);
142
+ let closed = false;
143
+ const close = () => {
144
+ if (closed) {
145
+ return;
146
+ }
147
+ closed = true;
148
+ input.off('data', onData);
149
+ input.setRawMode(false);
150
+ input.pause();
151
+ view.stop();
152
+ // The window of the shell is back: what ran, and what went wrong at the end
153
+ process.stdout.write(`${opened.summary().join('\n')}\n`);
154
+ for (const problem of problems) {
155
+ if (Date.now() - problem.at < 3000) {
156
+ process.stderr.write(`${problem.line}\n`);
157
+ }
158
+ }
159
+ };
160
+ process.once('exit', close);
161
+ // A crash prints its trace after this: on the window of the shell, not on the view that is about to go
162
+ process.once('uncaughtExceptionMonitor', close);
163
+ for (const signal of ['SIGINT', 'SIGTERM']) {
164
+ process.on(signal, () => opened.stopping());
165
+ }
166
+ view.start();
167
+ opened.draw();
168
+ return opened;
169
+ }
64
170
  // Without the live feed (no colour), the newest exchange is still noted for the r key
65
171
  let last = null;
66
172
  let markShown = false;
@@ -68,6 +174,16 @@ await main({
68
174
  argv,
69
175
  env: process.env,
70
176
  print: (line) => {
177
+ if (app !== null) {
178
+ app.line(line);
179
+ return;
180
+ }
181
+ if (held !== null && facts !== null && screen !== null) {
182
+ quiet();
183
+ facts.line(line);
184
+ held.push({ error: false, line: screen.render(line) });
185
+ return;
186
+ }
71
187
  if (color && screen !== null && (versionOnly || line.startsWith('Logged in '))) {
72
188
  hop();
73
189
  }
@@ -75,6 +191,17 @@ await main({
75
191
  },
76
192
  error: (line) => {
77
193
  quiet();
194
+ if (app !== null) {
195
+ problems.push({ at: Date.now(), line });
196
+ app.problem(line);
197
+ return;
198
+ }
199
+ // A notice while the tunnel starts: kept with the lines of the start, and on record in the Status tab
200
+ if (held !== null && facts !== null) {
201
+ facts.note(line);
202
+ held.push({ error: true, line });
203
+ return;
204
+ }
78
205
  const write = () => process.stderr.write(`${line}\n`);
79
206
  if (live === null) {
80
207
  write();
@@ -112,6 +239,10 @@ await main({
112
239
  exchange: color || keys
113
240
  ? (exchange, label = '') => {
114
241
  quiet();
242
+ if (app !== null) {
243
+ app.exchange(exchange, label);
244
+ return;
245
+ }
115
246
  if (exchange.source !== 'replay') {
116
247
  last = exchange;
117
248
  }
@@ -125,6 +256,12 @@ await main({
125
256
  : undefined,
126
257
  started: (running) => {
127
258
  quiet();
259
+ const info = fullScreen && facts !== null ? tunnelInfo(running) : null;
260
+ if (info !== null && facts !== null) {
261
+ app = openView(info, facts, running);
262
+ return;
263
+ }
264
+ release();
128
265
  const target = shortcutTarget(running);
129
266
  // The signing secrets named on the command line or in hopwire.yaml: webhook rows show their signature
130
267
  if (screen !== null &&
@@ -156,6 +293,7 @@ await main({
156
293
  failure: colorErrors && screen !== null
157
294
  ? (message, hint) => {
158
295
  quiet();
296
+ release();
159
297
  process.stderr.write(`${screen.failure(message, hint)}\n`);
160
298
  }
161
299
  : undefined,
package/dist/cli.js CHANGED
@@ -20,6 +20,7 @@ import { verify } from './commands/verify.js';
20
20
  import { parseTarget } from './traffic.js';
21
21
  import { ConfigError, isServiceName, loadConfig } from './config.js';
22
22
  import { HopwireError, TemporaryError, UsageError, errorCode } from './errors.js';
23
+ import { commandHelp, overview } from './help.js';
23
24
  import { loadOrCreateIdentity } from './identity.js';
24
25
  import { defaultLogName, isFollowablePath } from './log-follow.js';
25
26
  import { DOCS_URL, printable } from './output.js';
@@ -124,6 +125,7 @@ Options for http:
124
125
  Checks the signatures of a provider's webhooks with the signing secret in that
125
126
  environment variable and shows the result next to each request; repeatable. Providers:
126
127
  ${SIGNED_PROVIDERS.join(', ')}
128
+ --plain Print lines, as a pipe gets them, instead of the full-screen view of a terminal
127
129
 
128
130
  Options for init:
129
131
  --config <path> The file to write (default ${HOPWIRE_YAML_FILE} in the working directory). An existing file
@@ -147,6 +149,7 @@ Options for up:
147
149
  p2p.team in the file is --team of http, p2p.relay is --relay (and turns on p2p.team)
148
150
  --no-agent, --agent As for http, for every service; agent: false in the file turns it off too
149
151
  --force As for http: stop the tunnel that holds the data directory first
152
+ --plain As for http
150
153
 
151
154
  Options for login:
152
155
  --api <url> The URL of the control plane; default: the one of the last login on this data
@@ -193,6 +196,7 @@ Options for watch:
193
196
  --log <path> As for http: follow a log file of your own service, so the entries of your replays
194
197
  show next to them. They stay on this machine
195
198
  --force As for http: stop the tunnel that holds the data directory first
199
+ --plain As for http
196
200
 
197
201
  Options for snapshot:
198
202
  --since <time> Only requests of the last 30s, 30m, 2h or 1d (default 30m)
@@ -219,7 +223,8 @@ Global options:
219
223
  ~/.hopwire)
220
224
  --profile <name> Use the login of this profile for this command only, not the current one (default
221
225
  $HOPWIRE_PROFILE); identity, traffic log and inspector are the same for every profile
222
- -h, --help Show this help
226
+ -h, --help Show the help: of a command after its name (hopwire http --help), else the overview;
227
+ hopwire help --all prints this page
223
228
  --version Show the version
224
229
  `;
225
230
  /** What `hopwire mcp` says on standard error when a person starts it on a terminal. */
@@ -256,12 +261,13 @@ const COMMAND_OPTIONS = {
256
261
  'agent',
257
262
  'no-agent',
258
263
  'force',
264
+ 'plain',
259
265
  ],
260
- up: ['config', 'agent', 'no-agent', 'force'],
266
+ up: ['config', 'agent', 'no-agent', 'force', 'plain'],
261
267
  id: [],
262
268
  rotate: [],
263
269
  connect: ['port', 'service', 'allow-host', 'team', 'relay'],
264
- watch: ['replay-target', 'inspect', 'team', 'relay', 'agent', 'log', 'force'],
270
+ watch: ['replay-target', 'inspect', 'team', 'relay', 'agent', 'log', 'force', 'plain'],
265
271
  login: ['api', 'token', 'no-browser'],
266
272
  logout: [],
267
273
  profiles: [],
@@ -282,16 +288,22 @@ export async function run(argv, io) {
282
288
  }
283
289
  const { values, positionals } = parse(argv);
284
290
  const [command, ...rest] = positionals;
285
- if (values.help) {
291
+ // hopwire help --all: the full reference; hopwire <command> --help and hopwire help <command>: one command
292
+ if (values.all && (values.help || command === 'help')) {
286
293
  io.print(USAGE);
287
294
  return null;
288
295
  }
296
+ if (values.help || command === 'help') {
297
+ const about = command === 'help' ? rest[0] : command;
298
+ io.print((about === undefined ? null : commandHelp(about)) ?? overview());
299
+ return null;
300
+ }
289
301
  if (values.version) {
290
302
  io.print(readVersion());
291
303
  return null;
292
304
  }
293
305
  if (command === undefined) {
294
- io.print(USAGE);
306
+ io.print(overview());
295
307
  return null;
296
308
  }
297
309
  const allowed = COMMAND_OPTIONS[command];
@@ -752,7 +764,7 @@ async function runInit(argv, io) {
752
764
  }
753
765
  const { values, positionals } = parsed;
754
766
  if (values.help) {
755
- io.print(USAGE);
767
+ io.print(commandHelp('init') ?? overview());
756
768
  return;
757
769
  }
758
770
  if (values.version) {
@@ -815,6 +827,8 @@ function parse(argv) {
815
827
  allowPositionals: true,
816
828
  options: {
817
829
  help: { type: 'boolean', short: 'h' },
830
+ all: { type: 'boolean' },
831
+ plain: { type: 'boolean' },
818
832
  version: { type: 'boolean' },
819
833
  listen: { type: 'string' },
820
834
  inspect: { type: 'string' },
@@ -1,13 +1,11 @@
1
1
  import { ChecksFailed, HopwireError } from '../errors.js';
2
2
  import { printable } from '../output.js';
3
- import { isSignedProvider, signedBy } from '../signature.js';
3
+ import { carriesTime, isSignedProvider, signedBy } from '../signature.js';
4
4
  import { readSnapshot, send } from '../traffic.js';
5
5
  import { recogniseWebhook } from '../webhook.js';
6
6
  import { requestLabel, secretFor } from './verify.js';
7
7
  /** How far in the past a stale signature is made: twice the five minutes providers allow by default. */
8
8
  const STALE_SECONDS = 10 * 60;
9
- /** Providers whose signatures carry a time, so a stale one can be made. */
10
- const TIMESTAMPED = new Set(['stripe', 'slack', 'svix', 'paddle']);
11
9
  /** An id as providers write them: a lowercase prefix, an underscore, letters and digits with a digit or capital. */
12
10
  const ID = /^[a-z]{1,16}_(?=[A-Za-z0-9]*[0-9A-Z])[A-Za-z0-9]+$/;
13
11
  /** Headers that carry the id of a delivery, which handlers and libraries use to drop duplicates. */
@@ -18,29 +16,28 @@ const DELIVERY_HEADERS = new Set([
18
16
  'svix-id',
19
17
  'webhook-id',
20
18
  ]);
19
+ /** A JSON string literal, and the colon after it when it is the name of a member. */
20
+ const STRING_LITERAL = /"(?:[^"\\]|\\.)*"(\s*:)?/g;
21
21
  /**
22
- * A copy of a webhook whose ids are new: every string in the JSON body that looks like a provider id gets `tag`
22
+ * A copy of a webhook whose ids are new: every string value in the JSON body that looks like a provider id gets `tag`
23
23
  * appended, the same way in every webhook, so related events still name each other; delivery id headers too. The
24
+ * rest of the body stays byte for byte as recorded (numbers above 2^53 included, which a parse would round). The
24
25
  * signature is made again when it is sent.
25
26
  */
26
27
  export function freshCopy(exchange, tag) {
27
28
  const { request } = exchange;
28
29
  let bodyBase64 = request.bodyBase64;
30
+ const text = Buffer.from(request.bodyBase64, 'base64').toString('utf8');
29
31
  try {
30
- const parsed = JSON.parse(Buffer.from(request.bodyBase64, 'base64').toString('utf8'));
31
- const rewrite = (value) => {
32
- if (typeof value === 'string') {
33
- return ID.test(value) ? `${value}${tag}` : value;
32
+ JSON.parse(text);
33
+ const rewritten = text.replace(STRING_LITERAL, (literal, name) => {
34
+ if (name !== undefined) {
35
+ return literal;
34
36
  }
35
- if (Array.isArray(value)) {
36
- return value.map(rewrite);
37
- }
38
- if (typeof value === 'object' && value !== null) {
39
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, rewrite(child)]));
40
- }
41
- return value;
42
- };
43
- bodyBase64 = Buffer.from(JSON.stringify(rewrite(parsed))).toString('base64');
37
+ const value = JSON.parse(literal);
38
+ return ID.test(value) ? JSON.stringify(`${value}${tag}`) : literal;
39
+ });
40
+ bodyBase64 = Buffer.from(rewritten).toString('base64');
44
41
  }
45
42
  catch {
46
43
  // Not JSON: sent as it is
@@ -161,7 +158,10 @@ export async function chaos(options) {
161
158
  }
162
159
  }
163
160
  report('wrong signature', wrong, 'every webhook with a signature made with another key was refused with 4xx', 'a webhook with a wrong signature was not refused with 4xx; anyone who knows the URL can send events');
164
- const timed = signed.filter((exchange) => TIMESTAMPED.has(recogniseWebhook(exchange)?.provider ?? ''));
161
+ const timed = signed.filter((exchange) => {
162
+ const secret = secretFor(exchange, options.secrets);
163
+ return secret !== undefined && carriesTime(exchange.request.headers, secret);
164
+ });
165
165
  if (timed.length === 0) {
166
166
  options.print('skip stale signature: the signatures of these providers carry no time');
167
167
  }
package/dist/help.js ADDED
@@ -0,0 +1,279 @@
1
+ import { DOCS_URL } from './output.js';
2
+ const FORCE = { flag: '--force', what: 'Stop the tunnel that holds the data directory and start this one' };
3
+ const NO_AGENT = { flag: '--no-agent', what: 'Do not let a coding agent on this machine read the traffic' };
4
+ const AGENT = { flag: '--agent', what: 'Fail when the socket for coding agents cannot open' };
5
+ const WEBHOOK_SECRET_SIGN = {
6
+ flag: '--webhook-secret <provider>=<VARIABLE>',
7
+ what: 'Sign the webhooks again with the secret in that environment variable',
8
+ };
9
+ export const COMMANDS = {
10
+ http: {
11
+ args: '<port>',
12
+ summary: 'Put Hopwire in front of a local service',
13
+ options: [
14
+ { flag: '--public', what: 'Give the service a public HTTPS URL (run hopwire login once before)' },
15
+ { flag: '--subdomain <name>', what: 'With --public: a subdomain your organisation reserved' },
16
+ { flag: '--share', what: 'Let teammates reach the service and follow the traffic over P2P' },
17
+ { flag: '--allow <pubkey>', what: 'With --share: only this public key gets in; repeatable' },
18
+ { flag: '--team', what: 'With --share: only machines of your organisation get in (Team plan)' },
19
+ { flag: '--relay', what: 'With --share: teammates on strict networks come in through the edge' },
20
+ { flag: '--log <path>', what: 'Show new entries of a log file next to the requests; repeatable' },
21
+ {
22
+ flag: '--webhook-secret <provider>=<VARIABLE>',
23
+ what: 'Check webhook signatures with the secret in that environment variable',
24
+ },
25
+ { flag: '--listen <port>', what: 'Port of the entry point (default 4041, 0 picks a free one)' },
26
+ { flag: '--inspect <port>', what: 'Port of the inspector (default 4040, 0 picks a free one)' },
27
+ { flag: '--no-inspect', what: 'Run without the inspector' },
28
+ { flag: '--name <service>', what: 'Service name in the traffic log (default "default")' },
29
+ { flag: '--plain', what: 'Print lines instead of the full-screen view' },
30
+ { flag: '--share-logs', what: 'With --share and --log: teammates see the log entries too' },
31
+ { flag: '--log-request-id', what: 'With --log: send X-Hopwire-Exchange-Id to the service' },
32
+ { flag: '--allow-agents', what: "With --share: teammates' coding agents may read new traffic" },
33
+ { flag: '--no-ws-capture', what: 'Record the handshake of a WebSocket but not its messages' },
34
+ NO_AGENT,
35
+ AGENT,
36
+ FORCE,
37
+ ],
38
+ examples: [
39
+ ['hopwire http 3000', 'Record every request to the service on port 3000'],
40
+ ['hopwire http 3000 --public', 'The same, with a public URL for a webhook provider'],
41
+ ['hopwire http 3000 --share', 'The same, with keys to send to a teammate'],
42
+ ],
43
+ docs: 'getting-started',
44
+ },
45
+ up: {
46
+ args: '',
47
+ summary: 'Start every service of hopwire.yaml',
48
+ options: [
49
+ { flag: '--config <path>', what: 'The config file (default hopwire.yaml in the working directory)' },
50
+ { flag: '--plain', what: 'Print lines instead of the full-screen view' },
51
+ NO_AGENT,
52
+ AGENT,
53
+ FORCE,
54
+ ],
55
+ examples: [
56
+ ['hopwire init', 'Write a hopwire.yaml by answering a few questions'],
57
+ ['hopwire up', 'Start what the file says'],
58
+ ],
59
+ docs: 'hopwire-yaml',
60
+ },
61
+ init: {
62
+ args: '',
63
+ summary: 'Write a hopwire.yaml by answering questions',
64
+ options: [
65
+ { flag: '--config <path>', what: 'The file to write (default hopwire.yaml); never replaces one' },
66
+ { flag: '--yes', what: 'Ask nothing and write what the flags below say' },
67
+ { flag: '--service <name>=<port|url>', what: 'With --yes: a service and its port; repeatable' },
68
+ { flag: '--public <name>', what: 'With --yes: give this service a public URL; repeatable' },
69
+ { flag: '--subdomain <name>=<sub>', what: 'With --yes: the subdomain of a public service' },
70
+ { flag: '--share', what: 'With --yes: share over P2P' },
71
+ { flag: '--team', what: 'With --yes: share with your organisation only' },
72
+ { flag: '--allow-agents', what: "With --yes: teammates' coding agents may read new traffic" },
73
+ ],
74
+ examples: [
75
+ ['hopwire init', 'Answer a few questions'],
76
+ ['hopwire init --yes --service api=3000 --public api', 'The same without questions'],
77
+ ],
78
+ docs: 'hopwire-yaml',
79
+ },
80
+ watch: {
81
+ args: '<log-key>',
82
+ summary: "Follow a teammate's traffic and replay it",
83
+ options: [
84
+ { flag: '--replay-target <url>', what: 'Your own service that replays go to; without it Replay is off' },
85
+ { flag: '--team', what: 'For a teammate who shares with --team' },
86
+ { flag: '--relay', what: 'Go through the edge when no direct connection comes about' },
87
+ { flag: '--log <path>', what: 'Show new entries of a log file of your service; repeatable' },
88
+ { flag: '--inspect <port>', what: 'Port of the inspector (default 4040, 0 picks a free one)' },
89
+ { flag: '--plain', what: 'Print lines instead of the full-screen view' },
90
+ { flag: '--agent', what: 'Let a coding agent here read what your teammate allowed for agents' },
91
+ FORCE,
92
+ ],
93
+ examples: [
94
+ ['hopwire watch <log-key> --replay-target http://127.0.0.1:3000', 'Watch, and replay to your service'],
95
+ ],
96
+ docs: 'private-mode',
97
+ },
98
+ connect: {
99
+ args: '<peer-key>',
100
+ summary: "Reach a teammate's service",
101
+ options: [
102
+ { flag: '--port <port>', what: "Local port that reaches the teammate's service (0 picks a free one)" },
103
+ { flag: '--service <name>', what: 'Which service, when the teammate shares more than one' },
104
+ { flag: '--allow-host <host>', what: 'Also answer requests with this Host header; repeatable' },
105
+ { flag: '--team', what: 'For a teammate who shares with --team' },
106
+ { flag: '--relay', what: 'Go through the edge when no direct connection comes about' },
107
+ ],
108
+ examples: [['hopwire connect <peer-key> --port 4141', 'Then send requests to http://127.0.0.1:4141']],
109
+ docs: 'private-mode',
110
+ },
111
+ fix: {
112
+ args: '[<exchange-id>]',
113
+ summary: 'Replay a failed request until it passes',
114
+ options: [
115
+ { flag: '--watch <dir>', what: 'A folder whose changes start a new attempt; repeatable' },
116
+ WEBHOOK_SECRET_SIGN,
117
+ ],
118
+ examples: [['hopwire fix', 'The newest failed request of the running tunnel, after every file change']],
119
+ docs: 'cli-reference',
120
+ },
121
+ snapshot: {
122
+ args: '<file>',
123
+ summary: 'Write the recorded requests to a file',
124
+ options: [
125
+ { flag: '--since <time>', what: 'Only requests of the last 30s, 30m, 2h or 1d (default 30m)' },
126
+ { flag: '--last <n>', what: 'At most the newest n requests (default 200)' },
127
+ { flag: '--service <name>', what: 'Only requests of this service' },
128
+ { flag: '--path <text>', what: 'Only requests whose path contains this text' },
129
+ ],
130
+ examples: [['hopwire snapshot hooks.snapshot.json', 'The last 30 minutes of the running tunnel']],
131
+ docs: 'cli-reference',
132
+ },
133
+ verify: {
134
+ args: '<file>',
135
+ summary: 'Send a snapshot to your service and compare answers (CI)',
136
+ options: [
137
+ { flag: '--target <url>', what: 'Where the requests go: http://127.0.0.1:3000 or a port' },
138
+ WEBHOOK_SECRET_SIGN,
139
+ { flag: '--strict', what: 'Compare values too, not only the shape of JSON answers' },
140
+ { flag: '--ignore <field>', what: 'Leave a field out, as a dotted path; repeatable' },
141
+ ],
142
+ examples: [['hopwire verify hooks.snapshot.json --target 3000', 'Exits 1 when an answer differs']],
143
+ docs: 'cli-reference',
144
+ },
145
+ chaos: {
146
+ args: '<file>',
147
+ summary: 'Deliver webhooks the way providers really do',
148
+ options: [
149
+ { flag: '--target <url>', what: 'Where the requests go: http://127.0.0.1:3000 or a port' },
150
+ WEBHOOK_SECRET_SIGN,
151
+ ],
152
+ examples: [
153
+ [
154
+ 'hopwire chaos hooks.snapshot.json --target 3000',
155
+ 'Twice, out of order, with a wrong and an old signature',
156
+ ],
157
+ ],
158
+ docs: 'cli-reference',
159
+ },
160
+ mcp: {
161
+ args: '',
162
+ summary: 'Let your coding agent read and replay the traffic',
163
+ options: [{ flag: '--read-only', what: 'Leave out the replay tool' }],
164
+ examples: [
165
+ ['claude mcp add hopwire -- hopwire mcp', 'Register it with your coding agent; the agent starts it'],
166
+ ],
167
+ docs: 'coding-agents',
168
+ },
169
+ login: {
170
+ args: '',
171
+ summary: 'Sign in through the browser, for public mode',
172
+ options: [
173
+ { flag: '--profile <name>', what: 'Store the login in this profile (one per organisation)' },
174
+ { flag: '--token', what: 'Paste an API token instead of signing in through the browser' },
175
+ { flag: '--no-browser', what: 'Print the sign-in page without opening it' },
176
+ { flag: '--api <url>', what: 'The control plane (default https://hopwire.to)' },
177
+ ],
178
+ examples: [['hopwire login', 'Opens the sign-in page and waits for your approval']],
179
+ docs: 'public-mode',
180
+ },
181
+ logout: {
182
+ args: '',
183
+ summary: 'Remove the stored API token from this machine',
184
+ options: [],
185
+ examples: [],
186
+ docs: 'public-mode',
187
+ },
188
+ profiles: {
189
+ args: '',
190
+ summary: 'List the logins on this machine',
191
+ options: [],
192
+ examples: [],
193
+ docs: 'cli-reference',
194
+ },
195
+ use: {
196
+ args: '<profile>',
197
+ summary: 'Make another profile the current one',
198
+ options: [],
199
+ examples: [['hopwire use acme', 'After hopwire login --profile acme']],
200
+ docs: 'cli-reference',
201
+ },
202
+ id: {
203
+ args: '',
204
+ summary: 'Print the public key of this machine',
205
+ options: [],
206
+ examples: [],
207
+ docs: 'private-mode',
208
+ },
209
+ rotate: {
210
+ args: '',
211
+ summary: 'New keys for this machine, for when one went to the wrong person',
212
+ options: [],
213
+ examples: [],
214
+ docs: 'private-mode',
215
+ },
216
+ doctor: {
217
+ args: '',
218
+ summary: 'Print a report about this installation',
219
+ options: [{ flag: '--network', what: 'Also test whether this network allows direct P2P connections' }],
220
+ examples: [],
221
+ docs: 'troubleshooting',
222
+ },
223
+ };
224
+ /** The four groups of the overview; a name in one row shares the line. */
225
+ const GROUPS = [
226
+ { title: 'Start', rows: [['http'], ['up'], ['init']] },
227
+ { title: 'With your team', rows: [['watch'], ['connect']] },
228
+ { title: 'Test and debug', rows: [['fix'], ['snapshot'], ['verify'], ['chaos'], ['mcp']] },
229
+ ];
230
+ const ACCOUNT = ['login', 'logout', 'profiles', 'use', 'id', 'rotate', 'doctor'];
231
+ /** hopwire, hopwire --help and hopwire help: every command on one screen. */
232
+ export function overview() {
233
+ const lines = ['Usage: hopwire <command>', ''];
234
+ for (const group of GROUPS) {
235
+ lines.push(group.title);
236
+ for (const [name = ''] of group.rows) {
237
+ const command = COMMANDS[name];
238
+ if (command !== undefined) {
239
+ lines.push(` ${`${name} ${command.args}`.trimEnd().padEnd(19)}${command.summary}`);
240
+ }
241
+ }
242
+ lines.push('');
243
+ }
244
+ lines.push('Account and machine', ` ${ACCOUNT.join(', ')}`, '');
245
+ lines.push('hopwire <command> --help The options of a command, with examples', 'hopwire help --all Everything on one page', `Guides ${DOCS_URL}`);
246
+ return lines.join('\n');
247
+ }
248
+ /** hopwire <command> --help: what it does, examples, its options in a line each. Null for an unknown command. */
249
+ export function commandHelp(name) {
250
+ const command = COMMANDS[name];
251
+ if (command === undefined) {
252
+ return null;
253
+ }
254
+ const lines = [
255
+ `Usage: ${`hopwire ${name} ${command.args}`.trimEnd()}${command.options.length > 0 ? ' [options]' : ''}`,
256
+ ];
257
+ lines.push('', command.summary);
258
+ if (command.examples.length > 0) {
259
+ lines.push('', 'Examples');
260
+ for (const [example, what] of command.examples) {
261
+ lines.push(` ${example}`, ` ${what}`);
262
+ }
263
+ }
264
+ if (command.options.length > 0) {
265
+ const width = Math.min(Math.max(...command.options.map((option) => option.flag.length)), 24) + 2;
266
+ lines.push('', 'Options');
267
+ for (const option of command.options) {
268
+ // A flag wider than the column stands on a line of its own
269
+ if (option.flag.length + 2 > width) {
270
+ lines.push(` ${option.flag}`, ` ${' '.repeat(width)}${option.what}`);
271
+ }
272
+ else {
273
+ lines.push(` ${option.flag.padEnd(width)}${option.what}`);
274
+ }
275
+ }
276
+ }
277
+ lines.push('', 'Every command also takes --data-dir <path> and --profile <name>.', 'All details: hopwire help --all', `Guide: ${DOCS_URL}/${command.docs}`);
278
+ return lines.join('\n');
279
+ }