hopwire 0.0.0-stage → 0.1.0

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.
Files changed (85) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +8 -0
  3. package/README.md +29 -2
  4. package/dist/account.js +168 -0
  5. package/dist/agent/redact.js +101 -0
  6. package/dist/agent/summary.js +32 -0
  7. package/dist/agent-socket.js +93 -0
  8. package/dist/bin.js +22 -0
  9. package/dist/body-capture.js +28 -0
  10. package/dist/browser.js +42 -0
  11. package/dist/cli.js +674 -0
  12. package/dist/commands/connect.js +221 -0
  13. package/dist/commands/doctor.js +107 -0
  14. package/dist/commands/http.js +108 -0
  15. package/dist/commands/login.js +133 -0
  16. package/dist/commands/mcp.js +69 -0
  17. package/dist/commands/rotate.js +57 -0
  18. package/dist/commands/up.js +149 -0
  19. package/dist/commands/watch.js +146 -0
  20. package/dist/config.js +302 -0
  21. package/dist/control-plane-client.js +300 -0
  22. package/dist/data-dir-holder.js +178 -0
  23. package/dist/edge-bridge.js +1031 -0
  24. package/dist/errors.js +53 -0
  25. package/dist/identity.js +134 -0
  26. package/dist/inspector/THIRD-PARTY-NOTICES.txt +330 -0
  27. package/dist/inspector/assets/index-BvwyMIFs.css +2 -0
  28. package/dist/inspector/assets/index-Ctrz3UJp.js +2 -0
  29. package/dist/inspector/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  30. package/dist/inspector/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  31. package/dist/inspector/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  32. package/dist/inspector/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
  33. package/dist/inspector/assets/space-grotesk-latin-400-normal-CJ-V5oYT.woff2 +0 -0
  34. package/dist/inspector/assets/space-grotesk-latin-500-normal-lFbtlQH6.woff2 +0 -0
  35. package/dist/inspector/assets/space-grotesk-latin-ext-400-normal-CfP_5XZW.woff2 +0 -0
  36. package/dist/inspector/assets/space-grotesk-latin-ext-500-normal-DUe3BAxM.woff2 +0 -0
  37. package/dist/inspector/favicon.svg +1 -0
  38. package/dist/inspector/index.html +16 -0
  39. package/dist/inspector-api.js +508 -0
  40. package/dist/inspector-server.js +150 -0
  41. package/dist/interceptor.js +480 -0
  42. package/dist/log.js +393 -0
  43. package/dist/main.js +37 -0
  44. package/dist/mcp/body.js +134 -0
  45. package/dist/mcp/client.js +169 -0
  46. package/dist/mcp/jsonrpc.js +170 -0
  47. package/dist/mcp/tools.js +715 -0
  48. package/dist/output.js +249 -0
  49. package/dist/p2p-stream.js +226 -0
  50. package/dist/p2p.js +389 -0
  51. package/dist/prompt.js +62 -0
  52. package/dist/proxy-server.js +252 -0
  53. package/dist/serve.js +234 -0
  54. package/dist/style.js +60 -0
  55. package/dist/supervisor.js +146 -0
  56. package/dist/team-keys.js +129 -0
  57. package/dist/update-notice.js +67 -0
  58. package/dist/urls.js +45 -0
  59. package/dist/websocket.js +99 -0
  60. package/node_modules/@hopwire/protocol/LICENSE +201 -0
  61. package/node_modules/@hopwire/protocol/NOTICE +8 -0
  62. package/node_modules/@hopwire/protocol/dist/basic-auth.d.ts +9 -0
  63. package/node_modules/@hopwire/protocol/dist/basic-auth.js +21 -0
  64. package/node_modules/@hopwire/protocol/dist/constants.d.ts +91 -0
  65. package/node_modules/@hopwire/protocol/dist/constants.js +89 -0
  66. package/node_modules/@hopwire/protocol/dist/exchange.d.ts +54 -0
  67. package/node_modules/@hopwire/protocol/dist/exchange.js +71 -0
  68. package/node_modules/@hopwire/protocol/dist/frames.d.ts +177 -0
  69. package/node_modules/@hopwire/protocol/dist/frames.js +191 -0
  70. package/node_modules/@hopwire/protocol/dist/headers.d.ts +20 -0
  71. package/node_modules/@hopwire/protocol/dist/headers.js +58 -0
  72. package/node_modules/@hopwire/protocol/dist/index.d.ts +10 -0
  73. package/node_modules/@hopwire/protocol/dist/index.js +10 -0
  74. package/node_modules/@hopwire/protocol/dist/inspector.d.ts +46 -0
  75. package/node_modules/@hopwire/protocol/dist/inspector.js +42 -0
  76. package/node_modules/@hopwire/protocol/dist/p2p.d.ts +52 -0
  77. package/node_modules/@hopwire/protocol/dist/p2p.js +119 -0
  78. package/node_modules/@hopwire/protocol/dist/plan.d.ts +104 -0
  79. package/node_modules/@hopwire/protocol/dist/plan.js +180 -0
  80. package/node_modules/@hopwire/protocol/dist/subdomain.d.ts +10 -0
  81. package/node_modules/@hopwire/protocol/dist/subdomain.js +30 -0
  82. package/node_modules/@hopwire/protocol/dist/websocket.d.ts +70 -0
  83. package/node_modules/@hopwire/protocol/dist/websocket.js +113 -0
  84. package/node_modules/@hopwire/protocol/package.json +13 -0
  85. package/package.json +38 -5
package/dist/cli.js ADDED
@@ -0,0 +1,674 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { parseArgs } from 'node:util';
6
+ import { INSPECTOR_DEFAULT_PORT, LOCAL_ENTRY_DEFAULT_PORT, RANDOM_SUBDOMAIN_BYTES, HOPWIRE_YAML_FILE, isPublicKeyHex, isReservableSubdomain, randomSubdomain, } from '@hopwire/protocol';
7
+ import { bindEdge, boundEdge, readAccount } from './account.js';
8
+ import { startConnect } from './commands/connect.js';
9
+ import { doctor } from './commands/doctor.js';
10
+ import { startHttpTunnel } from './commands/http.js';
11
+ import { login, logout } from './commands/login.js';
12
+ import { startMcp } from './commands/mcp.js';
13
+ import { rotate } from './commands/rotate.js';
14
+ import { startUp } from './commands/up.js';
15
+ import { startWatch } from './commands/watch.js';
16
+ import { ConfigError, isServiceName, loadConfig } from './config.js';
17
+ import { HopwireError, TemporaryError, UsageError, errorCode } from './errors.js';
18
+ import { loadOrCreateIdentity } from './identity.js';
19
+ import { DOCS_URL, printable } from './output.js';
20
+ import { createUpdateNotice } from './update-notice.js';
21
+ import { parseControlPlaneUrl, parseEdgeUrl, parseLocalTarget } from './urls.js';
22
+ export { UsageError };
23
+ const USAGE = `Usage: hopwire <command>
24
+
25
+ Private mode: no account, no servers of ours, end-to-end encrypted between you and the teammates you choose.
26
+ With --team (Team plan) your account's control plane names who gets in; the traffic stays direct.
27
+ Public mode (--public): a public URL for the service through the edge; it needs an account (hopwire login).
28
+
29
+ Start here:
30
+ hopwire http 3000 Put Hopwire in front of the service on port 3000: every request is recorded
31
+ and shown in the inspector in your browser
32
+ hopwire http 3000 --public The same, with a public HTTPS URL to give to a webhook provider or a client
33
+ (run hopwire login once before)
34
+ hopwire http 3000 --share The same, with keys to send to a teammate, who reaches the service
35
+ (hopwire connect) or follows the traffic (hopwire watch) directly over P2P
36
+ Every command says after its start what to do next and what to send to whom. Guides: ${DOCS_URL}
37
+
38
+ Commands:
39
+ hopwire http <port> Forward a local entry point to http://127.0.0.1:<port>, log every exchange
40
+ and show the traffic in the inspector
41
+ hopwire up Start every service of hopwire.yaml: one traffic log and one inspector for all,
42
+ public URLs and P2P sharing as the file says
43
+ hopwire id Print the public key of this machine (creates the identity on first use)
44
+ hopwire rotate New peer key and new log key for this machine, for when a key went to the wrong
45
+ person: the old keys no longer lead anywhere, the traffic history is kept
46
+ hopwire connect <peer-key> Reach a teammate's shared service on 127.0.0.1:<port>
47
+ hopwire watch <log-key> Follow a teammate's shared traffic log live in the inspector
48
+ hopwire login Sign in through the browser and store an API token of the control plane on this
49
+ machine, for public mode (--token pastes a token instead)
50
+ hopwire logout Remove the stored API token from this machine
51
+ hopwire doctor Print a report about this installation (versions, data directory, account,
52
+ hopwire.yaml) to read or to paste into a bug report. It is sent nowhere
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
55
+
56
+ Options for http:
57
+ --listen <port> Loopback port of the entry point (default ${LOCAL_ENTRY_DEFAULT_PORT}, 0 picks a free one)
58
+ --inspect <port> Loopback port of the inspector (default ${INSPECTOR_DEFAULT_PORT}, 0 picks a free one)
59
+ --no-inspect Run without the inspector
60
+ --name <service> Service name written to the traffic log (default "default")
61
+ --share Let teammates reach the service (hopwire connect) and follow the traffic log
62
+ (hopwire watch) directly over P2P. The log holds headers and bodies as captured,
63
+ including credentials
64
+ --allow <pubkey> With --share: only this public key may connect or watch; can be given several times
65
+ --team With --share: only machines of the members of your organisation may connect or watch
66
+ (Team plan). Needs an account: run hopwire login first. The control plane of the
67
+ account names the keys of the team and gets the public key of this machine; this is
68
+ the one thing private mode asks a server. Your traffic still passes none
69
+ --public Serve the service under a public URL through the edge. Needs an account: run
70
+ hopwire login first; the edge is the one its control plane names. HOPWIRE_EDGE_URL
71
+ sets another one. A local edge (ws://127.0.0.1:8787) can be used without an account,
72
+ with HOPWIRE_EDGE_URL and its dev token in HOPWIRE_DEV_TOKEN
73
+ --subdomain <name> With --public: a subdomain your organisation reserved in the control plane; without
74
+ it the fixed t-... URL of your organisation is used (a random one with a dev token)
75
+ --force When another tunnel holds the data directory, stop it (as Ctrl+C does) and start
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
80
+
81
+ Options for up:
82
+ --config <path> The config file (default ${HOPWIRE_YAML_FILE} in the working directory). A public service
83
+ takes the URL of the edge from edge.url in the file. With controlPlane.url in the file
84
+ it uses your account (hopwire login), without it the dev token in HOPWIRE_DEV_TOKEN.
85
+ p2p.team in the file is --team of http
86
+ --agent As for http: the traffic of every service for hopwire mcp
87
+ --force As for http: stop the tunnel that holds the data directory first
88
+
89
+ Options for login:
90
+ --api <url> The URL of the control plane; default: the one of the last login on this data
91
+ directory, else https://hopwire.to
92
+ --token Paste an API token from the API tokens page instead of signing in through the
93
+ browser; it is asked for without showing it. HOPWIRE_TOKEN skips both
94
+ --no-browser Print the sign-in page without opening it, to open it on another device
95
+ Without --token the CLI prints a page of the control plane and a code, opens the
96
+ page, and waits until you sign in there and approve the code; the control plane
97
+ then creates an API token for this machine. The token is checked with the control
98
+ plane and stored in config.json of the data directory, readable for this user only
99
+
100
+ Options for mcp:
101
+ --read-only Leave out the replay tool; the agent can only read the traffic
102
+
103
+ Options for doctor:
104
+ --network Also test whether this network allows direct P2P connections. For that the
105
+ command joins the public DHT for a moment; its nodes see your IP address
106
+
107
+ Options for connect:
108
+ --port <port> Loopback port that reaches the teammate's service (0 picks a free one)
109
+ --service <name> Service of the teammate, when it shares more than one
110
+ --allow-host <host> Also answer requests whose Host header is this name (a virtual host of the teammate's
111
+ service); without it only 127.0.0.1:<port> and localhost:<port>. Can be given several times
112
+ --team For a teammate who shares with --team: registers the key of this machine with your
113
+ organisation (hopwire login first) and connects only to a machine of one of its members
114
+
115
+ Options for watch:
116
+ --replay-target <url> Local service that replays are sent to, for example http://127.0.0.1:3000;
117
+ without it Replay is off
118
+ --inspect <port> Loopback port of the inspector (default ${INSPECTOR_DEFAULT_PORT}, 0 picks a free one)
119
+ --team For a teammate who shares with --team: registers the key of this machine with your
120
+ organisation (hopwire login first), so the sharer lets it in
121
+ --force As for http: stop the tunnel that holds the data directory first
122
+
123
+ Global options:
124
+ --data-dir <path> Where identity, traffic log and the API token are stored (default $HOPWIRE_HOME or
125
+ ~/.hopwire)
126
+ -h, --help Show this help
127
+ --version Show the version
128
+ `;
129
+ /** Options every command takes, and the ones of each command. Anything else is a usage error. */
130
+ const GLOBAL_OPTIONS = ['help', 'version', 'data-dir'];
131
+ const COMMAND_OPTIONS = {
132
+ http: [
133
+ 'listen',
134
+ 'inspect',
135
+ 'no-inspect',
136
+ 'name',
137
+ 'share',
138
+ 'allow',
139
+ 'team',
140
+ 'public',
141
+ 'subdomain',
142
+ 'agent',
143
+ 'force',
144
+ ],
145
+ up: ['config', 'agent', 'force'],
146
+ id: [],
147
+ rotate: [],
148
+ connect: ['port', 'service', 'allow-host', 'team'],
149
+ watch: ['replay-target', 'inspect', 'team', 'force'],
150
+ login: ['api', 'token', 'no-browser'],
151
+ logout: [],
152
+ mcp: ['read-only'],
153
+ doctor: ['network'],
154
+ };
155
+ /** Parses the arguments and starts the command. Resolves with what keeps running, or null when the command is done. */
156
+ export async function run(argv, io) {
157
+ const { values, positionals } = parse(argv);
158
+ const [command, ...rest] = positionals;
159
+ if (values.help) {
160
+ io.print(USAGE);
161
+ return null;
162
+ }
163
+ if (values.version) {
164
+ io.print(readVersion());
165
+ return null;
166
+ }
167
+ if (command === undefined) {
168
+ io.print(USAGE);
169
+ return null;
170
+ }
171
+ const allowed = COMMAND_OPTIONS[command];
172
+ if (allowed === undefined) {
173
+ throw new UsageError(`Unknown command "${command}"`);
174
+ }
175
+ for (const name of Object.keys(values)) {
176
+ if (!GLOBAL_OPTIONS.includes(name) && !allowed.includes(name)) {
177
+ throw new UsageError(`--${name} is not an option of hopwire ${command}`);
178
+ }
179
+ }
180
+ if (values['data-dir'] === '') {
181
+ throw new UsageError('--data-dir needs the path of a directory');
182
+ }
183
+ // A variable that is set but empty counts as not set; as a path it would be the working directory
184
+ const home = io.env.HOPWIRE_HOME === '' ? undefined : io.env.HOPWIRE_HOME;
185
+ const dataDir = values['data-dir'] ?? home ?? path.join(os.homedir(), '.hopwire');
186
+ if (command === 'id') {
187
+ noMoreArguments(rest, 0, 'hopwire id');
188
+ io.print((await loadOrCreateIdentity(dataDir)).publicKey.toString('hex'));
189
+ return null;
190
+ }
191
+ if (command === 'rotate') {
192
+ noMoreArguments(rest, 0, 'hopwire rotate');
193
+ await rotate({ dataDir, print: io.print });
194
+ return null;
195
+ }
196
+ if (command === 'doctor') {
197
+ noMoreArguments(rest, 0, 'hopwire doctor [--network]');
198
+ await doctor({
199
+ dataDir,
200
+ cwd: io.cwd ?? process.cwd(),
201
+ version: readVersion(),
202
+ network: values.network ?? false,
203
+ // The DHT is only named when it is asked: without --network nothing leaves the machine
204
+ bootstrap: values.network ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
205
+ print: io.print,
206
+ signal: io.signal,
207
+ });
208
+ return null;
209
+ }
210
+ if (command === 'login') {
211
+ if (values.token && rest.length > 0) {
212
+ // The value is not repeated: it may be a token, which belongs neither in an error nor in shell history
213
+ throw new UsageError('--token takes no value: hopwire login --token asks for the token without showing it, or set HOPWIRE_TOKEN');
214
+ }
215
+ noMoreArguments(rest, 0, 'hopwire login [--api <url>] [--token] [--no-browser]');
216
+ await login({
217
+ dataDir,
218
+ apiUrl: values.api === undefined ? null : parseApiUrl(values.api),
219
+ token: io.env.HOPWIRE_TOKEN,
220
+ paste: values.token ?? false,
221
+ noBrowser: values['no-browser'] ?? false,
222
+ promptSecret: io.promptSecret,
223
+ openBrowser: io.openBrowser,
224
+ print: io.print,
225
+ signal: io.signal,
226
+ });
227
+ return null;
228
+ }
229
+ if (command === 'logout') {
230
+ noMoreArguments(rest, 0, 'hopwire logout');
231
+ await logout({ dataDir, print: io.print });
232
+ return null;
233
+ }
234
+ if (command === 'mcp') {
235
+ noMoreArguments(rest, 0, 'hopwire mcp [--read-only]');
236
+ const input = io.input?.();
237
+ if (input === undefined) {
238
+ throw new HopwireError('hopwire mcp needs standard input; it is started by a coding agent.');
239
+ }
240
+ return startMcp({
241
+ dataDir,
242
+ readOnly: values['read-only'] ?? false,
243
+ version: readVersion(),
244
+ input,
245
+ print: io.print,
246
+ });
247
+ }
248
+ if (command === 'connect') {
249
+ noMoreArguments(rest, 1, 'hopwire connect <peer-key>');
250
+ if (values.port === undefined) {
251
+ throw new UsageError('hopwire connect needs --port <port>, the loopback port that reaches the peer');
252
+ }
253
+ const peerKey = parseKey(rest[0], 'The peer key').toLowerCase();
254
+ const port = parsePort(values.port, '--port', 0);
255
+ const service = parseService(values.service);
256
+ const allowHosts = (values['allow-host'] ?? []).map(parseAllowedHost);
257
+ return startConnect({
258
+ peerKey,
259
+ port,
260
+ service,
261
+ allowHosts,
262
+ // The account is only read for --team: without it private mode never looks at it
263
+ team: values.team ? await teamAccess('--team', dataDir) : undefined,
264
+ dataDir,
265
+ print: io.print,
266
+ bootstrap: parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP),
267
+ signal: io.signal,
268
+ });
269
+ }
270
+ if (command === 'watch') {
271
+ noMoreArguments(rest, 1, 'hopwire watch <log-key>');
272
+ const logKey = parseKey(rest[0], 'The log key');
273
+ const replayTarget = values['replay-target'] === undefined ? null : parseReplayTarget(values['replay-target']);
274
+ const inspectPort = parsePort(values.inspect ?? String(INSPECTOR_DEFAULT_PORT), '--inspect', 0);
275
+ return startWatch({
276
+ force: values.force ?? false,
277
+ logKey,
278
+ replayTarget,
279
+ inspectPort,
280
+ // The account is only read for --team: without it private mode never looks at it
281
+ team: values.team ? await teamAccess('--team', dataDir) : undefined,
282
+ dataDir,
283
+ print: io.print,
284
+ bootstrap: parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP),
285
+ signal: io.signal,
286
+ });
287
+ }
288
+ if (command === 'up') {
289
+ noMoreArguments(rest, 0, 'hopwire up [--config <path>]');
290
+ if (values.config === '') {
291
+ throw new UsageError('--config needs the path of a config file');
292
+ }
293
+ const cwd = io.cwd ?? process.cwd();
294
+ const file = path.resolve(cwd, values.config ?? HOPWIRE_YAML_FILE);
295
+ // Sentences about the file name it as the user would: relative to the working directory when it lies in it
296
+ const relative = path.relative(cwd, file);
297
+ const shown = relative.startsWith('..') || path.isAbsolute(relative) ? file : relative;
298
+ const config = await loadConfig(file, values.config !== undefined, shown);
299
+ const update = createUpdateNotice(readVersion());
300
+ const running = await startUp({
301
+ force: values.force ?? false,
302
+ config,
303
+ configFile: file,
304
+ dataDir,
305
+ print: io.print,
306
+ // Token and account are only read when a service is public: private mode never looks at them
307
+ ...(config.services.some((service) => service.public)
308
+ ? update.watch(await publicAccess(shown, config, io.env, dataDir))
309
+ : {}),
310
+ // The account is only read for p2p.team: without it private mode never looks at it
311
+ team: config.team ? await teamAccessOfFile(shown, config, dataDir) : undefined,
312
+ bootstrap: config.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
313
+ agent: values.agent ?? false,
314
+ signal: io.signal,
315
+ });
316
+ // After the lines of the start, so the mode stays the first line of every tunnel
317
+ update.print(io.print);
318
+ return running;
319
+ }
320
+ noMoreArguments(rest, 1, 'hopwire http <port>');
321
+ if (values.inspect !== undefined && values['no-inspect']) {
322
+ throw new UsageError('--inspect and --no-inspect cannot be combined');
323
+ }
324
+ const allow = (values.allow ?? []).map((key) => parseKey(key, '--allow').toLowerCase());
325
+ if (allow.length > 0 && !values.share) {
326
+ throw new UsageError('--allow only works together with --share');
327
+ }
328
+ if (values.team && !values.share) {
329
+ throw new UsageError('--team only works together with --share');
330
+ }
331
+ if (values.team && allow.length > 0) {
332
+ throw new UsageError('--team and --allow cannot be combined: with --team the team is the list');
333
+ }
334
+ if (values.subdomain !== undefined && !values.public) {
335
+ throw new UsageError('--subdomain only works together with --public');
336
+ }
337
+ const port = parsePort(rest[0], 'port', 1);
338
+ if (values.name !== undefined && !isServiceName(values.name)) {
339
+ // The rule of a service name in hopwire.yaml: a teammate asks for a service by this name
340
+ throw new UsageError('--name must be a service name of 1 to 255 bytes without control characters');
341
+ }
342
+ const update = createUpdateNotice(readVersion());
343
+ const running = await startHttpTunnel({
344
+ force: values.force ?? false,
345
+ port,
346
+ listenPort: parsePort(values.listen ?? String(LOCAL_ENTRY_DEFAULT_PORT), '--listen', 0),
347
+ inspectPort: values['no-inspect']
348
+ ? null
349
+ : parsePort(values.inspect ?? String(INSPECTOR_DEFAULT_PORT), '--inspect', 0),
350
+ dataDir,
351
+ serviceName: values.name ?? 'default',
352
+ print: io.print,
353
+ share: values.share ?? false,
354
+ allow,
355
+ // The account is only read for --team: without it private mode never looks at it
356
+ team: values.team ? await teamAccess('--team', dataDir) : undefined,
357
+ bootstrap: values.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
358
+ // Edge URL, token and account are only read for --public: private mode never looks at them
359
+ public: values.public ? update.watch(await parsePublic(values.subdomain, io.env, dataDir)) : undefined,
360
+ agent: values.agent ?? false,
361
+ signal: io.signal,
362
+ });
363
+ // After the lines of the start, so the mode stays the first line of every tunnel
364
+ update.print(io.print);
365
+ return running;
366
+ }
367
+ function parse(argv) {
368
+ try {
369
+ return parseArgs({
370
+ args: argv,
371
+ allowPositionals: true,
372
+ options: {
373
+ help: { type: 'boolean', short: 'h' },
374
+ version: { type: 'boolean' },
375
+ listen: { type: 'string' },
376
+ inspect: { type: 'string' },
377
+ 'no-inspect': { type: 'boolean' },
378
+ network: { type: 'boolean' },
379
+ force: { type: 'boolean' },
380
+ name: { type: 'string' },
381
+ 'data-dir': { type: 'string' },
382
+ public: { type: 'boolean' },
383
+ subdomain: { type: 'string' },
384
+ share: { type: 'boolean' },
385
+ allow: { type: 'string', multiple: true },
386
+ team: { type: 'boolean' },
387
+ 'allow-host': { type: 'string', multiple: true },
388
+ port: { type: 'string' },
389
+ service: { type: 'string' },
390
+ 'replay-target': { type: 'string' },
391
+ config: { type: 'string' },
392
+ agent: { type: 'boolean' },
393
+ 'read-only': { type: 'boolean' },
394
+ api: { type: 'string' },
395
+ token: { type: 'boolean' },
396
+ 'no-browser': { type: 'boolean' },
397
+ },
398
+ });
399
+ }
400
+ catch (error) {
401
+ throw new UsageError(argumentProblem(error));
402
+ }
403
+ }
404
+ /**
405
+ * One sentence for a command line Node's parser refuses. Its own text is written for programmers (it explains how
406
+ * to pass a positional argument that starts with a hyphen), so only the name of the option is taken from it.
407
+ */
408
+ function argumentProblem(error) {
409
+ const message = error instanceof Error ? error.message : '';
410
+ // The option in the first pair of quotes; one with a short form is named as '-h, --help'
411
+ const quoted = /'([^']*)'/.exec(message)?.[1] ?? '';
412
+ const option = printable(quoted.match(/--?[^\s,=<>]+/g)?.pop() ?? '');
413
+ if (option === '') {
414
+ return 'The arguments could not be read';
415
+ }
416
+ if (errorCode(error) === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') {
417
+ return `${option} is not an option of hopwire`;
418
+ }
419
+ if (message.includes('does not take an argument')) {
420
+ return `${option} does not take a value`;
421
+ }
422
+ if (message.includes('ambiguous')) {
423
+ return `${option} needs a value; write ${option}=<value> when the value starts with a hyphen`;
424
+ }
425
+ return `${option} needs a value`;
426
+ }
427
+ function noMoreArguments(rest, expected, usage) {
428
+ if (rest.length > expected) {
429
+ throw new UsageError(`Too many arguments; the command is ${usage}`);
430
+ }
431
+ }
432
+ function parseKey(value, label) {
433
+ if (value === undefined || !isPublicKeyHex(value)) {
434
+ throw new UsageError(`${label} must be a public key: 64 hexadecimal characters, as hopwire prints them`);
435
+ }
436
+ return value;
437
+ }
438
+ function parseService(value) {
439
+ // The name travels in the connect preface, one line of at most 1024 bytes
440
+ if (value === '' || (value !== undefined && Buffer.byteLength(value) > 255)) {
441
+ throw new UsageError('--service must name a service (at most 255 bytes)');
442
+ }
443
+ return value ?? null;
444
+ }
445
+ /** The service replays go to: an http URL on a loopback host without a path, like a service in hopwire.yaml. */
446
+ function parseReplayTarget(value) {
447
+ const url = parseLocalTarget(value);
448
+ if (url === null) {
449
+ throw new UsageError('--replay-target must be an http URL on this machine without a path, for example http://127.0.0.1:3000');
450
+ }
451
+ return url;
452
+ }
453
+ /** --api: the control plane, an https URL without a path; http only for one on this machine. */
454
+ function parseApiUrl(value) {
455
+ const url = parseControlPlaneUrl(value.trim());
456
+ if (url === 'malformed') {
457
+ throw new UsageError('--api must be an http:// or https:// URL without a path, for example https://hopwire.to');
458
+ }
459
+ if (url === 'insecure') {
460
+ // The API token travels in a header of every request
461
+ throw new UsageError('--api must use https:// unless the control plane runs on this machine; over http:// the API token would travel unencrypted');
462
+ }
463
+ return url;
464
+ }
465
+ /**
466
+ * What --public needs: the edge URL and a way to get a token. With HOPWIRE_DEV_TOKEN set that is the dev token of a
467
+ * local edge, whose URL HOPWIRE_EDGE_URL names; otherwise the account of `hopwire login`, whose control plane issues a
468
+ * connect token for the subdomain, and the edge the account is bound to (the one its control plane names), unless
469
+ * HOPWIRE_EDGE_URL names it. `hopwire up` reads the edge from edge.url in hopwire.yaml instead.
470
+ */
471
+ async function parsePublic(subdomain, env, dataDir) {
472
+ if (subdomain !== undefined && !isReservableSubdomain(subdomain)) {
473
+ throw new UsageError('--subdomain 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');
474
+ }
475
+ const edge = env.HOPWIRE_EDGE_URL;
476
+ if ((edge === undefined || edge.trim() === '') && (env.HOPWIRE_DEV_TOKEN ?? '').trim() === '') {
477
+ return publicThroughAccountEdge(subdomain, dataDir);
478
+ }
479
+ if (edge === undefined || edge.trim() === '') {
480
+ throw new HopwireError('--public needs the URL of the edge: set HOPWIRE_EDGE_URL, for example ws://127.0.0.1:8787 for a local edge.');
481
+ }
482
+ const edgeUrl = parseEdgeUrl(edge.trim());
483
+ if (edgeUrl === 'malformed') {
484
+ throw new HopwireError('HOPWIRE_EDGE_URL must be a ws:// or wss:// URL without a path, for example wss://edge.hwr.sh.');
485
+ }
486
+ if (edgeUrl === 'insecure') {
487
+ // The token travels in a header of the connect request
488
+ throw new HopwireError('HOPWIRE_EDGE_URL must use wss:// unless the edge runs on this machine; over ws:// the token would travel unencrypted.');
489
+ }
490
+ const devToken = (env.HOPWIRE_DEV_TOKEN ?? '').trim();
491
+ if (devToken !== '') {
492
+ return {
493
+ edgeUrl,
494
+ token: devToken,
495
+ subdomain: subdomain ?? randomSubdomain(randomBytes(RANDOM_SUBDOMAIN_BYTES)),
496
+ };
497
+ }
498
+ const account = await readAccount(dataDir);
499
+ if (account === null) {
500
+ throw new HopwireError('--public needs an account: run hopwire login first. For a local edge without a control plane, set HOPWIRE_DEV_TOKEN to its dev token instead.');
501
+ }
502
+ const connectTokens = await tokensForEdge(dataDir, account, edgeUrl, (bound) => new HopwireError(`HOPWIRE_EDGE_URL is ${edgeUrl.origin}, but the connect tokens of the account on this machine go to the edge ${bound.origin}; run hopwire login again to use the account with another edge.`));
503
+ // Without --subdomain the control plane names the fixed URL of the organisation
504
+ return { edgeUrl, connectTokens, subdomain: subdomain ?? null };
505
+ }
506
+ /**
507
+ * --public without HOPWIRE_EDGE_URL: the account of `hopwire login` and the edge it is bound to. An account logged in
508
+ * before logins stored the edge asks its control plane once and is bound to the edge it names.
509
+ */
510
+ async function publicThroughAccountEdge(subdomain, dataDir) {
511
+ const account = await readAccount(dataDir);
512
+ if (account === null) {
513
+ throw new HopwireError('--public needs an account: run hopwire login first. For a local edge without a control plane, set HOPWIRE_EDGE_URL and HOPWIRE_DEV_TOKEN to its URL and dev token instead.');
514
+ }
515
+ const { createControlPlaneClient } = await import('./control-plane-client.js');
516
+ const connectTokens = createControlPlaneClient({ url: account.controlPlaneUrl, apiToken: account.apiToken });
517
+ let edgeUrl = await boundEdge(dataDir);
518
+ if (edgeUrl === null) {
519
+ edgeUrl = (await connectTokens.me()).edgeUrl;
520
+ if (edgeUrl === null) {
521
+ throw new HopwireError(`--public needs the URL of the edge: the control plane at ${account.controlPlaneUrl.origin} names none; set HOPWIRE_EDGE_URL.`);
522
+ }
523
+ edgeUrl = await bindEdge(dataDir, edgeUrl);
524
+ }
525
+ return { edgeUrl, connectTokens, subdomain: subdomain ?? null };
526
+ }
527
+ /**
528
+ * Where the public services of a hopwire.yaml get their token. With controlPlane.url it is the account of
529
+ * `hopwire login`, which has to be one at that control plane; without it the dev token of the edge from
530
+ * HOPWIRE_DEV_TOKEN.
531
+ */
532
+ async function publicAccess(file, config, env, dataDir) {
533
+ if (config.controlPlaneUrl === null) {
534
+ const token = env.HOPWIRE_DEV_TOKEN;
535
+ if (token === undefined || token.trim() === '') {
536
+ throw new HopwireError(`A service in ${file} is public and needs a token: set controlPlane.url in the file to use your account (hopwire login), or set HOPWIRE_DEV_TOKEN to the dev token of a local edge (HOPWIRE_DEV_TOKEN in its .dev.vars).`);
537
+ }
538
+ return { token: token.trim() };
539
+ }
540
+ const wanted = config.controlPlaneUrl.origin;
541
+ const account = await readAccount(dataDir);
542
+ if (account === null) {
543
+ throw new ConfigError(file, 'controlPlane.url', `is set, so the public services use your account there, but this machine is not logged in; run hopwire login --api ${wanted} first.`);
544
+ }
545
+ if (account.controlPlaneUrl.origin !== wanted) {
546
+ // The stored API token belongs to another control plane and is not sent to this one
547
+ throw new ConfigError(file, 'controlPlane.url', `is ${wanted}, but this machine is logged in at ${account.controlPlaneUrl.origin}; run hopwire login --api ${wanted}, or change the URL in the file.`);
548
+ }
549
+ if (config.edgeUrl !== null) {
550
+ // The file names the edge, but the account decides where its connect tokens go (see tokensForEdge)
551
+ const named = config.edgeUrl;
552
+ return {
553
+ connectTokens: await tokensForEdge(dataDir, account, named, (bound) => new ConfigError(file, 'edge.url', `is ${named.origin}, but the connect tokens of the account on this machine go to the edge ${bound.origin}; run hopwire login again to use the account with another edge, or change the URL in the file.`)),
554
+ };
555
+ }
556
+ return { connectTokens: await connectTokenSource(account) };
557
+ }
558
+ /**
559
+ * The connect tokens of the account for a start that names its edge (HOPWIRE_EDGE_URL, or edge.url of a project
560
+ * file). The account decides where its tokens go, not the name: an account that is bound to an edge is refused
561
+ * with `mismatch` when another one is named. An account that is not bound yet (stored by an earlier CLI, or logged
562
+ * in at a control plane that named no edge) asks its control plane before the first token is fetched and is bound
563
+ * to the edge named there; the named edge is taken only when the control plane names none, as a local one does.
564
+ * Otherwise the first public start in a cloned repository would send the account's connect token, and a channel
565
+ * into this machine's services, to the edge that repository's file names. The question is part of fetching the
566
+ * first token, so a start that is stopped gives it up like any request to the control plane.
567
+ */
568
+ async function tokensForEdge(dataDir, account, named, mismatch) {
569
+ const bound = await boundEdge(dataDir);
570
+ if (bound !== null && bound.origin !== named.origin) {
571
+ throw mismatch(bound);
572
+ }
573
+ const { createControlPlaneClient } = await import('./control-plane-client.js');
574
+ const client = createControlPlaneClient({ url: account.controlPlaneUrl, apiToken: account.apiToken });
575
+ if (bound !== null) {
576
+ return client;
577
+ }
578
+ let binding = null;
579
+ return {
580
+ async connectToken(subdomain, signal) {
581
+ binding ??= (async () => {
582
+ const ofControlPlane = (await client.me(signal)).edgeUrl;
583
+ const now = await bindEdge(dataDir, ofControlPlane ?? named);
584
+ if (now.origin !== named.origin) {
585
+ throw mismatch(now);
586
+ }
587
+ })();
588
+ try {
589
+ await binding;
590
+ }
591
+ catch (error) {
592
+ // A question that failed is asked again with the next token; a refusal stays one
593
+ if (!(error instanceof HopwireError) || error instanceof TemporaryError) {
594
+ binding = null;
595
+ }
596
+ throw error;
597
+ }
598
+ return client.connectToken(subdomain, signal);
599
+ },
600
+ };
601
+ }
602
+ /**
603
+ * What --team needs: the account of `hopwire login`, whose control plane names the keys of the team. Loaded only
604
+ * for --team (or p2p.team), the one case in which private mode asks a server anything.
605
+ */
606
+ async function teamAccess(option, dataDir) {
607
+ const account = await readAccount(dataDir);
608
+ if (account === null) {
609
+ throw new HopwireError(`${option} needs an account in an organisation on the Team plan: run hopwire login first. Without an account, restrict access with --allow <pubkey> (p2p.allow in hopwire.yaml) instead.`);
610
+ }
611
+ const { createControlPlaneClient } = await import('./control-plane-client.js');
612
+ return createControlPlaneClient({ url: account.controlPlaneUrl, apiToken: account.apiToken });
613
+ }
614
+ /** p2p.team of a hopwire.yaml: the account has to be one at the control plane the file names, when it names one. */
615
+ async function teamAccessOfFile(file, config, dataDir) {
616
+ const account = await readAccount(dataDir);
617
+ if (account === null) {
618
+ throw new ConfigError(file, 'p2p.team', 'is true, which needs an account in an organisation on the Team plan, but this machine is not logged in; run hopwire login first, or list the keys under p2p.allow instead.');
619
+ }
620
+ if (config.controlPlaneUrl !== null && account.controlPlaneUrl.origin !== config.controlPlaneUrl.origin) {
621
+ // The stored API token belongs to another control plane and is not sent to this one
622
+ throw new ConfigError(file, 'controlPlane.url', `is ${config.controlPlaneUrl.origin}, but this machine is logged in at ${account.controlPlaneUrl.origin}; run hopwire login --api ${config.controlPlaneUrl.origin}, or change the URL in the file.`);
623
+ }
624
+ return teamAccess('p2p.team', dataDir);
625
+ }
626
+ /** --allow-host: a host name or address as a Host header carries it, with or without a port; in lower case. */
627
+ function parseAllowedHost(value) {
628
+ const host = value.trim().toLowerCase();
629
+ if (host.length > 255 || !/^(\[[0-9a-f:.]+\]|[a-z0-9]([a-z0-9._-]*[a-z0-9])?)(:\d{1,5})?$/.test(host)) {
630
+ throw new UsageError('--allow-host needs a host name, with or without a port, for example app.test or app.test:8080');
631
+ }
632
+ return host;
633
+ }
634
+ /** The control plane of the account. Loaded only for a public tunnel of a logged-in user. */
635
+ async function connectTokenSource(account) {
636
+ const { createControlPlaneClient } = await import('./control-plane-client.js');
637
+ return createControlPlaneClient({ url: account.controlPlaneUrl, apiToken: account.apiToken });
638
+ }
639
+ /**
640
+ * HOPWIRE_DHT_BOOTSTRAP: comma-separated host:port list of the DHT to join instead of the public one. A switch for
641
+ * development and tests only: it is how the acceptance run of the spec points the built CLI at a local HyperDHT
642
+ * testnet. It is not a product setting and not part of the help.
643
+ */
644
+ function parseBootstrap(value) {
645
+ if (value === undefined || value.trim() === '') {
646
+ return undefined;
647
+ }
648
+ return value.split(',').map((entry) => {
649
+ const match = /^([^\s:]+):(\d{1,5})$/.exec(entry.trim());
650
+ const port = Number(match?.[2]);
651
+ if (match?.[1] === undefined || port < 1 || port > 65535) {
652
+ throw new HopwireError('HOPWIRE_DHT_BOOTSTRAP must be a comma-separated list of host:port, for example 127.0.0.1:49737.');
653
+ }
654
+ return { host: match[1], port };
655
+ });
656
+ }
657
+ /** The version of the package this file ships in; package.json lies next to `src` and `dist` alike. */
658
+ function readVersion() {
659
+ const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
660
+ if (typeof manifest === 'object' &&
661
+ manifest !== null &&
662
+ 'version' in manifest &&
663
+ typeof manifest.version === 'string') {
664
+ return manifest.version;
665
+ }
666
+ throw new Error('package.json carries no version');
667
+ }
668
+ function parsePort(value, label, min) {
669
+ const port = Number(value);
670
+ if (value === undefined || value === '' || !Number.isInteger(port) || port < min || port > 65535) {
671
+ throw new UsageError(`${label} must be a port number between ${min} and 65535`);
672
+ }
673
+ return port;
674
+ }