hopwire 0.2.0 → 0.3.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.
package/dist/cli.js CHANGED
@@ -1,15 +1,14 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { readFileSync } from 'node:fs';
3
2
  import os from 'node:os';
4
3
  import path from 'node:path';
5
4
  import { parseArgs } from 'node:util';
6
5
  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';
6
+ import { bindEdge, boundEdge, isProfileName, readAccount } from './account.js';
8
7
  import { startConnect } from './commands/connect.js';
9
8
  import { doctor } from './commands/doctor.js';
10
9
  import { init } from './commands/init.js';
11
10
  import { startHttpTunnel } from './commands/http.js';
12
- import { login, logout } from './commands/login.js';
11
+ import { login, logout, profiles, use } from './commands/login.js';
13
12
  import { startMcp } from './commands/mcp.js';
14
13
  import { rotate } from './commands/rotate.js';
15
14
  import { startUp } from './commands/up.js';
@@ -19,6 +18,7 @@ import { HopwireError, TemporaryError, UsageError, errorCode } from './errors.js
19
18
  import { loadOrCreateIdentity } from './identity.js';
20
19
  import { defaultLogName, isFollowablePath } from './log-follow.js';
21
20
  import { DOCS_URL, printable } from './output.js';
21
+ import { readVersion } from './version.js';
22
22
  import { createUpdateNotice } from './update-notice.js';
23
23
  import { parseControlPlaneUrl, parseEdgeUrl, parseLocalTarget } from './urls.js';
24
24
  export { UsageError };
@@ -26,7 +26,7 @@ const USAGE = `Usage: hopwire <command>
26
26
 
27
27
  Private mode: no account, no servers of ours, end-to-end encrypted between you and the teammates you choose.
28
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.
29
+ With --relay (turns on --team), a connection that cannot be made directly goes through our edge, end-to-end encrypted.
30
30
  Public mode (--public): a public URL for the service through the edge; it needs an account (hopwire login).
31
31
 
32
32
  Start here:
@@ -53,6 +53,9 @@ Commands:
53
53
  hopwire login Sign in through the browser and store an API token of the control plane on this
54
54
  machine, for public mode (--token pastes a token instead)
55
55
  hopwire logout Remove the stored API token from this machine
56
+ hopwire profiles List the logins on this machine (one profile per organisation) and which one
57
+ is current; nothing is contacted
58
+ hopwire use <profile> Make another profile the current one, for example after hopwire login --profile acme
56
59
  hopwire doctor Print a report about this installation (versions, data directory, account,
57
60
  hopwire.yaml) to read or to paste into a bug report. It is sent nowhere
58
61
  hopwire mcp An MCP server for a coding agent on this machine (stdio): it reads and replays
@@ -71,10 +74,11 @@ Options for http:
71
74
  (Team plan). Needs an account: run hopwire login first. The control plane of the
72
75
  account names the keys of the team and gets the public key of this machine; this is
73
76
  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
77
+ --relay With --share, turns on --team: teammates whose network allows no direct P2P connection
78
+ (UDP blocked, or both sides behind a strict NAT) come in through the relay of your
79
+ account's edge on port 443. End-to-end encrypted: the edge passes on bytes it cannot
80
+ read, and sees addresses, your organisation, keys and byte counts. Direct P2P is
81
+ always tried first
78
82
  --public Serve the service under a public URL through the edge. Needs an account: run
79
83
  hopwire login first; the edge is the one its control plane names. HOPWIRE_EDGE_URL
80
84
  sets another one. A local edge (ws://127.0.0.1:8787) can be used without an account,
@@ -123,7 +127,7 @@ Options for up:
123
127
  --config <path> The config file (default ${HOPWIRE_YAML_FILE} in the working directory). A public service
124
128
  takes the URL of the edge from edge.url in the file. With controlPlane.url in the file
125
129
  it uses your account (hopwire login), without it the dev token in HOPWIRE_DEV_TOKEN.
126
- p2p.team in the file is --team of http, p2p.relay is --relay
130
+ p2p.team in the file is --team of http, p2p.relay is --relay (and turns on p2p.team)
127
131
  --no-agent, --agent As for http, for every service; agent: false in the file turns it off too
128
132
  --force As for http: stop the tunnel that holds the data directory first
129
133
 
@@ -137,6 +141,9 @@ Options for login:
137
141
  page, and waits until you sign in there and approve the code; the control plane
138
142
  then creates an API token for this machine. The token is checked with the control
139
143
  plane and stored in config.json of the data directory, readable for this user only
144
+ --profile <name> Store the login in this profile and make it the current one (default: the current
145
+ profile, else "default"). One profile per organisation: hopwire login --profile acme
146
+ with a token of Acme keeps the login of your own organisation next to it
140
147
 
141
148
  Options for mcp:
142
149
  --read-only Leave out the replay tool; the agent can only read the traffic
@@ -152,7 +159,7 @@ Options for connect:
152
159
  service); without it only 127.0.0.1:<port> and localhost:<port>. Can be given several times
153
160
  --team For a teammate who shares with --team: registers the key of this machine with your
154
161
  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
162
+ --relay Turns on --team: when no direct connection comes about, go through the relay of your
156
163
  account's edge (the teammate shares with --relay); end-to-end encrypted
157
164
 
158
165
  Options for watch:
@@ -161,7 +168,7 @@ Options for watch:
161
168
  --inspect <port> Loopback port of the inspector (default ${INSPECTOR_DEFAULT_PORT}, 0 picks a free one)
162
169
  --team For a teammate who shares with --team: registers the key of this machine with your
163
170
  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
171
+ --relay Turns on --team: when no direct connection comes about, go through the relay of your
165
172
  account's edge (the teammate shares with --relay); end-to-end encrypted
166
173
  --agent Let a coding agent on this machine read the exchanges your teammate allowed for
167
174
  agents (they share with --allow-agents) through hopwire mcp; never on without it.
@@ -173,6 +180,8 @@ Options for watch:
173
180
  Global options:
174
181
  --data-dir <path> Where identity, traffic log and the API token are stored (default $HOPWIRE_HOME or
175
182
  ~/.hopwire)
183
+ --profile <name> Use the login of this profile for this command only, not the current one (default
184
+ $HOPWIRE_PROFILE); identity, traffic log and inspector are the same for every profile
176
185
  -h, --help Show this help
177
186
  --version Show the version
178
187
  `;
@@ -188,7 +197,7 @@ export const MCP_TERMINAL_HINT = [
188
197
  'Press Ctrl+C to stop.',
189
198
  ].join('\n');
190
199
  /** Options every command takes, and the ones of each command. Anything else is a usage error. */
191
- const GLOBAL_OPTIONS = ['help', 'version', 'data-dir'];
200
+ const GLOBAL_OPTIONS = ['help', 'version', 'data-dir', 'profile'];
192
201
  const COMMAND_OPTIONS = {
193
202
  http: [
194
203
  'listen',
@@ -217,6 +226,8 @@ const COMMAND_OPTIONS = {
217
226
  watch: ['replay-target', 'inspect', 'team', 'relay', 'agent', 'log', 'force'],
218
227
  login: ['api', 'token', 'no-browser'],
219
228
  logout: [],
229
+ profiles: [],
230
+ use: [],
220
231
  mcp: ['read-only'],
221
232
  doctor: ['network'],
222
233
  };
@@ -254,6 +265,9 @@ export async function run(argv, io) {
254
265
  throw new UsageError('--data-dir needs the path of a directory');
255
266
  }
256
267
  const dataDir = resolveDataDir(values['data-dir'], io.env);
268
+ const profile = resolveProfile(values.profile, io.env);
269
+ // The login a command uses: the profile it names, else the current one of the data directory
270
+ const store = { dataDir, profile };
257
271
  if (command === 'id') {
258
272
  noMoreArguments(rest, 0, 'hopwire id');
259
273
  io.print((await loadOrCreateIdentity(dataDir)).publicKey.toString('hex'));
@@ -268,6 +282,7 @@ export async function run(argv, io) {
268
282
  noMoreArguments(rest, 0, 'hopwire doctor [--network]');
269
283
  await doctor({
270
284
  dataDir,
285
+ profile,
271
286
  cwd: io.cwd ?? process.cwd(),
272
287
  version: readVersion(),
273
288
  network: values.network ?? false,
@@ -283,9 +298,10 @@ export async function run(argv, io) {
283
298
  // The value is not repeated: it may be a token, which belongs neither in an error nor in shell history
284
299
  throw new UsageError('--token takes no value: hopwire login --token asks for the token without showing it, or set HOPWIRE_TOKEN');
285
300
  }
286
- noMoreArguments(rest, 0, 'hopwire login [--api <url>] [--token] [--no-browser]');
301
+ noMoreArguments(rest, 0, 'hopwire login [--api <url>] [--token] [--no-browser] [--profile <name>]');
287
302
  await login({
288
303
  dataDir,
304
+ profile,
289
305
  apiUrl: values.api === undefined ? null : parseApiUrl(values.api),
290
306
  token: io.env.HOPWIRE_TOKEN,
291
307
  paste: values.token ?? false,
@@ -298,8 +314,18 @@ export async function run(argv, io) {
298
314
  return null;
299
315
  }
300
316
  if (command === 'logout') {
301
- noMoreArguments(rest, 0, 'hopwire logout');
302
- await logout({ dataDir, print: io.print });
317
+ noMoreArguments(rest, 0, 'hopwire logout [--profile <name>]');
318
+ await logout({ dataDir, profile, print: io.print });
319
+ return null;
320
+ }
321
+ if (command === 'profiles') {
322
+ noMoreArguments(rest, 0, 'hopwire profiles');
323
+ await profiles({ dataDir, print: io.print });
324
+ return null;
325
+ }
326
+ if (command === 'use') {
327
+ noMoreArguments(rest, 1, 'hopwire use <profile>');
328
+ await use({ dataDir, name: parseProfile(rest[0] ?? '', 'hopwire use'), print: io.print });
303
329
  return null;
304
330
  }
305
331
  if (command === 'mcp') {
@@ -330,15 +356,15 @@ export async function run(argv, io) {
330
356
  const port = parsePort(values.port, '--port', 0);
331
357
  const service = parseService(values.service);
332
358
  const allowHosts = (values['allow-host'] ?? []).map(parseAllowedHost);
333
- relayNeedsTeam(values);
359
+ relayImpliesTeam(values);
334
360
  return startConnect({
335
361
  peerKey,
336
362
  port,
337
363
  service,
338
364
  allowHosts,
339
365
  // The account is only read for --team: without it private mode never looks at it
340
- team: values.team ? await teamAccess('--team', dataDir) : undefined,
341
- relay: values.relay ? await relayAccess('--relay', dataDir) : undefined,
366
+ team: values.team ? await teamAccess(values.relay ? '--relay' : '--team', store) : undefined,
367
+ relay: values.relay ? await relayAccess('--relay', store) : undefined,
342
368
  dataDir,
343
369
  print: io.print,
344
370
  bootstrap: parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP),
@@ -350,7 +376,7 @@ export async function run(argv, io) {
350
376
  const logKey = parseKey(rest[0], 'The log key');
351
377
  const replayTarget = values['replay-target'] === undefined ? null : parseReplayTarget(values['replay-target']);
352
378
  const inspectPort = parsePort(values.inspect ?? String(INSPECTOR_DEFAULT_PORT), '--inspect', 0);
353
- relayNeedsTeam(values);
379
+ relayImpliesTeam(values);
354
380
  if (values.log !== undefined && replayTarget === null) {
355
381
  throw new UsageError('--log of hopwire watch only works together with --replay-target: it shows the entries of your replays');
356
382
  }
@@ -362,10 +388,11 @@ export async function run(argv, io) {
362
388
  replayTarget,
363
389
  inspectPort,
364
390
  // The account is only read for --team: without it private mode never looks at it
365
- team: values.team ? await teamAccess('--team', dataDir) : undefined,
366
- relay: values.relay ? await relayAccess('--relay', dataDir) : undefined,
391
+ team: values.team ? await teamAccess(values.relay ? '--relay' : '--team', store) : undefined,
392
+ relay: values.relay ? await relayAccess('--relay', store) : undefined,
367
393
  dataDir,
368
394
  print: io.print,
395
+ exchange: io.exchange,
369
396
  bootstrap: parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP),
370
397
  agent: values.agent ?? false,
371
398
  signal: io.signal,
@@ -387,14 +414,15 @@ export async function run(argv, io) {
387
414
  configFile: file,
388
415
  dataDir,
389
416
  print: io.print,
417
+ exchange: io.exchange,
390
418
  // Token and account are only read when a service is public: private mode never looks at them
391
419
  ...(config.services.some((service) => service.public)
392
- ? update.watch(await publicAccess(shown, config, io.env, dataDir))
420
+ ? update.watch(await publicAccess(shown, config, io.env, store))
393
421
  : {}),
394
422
  // The account is only read for p2p.team: without it private mode never looks at it
395
- team: config.team ? await teamAccessOfFile(shown, config, dataDir) : undefined,
423
+ team: config.team ? await teamAccessOfFile(shown, config, store) : undefined,
396
424
  // The edge is only contacted for p2p.relay, and then only through the relay
397
- relay: config.relay ? await relayAccess('p2p.relay', dataDir) : undefined,
425
+ relay: config.relay ? await relayAccess('p2p.relay', store) : undefined,
398
426
  bootstrap: config.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
399
427
  agent: agent ?? config.agent ?? undefined,
400
428
  signal: io.signal,
@@ -411,6 +439,13 @@ export async function run(argv, io) {
411
439
  if (allow.length > 0 && !values.share) {
412
440
  throw new UsageError('--allow only works together with --share');
413
441
  }
442
+ if (values.relay && !values.share) {
443
+ throw new UsageError('--relay only works together with --share');
444
+ }
445
+ if (values.relay && allow.length > 0) {
446
+ throw new UsageError('--relay and --allow cannot be combined: the relay of the edge (Team plan) only pairs machines of one organisation, so --relay shares with your team');
447
+ }
448
+ relayImpliesTeam(values);
414
449
  if (values.team && !values.share) {
415
450
  throw new UsageError('--team only works together with --share');
416
451
  }
@@ -427,7 +462,6 @@ export async function run(argv, io) {
427
462
  throw new UsageError('--log-request-id only works together with --log <path>');
428
463
  }
429
464
  const logs = parseLogs(values.log, io.cwd ?? process.cwd());
430
- relayNeedsTeam(values);
431
465
  if (values.team && allow.length > 0) {
432
466
  throw new UsageError('--team and --allow cannot be combined: with --team the team is the list');
433
467
  }
@@ -450,15 +484,16 @@ export async function run(argv, io) {
450
484
  dataDir,
451
485
  serviceName: values.name ?? 'default',
452
486
  print: io.print,
487
+ exchange: io.exchange,
453
488
  share: values.share ?? false,
454
489
  allowAgents: values['allow-agents'] ?? false,
455
490
  allow,
456
491
  // The account is only read for --team: without it private mode never looks at it
457
- team: values.team ? await teamAccess('--team', dataDir) : undefined,
458
- relay: values.relay ? await relayAccess('--relay', dataDir) : undefined,
492
+ team: values.team ? await teamAccess(values.relay ? '--relay' : '--team', store) : undefined,
493
+ relay: values.relay ? await relayAccess('--relay', store) : undefined,
459
494
  bootstrap: values.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
460
495
  // Edge URL, token and account are only read for --public: private mode never looks at them
461
- public: values.public ? update.watch(await parsePublic(values.subdomain, io.env, dataDir)) : undefined,
496
+ public: values.public ? update.watch(await parsePublic(values.subdomain, io.env, store)) : undefined,
462
497
  agent: agentChoice(values),
463
498
  captureWebSocket: !(values['no-ws-capture'] ?? false),
464
499
  logs,
@@ -493,6 +528,23 @@ function parseLogs(values, cwd) {
493
528
  }
494
529
  return logs;
495
530
  }
531
+ /**
532
+ * The profile a command names: --profile, else HOPWIRE_PROFILE; null leaves it to the current profile of the data
533
+ * directory. A variable that is set but empty counts as not set.
534
+ */
535
+ function resolveProfile(option, env) {
536
+ if (option !== undefined) {
537
+ return parseProfile(option, '--profile');
538
+ }
539
+ const fromEnv = env.HOPWIRE_PROFILE === '' ? undefined : env.HOPWIRE_PROFILE;
540
+ return fromEnv === undefined ? null : parseProfile(fromEnv, 'HOPWIRE_PROFILE');
541
+ }
542
+ function parseProfile(value, label) {
543
+ if (!isProfileName(value)) {
544
+ throw new UsageError(`${label} needs a profile name: a letter or digit, then up to 31 letters, digits, - or _ (for example acme)`);
545
+ }
546
+ return value;
547
+ }
496
548
  /** The data directory: --data-dir, else HOPWIRE_HOME, else ~/.hopwire. */
497
549
  function resolveDataDir(option, env) {
498
550
  // A variable that is set but empty counts as not set; as a path it would be the working directory
@@ -512,7 +564,7 @@ function commandOf(argv) {
512
564
  if (argument === '--') {
513
565
  return argv[index + 1];
514
566
  }
515
- if (argument === '--data-dir') {
567
+ if (argument === '--data-dir' || argument === '--profile') {
516
568
  index++;
517
569
  }
518
570
  else if (!argument.startsWith('-')) {
@@ -532,6 +584,7 @@ async function runInit(argv, io) {
532
584
  help: { type: 'boolean', short: 'h' },
533
585
  version: { type: 'boolean' },
534
586
  'data-dir': { type: 'string' },
587
+ profile: { type: 'string' },
535
588
  config: { type: 'string' },
536
589
  yes: { type: 'boolean' },
537
590
  service: { type: 'string', multiple: true },
@@ -591,6 +644,7 @@ async function runInit(argv, io) {
591
644
  named: values.config !== undefined,
592
645
  cwd,
593
646
  dataDir: resolveDataDir(values['data-dir'], io.env),
647
+ profile: resolveProfile(values.profile, io.env),
594
648
  flags,
595
649
  ask: promptLine === undefined ? undefined : (question) => promptLine(question, io.signal),
596
650
  say: (line) => (io.notice ?? io.print)(line),
@@ -619,6 +673,7 @@ function parse(argv) {
619
673
  force: { type: 'boolean' },
620
674
  name: { type: 'string' },
621
675
  'data-dir': { type: 'string' },
676
+ profile: { type: 'string' },
622
677
  public: { type: 'boolean' },
623
678
  subdomain: { type: 'string' },
624
679
  share: { type: 'boolean' },
@@ -715,13 +770,13 @@ function parseApiUrl(value) {
715
770
  * connect token for the subdomain, and the edge the account is bound to (the one its control plane names), unless
716
771
  * HOPWIRE_EDGE_URL names it. `hopwire up` reads the edge from edge.url in hopwire.yaml instead.
717
772
  */
718
- async function parsePublic(subdomain, env, dataDir) {
773
+ async function parsePublic(subdomain, env, store) {
719
774
  if (subdomain !== undefined && !isReservableSubdomain(subdomain)) {
720
775
  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');
721
776
  }
722
777
  const edge = env.HOPWIRE_EDGE_URL;
723
778
  if ((edge === undefined || edge.trim() === '') && (env.HOPWIRE_DEV_TOKEN ?? '').trim() === '') {
724
- return publicThroughAccountEdge(subdomain, dataDir);
779
+ return publicThroughAccountEdge(subdomain, store);
725
780
  }
726
781
  if (edge === undefined || edge.trim() === '') {
727
782
  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.');
@@ -742,11 +797,11 @@ async function parsePublic(subdomain, env, dataDir) {
742
797
  subdomain: subdomain ?? randomSubdomain(randomBytes(RANDOM_SUBDOMAIN_BYTES)),
743
798
  };
744
799
  }
745
- const account = await readAccount(dataDir);
800
+ const account = await readAccount(store);
746
801
  if (account === null) {
747
802
  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.');
748
803
  }
749
- 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.`));
804
+ const connectTokens = await tokensForEdge(store, 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.`));
750
805
  // Without --subdomain the control plane names the fixed URL of the organisation
751
806
  return { edgeUrl, connectTokens, subdomain: subdomain ?? null };
752
807
  }
@@ -754,20 +809,20 @@ async function parsePublic(subdomain, env, dataDir) {
754
809
  * --public without HOPWIRE_EDGE_URL: the account of `hopwire login` and the edge it is bound to. An account logged in
755
810
  * before logins stored the edge asks its control plane once and is bound to the edge it names.
756
811
  */
757
- async function publicThroughAccountEdge(subdomain, dataDir) {
758
- const account = await readAccount(dataDir);
812
+ async function publicThroughAccountEdge(subdomain, store) {
813
+ const account = await readAccount(store);
759
814
  if (account === null) {
760
815
  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.');
761
816
  }
762
817
  const { createControlPlaneClient } = await import('./control-plane-client.js');
763
818
  const connectTokens = createControlPlaneClient({ url: account.controlPlaneUrl, apiToken: account.apiToken });
764
- let edgeUrl = await boundEdge(dataDir);
819
+ let edgeUrl = await boundEdge(store);
765
820
  if (edgeUrl === null) {
766
821
  edgeUrl = (await connectTokens.me()).edgeUrl;
767
822
  if (edgeUrl === null) {
768
823
  throw new HopwireError(`--public needs the URL of the edge: the control plane at ${account.controlPlaneUrl.origin} names none; set HOPWIRE_EDGE_URL.`);
769
824
  }
770
- edgeUrl = await bindEdge(dataDir, edgeUrl);
825
+ edgeUrl = await bindEdge(store, edgeUrl);
771
826
  }
772
827
  return { edgeUrl, connectTokens, subdomain: subdomain ?? null };
773
828
  }
@@ -776,7 +831,7 @@ async function publicThroughAccountEdge(subdomain, dataDir) {
776
831
  * `hopwire login`, which has to be one at that control plane; without it the dev token of the edge from
777
832
  * HOPWIRE_DEV_TOKEN.
778
833
  */
779
- async function publicAccess(file, config, env, dataDir) {
834
+ async function publicAccess(file, config, env, store) {
780
835
  if (config.controlPlaneUrl === null) {
781
836
  const token = env.HOPWIRE_DEV_TOKEN;
782
837
  if (token === undefined || token.trim() === '') {
@@ -785,7 +840,7 @@ async function publicAccess(file, config, env, dataDir) {
785
840
  return { token: token.trim() };
786
841
  }
787
842
  const wanted = config.controlPlaneUrl.origin;
788
- const account = await readAccount(dataDir);
843
+ const account = await readAccount(store);
789
844
  if (account === null) {
790
845
  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.`);
791
846
  }
@@ -797,7 +852,7 @@ async function publicAccess(file, config, env, dataDir) {
797
852
  // The file names the edge, but the account decides where its connect tokens go (see tokensForEdge)
798
853
  const named = config.edgeUrl;
799
854
  return {
800
- 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.`)),
855
+ connectTokens: await tokensForEdge(store, 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.`)),
801
856
  };
802
857
  }
803
858
  return { connectTokens: await connectTokenSource(account) };
@@ -812,8 +867,8 @@ async function publicAccess(file, config, env, dataDir) {
812
867
  * into this machine's services, to the edge that repository's file names. The question is part of fetching the
813
868
  * first token, so a start that is stopped gives it up like any request to the control plane.
814
869
  */
815
- async function tokensForEdge(dataDir, account, named, mismatch) {
816
- const bound = await boundEdge(dataDir);
870
+ async function tokensForEdge(store, account, named, mismatch) {
871
+ const bound = await boundEdge(store);
817
872
  if (bound !== null && bound.origin !== named.origin) {
818
873
  throw mismatch(bound);
819
874
  }
@@ -827,7 +882,7 @@ async function tokensForEdge(dataDir, account, named, mismatch) {
827
882
  async connectToken(subdomain, signal) {
828
883
  binding ??= (async () => {
829
884
  const ofControlPlane = (await client.me(signal)).edgeUrl;
830
- const now = await bindEdge(dataDir, ofControlPlane ?? named);
885
+ const now = await bindEdge(store, ofControlPlane ?? named);
831
886
  if (now.origin !== named.origin) {
832
887
  throw mismatch(now);
833
888
  }
@@ -850,22 +905,25 @@ async function tokensForEdge(dataDir, account, named, mismatch) {
850
905
  * What --team needs: the account of `hopwire login`, whose control plane names the keys of the team. Loaded only
851
906
  * for --team (or p2p.team), the one case in which private mode asks a server anything.
852
907
  */
853
- async function teamAccess(option, dataDir) {
854
- return accountClient(option, dataDir);
908
+ async function teamAccess(option, store) {
909
+ return accountClient(option, store);
855
910
  }
856
911
  /** The control plane of the stored account, for --team and --relay. */
857
- async function accountClient(option, dataDir) {
858
- const account = await readAccount(dataDir);
912
+ async function accountClient(option, store) {
913
+ const account = await readAccount(store);
859
914
  if (account === null) {
860
915
  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.`);
861
916
  }
862
917
  const { createControlPlaneClient } = await import('./control-plane-client.js');
863
918
  return createControlPlaneClient({ url: account.controlPlaneUrl, apiToken: account.apiToken });
864
919
  }
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');
920
+ /**
921
+ * --relay pairs machines of one organisation only, so it turns on --team: giving --team as well is not needed.
922
+ * Called before anything reads values.team.
923
+ */
924
+ function relayImpliesTeam(values) {
925
+ if (values.relay) {
926
+ values.team = true;
869
927
  }
870
928
  }
871
929
  /**
@@ -873,21 +931,21 @@ function relayNeedsTeam(values) {
873
931
  * control plane, which issues the relay tokens. Loaded only for --relay, the one case in which private mode contacts
874
932
  * the edge, and then only when no direct connection comes about.
875
933
  */
876
- async function relayAccess(option, dataDir) {
877
- const client = await accountClient(option, dataDir);
878
- let edgeUrl = await boundEdge(dataDir);
934
+ async function relayAccess(option, store) {
935
+ const client = await accountClient(option, store);
936
+ let edgeUrl = await boundEdge(store);
879
937
  if (edgeUrl === null) {
880
938
  const named = (await client.me()).edgeUrl;
881
939
  if (named === null) {
882
940
  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
941
  }
884
- edgeUrl = await bindEdge(dataDir, named);
942
+ edgeUrl = await bindEdge(store, named);
885
943
  }
886
944
  return { edgeUrl, tokens: client };
887
945
  }
888
946
  /** p2p.team of a hopwire.yaml: the account has to be one at the control plane the file names, when it names one. */
889
- async function teamAccessOfFile(file, config, dataDir) {
890
- const account = await readAccount(dataDir);
947
+ async function teamAccessOfFile(file, config, store) {
948
+ const account = await readAccount(store);
891
949
  if (account === null) {
892
950
  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.');
893
951
  }
@@ -895,7 +953,7 @@ async function teamAccessOfFile(file, config, dataDir) {
895
953
  // The stored API token belongs to another control plane and is not sent to this one
896
954
  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.`);
897
955
  }
898
- return teamAccess('p2p.team', dataDir);
956
+ return teamAccess('p2p.team', store);
899
957
  }
900
958
  /** --allow-host: a host name or address as a Host header carries it, with or without a port; in lower case. */
901
959
  function parseAllowedHost(value) {
@@ -928,17 +986,6 @@ function parseBootstrap(value) {
928
986
  return { host: match[1], port };
929
987
  });
930
988
  }
931
- /** The version of the package this file ships in; package.json lies next to `src` and `dist` alike. */
932
- function readVersion() {
933
- const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
934
- if (typeof manifest === 'object' &&
935
- manifest !== null &&
936
- 'version' in manifest &&
937
- typeof manifest.version === 'string') {
938
- return manifest.version;
939
- }
940
- throw new Error('package.json carries no version');
941
- }
942
989
  function parsePort(value, label, min) {
943
990
  const port = Number(value);
944
991
  if (value === undefined || value === '' || !Number.isInteger(port) || port < min || port > 65535) {
@@ -2,7 +2,7 @@ import { access, stat } from 'node:fs/promises';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { HOPWIRE_YAML_FILE } from '@hopwire/protocol';
5
- import { accountFile, boundEdge, readAccount } from '../account.js';
5
+ import { DEFAULT_PROFILE, accountFile, boundEdge, listProfiles, profileName, readAccount, } from '../account.js';
6
6
  import { loadConfig } from '../config.js';
7
7
  import { errorCode } from '../errors.js';
8
8
  import { describeProxy, proxyFor } from '../outbound-proxy.js';
@@ -19,20 +19,21 @@ import { printable } from '../output.js';
19
19
  */
20
20
  export async function doctor(options) {
21
21
  const { print, dataDir } = options;
22
+ const store = { dataDir, profile: options.profile ?? null };
22
23
  print(`Hopwire ${options.version}`);
23
24
  print(`Node.js ${process.version}`);
24
25
  print(`System ${process.platform} ${process.arch} (${os.release()})`);
25
26
  print(`Data dir ${printable(dataDir)} (${await entry(dataDir, 0o700)})`);
26
27
  print(`Identity ${await entry(path.join(dataDir, 'identity.json'), 0o600, 'none yet; the first tunnel or hopwire id creates it')}`);
27
28
  print(`Traffic log ${await entry(path.join(dataDir, 'store'), 0o700, 'none yet; the first tunnel creates it')}`);
28
- print(`Account ${await account(dataDir)}`);
29
+ print(`Account ${await account(store)}`);
29
30
  print(`Config ${await config(options.cwd)}`);
30
31
  print(`Proxy ${proxy(options.env ?? process.env)}`);
31
32
  print(`Network ${options.network ? await network(options) : NOT_CHECKED}`);
32
- const edge = options.network ? await relayEdge(dataDir) : null;
33
+ const edge = options.network ? await relayEdge(store) : null;
33
34
  print(`Relay ${options.network ? await relay(edge) : RELAY_NOT_CHECKED}`);
34
35
  // Only with --network: the list comes from the control plane, and without it nothing leaves the machine
35
- const domains = options.network ? await customDomains(dataDir, options.signal) : null;
36
+ const domains = options.network ? await customDomains(store, options.signal) : null;
36
37
  for (const line of domains ?? []) {
37
38
  print(line);
38
39
  }
@@ -81,15 +82,19 @@ async function entry(file, expected, missing = 'missing') {
81
82
  : `present, mode ${shown}: others on this machine can get at it; it should be ${expected.toString(8).padStart(4, '0')}`;
82
83
  }
83
84
  /** Where the machine is logged in. The API token is never part of the answer. */
84
- async function account(dataDir) {
85
+ async function account(store) {
85
86
  try {
86
- const stored = await readAccount(dataDir);
87
+ const stored = await readAccount(store);
88
+ // The profile is named once there is a choice: another name than default, or more than one
89
+ const count = (await listProfiles(store.dataDir)).length;
90
+ const name = await profileName(store);
91
+ const profile = count > 1 || name !== DEFAULT_PROFILE ? `, profile ${name} (${count} on this machine)` : '';
87
92
  if (stored === null) {
88
- return 'not logged in (only public mode needs an account)';
93
+ return `not logged in${profile} (only public mode needs an account)`;
89
94
  }
90
- const edge = await boundEdge(dataDir);
91
- const file = await entry(accountFile(dataDir), 0o600);
92
- return printable(`logged in at ${stored.controlPlaneUrl.origin}, edge ${edge === null ? 'not bound yet' : edge.origin}; config.json ${file}`);
95
+ const edge = await boundEdge(store);
96
+ const file = await entry(accountFile(store.dataDir), 0o600);
97
+ return printable(`logged in at ${stored.controlPlaneUrl.origin}${profile}, edge ${edge === null ? 'not bound yet' : edge.origin}; config.json ${file}`);
93
98
  }
94
99
  catch (error) {
95
100
  return `config.json cannot be used: ${message(error)}`;
@@ -131,9 +136,9 @@ async function network(options) {
131
136
  return 'direct P2P will often fail from here: this network picks a new outside port for every destination (a symmetric NAT). It still works when the teammate is on a network that keeps its port; two networks of this kind cannot connect directly. On the Team plan --team --relay goes through the relay of the edge then; public mode works from here';
132
137
  }
133
138
  /** The edge whose relay is checked: the one the logged-in account is bound to; null when there is none. */
134
- async function relayEdge(dataDir) {
139
+ async function relayEdge(store) {
135
140
  try {
136
- return (await readAccount(dataDir)) === null ? null : await boundEdge(dataDir);
141
+ return (await readAccount(store)) === null ? null : await boundEdge(store);
137
142
  }
138
143
  catch {
139
144
  return null;
@@ -163,9 +168,9 @@ const DOMAIN_STATUS_WORDS = {
163
168
  * The custom domains of the account, one line each, from GET /api/v1/me; null when this machine is not logged in (nothing was asked), nothing when
164
169
  * the account has none or the control plane cannot be asked right now (the report is not about that).
165
170
  */
166
- async function customDomains(dataDir, signal) {
171
+ async function customDomains(store, signal) {
167
172
  try {
168
- const stored = await readAccount(dataDir);
173
+ const stored = await readAccount(store);
169
174
  if (stored === null) {
170
175
  return null;
171
176
  }
@@ -1,4 +1,4 @@
1
- import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, relayLine, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, AGENTS_ALLOWED_LINE, agentLine, agentOffLine, formatExchange, formatLimitReached, formatLogNotice, logLines, formatMeteredUsage, formatRelayEvent, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, mainPublicUrl, publicUrlText, } from '../output.js';
1
+ import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, relayLine, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, AGENTS_ALLOWED_LINE, agentLine, agentOffLine, exchangeSink, formatPeerEvent, formatLimitReached, formatLogNotice, logLines, formatMeteredUsage, formatRelayEvent, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, mainPublicUrl, publicUrlText, } from '../output.js';
2
2
  import { startServing } from '../serve.js';
3
3
  export { INSPECTOR_FILES } from '../serve.js';
4
4
  /**
@@ -35,6 +35,7 @@ export async function startHttpTunnel(options) {
35
35
  onTeamEvent: (event, organisation) => options.print(formatTeamEvent(event, organisation)),
36
36
  relay: options.relay,
37
37
  onRelayEvent: (event) => options.print(formatRelayEvent(event)),
38
+ onPeerEvent: (event) => options.print(formatPeerEvent(event)),
38
39
  bootstrap: options.bootstrap,
39
40
  inspectorFiles: options.inspectorFiles,
40
41
  agent: options.agent,
@@ -42,7 +43,7 @@ export async function startHttpTunnel(options) {
42
43
  signal: options.signal,
43
44
  listenOption: '--listen <port>',
44
45
  inspectOption: '--inspect <port> or run with --no-inspect',
45
- onExchange: (exchange) => options.print(formatExchange(exchange)),
46
+ onExchange: (exchange) => exchangeSink(options.print, options.exchange)(exchange),
46
47
  onLogError: () => options.print('Could not write to the traffic log; the request was still forwarded'),
47
48
  onBridgeEvent: (_service, event) => options.print(formatBridgeEvent(event)),
48
49
  });