hopwire 0.1.9 → 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.
Files changed (35) hide show
  1. package/dist/account.js +180 -35
  2. package/dist/agent/redact.js +55 -8
  3. package/dist/cli.js +172 -58
  4. package/dist/commands/doctor.js +53 -12
  5. package/dist/commands/http.js +19 -4
  6. package/dist/commands/init.js +38 -9
  7. package/dist/commands/login.js +47 -8
  8. package/dist/commands/up.js +16 -3
  9. package/dist/commands/watch.js +33 -4
  10. package/dist/config-template.js +11 -1
  11. package/dist/config.js +65 -6
  12. package/dist/control-plane-client.js +42 -0
  13. package/dist/inspector/assets/index-CIOfyIbK.js +5 -0
  14. package/dist/inspector/assets/index-Du4-DCNN.css +2 -0
  15. package/dist/inspector/index.html +2 -2
  16. package/dist/inspector-api.js +145 -0
  17. package/dist/interceptor.js +19 -4
  18. package/dist/log-follow.js +473 -0
  19. package/dist/log.js +178 -11
  20. package/dist/mcp/logs.js +46 -0
  21. package/dist/mcp/tools.js +136 -3
  22. package/dist/output.js +38 -0
  23. package/dist/relay.js +1 -1
  24. package/dist/serve.js +49 -2
  25. package/node_modules/@hopwire/protocol/dist/constants.d.ts +10 -0
  26. package/node_modules/@hopwire/protocol/dist/constants.js +10 -0
  27. package/node_modules/@hopwire/protocol/dist/index.d.ts +1 -0
  28. package/node_modules/@hopwire/protocol/dist/index.js +1 -0
  29. package/node_modules/@hopwire/protocol/dist/inspector.d.ts +18 -0
  30. package/node_modules/@hopwire/protocol/dist/log-entries.d.ts +72 -0
  31. package/node_modules/@hopwire/protocol/dist/log-entries.js +147 -0
  32. package/node_modules/@hopwire/protocol/dist/ws-messages.d.ts +2 -1
  33. package/package.json +1 -1
  34. package/dist/inspector/assets/index-D3yNjmSA.js +0 -2
  35. package/dist/inspector/assets/index-XotF7D1X.css +0 -2
@@ -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,21 +19,27 @@ 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}`);
35
+ // Only with --network: the list comes from the control plane, and without it nothing leaves the machine
36
+ const domains = options.network ? await customDomains(store, options.signal) : null;
37
+ for (const line of domains ?? []) {
38
+ print(line);
39
+ }
34
40
  print('');
35
41
  print(options.network
36
- ? `${edge === null ? 'Nothing was sent to us. ' : ''}The network check joined the DHT for a moment; its nodes saw the IP address of this machine.${edge === null ? '' : ' It also asked the edge of your account whether its relay answers, without a token: the edge saw the IP address, nothing else.'}`
42
+ ? `${edge === null && domains === null ? 'Nothing was sent to us. ' : ''}The network check joined the DHT for a moment; its nodes saw the IP address of this machine.${edge === null ? '' : ' It also asked the edge of your account whether its relay answers, without a token: the edge saw the IP address, nothing else.'}${domains === null ? '' : ' It asked the control plane of your account for its custom domains, with your API token.'}`
37
43
  : 'Nothing was sent anywhere: this report was put together on this machine without a network connection.');
38
44
  print('It holds no keys, no tokens and no traffic. If you paste it into a bug report, read it first: the paths can name your user.');
39
45
  }
@@ -76,15 +82,19 @@ async function entry(file, expected, missing = 'missing') {
76
82
  : `present, mode ${shown}: others on this machine can get at it; it should be ${expected.toString(8).padStart(4, '0')}`;
77
83
  }
78
84
  /** Where the machine is logged in. The API token is never part of the answer. */
79
- async function account(dataDir) {
85
+ async function account(store) {
80
86
  try {
81
- 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)` : '';
82
92
  if (stored === null) {
83
- return 'not logged in (only public mode needs an account)';
93
+ return `not logged in${profile} (only public mode needs an account)`;
84
94
  }
85
- const edge = await boundEdge(dataDir);
86
- const file = await entry(accountFile(dataDir), 0o600);
87
- 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}`);
88
98
  }
89
99
  catch (error) {
90
100
  return `config.json cannot be used: ${message(error)}`;
@@ -126,9 +136,9 @@ async function network(options) {
126
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';
127
137
  }
128
138
  /** The edge whose relay is checked: the one the logged-in account is bound to; null when there is none. */
129
- async function relayEdge(dataDir) {
139
+ async function relayEdge(store) {
130
140
  try {
131
- return (await readAccount(dataDir)) === null ? null : await boundEdge(dataDir);
141
+ return (await readAccount(store)) === null ? null : await boundEdge(store);
132
142
  }
133
143
  catch {
134
144
  return null;
@@ -146,6 +156,37 @@ async function relay(edge) {
146
156
  ? `the relay of ${edge.origin} can be reached from here: --team --relay works on this network when direct P2P does not`
147
157
  : `the relay of ${edge.origin} cannot be reached from here (${found.problem})`;
148
158
  }
159
+ /** What the control plane says about the status of a custom domain, in plain words. */
160
+ const DOMAIN_STATUS_WORDS = {
161
+ active: 'active',
162
+ pending_dns: 'waiting for DNS',
163
+ pending_certificate: 'waiting for certificate',
164
+ failed: 'failed',
165
+ offline_plan: 'off (beyond plan)',
166
+ };
167
+ /**
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
169
+ * the account has none or the control plane cannot be asked right now (the report is not about that).
170
+ */
171
+ async function customDomains(store, signal) {
172
+ try {
173
+ const stored = await readAccount(store);
174
+ if (stored === null) {
175
+ return null;
176
+ }
177
+ // Loaded only here: doctor without --network never contacts the control plane
178
+ const { createControlPlaneClient } = await import('../control-plane-client.js');
179
+ const { customDomains: domains } = await createControlPlaneClient({
180
+ url: stored.controlPlaneUrl,
181
+ apiToken: stored.apiToken,
182
+ }).me(signal);
183
+ return domains.map((domain, index) => `${index === 0 ? 'Domains' : ''}`.padEnd(13) +
184
+ printable(`${domain.host} (${DOMAIN_STATUS_WORDS[domain.status]}; ${domain.subdomain})`));
185
+ }
186
+ catch {
187
+ return [];
188
+ }
189
+ }
149
190
  function message(error) {
150
191
  return printable(error instanceof Error ? error.message : String(error));
151
192
  }
@@ -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, formatMeteredUsage, formatRelayEvent, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, } 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, formatExchange, 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
  /**
@@ -12,7 +12,18 @@ export async function startHttpTunnel(options) {
12
12
  // The line about a tunnel --force stopped follows the startup lines: the mode stays the first line
13
13
  const stopped = [];
14
14
  const serving = await startServing({
15
- services: [{ name: options.serviceName, target, listenPort: options.listenPort, public: options.public }],
15
+ services: [
16
+ {
17
+ name: options.serviceName,
18
+ target,
19
+ listenPort: options.listenPort,
20
+ public: options.public,
21
+ logs: options.logs,
22
+ },
23
+ ],
24
+ shareLogs: options.shareLogs ?? false,
25
+ logRequestId: options.logRequestId ?? false,
26
+ onLogNotice: (serviceName, line) => options.print(formatLogNotice(serviceName, line)),
16
27
  inspectPort: options.inspectPort,
17
28
  dataDir: options.dataDir,
18
29
  force: options.force ?? false,
@@ -38,6 +49,7 @@ export async function startHttpTunnel(options) {
38
49
  const { inspectorUrl, agentSocket, logKey, peerKey, ended, close } = serving;
39
50
  const url = serving.services[0]?.url ?? '';
40
51
  const publicUrl = serving.services[0]?.publicUrl ?? null;
52
+ const customDomains = serving.services[0]?.customDomains ?? [];
41
53
  const subdomain = serving.services[0]?.subdomain ?? '';
42
54
  const usage = serving.services[0]?.usage ?? null;
43
55
  const access = serving.team === null
@@ -53,7 +65,7 @@ export async function startHttpTunnel(options) {
53
65
  }
54
66
  options.print(`Forwarding ${url} -> ${target.origin}`);
55
67
  if (options.public !== undefined) {
56
- options.print(`Public URL ${publicUrl ?? `subdomain ${subdomain} (the edge did not report its URL)`}`);
68
+ options.print(`Public URL ${publicUrlText(publicUrl, customDomains) ?? `subdomain ${subdomain} (the edge did not report its URL)`}`);
57
69
  if (usage !== null) {
58
70
  options.print(formatUsage(usage));
59
71
  }
@@ -69,6 +81,9 @@ export async function startHttpTunnel(options) {
69
81
  options.print(AGENTS_ALLOWED_LINE);
70
82
  }
71
83
  }
84
+ for (const line of logLines(serving.logs, peerKey !== null && options.shareLogs === true, options.cwd ?? process.cwd())) {
85
+ options.print(line);
86
+ }
72
87
  if (inspectorUrl !== null) {
73
88
  options.print(`Inspector ${inspectorUrl}`);
74
89
  }
@@ -84,7 +99,7 @@ export async function startHttpTunnel(options) {
84
99
  name: options.serviceName,
85
100
  url,
86
101
  target: target.origin,
87
- publicUrl,
102
+ publicUrl: mainPublicUrl(publicUrl, customDomains),
88
103
  stableUrl: options.public?.connectTokens !== undefined,
89
104
  },
90
105
  ],
@@ -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
  }
@@ -80,7 +83,7 @@ async function fromFlags(flags, dataDir) {
80
83
  if (local === null) {
81
84
  throw new UsageError(`--service ${printable(name)} needs a port or an http URL on this machine without a path, for example ${printable(name)}=3000 or ${printable(name)}=http://127.0.0.1:3000`);
82
85
  }
83
- return { name, local, public: false, subdomain: null };
86
+ return { name, local, public: false, subdomain: null, logs: [] };
84
87
  });
85
88
  const byName = new Map();
86
89
  for (const service of services) {
@@ -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.'
@@ -147,6 +150,7 @@ async function fromFlags(flags, dataDir) {
147
150
  share: flags.share,
148
151
  team: flags.team,
149
152
  allowAgents: flags.allowAgents,
153
+ shareLogs: false,
150
154
  };
151
155
  }
152
156
  /** A port (`3000` becomes http://127.0.0.1:3000) or a loopback http URL without a path; null for anything else. */
@@ -181,7 +185,7 @@ async function interview(options) {
181
185
  }
182
186
  };
183
187
  // Read once, before the first question: whether a service can be public at all
184
- const urls = await accountUrls(options.dataDir);
188
+ const urls = await accountUrls(storeOf(options));
185
189
  const detected = await detectPort(options.cwd);
186
190
  const services = [];
187
191
  let toldAboutPublic = false;
@@ -208,7 +212,7 @@ async function interview(options) {
208
212
  }
209
213
  say('Give a port, for example 3000, or an http URL on this machine without a path, for example http://127.0.0.1:3000.');
210
214
  }
211
- const service = { name, local, public: false, subdomain: null };
215
+ const service = { name, local, public: false, subdomain: null, logs: [] };
212
216
  if (typeof urls === 'object') {
213
217
  service.public = await yesNo('Serve it under a public URL?');
214
218
  if (service.public) {
@@ -234,15 +238,37 @@ async function interview(options) {
234
238
  say(urls === 'logged-out' ? PUBLIC_NEEDS_LOGIN : NO_EDGE);
235
239
  toldAboutPublic = true;
236
240
  }
241
+ // Phase 15: nothing is followed that was not named here
242
+ for (;;) {
243
+ const suggested = services.length === 0 && (await present(path.join(options.cwd, LARAVEL_LOG)));
244
+ const answer = await question('Log file to show next to the traffic (empty for none)', suggested ? LARAVEL_LOG : null);
245
+ if (answer === '') {
246
+ break;
247
+ }
248
+ if (printable(answer) !== answer || path.dirname(answer).includes('*')) {
249
+ say('Give the path of a log file, with a * at most in the file name, or nothing.');
250
+ continue;
251
+ }
252
+ // In the file the path is relative to its folder
253
+ const absolute = path.resolve(options.cwd, answer);
254
+ const relative = path.relative(path.dirname(options.file), absolute);
255
+ service.logs.push(path.isAbsolute(answer) || relative.startsWith('..') ? absolute : relative);
256
+ break;
257
+ }
237
258
  services.push(service);
238
259
  } while (await yesNo('Another service?'));
239
260
  const share = await yesNo('Share with teammates over P2P (hopwire watch, hopwire connect)?');
240
261
  let team = false;
241
262
  let allowAgents = false;
263
+ let shareLogs = false;
242
264
  if (share) {
243
265
  if (urls !== 'logged-out') {
244
266
  team = await yesNo("Only machines of your organisation's members (Team plan)?");
245
267
  }
268
+ if (services.some((service) => service.logs.length > 0)) {
269
+ say("Logs often hold secrets and other people's data.");
270
+ shareLogs = await yesNo('Show the log entries to teammates who watch too?');
271
+ }
246
272
  say("What a teammate's coding agent reads goes to its model provider.");
247
273
  allowAgents = await yesNo("Let teammates' coding agents read what is captured?");
248
274
  }
@@ -254,8 +280,11 @@ async function interview(options) {
254
280
  share,
255
281
  team,
256
282
  allowAgents,
283
+ shareLogs,
257
284
  };
258
285
  }
286
+ /** The log file `hopwire init` suggests when the working directory has it. */
287
+ const LARAVEL_LOG = 'storage/logs/laravel.log';
259
288
  // --- The port suggestion ---
260
289
  /**
261
290
  * The port suggested for the first service, never used with --yes: PORT=<n> in .env of the working directory (only
@@ -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
  }
@@ -1,7 +1,8 @@
1
1
  import { randomBytes } from 'node:crypto';
2
+ import path from 'node:path';
2
3
  import { LOCAL_ENTRY_DEFAULT_PORT, RANDOM_SUBDOMAIN_BYTES, randomSubdomain } from '@hopwire/protocol';
3
4
  import { HopwireError } from '../errors.js';
4
- import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, relayLine, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, AGENTS_ALLOWED_LINE, agentLine, agentOffLine, formatExchange, formatRelayEvent, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, } from '../output.js';
5
+ import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, relayLine, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, AGENTS_ALLOWED_LINE, agentLine, agentOffLine, formatExchange, formatLogNotice, logLines, formatRelayEvent, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, mainPublicUrl, publicUrlText, } from '../output.js';
5
6
  import { startServing } from '../serve.js';
6
7
  import { formatBridgeEvent } from './http.js';
7
8
  /**
@@ -30,6 +31,11 @@ export async function startUp(options) {
30
31
  listenPort: port > 65535 ? 0 : port,
31
32
  listenFallback: true,
32
33
  public: publicOptions(service, config, options),
34
+ // Relative to the folder of hopwire.yaml
35
+ logs: service.logs.map((log) => ({
36
+ name: log.name,
37
+ path: path.resolve(path.dirname(path.resolve(options.configFile)), log.path),
38
+ })),
33
39
  };
34
40
  });
35
41
  // The line about a tunnel --force stopped follows the startup lines: the mode stays the first line
@@ -51,6 +57,9 @@ export async function startUp(options) {
51
57
  inspectorFiles: options.inspectorFiles,
52
58
  agent: options.agent,
53
59
  captureWebSocketMessages: config.captureWebSocket,
60
+ shareLogs: config.shareLogs,
61
+ logRequestId: config.logRequestId,
62
+ onLogNotice: (name, line) => options.print(formatLogNotice(name, line, config.services.length)),
54
63
  signal: options.signal,
55
64
  listenOption: 'a free port',
56
65
  inspectOption: 'inspector.port in hopwire.yaml',
@@ -76,7 +85,8 @@ export async function startUp(options) {
76
85
  }
77
86
  options.print(`Forwarding ${service.url} -> ${service.target}`);
78
87
  if (service.subdomain !== null) {
79
- const url = service.publicUrl ?? `subdomain ${service.subdomain} (the edge did not report its URL)`;
88
+ const url = publicUrlText(service.publicUrl, service.customDomains) ??
89
+ `subdomain ${service.subdomain} (the edge did not report its URL)`;
80
90
  options.print(`Public URL ${url}${settings?.basicAuth == null ? '' : ' (asks for the user and password of auth.basic)'}`);
81
91
  if (service.usage !== null) {
82
92
  options.print(formatUsage(service.usage));
@@ -94,6 +104,9 @@ export async function startUp(options) {
94
104
  options.print(AGENTS_ALLOWED_LINE);
95
105
  }
96
106
  }
107
+ for (const line of logLines(serving.logs, serving.peerKey !== null && config.shareLogs, path.dirname(path.resolve(options.configFile)), config.services.length)) {
108
+ options.print(line);
109
+ }
97
110
  options.print(`Inspector ${serving.inspectorUrl ?? ''}`);
98
111
  if (serving.agentSocket !== null) {
99
112
  const [first, ...rest] = serving.services;
@@ -107,7 +120,7 @@ export async function startUp(options) {
107
120
  name: service.name,
108
121
  url: service.url,
109
122
  target: service.target,
110
- publicUrl: service.publicUrl,
123
+ publicUrl: mainPublicUrl(service.publicUrl, service.customDomains),
111
124
  basicAuth: config.services[index]?.basicAuth != null,
112
125
  stableUrl: options.connectTokens !== undefined,
113
126
  })),
@@ -2,11 +2,12 @@ import { openOwnLog } from '../data-dir-holder.js';
2
2
  import { startAgentSocket } from '../agent-socket.js';
3
3
  import { HopwireError, listenError } from '../errors.js';
4
4
  import { loadOrCreateIdentity } from '../identity.js';
5
- import { agentsOnly, createInspectorApi } from '../inspector-api.js';
5
+ import { agentsOnly, createInspectorApi, withLocalLogs } from '../inspector-api.js';
6
6
  import { startInspectorServer } from '../inspector-server.js';
7
7
  import { createInterceptor } from '../interceptor.js';
8
+ import { InFlightExchanges, followLogFile } from '../log-follow.js';
8
9
  import { REMOTE_LOG_BUDGET_BYTES } from '../log.js';
9
- import { MODE_P2P, MODE_P2P_RELAYED, MODE_P2P_TEAM, formatExchange, printable, relayedLine, shortKey, watchAgentLine, watchGuide, } from '../output.js';
10
+ import { MODE_P2P, MODE_P2P_RELAYED, MODE_P2P_TEAM, formatExchange, formatLogNotice, logLines, printable, relayedLine, shortKey, watchAgentLine, watchGuide, } from '../output.js';
10
11
  import { INSPECTOR_FILES } from '../serve.js';
11
12
  import { Supervisor, unlessAborted } from '../supervisor.js';
12
13
  /**
@@ -76,6 +77,30 @@ export async function startWatch(options) {
76
77
  // here, instead of an inspector that stays empty
77
78
  throw joinError('no_connection', logKey, peerKey, options.team !== undefined);
78
79
  }
80
+ // The watcher's own log files: never shared, so into the local-only core
81
+ const logs = options.replayTarget === null ? [] : (options.logs ?? []);
82
+ let localLogs = null;
83
+ const inFlight = logs.length > 0 ? new InFlightExchanges() : undefined;
84
+ const followed = [];
85
+ if (inFlight !== undefined && options.replayTarget !== null) {
86
+ const local = await own.openLocalLogs();
87
+ localLogs = local;
88
+ supervisor.add('store', () => local.close());
89
+ const serviceName = options.replayTarget.host;
90
+ for (const file of logs) {
91
+ proceed();
92
+ const follower = await followLogFile({
93
+ ...file,
94
+ serviceName,
95
+ inFlight,
96
+ append: (block) => local.append(block),
97
+ onNotice: (line) => options.print(formatLogNotice(serviceName, line)),
98
+ });
99
+ supervisor.add('servers', () => follower.stop());
100
+ followed.push({ serviceName, name: file.name, path: file.path, waiting: follower.waiting });
101
+ }
102
+ }
103
+ const ownSource = withLocalLogs(own, localLogs);
79
104
  // Replays keep the service name of the exchange they repeat
80
105
  const interceptors = new Map();
81
106
  const replayThrough = (serviceName) => {
@@ -88,6 +113,7 @@ export async function startWatch(options) {
88
113
  target: options.replayTarget,
89
114
  serviceName,
90
115
  log: own,
116
+ inFlight,
91
117
  onExchange: (exchange) => options.print(formatExchange(exchange)),
92
118
  onLogError: () => options.print('Could not write to the traffic log; the replay was still sent'),
93
119
  });
@@ -109,7 +135,7 @@ export async function startWatch(options) {
109
135
  staticDir: options.inspectorFiles ?? INSPECTOR_FILES,
110
136
  sources: [
111
137
  { origin: 'remote', log: remote },
112
- { origin: 'own', log: own },
138
+ { origin: 'own', log: ownSource },
113
139
  ],
114
140
  status: () => status,
115
141
  replayThrough: (exchange) => replayThrough(exchange.serviceName),
@@ -124,7 +150,7 @@ export async function startWatch(options) {
124
150
  const api = createInspectorApi({
125
151
  sources: [
126
152
  { origin: 'remote', log: agentsOnly(remote) },
127
- { origin: 'own', log: own },
153
+ { origin: 'own', log: ownSource },
128
154
  ],
129
155
  status: () => status,
130
156
  replayThrough: (exchange) => replayThrough(exchange.serviceName),
@@ -151,6 +177,9 @@ export async function startWatch(options) {
151
177
  options.print(options.replayTarget === null
152
178
  ? 'Replay off; start hopwire watch with --replay-target <url> to replay to a local service'
153
179
  : `Replay to ${options.replayTarget.origin}`);
180
+ for (const line of logLines(followed, false, options.cwd ?? process.cwd())) {
181
+ options.print(line);
182
+ }
154
183
  options.print(`Inspector ${inspector.url}`);
155
184
  if (agentSocket !== null) {
156
185
  options.print(watchAgentLine(agentSocket, options.replayTarget?.origin ?? null));
@@ -23,6 +23,9 @@ export function renderConfig(answers) {
23
23
  '# 2 MB or 10,000 messages per WebSocket). Uncomment to record the handshake only, as --no-ws-capture does.',
24
24
  '# capture:',
25
25
  '# websocket: false',
26
+ '# # Every request forwarded to a service carries X-Hopwire-Exchange-Id; a service that writes it into its',
27
+ '# # log (Log::withContext in Laravel) gets exact links between its log entries and the requests.',
28
+ '# logRequestId: true',
26
29
  '',
27
30
  ];
28
31
  if (answers.edgeUrl !== null && answers.controlPlaneUrl !== null) {
@@ -38,13 +41,20 @@ export function renderConfig(answers) {
38
41
  else {
39
42
  lines.push(`${INDENT}# Only these public keys may watch and connect (each teammate prints theirs with \`hopwire id\`).`, `${INDENT}# Without the list everyone who has the keys gets in.`, `${INDENT}# allow:`, `${INDENT}# - 0000000000000000000000000000000000000000000000000000000000000000`, `${INDENT}# Instead of the list: only machines of the members of your organisation (Team plan, \`hopwire login\`).`, `${INDENT}# The control plane of your account then names the keys of the team; your traffic still passes no server.`, `${INDENT}# team: true`);
40
43
  }
41
- lines.push(`${INDENT}# With team: teammates whose network allows no direct connection (UDP blocked, strict NAT on both sides) come`, `${INDENT}# in through the relay of your account's edge on port 443, end-to-end encrypted. Direct P2P is tried first.`, `${INDENT}# relay: true`, `${INDENT}# With share: the coding agents of teammates who watch the log (\`hopwire watch --agent\`) may read the`, `${INDENT}# exchanges captured from now on. What an agent reads goes to its model provider.`, answers.allowAgents ? `${INDENT}allowAgents: true` : `${INDENT}# allowAgents: true`, '', '# One entry per local service; the name shows in the inspector and is what a teammate passes to --service.', '# Every service gets a loopback entry point, counted up from 4041 in the order of this file (the port of the', '# inspector is left out).', 'services:');
44
+ lines.push(`${INDENT}# With team: teammates whose network allows no direct connection (UDP blocked, strict NAT on both sides) come`, `${INDENT}# in through the relay of your account's edge on port 443, end-to-end encrypted. Direct P2P is tried first.`, `${INDENT}# relay: true`, `${INDENT}# With share: the coding agents of teammates who watch the log (\`hopwire watch --agent\`) may read the`, `${INDENT}# exchanges captured from now on. What an agent reads goes to its model provider.`, answers.allowAgents ? `${INDENT}allowAgents: true` : `${INDENT}# allowAgents: true`, `${INDENT}# With share: teammates who watch the log also see the new entries of the services' log files (logs:).`, `${INDENT}# Logs often hold secrets and other people's data; their coding agents read them only with allowAgents.`, answers.shareLogs ? `${INDENT}shareLogs: true` : `${INDENT}# shareLogs: true`, '', '# One entry per local service; the name shows in the inspector and is what a teammate passes to --service.', '# Every service gets a loopback entry point, counted up from 4041 in the order of this file (the port of the', '# inspector is left out).', 'services:');
42
45
  answers.services.forEach((service, index) => {
43
46
  if (index > 0) {
44
47
  lines.push('');
45
48
  }
46
49
  lines.push(`${INDENT}${yamlKey(service.name)}:`, `${INDENT}${INDENT}# An http URL on this machine without a path.`);
47
50
  lines.push(`${INDENT}${INDENT}local: ${service.local.origin}`);
51
+ lines.push(`${INDENT}${INDENT}# Log files whose new entries are shown next to the traffic, linked to the requests they were written`, `${INDENT}${INDENT}# during (nothing written before the start is read). Relative to this file; a * in the file name follows`, `${INDENT}${INDENT}# the newest match. They stay on this machine unless p2p.shareLogs.`);
52
+ if (service.logs.length > 0) {
53
+ lines.push(`${INDENT}${INDENT}logs:`, ...service.logs.map((log) => `${INDENT}${INDENT}${INDENT}- ${JSON.stringify(log)}`));
54
+ }
55
+ else {
56
+ lines.push(`${INDENT}${INDENT}# logs:`, `${INDENT}${INDENT}# - storage/logs/laravel.log`);
57
+ }
48
58
  if (!service.public) {
49
59
  return;
50
60
  }