hopwire 0.1.8 → 0.2.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 (41) hide show
  1. package/README.md +2 -0
  2. package/dist/agent/redact.js +38 -0
  3. package/dist/bin.js +5 -1
  4. package/dist/cli.js +237 -10
  5. package/dist/commands/connect.js +23 -7
  6. package/dist/commands/doctor.js +63 -3
  7. package/dist/commands/http.js +25 -4
  8. package/dist/commands/init.js +355 -0
  9. package/dist/commands/up.js +22 -3
  10. package/dist/commands/watch.js +54 -9
  11. package/dist/config-template.js +80 -0
  12. package/dist/config.js +65 -5
  13. package/dist/control-plane-client.js +70 -0
  14. package/dist/inspector/assets/index-CIOfyIbK.js +5 -0
  15. package/dist/inspector/assets/index-Du4-DCNN.css +2 -0
  16. package/dist/inspector/index.html +2 -2
  17. package/dist/inspector-api.js +145 -0
  18. package/dist/interceptor.js +19 -4
  19. package/dist/log-follow.js +473 -0
  20. package/dist/log.js +178 -11
  21. package/dist/main.js +1 -0
  22. package/dist/mcp/logs.js +46 -0
  23. package/dist/mcp/tools.js +136 -3
  24. package/dist/output.js +67 -1
  25. package/dist/p2p.js +249 -24
  26. package/dist/prompt.js +63 -0
  27. package/dist/relay.js +545 -0
  28. package/dist/serve.js +62 -2
  29. package/node_modules/@hopwire/protocol/dist/constants.d.ts +10 -0
  30. package/node_modules/@hopwire/protocol/dist/constants.js +10 -0
  31. package/node_modules/@hopwire/protocol/dist/index.d.ts +2 -0
  32. package/node_modules/@hopwire/protocol/dist/index.js +2 -0
  33. package/node_modules/@hopwire/protocol/dist/inspector.d.ts +18 -0
  34. package/node_modules/@hopwire/protocol/dist/log-entries.d.ts +72 -0
  35. package/node_modules/@hopwire/protocol/dist/log-entries.js +147 -0
  36. package/node_modules/@hopwire/protocol/dist/relay.d.ts +81 -0
  37. package/node_modules/@hopwire/protocol/dist/relay.js +102 -0
  38. package/node_modules/@hopwire/protocol/dist/ws-messages.d.ts +2 -1
  39. package/package.json +2 -1
  40. package/dist/inspector/assets/index-D3yNjmSA.js +0 -2
  41. package/dist/inspector/assets/index-XotF7D1X.css +0 -2
package/README.md CHANGED
@@ -15,6 +15,8 @@ hopwire http 3000 # record and inspect the traffic of the service on
15
15
  hopwire http 3000 --share # let teammates watch and replay it, peer to peer
16
16
  hopwire login # once, for public URLs
17
17
  hopwire http 3000 --public # a public HTTPS URL for the service
18
+ hopwire init # write a hopwire.yaml for every service of the project
19
+ hopwire up # start them all
18
20
  ```
19
21
 
20
22
  Documentation: https://hopwire.to/docs. Terms: https://hopwire.to/terms. Security reports:
@@ -126,3 +126,41 @@ function decodeComponent(text) {
126
126
  export function redactJsonText(text) {
127
127
  return text.replace(/"((?:[^"\\]|\\.)*)"(\s*:\s*)("(?:[^"\\]|\\.)*"?|[^,}\]\s"{[]+)/g, (whole, key, colon, value) => isRedactedField(key) ? `"${key}"${colon}"${redacted(value.replace(/^"|"$/g, ''))}"` : whole);
128
128
  }
129
+ /** Shapes of keys and tokens that are redacted wherever they stand in a log entry */
130
+ const KNOWN_SECRETS = [
131
+ /\b[sr]k_(?:live|test)_[A-Za-z0-9]{6,}/g,
132
+ /\bwhsec_[A-Za-z0-9+/=]{8,}/g,
133
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
134
+ /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
135
+ /\bxox[abprs]-[A-Za-z0-9-]{10,}/g,
136
+ /\bAKIA[0-9A-Z]{16}\b/g,
137
+ /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}/g,
138
+ ];
139
+ /** `Bearer abc…` and `Basic abc…`: the scheme stays, the credential goes */
140
+ const AUTH_SCHEME = /\b(Bearer|Basic|Token)\s+([A-Za-z0-9._~+/=-]{6,})/g;
141
+ /**
142
+ * `password=secret`, `token: abc`, `api_key="x y"` in free text: a sensitive name, `=` or `:`, and a value up to the
143
+ * next space, comma or semicolon (or its closing quote). A value that is already redacted, or a scheme whose
144
+ * credential was, is left alone.
145
+ */
146
+ const KEY_VALUE = /([A-Za-z0-9_.-]+)(\s*[=:]\s*)(?!\[redacted|(?:Bearer|Basic|Token)\s)("[^"\n]*"|'[^'\n]*'|[^\s,;&}\])"']+)/g;
147
+ /**
148
+ * A log entry as an agent is shown it (phase 15, decision 144): JSON keys and `key=value` / `key: value` pairs with a
149
+ * sensitive name, Bearer and Basic credentials, and the known shapes of keys (Stripe, GitHub, Slack, AWS, JWTs)
150
+ * redacted. Best effort: a log may hold secrets no pattern recognises, and the docs say so.
151
+ */
152
+ export function redactLogText(text) {
153
+ let shown = redactJsonText(text);
154
+ shown = shown.replace(AUTH_SCHEME, (_whole, scheme, credential) => `${scheme} ${redacted(credential)}`);
155
+ for (const pattern of KNOWN_SECRETS) {
156
+ shown = shown.replace(pattern, (secret) => redacted(secret));
157
+ }
158
+ return shown.replace(KEY_VALUE, (whole, key, separator, value) => {
159
+ if (!isRedactedField(key)) {
160
+ return whole;
161
+ }
162
+ const quote = /^["']/.exec(value)?.[0] ?? '';
163
+ const inner = quote === '' ? value : value.slice(1, -1);
164
+ return `${key}${separator}${quote}${redacted(inner)}${quote}`;
165
+ });
166
+ }
package/dist/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { openBrowser } from './browser.js';
3
3
  import { main } from './main.js';
4
- import { promptHidden } from './prompt.js';
4
+ import { promptHidden, promptLine } from './prompt.js';
5
5
  import { decorate, wantsColor } from './style.js';
6
6
  const color = wantsColor(process.stdout, process.env);
7
7
  await main({
@@ -17,6 +17,10 @@ await main({
17
17
  promptSecret: process.stdin.isTTY
18
18
  ? (question, stop) => promptHidden(question, process.stdin, process.stderr, stop)
19
19
  : undefined,
20
+ // hopwire init asks its questions on standard error, so standard output keeps the lines of the result
21
+ promptLine: process.stdin.isTTY
22
+ ? (question, stop) => promptLine(question, process.stdin, process.stderr, stop)
23
+ : undefined,
20
24
  // hopwire login opens its sign-in page; the URL is printed too
21
25
  openBrowser: (url) => openBrowser(url),
22
26
  });
package/dist/cli.js CHANGED
@@ -7,6 +7,7 @@ import { INSPECTOR_DEFAULT_PORT, LOCAL_ENTRY_DEFAULT_PORT, RANDOM_SUBDOMAIN_BYTE
7
7
  import { bindEdge, boundEdge, readAccount } from './account.js';
8
8
  import { startConnect } from './commands/connect.js';
9
9
  import { doctor } from './commands/doctor.js';
10
+ import { init } from './commands/init.js';
10
11
  import { startHttpTunnel } from './commands/http.js';
11
12
  import { login, logout } from './commands/login.js';
12
13
  import { startMcp } from './commands/mcp.js';
@@ -16,6 +17,7 @@ import { startWatch } from './commands/watch.js';
16
17
  import { ConfigError, isServiceName, loadConfig } from './config.js';
17
18
  import { HopwireError, TemporaryError, UsageError, errorCode } from './errors.js';
18
19
  import { loadOrCreateIdentity } from './identity.js';
20
+ import { defaultLogName, isFollowablePath } from './log-follow.js';
19
21
  import { DOCS_URL, printable } from './output.js';
20
22
  import { createUpdateNotice } from './update-notice.js';
21
23
  import { parseControlPlaneUrl, parseEdgeUrl, parseLocalTarget } from './urls.js';
@@ -24,6 +26,7 @@ const USAGE = `Usage: hopwire <command>
24
26
 
25
27
  Private mode: no account, no servers of ours, end-to-end encrypted between you and the teammates you choose.
26
28
  With --team (Team plan) your account's control plane names who gets in; the traffic stays direct.
29
+ With --relay as well, a connection that cannot be made directly goes through our edge, end-to-end encrypted.
27
30
  Public mode (--public): a public URL for the service through the edge; it needs an account (hopwire login).
28
31
 
29
32
  Start here:
@@ -38,6 +41,8 @@ Start here:
38
41
  Commands:
39
42
  hopwire http <port> Forward a local entry point to http://127.0.0.1:<port>, log every exchange
40
43
  and show the traffic in the inspector
44
+ hopwire init Write a commented hopwire.yaml for hopwire up by answering a few questions
45
+ (or from --service name=port ... --yes, without questions)
41
46
  hopwire up Start every service of hopwire.yaml: one traffic log and one inspector for all,
42
47
  public URLs and P2P sharing as the file says
43
48
  hopwire id Print the public key of this machine (creates the identity on first use)
@@ -66,6 +71,10 @@ Options for http:
66
71
  (Team plan). Needs an account: run hopwire login first. The control plane of the
67
72
  account names the keys of the team and gets the public key of this machine; this is
68
73
  the one thing private mode asks a server. Your traffic still passes none
74
+ --relay With --team: teammates whose network allows no direct P2P connection (UDP blocked,
75
+ or both sides behind a strict NAT) come in through the relay of your account's edge
76
+ on port 443. End-to-end encrypted: the edge passes on bytes it cannot read, and sees
77
+ addresses, your organisation, keys and byte counts. Direct P2P is always tried first
69
78
  --public Serve the service under a public URL through the edge. Needs an account: run
70
79
  hopwire login first; the edge is the one its control plane names. HOPWIRE_EDGE_URL
71
80
  sets another one. A local edge (ws://127.0.0.1:8787) can be used without an account,
@@ -85,12 +94,36 @@ Options for http:
85
94
  model provider; exchanges captured without it stay closed to agents
86
95
  --no-ws-capture Log the handshake of a WebSocket but not its messages (by default both directions
87
96
  are recorded, up to 64 KiB per message and 2 MB or 10,000 messages per WebSocket)
97
+ --log <path> Follow a log file of the service (storage/logs/laravel.log) and show its new entries
98
+ next to the traffic, linked to the requests they were written during. Nothing written
99
+ before the start is read; a * in the file name follows the newest match. Can be given
100
+ several times. The entries stay on this machine unless --share-logs
101
+ --share-logs With --share and --log: teammates who watch the log also see the new entries of the
102
+ --log files (their coding agents only with --allow-agents). Logs often hold secrets and
103
+ other people's data. Neither the edge nor the control plane ever sees them
104
+ --log-request-id With --log: every request forwarded to the service carries X-Hopwire-Exchange-Id; a
105
+ service that writes it into its log gets exact links when requests overlap
106
+
107
+ Options for init:
108
+ --config <path> The file to write (default ${HOPWIRE_YAML_FILE} in the working directory). An existing file
109
+ is never replaced. Nothing is contacted; a public service takes the edge and the
110
+ control plane of the account on this machine (hopwire login)
111
+ --yes Ask nothing and write exactly what the flags below say; what is not given stays off
112
+ --service <name>=<port|url>
113
+ With --yes: a service and its port (or an http URL on this machine); can be given
114
+ several times
115
+ --public <name> With --yes: serve this service under a public URL (needs hopwire login); can be
116
+ given several times
117
+ --subdomain <name>=<sub>
118
+ With --yes: the subdomain of a public service, reserved by your organisation
119
+ --share, --team, --allow-agents
120
+ With --yes: p2p.share, p2p.team and p2p.allowAgents, as for http
88
121
 
89
122
  Options for up:
90
123
  --config <path> The config file (default ${HOPWIRE_YAML_FILE} in the working directory). A public service
91
124
  takes the URL of the edge from edge.url in the file. With controlPlane.url in the file
92
125
  it uses your account (hopwire login), without it the dev token in HOPWIRE_DEV_TOKEN.
93
- p2p.team in the file is --team of http
126
+ p2p.team in the file is --team of http, p2p.relay is --relay
94
127
  --no-agent, --agent As for http, for every service; agent: false in the file turns it off too
95
128
  --force As for http: stop the tunnel that holds the data directory first
96
129
 
@@ -119,6 +152,8 @@ Options for connect:
119
152
  service); without it only 127.0.0.1:<port> and localhost:<port>. Can be given several times
120
153
  --team For a teammate who shares with --team: registers the key of this machine with your
121
154
  organisation (hopwire login first) and connects only to a machine of one of its members
155
+ --relay With --team: when no direct connection comes about, go through the relay of your
156
+ account's edge (the teammate shares with --relay); end-to-end encrypted
122
157
 
123
158
  Options for watch:
124
159
  --replay-target <url> Local service that replays are sent to, for example http://127.0.0.1:3000;
@@ -126,9 +161,13 @@ Options for watch:
126
161
  --inspect <port> Loopback port of the inspector (default ${INSPECTOR_DEFAULT_PORT}, 0 picks a free one)
127
162
  --team For a teammate who shares with --team: registers the key of this machine with your
128
163
  organisation (hopwire login first), so the sharer lets it in
164
+ --relay With --team: when no direct connection comes about, go through the relay of your
165
+ account's edge (the teammate shares with --relay); end-to-end encrypted
129
166
  --agent Let a coding agent on this machine read the exchanges your teammate allowed for
130
167
  agents (they share with --allow-agents) through hopwire mcp; never on without it.
131
168
  What the agent reads goes to its model provider
169
+ --log <path> As for http: follow a log file of your own service, so the entries of your replays
170
+ show next to them. They stay on this machine
132
171
  --force As for http: stop the tunnel that holds the data directory first
133
172
 
134
173
  Global options:
@@ -159,8 +198,12 @@ const COMMAND_OPTIONS = {
159
198
  'share',
160
199
  'allow',
161
200
  'team',
201
+ 'relay',
162
202
  'allow-agents',
163
203
  'no-ws-capture',
204
+ 'log',
205
+ 'share-logs',
206
+ 'log-request-id',
164
207
  'public',
165
208
  'subdomain',
166
209
  'agent',
@@ -170,8 +213,8 @@ const COMMAND_OPTIONS = {
170
213
  up: ['config', 'agent', 'no-agent', 'force'],
171
214
  id: [],
172
215
  rotate: [],
173
- connect: ['port', 'service', 'allow-host', 'team'],
174
- watch: ['replay-target', 'inspect', 'team', 'agent', 'force'],
216
+ connect: ['port', 'service', 'allow-host', 'team', 'relay'],
217
+ watch: ['replay-target', 'inspect', 'team', 'relay', 'agent', 'log', 'force'],
175
218
  login: ['api', 'token', 'no-browser'],
176
219
  logout: [],
177
220
  mcp: ['read-only'],
@@ -179,6 +222,11 @@ const COMMAND_OPTIONS = {
179
222
  };
180
223
  /** Parses the arguments and starts the command. Resolves with what keeps running, or null when the command is done. */
181
224
  export async function run(argv, io) {
225
+ // hopwire init takes --public and --subdomain with other values than http, so it has a parser of its own
226
+ if (commandOf(argv) === 'init') {
227
+ await runInit(argv, io);
228
+ return null;
229
+ }
182
230
  const { values, positionals } = parse(argv);
183
231
  const [command, ...rest] = positionals;
184
232
  if (values.help) {
@@ -205,9 +253,7 @@ export async function run(argv, io) {
205
253
  if (values['data-dir'] === '') {
206
254
  throw new UsageError('--data-dir needs the path of a directory');
207
255
  }
208
- // A variable that is set but empty counts as not set; as a path it would be the working directory
209
- const home = io.env.HOPWIRE_HOME === '' ? undefined : io.env.HOPWIRE_HOME;
210
- const dataDir = values['data-dir'] ?? home ?? path.join(os.homedir(), '.hopwire');
256
+ const dataDir = resolveDataDir(values['data-dir'], io.env);
211
257
  if (command === 'id') {
212
258
  noMoreArguments(rest, 0, 'hopwire id');
213
259
  io.print((await loadOrCreateIdentity(dataDir)).publicKey.toString('hex'));
@@ -284,6 +330,7 @@ export async function run(argv, io) {
284
330
  const port = parsePort(values.port, '--port', 0);
285
331
  const service = parseService(values.service);
286
332
  const allowHosts = (values['allow-host'] ?? []).map(parseAllowedHost);
333
+ relayNeedsTeam(values);
287
334
  return startConnect({
288
335
  peerKey,
289
336
  port,
@@ -291,6 +338,7 @@ export async function run(argv, io) {
291
338
  allowHosts,
292
339
  // The account is only read for --team: without it private mode never looks at it
293
340
  team: values.team ? await teamAccess('--team', dataDir) : undefined,
341
+ relay: values.relay ? await relayAccess('--relay', dataDir) : undefined,
294
342
  dataDir,
295
343
  print: io.print,
296
344
  bootstrap: parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP),
@@ -302,13 +350,20 @@ export async function run(argv, io) {
302
350
  const logKey = parseKey(rest[0], 'The log key');
303
351
  const replayTarget = values['replay-target'] === undefined ? null : parseReplayTarget(values['replay-target']);
304
352
  const inspectPort = parsePort(values.inspect ?? String(INSPECTOR_DEFAULT_PORT), '--inspect', 0);
353
+ relayNeedsTeam(values);
354
+ if (values.log !== undefined && replayTarget === null) {
355
+ throw new UsageError('--log of hopwire watch only works together with --replay-target: it shows the entries of your replays');
356
+ }
305
357
  return startWatch({
306
358
  force: values.force ?? false,
359
+ logs: parseLogs(values.log, io.cwd ?? process.cwd()),
360
+ cwd: io.cwd ?? process.cwd(),
307
361
  logKey,
308
362
  replayTarget,
309
363
  inspectPort,
310
364
  // The account is only read for --team: without it private mode never looks at it
311
365
  team: values.team ? await teamAccess('--team', dataDir) : undefined,
366
+ relay: values.relay ? await relayAccess('--relay', dataDir) : undefined,
312
367
  dataDir,
313
368
  print: io.print,
314
369
  bootstrap: parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP),
@@ -323,10 +378,7 @@ export async function run(argv, io) {
323
378
  throw new UsageError('--config needs the path of a config file');
324
379
  }
325
380
  const cwd = io.cwd ?? process.cwd();
326
- const file = path.resolve(cwd, values.config ?? HOPWIRE_YAML_FILE);
327
- // Sentences about the file name it as the user would: relative to the working directory when it lies in it
328
- const relative = path.relative(cwd, file);
329
- const shown = relative.startsWith('..') || path.isAbsolute(relative) ? file : relative;
381
+ const { file, shown } = configFile(cwd, values.config);
330
382
  const config = await loadConfig(file, values.config !== undefined, shown);
331
383
  const update = createUpdateNotice(readVersion());
332
384
  const running = await startUp({
@@ -341,6 +393,8 @@ export async function run(argv, io) {
341
393
  : {}),
342
394
  // The account is only read for p2p.team: without it private mode never looks at it
343
395
  team: config.team ? await teamAccessOfFile(shown, config, dataDir) : undefined,
396
+ // The edge is only contacted for p2p.relay, and then only through the relay
397
+ relay: config.relay ? await relayAccess('p2p.relay', dataDir) : undefined,
344
398
  bootstrap: config.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
345
399
  agent: agent ?? config.agent ?? undefined,
346
400
  signal: io.signal,
@@ -363,6 +417,17 @@ export async function run(argv, io) {
363
417
  if (values['allow-agents'] && !values.share) {
364
418
  throw new UsageError('--allow-agents only works together with --share');
365
419
  }
420
+ if (values['share-logs'] && !values.share) {
421
+ throw new UsageError('--share-logs only works together with --share');
422
+ }
423
+ if (values['share-logs'] && values.log === undefined) {
424
+ throw new UsageError('--share-logs only works together with --log <path>');
425
+ }
426
+ if (values['log-request-id'] && values.log === undefined) {
427
+ throw new UsageError('--log-request-id only works together with --log <path>');
428
+ }
429
+ const logs = parseLogs(values.log, io.cwd ?? process.cwd());
430
+ relayNeedsTeam(values);
366
431
  if (values.team && allow.length > 0) {
367
432
  throw new UsageError('--team and --allow cannot be combined: with --team the team is the list');
368
433
  }
@@ -390,17 +455,148 @@ export async function run(argv, io) {
390
455
  allow,
391
456
  // The account is only read for --team: without it private mode never looks at it
392
457
  team: values.team ? await teamAccess('--team', dataDir) : undefined,
458
+ relay: values.relay ? await relayAccess('--relay', dataDir) : undefined,
393
459
  bootstrap: values.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
394
460
  // Edge URL, token and account are only read for --public: private mode never looks at them
395
461
  public: values.public ? update.watch(await parsePublic(values.subdomain, io.env, dataDir)) : undefined,
396
462
  agent: agentChoice(values),
397
463
  captureWebSocket: !(values['no-ws-capture'] ?? false),
464
+ logs,
465
+ shareLogs: values['share-logs'] ?? false,
466
+ logRequestId: values['log-request-id'] ?? false,
467
+ cwd: io.cwd ?? process.cwd(),
398
468
  signal: io.signal,
399
469
  });
400
470
  // After the lines of the start, so the mode stays the first line of every tunnel
401
471
  update.print(io.print);
402
472
  return running;
403
473
  }
474
+ /**
475
+ * The files of --log, resolved against the working directory and named after themselves. Two files with the same name
476
+ * would label their entries alike; hopwire.yaml can name them apart.
477
+ */
478
+ function parseLogs(values, cwd) {
479
+ const logs = [];
480
+ for (const value of values ?? []) {
481
+ if (value === '') {
482
+ throw new UsageError('--log needs the path of a log file');
483
+ }
484
+ const file = path.resolve(cwd, value);
485
+ if (!isFollowablePath(file)) {
486
+ throw new UsageError('--log takes a * only in the file name, not in a directory of the path');
487
+ }
488
+ const name = defaultLogName(file);
489
+ if (logs.some((log) => log.name === name)) {
490
+ throw new UsageError(`Two --log files are both named ${name}; give them names of their own under logs: in hopwire.yaml`);
491
+ }
492
+ logs.push({ path: file, name });
493
+ }
494
+ return logs;
495
+ }
496
+ /** The data directory: --data-dir, else HOPWIRE_HOME, else ~/.hopwire. */
497
+ function resolveDataDir(option, env) {
498
+ // A variable that is set but empty counts as not set; as a path it would be the working directory
499
+ const home = env.HOPWIRE_HOME === '' ? undefined : env.HOPWIRE_HOME;
500
+ return option ?? home ?? path.join(os.homedir(), '.hopwire');
501
+ }
502
+ /** The hopwire.yaml of up and init, and how sentences name it: relative to the working directory when it lies in it. */
503
+ function configFile(cwd, option) {
504
+ const file = path.resolve(cwd, option ?? HOPWIRE_YAML_FILE);
505
+ const relative = path.relative(cwd, file);
506
+ return { file, shown: relative.startsWith('..') || path.isAbsolute(relative) ? file : relative };
507
+ }
508
+ /** The command of a command line: the first argument that is neither an option nor the value of --data-dir. */
509
+ function commandOf(argv) {
510
+ for (let index = 0; index < argv.length; index++) {
511
+ const argument = argv[index] ?? '';
512
+ if (argument === '--') {
513
+ return argv[index + 1];
514
+ }
515
+ if (argument === '--data-dir') {
516
+ index++;
517
+ }
518
+ else if (!argument.startsWith('-')) {
519
+ return argument;
520
+ }
521
+ }
522
+ return undefined;
523
+ }
524
+ /** hopwire init: its own options, then the questions or the flags of --yes. */
525
+ async function runInit(argv, io) {
526
+ let parsed;
527
+ try {
528
+ parsed = parseArgs({
529
+ args: argv,
530
+ allowPositionals: true,
531
+ options: {
532
+ help: { type: 'boolean', short: 'h' },
533
+ version: { type: 'boolean' },
534
+ 'data-dir': { type: 'string' },
535
+ config: { type: 'string' },
536
+ yes: { type: 'boolean' },
537
+ service: { type: 'string', multiple: true },
538
+ public: { type: 'string', multiple: true },
539
+ subdomain: { type: 'string', multiple: true },
540
+ share: { type: 'boolean' },
541
+ team: { type: 'boolean' },
542
+ 'allow-agents': { type: 'boolean' },
543
+ },
544
+ });
545
+ }
546
+ catch (error) {
547
+ const problem = argumentProblem(error);
548
+ throw new UsageError(problem.endsWith(' is not an option of hopwire') ? `${problem} init` : problem);
549
+ }
550
+ const { values, positionals } = parsed;
551
+ if (values.help) {
552
+ io.print(USAGE);
553
+ return;
554
+ }
555
+ if (values.version) {
556
+ io.print(readVersion());
557
+ return;
558
+ }
559
+ noMoreArguments(positionals, 1, 'hopwire init [--config <path>]');
560
+ if (values['data-dir'] === '') {
561
+ throw new UsageError('--data-dir needs the path of a directory');
562
+ }
563
+ if (values.config === '') {
564
+ throw new UsageError('--config needs the path of the file to write');
565
+ }
566
+ const answered = values.service !== undefined ||
567
+ values.public !== undefined ||
568
+ values.subdomain !== undefined ||
569
+ values.share === true ||
570
+ values.team === true ||
571
+ values['allow-agents'] === true;
572
+ if (answered && values.yes !== true) {
573
+ throw new UsageError('--service, --public, --subdomain, --share, --team and --allow-agents of hopwire init only work together with --yes');
574
+ }
575
+ const flags = values.yes === true
576
+ ? {
577
+ services: values.service ?? [],
578
+ public: values.public ?? [],
579
+ subdomains: values.subdomain ?? [],
580
+ share: values.share ?? false,
581
+ team: values.team ?? false,
582
+ allowAgents: values['allow-agents'] ?? false,
583
+ }
584
+ : null;
585
+ const cwd = io.cwd ?? process.cwd();
586
+ const { file, shown } = configFile(cwd, values.config);
587
+ const promptLine = io.promptLine;
588
+ await init({
589
+ file,
590
+ shown,
591
+ named: values.config !== undefined,
592
+ cwd,
593
+ dataDir: resolveDataDir(values['data-dir'], io.env),
594
+ flags,
595
+ ask: promptLine === undefined ? undefined : (question) => promptLine(question, io.signal),
596
+ say: (line) => (io.notice ?? io.print)(line),
597
+ print: io.print,
598
+ });
599
+ }
404
600
  /** --agent or --no-agent; undefined leaves the choice to hopwire.yaml or the default (on, decision 139). */
405
601
  function agentChoice(values) {
406
602
  if (values.agent && values['no-agent']) {
@@ -428,6 +624,7 @@ function parse(argv) {
428
624
  share: { type: 'boolean' },
429
625
  allow: { type: 'string', multiple: true },
430
626
  team: { type: 'boolean' },
627
+ relay: { type: 'boolean' },
431
628
  'allow-agents': { type: 'boolean' },
432
629
  'allow-host': { type: 'string', multiple: true },
433
630
  port: { type: 'string' },
@@ -437,6 +634,9 @@ function parse(argv) {
437
634
  agent: { type: 'boolean' },
438
635
  'no-agent': { type: 'boolean' },
439
636
  'no-ws-capture': { type: 'boolean' },
637
+ log: { type: 'string', multiple: true },
638
+ 'share-logs': { type: 'boolean' },
639
+ 'log-request-id': { type: 'boolean' },
440
640
  'read-only': { type: 'boolean' },
441
641
  api: { type: 'string' },
442
642
  token: { type: 'boolean' },
@@ -651,6 +851,10 @@ async function tokensForEdge(dataDir, account, named, mismatch) {
651
851
  * for --team (or p2p.team), the one case in which private mode asks a server anything.
652
852
  */
653
853
  async function teamAccess(option, dataDir) {
854
+ return accountClient(option, dataDir);
855
+ }
856
+ /** The control plane of the stored account, for --team and --relay. */
857
+ async function accountClient(option, dataDir) {
654
858
  const account = await readAccount(dataDir);
655
859
  if (account === null) {
656
860
  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.`);
@@ -658,6 +862,29 @@ async function teamAccess(option, dataDir) {
658
862
  const { createControlPlaneClient } = await import('./control-plane-client.js');
659
863
  return createControlPlaneClient({ url: account.controlPlaneUrl, apiToken: account.apiToken });
660
864
  }
865
+ /** --relay pairs machines of one organisation only, so it needs --team. */
866
+ function relayNeedsTeam(values) {
867
+ if (values.relay && !values.team) {
868
+ throw new UsageError('--relay only works together with --team: the relay of the edge (Team plan) only pairs machines of one organisation');
869
+ }
870
+ }
871
+ /**
872
+ * What --relay (or p2p.relay) needs besides --team: the edge the account is bound to, which carries the relay, and the
873
+ * control plane, which issues the relay tokens. Loaded only for --relay, the one case in which private mode contacts
874
+ * the edge, and then only when no direct connection comes about.
875
+ */
876
+ async function relayAccess(option, dataDir) {
877
+ const client = await accountClient(option, dataDir);
878
+ let edgeUrl = await boundEdge(dataDir);
879
+ if (edgeUrl === null) {
880
+ const named = (await client.me()).edgeUrl;
881
+ if (named === null) {
882
+ throw new HopwireError(`${option} goes through the edge of your account, but its control plane names none; run hopwire login again, or leave ${option} out.`);
883
+ }
884
+ edgeUrl = await bindEdge(dataDir, named);
885
+ }
886
+ return { edgeUrl, tokens: client };
887
+ }
661
888
  /** p2p.team of a hopwire.yaml: the account has to be one at the control plane the file names, when it names one. */
662
889
  async function teamAccessOfFile(file, config, dataDir) {
663
890
  const account = await readAccount(dataDir);
@@ -2,7 +2,7 @@ import { once } from 'node:events';
2
2
  import net, {} from 'node:net';
3
3
  import { HopwireError, listenError } from '../errors.js';
4
4
  import { loadOrCreateIdentity } from '../identity.js';
5
- import { MODE_P2P, MODE_P2P_TEAM, connectGuide, printable, shortKey } from '../output.js';
5
+ import { MODE_P2P, MODE_P2P_RELAYED, MODE_P2P_TEAM, connectGuide, printable, relayedLine, shortKey } from '../output.js';
6
6
  import { Supervisor, unlessAborted } from '../supervisor.js';
7
7
  /**
8
8
  * `hopwire connect <peer-key> --port <p>`: a loopback listener whose every TCP connection becomes one end-to-end
@@ -22,6 +22,12 @@ export async function startConnect(options) {
22
22
  throw new HopwireError(`No member of ${organisation} has registered the key ${shortKey(options.peerKey)}; check the key, and that your teammate shares with --team (or p2p.team in hopwire.yaml) from an account in that organisation. Without --team this command connects to any key.`);
23
23
  }
24
24
  }
25
+ let relay;
26
+ if (options.relay !== undefined) {
27
+ // Loaded only here: without --relay nothing opens a relay socket
28
+ const { relaySetup } = await import('../relay.js');
29
+ relay = relaySetup(options.relay, ownKey);
30
+ }
25
31
  const { PeerConnectError, createPeerConnector } = await import('../p2p.js');
26
32
  options.signal?.throwIfAborted();
27
33
  const connector = createPeerConnector({
@@ -29,6 +35,7 @@ export async function startConnect(options) {
29
35
  peerKey: options.peerKey,
30
36
  service: options.service,
31
37
  bootstrap: options.bootstrap,
38
+ relay,
32
39
  });
33
40
  // Closed in the order of every command: the listener and its connections, then the DHT node
34
41
  const supervisor = new Supervisor();
@@ -40,7 +47,7 @@ export async function startConnect(options) {
40
47
  probe.destroy();
41
48
  }
42
49
  catch (error) {
43
- throw error instanceof PeerConnectError ? connectError(error.code, options, ownKey) : error;
50
+ throw error instanceof PeerConnectError ? connectError(error.code, options, ownKey, error.problem) : error;
44
51
  }
45
52
  const clients = new Set();
46
53
  /** Hosts whose refusal was said already: one line each, and no more than a few */
@@ -52,7 +59,10 @@ export async function startConnect(options) {
52
59
  admit(client, answeredHosts(port, options.allowHosts ?? []), () => bridge(client, connector, (error) => {
53
60
  // The client only sees a closed connection; the reason is said here
54
61
  const code = error instanceof PeerConnectError ? error.code : 'UNKNOWN';
55
- options.print(connectError(code, options, ownKey).message);
62
+ const problem = error instanceof PeerConnectError ? error.problem : null;
63
+ options.print(error instanceof PeerConnectError && error.limit
64
+ ? `Limit ${problem ?? 'a limit of the relay'}`
65
+ : connectError(code, options, ownKey, problem).message);
56
66
  }), (host) => {
57
67
  const shown = printableHost(host);
58
68
  if (!refused.has(shown) && refused.size < REFUSALS_SAID) {
@@ -78,12 +88,16 @@ export async function startConnect(options) {
78
88
  // Stopped at the last step: nothing is reported as running
79
89
  options.signal?.throwIfAborted();
80
90
  const url = `http://127.0.0.1:${server.address().port}`;
81
- options.print(organisation === null ? MODE_P2P : MODE_P2P_TEAM);
91
+ const relayed = connector.relayed() && options.relay !== undefined;
92
+ options.print(relayed ? MODE_P2P_RELAYED : organisation === null ? MODE_P2P : MODE_P2P_TEAM);
82
93
  options.print(`Forwarding ${url} -> peer ${options.peerKey}${options.service === null ? '' : ` (service ${options.service})`}`);
83
94
  options.print(`Peer key ${ownKey}`);
84
95
  if (organisation !== null) {
85
96
  options.print(`Team ${organisation}: the peer is a machine of a member, and this machine's key is registered there`);
86
97
  }
98
+ if (relayed && options.relay !== undefined) {
99
+ options.print(relayedLine(options.relay.edgeUrl));
100
+ }
87
101
  // What reaches the peer is recorded there (spec decision 112): said before anything is sent
88
102
  options.print(CONNECT_RECORDING_NOTICE);
89
103
  for (const line of connectGuide(url)) {
@@ -194,9 +208,11 @@ function bridge(client, connector, onUnreachable) {
194
208
  });
195
209
  }
196
210
  /** One sentence for a stream that could not be opened: what happened and what to do. */
197
- function connectError(code, options, ownKey) {
211
+ function connectError(code, options, ownKey, relayProblem = null) {
198
212
  const peer = shortKey(options.peerKey);
199
213
  switch (code) {
214
+ case 'relay':
215
+ return new HopwireError(`No direct connection to the peer ${peer} came about, and the relay did not connect either: ${relayProblem ?? 'it failed'}.`);
200
216
  case 'PEER_NOT_FOUND':
201
217
  return new HopwireError(`No peer with the key ${peer} was found; check the key, your network connection and that your teammate's tunnel is running and shared (--share, or p2p.share in hopwire.yaml).`);
202
218
  case 'unknown_service':
@@ -215,7 +231,7 @@ function connectError(code, options, ownKey) {
215
231
  ? `The peer ${peer} was found but did not accept the connection; if your teammate uses --allow, it has to list this machine's key ${ownKey}. If your teammate shares with --team, run this command with --team.`
216
232
  : `The peer ${peer} was found but did not accept the connection; if your teammate uses --allow instead of --team, it has to list this machine's key ${ownKey}. Otherwise try again in a minute.`);
217
233
  default:
218
- // Hole punching failed in one of its ways; V1 has no relay to fall back to
219
- return new HopwireError(`No direct connection to the peer ${peer} was possible (${code}); Hopwire has no relay, so try again from another network.`);
234
+ // Hole punching failed in one of its ways, and no relay was asked for
235
+ return new HopwireError(`No direct connection to the peer ${peer} was possible (${code}); try again from another network, or, on the Team plan, connect through the relay of the edge with --team --relay (your teammate shares with --relay too).`);
220
236
  }
221
237
  }