hopwire 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/account.js CHANGED
@@ -17,19 +17,86 @@ export function isApiToken(value) {
17
17
  export function accountFile(dataDir) {
18
18
  return path.join(dataDir, ACCOUNT_FILE);
19
19
  }
20
+ /** The profile a machine has before anyone names one, and the one an older config.json is read as. */
21
+ export const DEFAULT_PROFILE = 'default';
22
+ /** A profile name: a letter or digit, then up to 31 letters, digits, - or _. */
23
+ const PROFILE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/;
24
+ export function isProfileName(value) {
25
+ return PROFILE_PATTERN.test(value);
26
+ }
27
+ function dataDirOf(ref) {
28
+ return typeof ref === 'string' ? ref : ref.dataDir;
29
+ }
30
+ function namedProfile(ref) {
31
+ return typeof ref === 'string' ? null : ref.profile;
32
+ }
33
+ /** The profile a command uses: the named one, else the current one of the file, else `default`. */
34
+ function profileOf(ref, file) {
35
+ return namedProfile(ref) ?? file?.currentProfile ?? DEFAULT_PROFILE;
36
+ }
37
+ /**
38
+ * The login of the profile; null when there is none. A profile that is named but not on this machine is refused
39
+ * with what to do, so a typo is not taken for a missing login.
40
+ */
41
+ async function readProfile(ref) {
42
+ const file = await readStored(dataDirOf(ref));
43
+ const name = profileOf(ref, file);
44
+ const stored = file?.profiles.get(name) ?? null;
45
+ if (stored === null && namedProfile(ref) !== null && (file?.profiles.size ?? 0) > 0) {
46
+ throw new HopwireError(`There is no profile "${name}" on this machine; run hopwire login --profile ${name} to create it, or hopwire profiles to list the ones there are.`);
47
+ }
48
+ return { name, stored };
49
+ }
20
50
  /** The stored account, null when nobody is logged in. A file that is not what `hopwire login` wrote is refused. */
21
- export async function readAccount(dataDir) {
22
- const stored = await readStored(dataDir);
51
+ export async function readAccount(ref) {
52
+ const { stored } = await readProfile(ref);
23
53
  return stored === null || stored.apiToken === null
24
54
  ? null
25
55
  : { apiToken: stored.apiToken, controlPlaneUrl: stored.controlPlaneUrl };
26
56
  }
27
57
  /**
28
- * The control plane of the last login, also after a logout; null when this machine was never logged in. A file that
29
- * is not what `hopwire login` wrote is refused.
58
+ * The control plane of the last login of the profile, also after a logout. A profile that has none yet takes the
59
+ * one of the current profile, so a second organisation at the same control plane needs no --api. Null when this
60
+ * machine was never logged in. A file that is not what `hopwire login` wrote is refused.
30
61
  */
31
- export async function readControlPlaneUrl(dataDir) {
32
- return (await readStored(dataDir))?.controlPlaneUrl ?? null;
62
+ export async function readControlPlaneUrl(ref) {
63
+ const file = await readStored(dataDirOf(ref));
64
+ if (file === null) {
65
+ return null;
66
+ }
67
+ const stored = file.profiles.get(profileOf(ref, file)) ?? file.profiles.get(file.currentProfile);
68
+ return stored?.controlPlaneUrl ?? null;
69
+ }
70
+ /** The name of the profile a command with this ref uses; no profile has to exist for it. */
71
+ export async function profileName(ref) {
72
+ return profileOf(ref, await readStored(dataDirOf(ref)));
73
+ }
74
+ /** Every profile of the data directory, in the order of their names; empty before the first login. */
75
+ export async function listProfiles(dataDir) {
76
+ const file = await readStored(dataDir);
77
+ if (file === null) {
78
+ return [];
79
+ }
80
+ return [...file.profiles.entries()]
81
+ .sort(([a], [b]) => a.localeCompare(b))
82
+ .map(([name, stored]) => ({
83
+ name,
84
+ current: name === file.currentProfile,
85
+ loggedIn: stored.apiToken !== null,
86
+ controlPlaneUrl: stored.controlPlaneUrl,
87
+ edgeUrl: stored.edgeUrl,
88
+ organisation: stored.organisation,
89
+ plan: stored.plan,
90
+ }));
91
+ }
92
+ /** Makes a profile the current one. Nothing is contacted. Resolves with false when there is no such profile. */
93
+ export async function useProfile(dataDir, name) {
94
+ const file = await readStored(dataDir);
95
+ if (file === null || !file.profiles.has(name)) {
96
+ return false;
97
+ }
98
+ await writeStored(dataDir, { ...file, currentProfile: name });
99
+ return true;
33
100
  }
34
101
  async function readStored(dataDir) {
35
102
  const file = accountFile(dataDir);
@@ -52,15 +119,36 @@ async function readStored(dataDir) {
52
119
  return stored;
53
120
  }
54
121
  /**
55
- * Stores the account, replacing an earlier one. The file is complete and owner-only from the moment it exists. A new
56
- * login binds the account to the edge its control plane names; without one, the next public start binds it.
122
+ * Stores the account in the profile, replacing an earlier login of that profile, and makes the profile the current
123
+ * one. Other profiles stay as they are. The file is complete and owner-only from the moment it exists. A new login
124
+ * binds the account to the edge its control plane names; without one, the next public start binds it.
57
125
  */
58
- export async function writeAccount(dataDir, account, edgeUrl = null) {
59
- await writeStored(dataDir, { ...account, edgeUrl: edgeUrl === null ? null : new URL(edgeUrl.origin) });
126
+ export async function writeAccount(ref, account, edgeUrl = null, details = { organisation: null, plan: null }) {
127
+ const dataDir = dataDirOf(ref);
128
+ let file;
129
+ try {
130
+ file = await readStored(dataDir);
131
+ }
132
+ catch (error) {
133
+ // A damaged file is replaced, as before profiles: the login is what repairs it
134
+ if (!(error instanceof HopwireError)) {
135
+ throw error;
136
+ }
137
+ file = null;
138
+ }
139
+ const name = profileOf(ref, file);
140
+ const profiles = new Map(file?.profiles ?? []);
141
+ profiles.set(name, {
142
+ ...account,
143
+ edgeUrl: edgeUrl === null ? null : new URL(edgeUrl.origin),
144
+ organisation: details.organisation,
145
+ plan: details.plan,
146
+ });
147
+ await writeStored(dataDir, { currentProfile: name, profiles });
60
148
  }
61
149
  /** The edge the logged-in account is bound to; null when nobody is logged in or no edge is bound yet. */
62
- export async function boundEdge(dataDir) {
63
- const stored = await readStored(dataDir);
150
+ export async function boundEdge(ref) {
151
+ const { stored } = await readProfile(ref);
64
152
  return stored === null || stored.apiToken === null ? null : stored.edgeUrl;
65
153
  }
66
154
  /**
@@ -68,28 +156,40 @@ export async function boundEdge(dataDir) {
68
156
  * stores the origin of its edge; every later one gets that origin back and has to use the same edge, so a project
69
157
  * file or an environment cannot send the account's tokens (and a channel into this machine's services) to an edge
70
158
  * of its choosing. The caller of a first start passes the edge the control plane of the account names when it names
71
- * one (cli.ts, accountEdge). Resolves with the bound edge. A new `hopwire login` clears the binding.
159
+ * one (cli.ts, accountEdge). Resolves with the bound edge. A new `hopwire login` clears the binding. Each profile has
160
+ * its own binding.
72
161
  */
73
- export async function bindEdge(dataDir, edgeUrl) {
74
- const stored = await readStored(dataDir);
75
- if (stored === null || stored.apiToken === null) {
162
+ export async function bindEdge(ref, edgeUrl) {
163
+ const dataDir = dataDirOf(ref);
164
+ const file = await readStored(dataDir);
165
+ const name = profileOf(ref, file);
166
+ const stored = file?.profiles.get(name) ?? null;
167
+ if (file === null || stored === null || stored.apiToken === null) {
76
168
  throw new HopwireError('This machine is not logged in; run hopwire login first.');
77
169
  }
78
170
  if (stored.edgeUrl !== null) {
79
171
  return stored.edgeUrl;
80
172
  }
81
- await writeStored(dataDir, { ...stored, edgeUrl: new URL(edgeUrl.origin) });
173
+ const profiles = new Map(file.profiles);
174
+ profiles.set(name, { ...stored, edgeUrl: new URL(edgeUrl.origin) });
175
+ await writeStored(dataDir, { ...file, profiles });
82
176
  return edgeUrl;
83
177
  }
84
178
  async function writeStored(dataDir, stored) {
85
179
  // A data directory that has to be created holds key material and traffic: owner only
86
180
  await mkdir(dataDir, { recursive: true, mode: 0o700 });
87
181
  const file = accountFile(dataDir);
88
- const content = JSON.stringify({
89
- ...(stored.apiToken === null ? {} : { apiToken: stored.apiToken }),
90
- controlPlaneUrl: stored.controlPlaneUrl.origin,
91
- ...(stored.edgeUrl === null ? {} : { edgeUrl: stored.edgeUrl.origin }),
92
- }, null, 4);
182
+ const profiles = {};
183
+ for (const [name, profile] of [...stored.profiles.entries()].sort(([a], [b]) => a.localeCompare(b))) {
184
+ profiles[name] = {
185
+ ...(profile.apiToken === null ? {} : { apiToken: profile.apiToken }),
186
+ controlPlaneUrl: profile.controlPlaneUrl.origin,
187
+ ...(profile.edgeUrl === null ? {} : { edgeUrl: profile.edgeUrl.origin }),
188
+ ...(profile.organisation === null ? {} : { organisation: profile.organisation }),
189
+ ...(profile.plan === null ? {} : { plan: profile.plan }),
190
+ };
191
+ }
192
+ const content = JSON.stringify({ currentProfile: stored.currentProfile, profiles }, null, 4);
93
193
  const draft = `${file}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
94
194
  await writeFile(draft, `${content}\n`, { mode: 0o600, flag: 'wx' });
95
195
  try {
@@ -101,13 +201,14 @@ async function writeStored(dataDir, stored) {
101
201
  }
102
202
  }
103
203
  /**
104
- * Removes the stored API token and keeps the URL of the control plane it belonged to. A damaged file is removed as
105
- * a whole. Resolves with false when no token was stored.
204
+ * Removes the stored API token of the profile and keeps the URL of the control plane it belonged to. A damaged file
205
+ * is removed as a whole. Resolves with false when no token was stored in the profile.
106
206
  */
107
- export async function removeAccount(dataDir) {
108
- let stored;
207
+ export async function removeAccount(ref) {
208
+ const dataDir = dataDirOf(ref);
209
+ let file;
109
210
  try {
110
- stored = await readStored(dataDir);
211
+ file = await readStored(dataDir);
111
212
  }
112
213
  catch (error) {
113
214
  if (!(error instanceof HopwireError)) {
@@ -121,13 +222,19 @@ export async function removeAccount(dataDir) {
121
222
  });
122
223
  return true;
123
224
  }
124
- if (stored === null || stored.apiToken === null) {
225
+ const name = profileOf(ref, file);
226
+ const stored = file?.profiles.get(name) ?? null;
227
+ if (file === null || stored === null || stored.apiToken === null) {
125
228
  return false;
126
229
  }
127
230
  // Written anew and renamed into place: the token is in no file any more once this resolves
128
- await writeStored(dataDir, { ...stored, apiToken: null });
231
+ const profiles = new Map(file.profiles);
232
+ profiles.set(name, { ...stored, apiToken: null });
233
+ await writeStored(dataDir, { ...file, profiles });
129
234
  return true;
130
235
  }
236
+ /** The longest organisation or plan name kept for listing; text of the control plane, cut rather than refused. */
237
+ const DETAIL_MAX = 200;
131
238
  function parse(text) {
132
239
  let value;
133
240
  try {
@@ -136,11 +243,37 @@ function parse(text) {
136
243
  catch {
137
244
  return null;
138
245
  }
139
- if (typeof value !== 'object' ||
140
- value === null ||
141
- Array.isArray(value) ||
142
- !('controlPlaneUrl' in value) ||
143
- typeof value.controlPlaneUrl !== 'string') {
246
+ if (!isObject(value)) {
247
+ return null;
248
+ }
249
+ // Written by a CLI before profiles: one login, read as the profile `default` and rewritten on the next write
250
+ if (!('profiles' in value)) {
251
+ const stored = parseProfile(value);
252
+ return stored === null
253
+ ? null
254
+ : { currentProfile: DEFAULT_PROFILE, profiles: new Map([[DEFAULT_PROFILE, stored]]) };
255
+ }
256
+ if (!isObject(value.profiles) ||
257
+ !('currentProfile' in value) ||
258
+ typeof value.currentProfile !== 'string' ||
259
+ !isProfileName(value.currentProfile)) {
260
+ return null;
261
+ }
262
+ const profiles = new Map();
263
+ for (const [name, entry] of Object.entries(value.profiles)) {
264
+ const stored = isProfileName(name) && isObject(entry) ? parseProfile(entry) : null;
265
+ if (stored === null) {
266
+ return null;
267
+ }
268
+ profiles.set(name, stored);
269
+ }
270
+ return { currentProfile: value.currentProfile, profiles };
271
+ }
272
+ function isObject(value) {
273
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
274
+ }
275
+ function parseProfile(value) {
276
+ if (typeof value.controlPlaneUrl !== 'string') {
144
277
  return null;
145
278
  }
146
279
  // Without a token: logged out. With one, it has to be a token
@@ -164,5 +297,17 @@ function parse(text) {
164
297
  }
165
298
  edgeUrl = parsed;
166
299
  }
167
- return { apiToken, controlPlaneUrl, edgeUrl };
300
+ const organisation = detail(value.organisation);
301
+ const plan = detail(value.plan);
302
+ if (organisation === undefined || plan === undefined) {
303
+ return null;
304
+ }
305
+ return { apiToken, controlPlaneUrl, edgeUrl, organisation, plan };
306
+ }
307
+ /** An optional text of the control plane; undefined when it is there but no text. */
308
+ function detail(value) {
309
+ if (value === undefined) {
310
+ return null;
311
+ }
312
+ return typeof value === 'string' ? value.slice(0, DETAIL_MAX) : undefined;
168
313
  }
@@ -7,10 +7,13 @@
7
7
  export const REDACTION_MARKER = '[redacted';
8
8
  /** Headers that are always redacted, besides the names that match SENSITIVE_NAME */
9
9
  const SENSITIVE_HEADERS = new Set(['authorization', 'proxy-authorization', 'cookie', 'set-cookie', 'x-api-key']);
10
- /** Names of headers that carry credentials or signatures */
11
- const SENSITIVE_NAME = /(token|secret|signature|password|passwd|session|api[-_]?key|auth)/i;
10
+ /**
11
+ * Names of headers that carry credentials or signatures. `hmac` covers Shopify's `X-Shopify-Hmac-SHA256`; `sig` as a
12
+ * word of its own covers PayPal's `PAYPAL-TRANSMISSION-SIG` (and not names such as `x-signal`).
13
+ */
14
+ const SENSITIVE_NAME = /(token|secret|signature|password|passwd|session|api[-_]?key|auth|hmac|(?:^|[-_])sig(?:[-_]|$))/i;
12
15
  /** Names of query parameters, form fields and JSON keys: the header names plus payment data */
13
- const SENSITIVE_FIELD = /(token|secret|signature|password|passwd|session|api[-_]?key|auth|card|cvc|cvv|iban)/i;
16
+ const SENSITIVE_FIELD = /(token|secret|signature|password|passwd|session|api[-_]?key|auth|hmac|(?:^|[-_])sig(?:[-_]|$)|card|cvc|cvv|iban)/i;
14
17
  /** What is shown instead of a value: its length, nothing of its content. */
15
18
  export function redacted(value) {
16
19
  return `${REDACTION_MARKER}, ${[...value].length} chars]`;
@@ -32,6 +35,10 @@ export function redactHeaders(headers) {
32
35
  return [name, value];
33
36
  }
34
37
  const lower = name.toLowerCase();
38
+ // the time of a signature in a header of its own (Discord's X-Signature-Timestamp): digits only, no secret
39
+ if (lower.endsWith('timestamp') && /^\d{1,13}$/.test(value)) {
40
+ return [name, value];
41
+ }
35
42
  if (lower === 'authorization' || lower === 'proxy-authorization') {
36
43
  const scheme = /^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*) +(.*)$/s.exec(value);
37
44
  if (scheme?.[1] !== undefined && scheme[2] !== undefined) {
@@ -47,12 +54,14 @@ export function redactHeaders(headers) {
47
54
  /** Names of the parts of a signature header that carry its time, shown when they are digits only */
48
55
  const SIGNATURE_TIME_PARTS = new Set(['t', 'ts', 'timestamp']);
49
56
  /**
50
- * A signature header of `name=value` parts separated by commas (Stripe's `t=…,v1=…`, GitHub's `sha256=…`) with every
51
- * value redacted but a timestamp, so an agent can tell whether a provider's tolerance has passed before it replays.
52
- * Null when the value has another form; the caller then redacts it as a whole.
57
+ * A signature header of `name=value` parts separated by commas or semicolons (Stripe's `t=…,v1=…`, GitHub's
58
+ * `sha256=…`, Paddle's `ts=…;h1=…`) with every value redacted but a timestamp, so an agent can tell whether a
59
+ * provider's tolerance has passed before it replays. Null when the value has another form; the caller then redacts it
60
+ * as a whole.
53
61
  */
54
62
  function redactSignature(value) {
55
- const parts = value.split(',');
63
+ const separator = value.includes(',') ? ',' : ';';
64
+ const parts = value.split(separator);
56
65
  const shown = [];
57
66
  for (const part of parts) {
58
67
  const match = /^(\s*)([A-Za-z0-9_-]{1,32})=(.*)$/s.exec(part);
@@ -63,7 +72,7 @@ function redactSignature(value) {
63
72
  const isTime = SIGNATURE_TIME_PARTS.has(key.toLowerCase()) && /^\d{1,13}$/.test(inner);
64
73
  shown.push(`${space}${key}=${isTime ? inner : redacted(inner)}`);
65
74
  }
66
- return shown.join(',');
75
+ return shown.join(separator);
67
76
  }
68
77
  /** A path with the values of sensitive query parameters redacted; the rest is kept as it was written. */
69
78
  export function redactPath(requestPath) {
package/dist/cli.js CHANGED
@@ -4,12 +4,12 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { parseArgs } from 'node:util';
6
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';
7
+ import { bindEdge, boundEdge, isProfileName, readAccount } from './account.js';
8
8
  import { startConnect } from './commands/connect.js';
9
9
  import { doctor } from './commands/doctor.js';
10
10
  import { init } from './commands/init.js';
11
11
  import { startHttpTunnel } from './commands/http.js';
12
- import { login, logout } from './commands/login.js';
12
+ import { login, logout, profiles, use } from './commands/login.js';
13
13
  import { startMcp } from './commands/mcp.js';
14
14
  import { rotate } from './commands/rotate.js';
15
15
  import { startUp } from './commands/up.js';
@@ -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,8 +388,8 @@ 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,
369
395
  bootstrap: parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP),
@@ -389,12 +415,12 @@ export async function run(argv, io) {
389
415
  print: io.print,
390
416
  // Token and account are only read when a service is public: private mode never looks at them
391
417
  ...(config.services.some((service) => service.public)
392
- ? update.watch(await publicAccess(shown, config, io.env, dataDir))
418
+ ? update.watch(await publicAccess(shown, config, io.env, store))
393
419
  : {}),
394
420
  // 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,
421
+ team: config.team ? await teamAccessOfFile(shown, config, store) : undefined,
396
422
  // The edge is only contacted for p2p.relay, and then only through the relay
397
- relay: config.relay ? await relayAccess('p2p.relay', dataDir) : undefined,
423
+ relay: config.relay ? await relayAccess('p2p.relay', store) : undefined,
398
424
  bootstrap: config.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
399
425
  agent: agent ?? config.agent ?? undefined,
400
426
  signal: io.signal,
@@ -411,6 +437,13 @@ export async function run(argv, io) {
411
437
  if (allow.length > 0 && !values.share) {
412
438
  throw new UsageError('--allow only works together with --share');
413
439
  }
440
+ if (values.relay && !values.share) {
441
+ throw new UsageError('--relay only works together with --share');
442
+ }
443
+ if (values.relay && allow.length > 0) {
444
+ 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');
445
+ }
446
+ relayImpliesTeam(values);
414
447
  if (values.team && !values.share) {
415
448
  throw new UsageError('--team only works together with --share');
416
449
  }
@@ -427,7 +460,6 @@ export async function run(argv, io) {
427
460
  throw new UsageError('--log-request-id only works together with --log <path>');
428
461
  }
429
462
  const logs = parseLogs(values.log, io.cwd ?? process.cwd());
430
- relayNeedsTeam(values);
431
463
  if (values.team && allow.length > 0) {
432
464
  throw new UsageError('--team and --allow cannot be combined: with --team the team is the list');
433
465
  }
@@ -454,11 +486,11 @@ export async function run(argv, io) {
454
486
  allowAgents: values['allow-agents'] ?? false,
455
487
  allow,
456
488
  // 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,
489
+ team: values.team ? await teamAccess(values.relay ? '--relay' : '--team', store) : undefined,
490
+ relay: values.relay ? await relayAccess('--relay', store) : undefined,
459
491
  bootstrap: values.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
460
492
  // 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,
493
+ public: values.public ? update.watch(await parsePublic(values.subdomain, io.env, store)) : undefined,
462
494
  agent: agentChoice(values),
463
495
  captureWebSocket: !(values['no-ws-capture'] ?? false),
464
496
  logs,
@@ -493,6 +525,23 @@ function parseLogs(values, cwd) {
493
525
  }
494
526
  return logs;
495
527
  }
528
+ /**
529
+ * The profile a command names: --profile, else HOPWIRE_PROFILE; null leaves it to the current profile of the data
530
+ * directory. A variable that is set but empty counts as not set.
531
+ */
532
+ function resolveProfile(option, env) {
533
+ if (option !== undefined) {
534
+ return parseProfile(option, '--profile');
535
+ }
536
+ const fromEnv = env.HOPWIRE_PROFILE === '' ? undefined : env.HOPWIRE_PROFILE;
537
+ return fromEnv === undefined ? null : parseProfile(fromEnv, 'HOPWIRE_PROFILE');
538
+ }
539
+ function parseProfile(value, label) {
540
+ if (!isProfileName(value)) {
541
+ throw new UsageError(`${label} needs a profile name: a letter or digit, then up to 31 letters, digits, - or _ (for example acme)`);
542
+ }
543
+ return value;
544
+ }
496
545
  /** The data directory: --data-dir, else HOPWIRE_HOME, else ~/.hopwire. */
497
546
  function resolveDataDir(option, env) {
498
547
  // A variable that is set but empty counts as not set; as a path it would be the working directory
@@ -512,7 +561,7 @@ function commandOf(argv) {
512
561
  if (argument === '--') {
513
562
  return argv[index + 1];
514
563
  }
515
- if (argument === '--data-dir') {
564
+ if (argument === '--data-dir' || argument === '--profile') {
516
565
  index++;
517
566
  }
518
567
  else if (!argument.startsWith('-')) {
@@ -532,6 +581,7 @@ async function runInit(argv, io) {
532
581
  help: { type: 'boolean', short: 'h' },
533
582
  version: { type: 'boolean' },
534
583
  'data-dir': { type: 'string' },
584
+ profile: { type: 'string' },
535
585
  config: { type: 'string' },
536
586
  yes: { type: 'boolean' },
537
587
  service: { type: 'string', multiple: true },
@@ -591,6 +641,7 @@ async function runInit(argv, io) {
591
641
  named: values.config !== undefined,
592
642
  cwd,
593
643
  dataDir: resolveDataDir(values['data-dir'], io.env),
644
+ profile: resolveProfile(values.profile, io.env),
594
645
  flags,
595
646
  ask: promptLine === undefined ? undefined : (question) => promptLine(question, io.signal),
596
647
  say: (line) => (io.notice ?? io.print)(line),
@@ -619,6 +670,7 @@ function parse(argv) {
619
670
  force: { type: 'boolean' },
620
671
  name: { type: 'string' },
621
672
  'data-dir': { type: 'string' },
673
+ profile: { type: 'string' },
622
674
  public: { type: 'boolean' },
623
675
  subdomain: { type: 'string' },
624
676
  share: { type: 'boolean' },
@@ -715,13 +767,13 @@ function parseApiUrl(value) {
715
767
  * connect token for the subdomain, and the edge the account is bound to (the one its control plane names), unless
716
768
  * HOPWIRE_EDGE_URL names it. `hopwire up` reads the edge from edge.url in hopwire.yaml instead.
717
769
  */
718
- async function parsePublic(subdomain, env, dataDir) {
770
+ async function parsePublic(subdomain, env, store) {
719
771
  if (subdomain !== undefined && !isReservableSubdomain(subdomain)) {
720
772
  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
773
  }
722
774
  const edge = env.HOPWIRE_EDGE_URL;
723
775
  if ((edge === undefined || edge.trim() === '') && (env.HOPWIRE_DEV_TOKEN ?? '').trim() === '') {
724
- return publicThroughAccountEdge(subdomain, dataDir);
776
+ return publicThroughAccountEdge(subdomain, store);
725
777
  }
726
778
  if (edge === undefined || edge.trim() === '') {
727
779
  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 +794,11 @@ async function parsePublic(subdomain, env, dataDir) {
742
794
  subdomain: subdomain ?? randomSubdomain(randomBytes(RANDOM_SUBDOMAIN_BYTES)),
743
795
  };
744
796
  }
745
- const account = await readAccount(dataDir);
797
+ const account = await readAccount(store);
746
798
  if (account === null) {
747
799
  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
800
  }
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.`));
801
+ 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
802
  // Without --subdomain the control plane names the fixed URL of the organisation
751
803
  return { edgeUrl, connectTokens, subdomain: subdomain ?? null };
752
804
  }
@@ -754,20 +806,20 @@ async function parsePublic(subdomain, env, dataDir) {
754
806
  * --public without HOPWIRE_EDGE_URL: the account of `hopwire login` and the edge it is bound to. An account logged in
755
807
  * before logins stored the edge asks its control plane once and is bound to the edge it names.
756
808
  */
757
- async function publicThroughAccountEdge(subdomain, dataDir) {
758
- const account = await readAccount(dataDir);
809
+ async function publicThroughAccountEdge(subdomain, store) {
810
+ const account = await readAccount(store);
759
811
  if (account === null) {
760
812
  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
813
  }
762
814
  const { createControlPlaneClient } = await import('./control-plane-client.js');
763
815
  const connectTokens = createControlPlaneClient({ url: account.controlPlaneUrl, apiToken: account.apiToken });
764
- let edgeUrl = await boundEdge(dataDir);
816
+ let edgeUrl = await boundEdge(store);
765
817
  if (edgeUrl === null) {
766
818
  edgeUrl = (await connectTokens.me()).edgeUrl;
767
819
  if (edgeUrl === null) {
768
820
  throw new HopwireError(`--public needs the URL of the edge: the control plane at ${account.controlPlaneUrl.origin} names none; set HOPWIRE_EDGE_URL.`);
769
821
  }
770
- edgeUrl = await bindEdge(dataDir, edgeUrl);
822
+ edgeUrl = await bindEdge(store, edgeUrl);
771
823
  }
772
824
  return { edgeUrl, connectTokens, subdomain: subdomain ?? null };
773
825
  }
@@ -776,7 +828,7 @@ async function publicThroughAccountEdge(subdomain, dataDir) {
776
828
  * `hopwire login`, which has to be one at that control plane; without it the dev token of the edge from
777
829
  * HOPWIRE_DEV_TOKEN.
778
830
  */
779
- async function publicAccess(file, config, env, dataDir) {
831
+ async function publicAccess(file, config, env, store) {
780
832
  if (config.controlPlaneUrl === null) {
781
833
  const token = env.HOPWIRE_DEV_TOKEN;
782
834
  if (token === undefined || token.trim() === '') {
@@ -785,7 +837,7 @@ async function publicAccess(file, config, env, dataDir) {
785
837
  return { token: token.trim() };
786
838
  }
787
839
  const wanted = config.controlPlaneUrl.origin;
788
- const account = await readAccount(dataDir);
840
+ const account = await readAccount(store);
789
841
  if (account === null) {
790
842
  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
843
  }
@@ -797,7 +849,7 @@ async function publicAccess(file, config, env, dataDir) {
797
849
  // The file names the edge, but the account decides where its connect tokens go (see tokensForEdge)
798
850
  const named = config.edgeUrl;
799
851
  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.`)),
852
+ 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
853
  };
802
854
  }
803
855
  return { connectTokens: await connectTokenSource(account) };
@@ -812,8 +864,8 @@ async function publicAccess(file, config, env, dataDir) {
812
864
  * into this machine's services, to the edge that repository's file names. The question is part of fetching the
813
865
  * first token, so a start that is stopped gives it up like any request to the control plane.
814
866
  */
815
- async function tokensForEdge(dataDir, account, named, mismatch) {
816
- const bound = await boundEdge(dataDir);
867
+ async function tokensForEdge(store, account, named, mismatch) {
868
+ const bound = await boundEdge(store);
817
869
  if (bound !== null && bound.origin !== named.origin) {
818
870
  throw mismatch(bound);
819
871
  }
@@ -827,7 +879,7 @@ async function tokensForEdge(dataDir, account, named, mismatch) {
827
879
  async connectToken(subdomain, signal) {
828
880
  binding ??= (async () => {
829
881
  const ofControlPlane = (await client.me(signal)).edgeUrl;
830
- const now = await bindEdge(dataDir, ofControlPlane ?? named);
882
+ const now = await bindEdge(store, ofControlPlane ?? named);
831
883
  if (now.origin !== named.origin) {
832
884
  throw mismatch(now);
833
885
  }
@@ -850,22 +902,25 @@ async function tokensForEdge(dataDir, account, named, mismatch) {
850
902
  * What --team needs: the account of `hopwire login`, whose control plane names the keys of the team. Loaded only
851
903
  * for --team (or p2p.team), the one case in which private mode asks a server anything.
852
904
  */
853
- async function teamAccess(option, dataDir) {
854
- return accountClient(option, dataDir);
905
+ async function teamAccess(option, store) {
906
+ return accountClient(option, store);
855
907
  }
856
908
  /** The control plane of the stored account, for --team and --relay. */
857
- async function accountClient(option, dataDir) {
858
- const account = await readAccount(dataDir);
909
+ async function accountClient(option, store) {
910
+ const account = await readAccount(store);
859
911
  if (account === null) {
860
912
  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
913
  }
862
914
  const { createControlPlaneClient } = await import('./control-plane-client.js');
863
915
  return createControlPlaneClient({ url: account.controlPlaneUrl, apiToken: account.apiToken });
864
916
  }
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');
917
+ /**
918
+ * --relay pairs machines of one organisation only, so it turns on --team: giving --team as well is not needed.
919
+ * Called before anything reads values.team.
920
+ */
921
+ function relayImpliesTeam(values) {
922
+ if (values.relay) {
923
+ values.team = true;
869
924
  }
870
925
  }
871
926
  /**
@@ -873,21 +928,21 @@ function relayNeedsTeam(values) {
873
928
  * control plane, which issues the relay tokens. Loaded only for --relay, the one case in which private mode contacts
874
929
  * the edge, and then only when no direct connection comes about.
875
930
  */
876
- async function relayAccess(option, dataDir) {
877
- const client = await accountClient(option, dataDir);
878
- let edgeUrl = await boundEdge(dataDir);
931
+ async function relayAccess(option, store) {
932
+ const client = await accountClient(option, store);
933
+ let edgeUrl = await boundEdge(store);
879
934
  if (edgeUrl === null) {
880
935
  const named = (await client.me()).edgeUrl;
881
936
  if (named === null) {
882
937
  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
938
  }
884
- edgeUrl = await bindEdge(dataDir, named);
939
+ edgeUrl = await bindEdge(store, named);
885
940
  }
886
941
  return { edgeUrl, tokens: client };
887
942
  }
888
943
  /** 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);
944
+ async function teamAccessOfFile(file, config, store) {
945
+ const account = await readAccount(store);
891
946
  if (account === null) {
892
947
  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
948
  }
@@ -895,7 +950,7 @@ async function teamAccessOfFile(file, config, dataDir) {
895
950
  // The stored API token belongs to another control plane and is not sent to this one
896
951
  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
952
  }
898
- return teamAccess('p2p.team', dataDir);
953
+ return teamAccess('p2p.team', store);
899
954
  }
900
955
  /** --allow-host: a host name or address as a Host header carries it, with or without a port; in lower case. */
901
956
  function parseAllowedHost(value) {
@@ -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
  }
@@ -18,7 +18,7 @@ export async function init(options) {
18
18
  if (await present(options.file)) {
19
19
  throw exists(options.shown);
20
20
  }
21
- const answers = options.flags === null ? await interview(options) : await fromFlags(options.flags, options.dataDir);
21
+ const answers = options.flags === null ? await interview(options) : await fromFlags(options.flags, storeOf(options));
22
22
  const text = renderConfig(answers);
23
23
  // The parser of hopwire up decides; a refusal here is a fault of init and ends with its sentence
24
24
  parseConfig(text, options.shown);
@@ -55,18 +55,21 @@ async function present(file) {
55
55
  throw new HopwireError(`${file} cannot be checked (${errorCode(error)}); check the permissions of its directory.`);
56
56
  }
57
57
  }
58
+ function storeOf(options) {
59
+ return { dataDir: options.dataDir, profile: options.profile ?? null };
60
+ }
58
61
  /** What the account gives a public service: its edge and its control plane. Null when the machine cannot have one. */
59
- async function accountUrls(dataDir) {
60
- const account = await readAccount(dataDir);
62
+ async function accountUrls(store) {
63
+ const account = await readAccount(store);
61
64
  if (account === null) {
62
65
  return 'logged-out';
63
66
  }
64
- const edgeUrl = await boundEdge(dataDir);
67
+ const edgeUrl = await boundEdge(store);
65
68
  return edgeUrl === null ? 'no-edge' : { edgeUrl, controlPlaneUrl: account.controlPlaneUrl };
66
69
  }
67
70
  const NO_EDGE = 'The account on this machine names no edge yet; run hopwire login again (or start hopwire http <port> --public once), then hopwire init again.';
68
71
  // --- The flags ---
69
- async function fromFlags(flags, dataDir) {
72
+ async function fromFlags(flags, store) {
70
73
  if (flags.services.length === 0) {
71
74
  throw new UsageError('hopwire init --yes needs at least one --service name=port, for example --service web=3000');
72
75
  }
@@ -126,7 +129,7 @@ async function fromFlags(flags, dataDir) {
126
129
  let edgeUrl = null;
127
130
  let controlPlaneUrl = null;
128
131
  if (flags.public.length > 0 || flags.team) {
129
- const urls = await accountUrls(dataDir);
132
+ const urls = await accountUrls(store);
130
133
  if (urls === 'logged-out') {
131
134
  throw new HopwireError(flags.public.length > 0
132
135
  ? '--public needs an account: run hopwire login first; nothing was written.'
@@ -182,7 +185,7 @@ async function interview(options) {
182
185
  }
183
186
  };
184
187
  // Read once, before the first question: whether a service can be public at all
185
- const urls = await accountUrls(options.dataDir);
188
+ const urls = await accountUrls(storeOf(options));
186
189
  const detected = await detectPort(options.cwd);
187
190
  const services = [];
188
191
  let toldAboutPublic = false;
@@ -1,4 +1,4 @@
1
- import { DEFAULT_CONTROL_PLANE_URL, accountFile, isApiToken, readControlPlaneUrl, removeAccount, writeAccount, } from '../account.js';
1
+ import { DEFAULT_CONTROL_PLANE_URL, DEFAULT_PROFILE, accountFile, isApiToken, listProfiles, profileName, readControlPlaneUrl, removeAccount, useProfile, writeAccount, } from '../account.js';
2
2
  import { setTimeout as sleep } from 'node:timers/promises';
3
3
  import { HopwireError, TemporaryError } from '../errors.js';
4
4
  import { LOGIN_NEXT, printable } from '../output.js';
@@ -11,7 +11,8 @@ import { LOGIN_NEXT, printable } from '../output.js';
11
11
  * is stored unless the control plane accepted the token. The token is never printed.
12
12
  */
13
13
  export async function login(options) {
14
- const controlPlaneUrl = options.apiUrl ?? (await storedUrl(options.dataDir)) ?? new URL(DEFAULT_CONTROL_PLANE_URL);
14
+ const ref = { dataDir: options.dataDir, profile: options.profile ?? null };
15
+ const controlPlaneUrl = options.apiUrl ?? (await storedUrl(ref)) ?? new URL(DEFAULT_CONTROL_PLANE_URL);
15
16
  const fromEnv = (options.token ?? '').trim();
16
17
  const apiToken = fromEnv ||
17
18
  (options.paste
@@ -27,7 +28,11 @@ export async function login(options) {
27
28
  apiToken,
28
29
  }).me(options.signal);
29
30
  // The account is bound to the edge its control plane names: public tunnels need no HOPWIRE_EDGE_URL
30
- await writeAccount(options.dataDir, { apiToken, controlPlaneUrl }, edgeUrl);
31
+ const profile = await profileName(ref).catch(() => options.profile ?? DEFAULT_PROFILE);
32
+ await writeAccount({ dataDir: options.dataDir, profile }, { apiToken, controlPlaneUrl }, edgeUrl, {
33
+ organisation: organisation?.name ?? null,
34
+ plan,
35
+ });
31
36
  // The address comes from another machine: nothing of it reaches the terminal as an escape sequence
32
37
  options.print(`Logged in ${printable(email)} at ${controlPlaneUrl.origin}`);
33
38
  if (organisation !== null) {
@@ -37,6 +42,7 @@ export async function login(options) {
37
42
  options.print(`Edge ${edgeUrl.origin} (public tunnels of this account go there)`);
38
43
  }
39
44
  options.print(`Token stored in ${accountFile(options.dataDir)} (readable for this user only)`);
45
+ options.print(`Profile ${profile} (current; hopwire profiles lists them, hopwire login --profile <name> adds one)`);
40
46
  for (const line of LOGIN_NEXT) {
41
47
  options.print(line);
42
48
  }
@@ -48,16 +54,49 @@ export async function login(options) {
48
54
  */
49
55
  export async function logout(options) {
50
56
  const file = accountFile(options.dataDir);
51
- if (await removeAccount(options.dataDir)) {
52
- options.print(`Logged out the token was removed from ${file}; it stays valid until you revoke it on the API tokens page of the control plane`);
57
+ const ref = { dataDir: options.dataDir, profile: options.profile ?? null };
58
+ // A machine that was never logged in, or a damaged file, has no profiles to name; a damaged file goes as a whole
59
+ const known = (await listProfiles(options.dataDir).catch(() => [])).length > 0;
60
+ const of = known ? ` of profile ${await profileName(ref)}` : '';
61
+ if (await removeAccount(ref)) {
62
+ options.print(`Logged out the token${of} was removed from ${file}; it stays valid until you revoke it on the API tokens page of the control plane`);
53
63
  }
54
64
  else {
55
- options.print(`Logged out no token was stored in ${file}`);
65
+ options.print(`Logged out no token${of} was stored in ${file}`);
66
+ }
67
+ }
68
+ /**
69
+ * `hopwire profiles`: the logins of this data directory, one line each, with the organisation and plan the control
70
+ * plane named at login. Nothing is contacted; the token is never printed.
71
+ */
72
+ export async function profiles(options) {
73
+ const found = await listProfiles(options.dataDir);
74
+ if (found.length === 0) {
75
+ options.print('No profiles yet: hopwire login stores the first one (named default; --profile <name> names it)');
76
+ return;
77
+ }
78
+ const width = Math.max(...found.map((profile) => profile.name.length));
79
+ for (const profile of found) {
80
+ const organisation = profile.organisation === null
81
+ ? 'organisation not known'
82
+ : `${profile.organisation}${profile.plan === null ? '' : ` (${profile.plan} plan)`}`;
83
+ const state = profile.loggedIn ? '' : ', logged out';
84
+ // Names of organisations come from another machine: nothing of them reaches the terminal as an escape sequence
85
+ options.print(printable(`${profile.current ? '*' : ' '} ${profile.name.padEnd(width)} ${organisation} at ${profile.controlPlaneUrl.origin}${state}`));
86
+ }
87
+ options.print('');
88
+ options.print('* is the current profile; hopwire use <name> switches, --profile <name> picks one for one command');
89
+ }
90
+ /** `hopwire use <name>`: makes a profile the current one. Nothing is contacted. */
91
+ export async function use(options) {
92
+ if (!(await useProfile(options.dataDir, options.name))) {
93
+ throw new HopwireError(`There is no profile "${options.name}" on this machine; run hopwire login --profile ${options.name} to create it, or hopwire profiles to list the ones there are.`);
56
94
  }
95
+ options.print(`Profile ${options.name} is now the current one`);
57
96
  }
58
97
  /** The control plane of an earlier login, logged out since or not; a damaged file counts as none, the login replaces it. */
59
- async function storedUrl(dataDir) {
60
- return readControlPlaneUrl(dataDir).catch((error) => {
98
+ async function storedUrl(ref) {
99
+ return readControlPlaneUrl(ref).catch((error) => {
61
100
  if (error instanceof HopwireError) {
62
101
  return null;
63
102
  }
package/dist/config.js CHANGED
@@ -157,9 +157,14 @@ function validate(value, ordered) {
157
157
  team = boolean(p2p.team, ['p2p', 'team']);
158
158
  allowAgents = boolean(p2p.allowAgents, ['p2p', 'allowAgents']);
159
159
  relay = boolean(p2p.relay, ['p2p', 'relay']);
160
- if (relay && !team) {
161
- throw new Problem(['p2p', 'relay'], 'needs p2p.team: true; the relay of the edge (Team plan) only pairs machines of one organisation.');
160
+ if (relay && !share) {
161
+ throw new Problem(['p2p', 'relay'], 'only works together with p2p.share: true; it lets teammates without a direct connection reach the shared services and the shared log.');
162
162
  }
163
+ if (relay && p2p.allow !== undefined) {
164
+ throw new Problem(['p2p', 'allow'], 'cannot be combined with p2p.relay: the relay of the edge (Team plan) only pairs machines of one organisation, so p2p.relay shares with your team; remove p2p.allow.');
165
+ }
166
+ // The relay only pairs machines of one organisation, so p2p.relay turns on p2p.team
167
+ team = team || relay;
163
168
  if (allowAgents && !share) {
164
169
  throw new Problem(['p2p', 'allowAgents'], 'needs p2p.share: true; it lets the coding agents of teammates who watch the shared log read it.');
165
170
  }
package/dist/relay.js CHANGED
@@ -11,7 +11,7 @@ import { proxiedConnection, proxyFor, throughProxy } from './outbound-proxy.js';
11
11
  * DHT path (@hyperswarm/secret-stream, the same key pairs), so the edge passes on bytes it cannot read, and whoever
12
12
  * gets in is decided by the sharer on the peer's public key, as on the DHT path.
13
13
  *
14
- * This is the only module that opens a relay socket. It is loaded only for --relay, which needs --team: without it
14
+ * This is the only module that opens a relay socket. It is loaded only for --relay, which turns on --team: without it
15
15
  * private mode never contacts the edge.
16
16
  */
17
17
  /** How long the edge may take to answer the upgrade request. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hopwire",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "mcpName": "to.hopwire/hopwire",
5
5
  "description": "Record, share and replay the HTTP traffic of your local services: private P2P sharing with teammates, and public HTTPS URLs.",
6
6
  "license": "Apache-2.0",