hopwire 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +2 -0
  2. package/dist/agent/redact.js +38 -0
  3. package/dist/bin.js +5 -1
  4. package/dist/cli.js +237 -10
  5. package/dist/commands/connect.js +23 -7
  6. package/dist/commands/doctor.js +63 -3
  7. package/dist/commands/http.js +25 -4
  8. package/dist/commands/init.js +355 -0
  9. package/dist/commands/up.js +22 -3
  10. package/dist/commands/watch.js +54 -9
  11. package/dist/config-template.js +80 -0
  12. package/dist/config.js +65 -5
  13. package/dist/control-plane-client.js +70 -0
  14. package/dist/inspector/assets/index-CIOfyIbK.js +5 -0
  15. package/dist/inspector/assets/index-Du4-DCNN.css +2 -0
  16. package/dist/inspector/index.html +2 -2
  17. package/dist/inspector-api.js +145 -0
  18. package/dist/interceptor.js +19 -4
  19. package/dist/log-follow.js +473 -0
  20. package/dist/log.js +178 -11
  21. package/dist/main.js +1 -0
  22. package/dist/mcp/logs.js +46 -0
  23. package/dist/mcp/tools.js +136 -3
  24. package/dist/output.js +67 -1
  25. package/dist/p2p.js +249 -24
  26. package/dist/prompt.js +63 -0
  27. package/dist/relay.js +545 -0
  28. package/dist/serve.js +62 -2
  29. package/node_modules/@hopwire/protocol/dist/constants.d.ts +10 -0
  30. package/node_modules/@hopwire/protocol/dist/constants.js +10 -0
  31. package/node_modules/@hopwire/protocol/dist/index.d.ts +2 -0
  32. package/node_modules/@hopwire/protocol/dist/index.js +2 -0
  33. package/node_modules/@hopwire/protocol/dist/inspector.d.ts +18 -0
  34. package/node_modules/@hopwire/protocol/dist/log-entries.d.ts +72 -0
  35. package/node_modules/@hopwire/protocol/dist/log-entries.js +147 -0
  36. package/node_modules/@hopwire/protocol/dist/relay.d.ts +81 -0
  37. package/node_modules/@hopwire/protocol/dist/relay.js +102 -0
  38. package/node_modules/@hopwire/protocol/dist/ws-messages.d.ts +2 -1
  39. package/package.json +2 -1
  40. package/dist/inspector/assets/index-D3yNjmSA.js +0 -2
  41. package/dist/inspector/assets/index-XotF7D1X.css +0 -2
@@ -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_TEAM, formatExchange, printable, 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
  /**
@@ -49,15 +50,23 @@ export async function startWatch(options) {
49
50
  ? null
50
51
  : printable((await options.team.teamKeys(peerKey, options.signal)).organisation.name);
51
52
  proceed();
53
+ let relay;
54
+ if (options.relay !== undefined) {
55
+ // Loaded only here: without --relay nothing opens a relay socket
56
+ const { relaySetup } = await import('../relay.js');
57
+ relay = relaySetup(options.relay, peerKey);
58
+ }
52
59
  const { JoinError, joinLog } = await import('../p2p.js');
53
60
  const joined = await joinLog({
54
61
  identity,
55
62
  log: remote,
56
63
  bootstrap: options.bootstrap,
57
64
  signal: options.signal,
65
+ relay,
66
+ onRelayLost: (problem, limit) => options.print(limit ? `Limit ${problem}` : `Relay ${problem}; trying again`),
58
67
  }).catch((error) => {
59
68
  throw error instanceof JoinError
60
- ? joinError(error.code, logKey, peerKey, options.team !== undefined)
69
+ ? joinError(error.code, logKey, peerKey, options.team !== undefined, error.relayProblem)
61
70
  : error;
62
71
  });
63
72
  supervisor.add('p2p', () => joined.close());
@@ -68,6 +77,30 @@ export async function startWatch(options) {
68
77
  // here, instead of an inspector that stays empty
69
78
  throw joinError('no_connection', logKey, peerKey, options.team !== undefined);
70
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);
71
104
  // Replays keep the service name of the exchange they repeat
72
105
  const interceptors = new Map();
73
106
  const replayThrough = (serviceName) => {
@@ -80,6 +113,7 @@ export async function startWatch(options) {
80
113
  target: options.replayTarget,
81
114
  serviceName,
82
115
  log: own,
116
+ inFlight,
83
117
  onExchange: (exchange) => options.print(formatExchange(exchange)),
84
118
  onLogError: () => options.print('Could not write to the traffic log; the replay was still sent'),
85
119
  });
@@ -101,7 +135,7 @@ export async function startWatch(options) {
101
135
  staticDir: options.inspectorFiles ?? INSPECTOR_FILES,
102
136
  sources: [
103
137
  { origin: 'remote', log: remote },
104
- { origin: 'own', log: own },
138
+ { origin: 'own', log: ownSource },
105
139
  ],
106
140
  status: () => status,
107
141
  replayThrough: (exchange) => replayThrough(exchange.serviceName),
@@ -116,7 +150,7 @@ export async function startWatch(options) {
116
150
  const api = createInspectorApi({
117
151
  sources: [
118
152
  { origin: 'remote', log: agentsOnly(remote) },
119
- { origin: 'own', log: own },
153
+ { origin: 'own', log: ownSource },
120
154
  ],
121
155
  status: () => status,
122
156
  replayThrough: (exchange) => replayThrough(exchange.serviceName),
@@ -131,15 +165,21 @@ export async function startWatch(options) {
131
165
  const stopPrinting = remote.subscribe((_index, exchange) => options.print(formatExchange(exchange)));
132
166
  supervisor.add('servers', async () => stopPrinting());
133
167
  void remote.exhausted.then(() => options.print(`Watching stopped: this run has downloaded ${REMOTE_LOG_BUDGET_BYTES / (1024 * 1024)} MB of the log; new exchanges are no longer fetched until hopwire watch is started again`));
134
- options.print(organisation === null ? MODE_P2P : MODE_P2P_TEAM);
168
+ options.print(joined.relayed ? MODE_P2P_RELAYED : organisation === null ? MODE_P2P : MODE_P2P_TEAM);
135
169
  options.print(`Watching ${logKey} (${remote.length} exchanges)`);
136
170
  options.print(`Peer key ${peerKey}`);
137
171
  if (organisation !== null) {
138
172
  options.print(`Team ${organisation}: this machine's key is registered there`);
139
173
  }
174
+ if (joined.relayed && options.relay !== undefined) {
175
+ options.print(relayedLine(options.relay.edgeUrl));
176
+ }
140
177
  options.print(options.replayTarget === null
141
178
  ? 'Replay off; start hopwire watch with --replay-target <url> to replay to a local service'
142
179
  : `Replay to ${options.replayTarget.origin}`);
180
+ for (const line of logLines(followed, false, options.cwd ?? process.cwd())) {
181
+ options.print(line);
182
+ }
143
183
  options.print(`Inspector ${inspector.url}`);
144
184
  if (agentSocket !== null) {
145
185
  options.print(watchAgentLine(agentSocket, options.replayTarget?.origin ?? null));
@@ -158,11 +198,16 @@ export async function startWatch(options) {
158
198
  }
159
199
  }
160
200
  /** One sentence for a log that could not be joined: what happened and what to do. */
161
- function joinError(code, logKey, ownKey, team) {
201
+ function joinError(code, logKey, ownKey, team, relayProblem = null) {
202
+ if (relayProblem !== null) {
203
+ return new HopwireError(code === 'not_found'
204
+ ? `Nobody shares the log ${shortKey(logKey)} on the DHT, and the relay did not connect either: ${relayProblem}.`
205
+ : `The sharer of the log ${shortKey(logKey)} was found but no direct connection came about, and the relay did not connect either: ${relayProblem}.`);
206
+ }
162
207
  if (code === 'not_found') {
163
208
  return new HopwireError(`Nobody is sharing the log ${shortKey(logKey)} right now; check the key, your network connection and that your teammate's tunnel is running and shared (--share, or p2p.share in hopwire.yaml).`);
164
209
  }
165
210
  return new HopwireError(team
166
- ? `The sharer of the log ${shortKey(logKey)} was found but no connection came about: either no direct connection was possible (Hopwire has no relay), or it shares with another team than the one this machine is logged in to, or it runs with --allow, which then has to list this machine's key ${ownKey}.`
167
- : `The sharer of the log ${shortKey(logKey)} was found but no connection came about: either no direct connection was possible (Hopwire has no relay), or it runs with --allow, which then has to list this machine's key ${ownKey}, or it shares with --team: then run this command with --team.`);
211
+ ? `The sharer of the log ${shortKey(logKey)} was found but no connection came about: either no direct connection was possible (on the Team plan --relay goes through the relay of the edge then, when the sharer uses it too), or it shares with another team than the one this machine is logged in to, or it runs with --allow, which then has to list this machine's key ${ownKey}.`
212
+ : `The sharer of the log ${shortKey(logKey)} was found but no connection came about: either no direct connection was possible (on the Team plan --team --relay goes through the relay of the edge then), or it runs with --allow, which then has to list this machine's key ${ownKey}, or it shares with --team: then run this command with --team.`);
168
213
  }
@@ -0,0 +1,80 @@
1
+ import { HOPWIRE_YAML_VERSION, INSPECTOR_DEFAULT_PORT } from '@hopwire/protocol';
2
+ import { DOCS_URL } from './output.js';
3
+ const INDENT = ' ';
4
+ export function renderConfig(answers) {
5
+ const lines = [
6
+ '# The project config of `hopwire up`, written by `hopwire init`: every local service of this project in one',
7
+ '# file. Change it as you like; `hopwire up` refuses a field it does not know and names it by its path, for',
8
+ '# example "services.web.local". Every field is described at',
9
+ `# ${DOCS_URL}/hopwire-yaml`,
10
+ '',
11
+ '# The one version of this format.',
12
+ `version: ${HOPWIRE_YAML_VERSION}`,
13
+ '',
14
+ `# The inspector shows the traffic of all services: http://127.0.0.1:<port>. Default ${INSPECTOR_DEFAULT_PORT}; 0 picks a free port.`,
15
+ '# inspector:',
16
+ `# port: ${INSPECTOR_DEFAULT_PORT}`,
17
+ '',
18
+ '# A coding agent on this machine can read the traffic and replay it through `hopwire mcp` (on by default).',
19
+ '# Uncomment to turn that off for every service, as --no-agent does.',
20
+ '# agent: false',
21
+ '',
22
+ '# The messages of WebSockets are recorded after their handshake (on by default, up to 64 KiB per message and',
23
+ '# 2 MB or 10,000 messages per WebSocket). Uncomment to record the handshake only, as --no-ws-capture does.',
24
+ '# capture:',
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',
29
+ '',
30
+ ];
31
+ if (answers.edgeUrl !== null && answers.controlPlaneUrl !== null) {
32
+ lines.push('# The edge that serves the public URLs and the control plane that issues their connect tokens: the ones of', '# the account this machine is logged in to (hopwire login). The API token stays on this machine.', 'edge:', `${INDENT}url: ${answers.edgeUrl.origin}`, 'controlPlane:', `${INDENT}url: ${answers.controlPlaneUrl.origin}`, '');
33
+ }
34
+ else {
35
+ lines.push('# Public URLs (public: true on a service) need an account: run `hopwire login`, then write the edge and the', '# control plane of the account here, or remove this file and run `hopwire init` again.', '# edge:', '# url: wss://<the edge of your account>', '# controlPlane:', '# url: https://hopwire.to', '');
36
+ }
37
+ lines.push('# Private mode: direct P2P with teammates, no account, no servers of ours.', 'p2p:', `${INDENT}# true announces the traffic log (\`hopwire watch <log-key>\`) and lets teammates reach every service below`, `${INDENT}# (\`hopwire connect <peer-key> --port <port> --service <name>\`). The shared log holds headers and bodies as`, `${INDENT}# captured, including credentials.`, `${INDENT}share: ${String(answers.share)}`);
38
+ if (answers.team) {
39
+ lines.push(`${INDENT}# Only machines of the members of your organisation (Team plan, \`hopwire login\`). The control plane of`, `${INDENT}# your account names the keys of the team; your traffic still passes no server.`, `${INDENT}team: true`);
40
+ }
41
+ else {
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`);
43
+ }
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:');
45
+ answers.services.forEach((service, index) => {
46
+ if (index > 0) {
47
+ lines.push('');
48
+ }
49
+ lines.push(`${INDENT}${yamlKey(service.name)}:`, `${INDENT}${INDENT}# An http URL on this machine without a path.`);
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
+ }
58
+ if (!service.public) {
59
+ return;
60
+ }
61
+ lines.push(`${INDENT}${INDENT}public: true`);
62
+ if (service.subdomain !== null) {
63
+ lines.push(`${INDENT}${INDENT}# Reserved by your organisation in the control plane.`, `${INDENT}${INDENT}subdomain: ${service.subdomain}`);
64
+ }
65
+ else {
66
+ lines.push(`${INDENT}${INDENT}# Without a subdomain the fixed URL of your organisation is served. A subdomain it reserved:`, `${INDENT}${INDENT}# subdomain: my-app`);
67
+ }
68
+ lines.push(`${INDENT}${INDENT}# Uncomment to have the edge ask for user and password (HTTP Basic Auth) before a request reaches`, `${INDENT}${INDENT}# this machine. The password is stored in clear text: keep the file out of git then.`, `${INDENT}${INDENT}# auth:`, `${INDENT}${INDENT}# basic: user:password`);
69
+ });
70
+ return `${lines.join('\n')}\n`;
71
+ }
72
+ /**
73
+ * A service name as a key of the mapping: plain when it is a plain word YAML reads as a string, otherwise in double
74
+ * quotes (a JSON string is a valid double-quoted YAML scalar). `true`, `null`, `8080` or `my app` are quoted.
75
+ */
76
+ function yamlKey(name) {
77
+ return /^[A-Za-z_][A-Za-z0-9_-]*$/.test(name) && !/^(true|false|null|yes|no|on|off|y|n)$/i.test(name)
78
+ ? name
79
+ : JSON.stringify(name);
80
+ }
package/dist/config.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
2
3
  import { parseDocument } from 'yaml';
3
4
  import { INSPECTOR_DEFAULT_PORT, HOPWIRE_YAML_FILE, HOPWIRE_YAML_VERSION, isBasicCredentials, isPublicKeyHex, isReservableSubdomain, } from '@hopwire/protocol';
4
5
  import { HopwireError } from './errors.js';
6
+ import { defaultLogName } from './log-follow.js';
5
7
  import { printable } from './output.js';
6
8
  import { parseControlPlaneUrl, parseEdgeUrl, parseLocalTarget } from './urls.js';
7
9
  /** A hopwire.yaml that cannot be used. `path` is the offending field, null when the file as a whole is at fault. */
@@ -24,7 +26,7 @@ class Problem {
24
26
  }
25
27
  }
26
28
  const ROOT_KEYS = ['version', 'inspector', 'agent', 'capture', 'edge', 'controlPlane', 'p2p', 'services'];
27
- const SERVICE_KEYS = ['local', 'public', 'subdomain', 'auth'];
29
+ const SERVICE_KEYS = ['local', 'public', 'subdomain', 'auth', 'logs'];
28
30
  const LOCAL_RULE = 'must be an http URL on this machine without a path, for example http://127.0.0.1:3000; Hopwire only forwards to loopback addresses.';
29
31
  const SUBDOMAIN_RULE = '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.';
30
32
  /**
@@ -41,7 +43,7 @@ export async function loadConfig(file, named, shown = file) {
41
43
  if (code === 'ENOENT') {
42
44
  throw new HopwireError(named
43
45
  ? `The config file ${shown} does not exist; check the path given to --config.`
44
- : `There is no ${HOPWIRE_YAML_FILE} in this directory; create one (hopwire.example.yaml shows every field) or name a file with --config <path>.`);
46
+ : `There is no ${HOPWIRE_YAML_FILE} in this directory; create one with hopwire init, or name a file with --config <path>.`);
45
47
  }
46
48
  throw new HopwireError(`The config file ${shown} cannot be read (${code}); check that it is a readable file.`);
47
49
  }
@@ -143,11 +145,21 @@ function validate(value, ordered) {
143
145
  let allow = null;
144
146
  let team = false;
145
147
  let allowAgents = false;
148
+ let relay = false;
149
+ let shareLogs = false;
146
150
  if (root.p2p !== undefined) {
147
- const p2p = mapping(root.p2p, ['p2p'], ['share', 'allow', 'team', 'allowAgents'], 'p2p');
151
+ const p2p = mapping(root.p2p, ['p2p'], ['share', 'allow', 'team', 'allowAgents', 'relay', 'shareLogs'], 'p2p');
148
152
  share = boolean(p2p.share, ['p2p', 'share']);
153
+ shareLogs = boolean(p2p.shareLogs, ['p2p', 'shareLogs']);
154
+ if (shareLogs && !share) {
155
+ throw new Problem(['p2p', 'shareLogs'], 'needs p2p.share: true; it lets teammates who watch the shared log see the entries of the log files.');
156
+ }
149
157
  team = boolean(p2p.team, ['p2p', 'team']);
150
158
  allowAgents = boolean(p2p.allowAgents, ['p2p', 'allowAgents']);
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.');
162
+ }
151
163
  if (allowAgents && !share) {
152
164
  throw new Problem(['p2p', 'allowAgents'], 'needs p2p.share: true; it lets the coding agents of teammates who watch the shared log read it.');
153
165
  }
@@ -196,13 +208,18 @@ function validate(value, ordered) {
196
208
  if (edgeUrl === null && services.some((service) => service.public)) {
197
209
  throw new Problem(['edge', 'url'], 'is missing, and a service is public; add the URL of the edge, for example ws://127.0.0.1:8787 for a local edge.');
198
210
  }
211
+ if (shareLogs && services.every((service) => service.logs.length === 0)) {
212
+ throw new Problem(['p2p', 'shareLogs'], 'needs a service with logs; name the log files to share under services.<name>.logs.');
213
+ }
199
214
  const agent = root.agent === undefined ? null : boolean(root.agent, ['agent']);
200
215
  let captureWebSocket = true;
216
+ let logRequestId = false;
201
217
  if (root.capture !== undefined) {
202
- const capture = mapping(root.capture, ['capture'], ['websocket'], 'capture');
218
+ const capture = mapping(root.capture, ['capture'], ['websocket', 'logRequestId'], 'capture');
203
219
  if (capture.websocket !== undefined) {
204
220
  captureWebSocket = boolean(capture.websocket, ['capture', 'websocket']);
205
221
  }
222
+ logRequestId = boolean(capture.logRequestId, ['capture', 'logRequestId']);
206
223
  }
207
224
  return {
208
225
  inspectorPort,
@@ -212,8 +229,11 @@ function validate(value, ordered) {
212
229
  allow,
213
230
  team,
214
231
  allowAgents,
232
+ relay,
215
233
  agent,
216
234
  captureWebSocket,
235
+ logRequestId,
236
+ shareLogs,
217
237
  services,
218
238
  };
219
239
  }
@@ -278,7 +298,47 @@ function validateService(name, value) {
278
298
  basicAuth = auth.basic;
279
299
  }
280
300
  }
281
- return { name, local, public: boolean(service.public, [...path, 'public']), subdomain, basicAuth };
301
+ return {
302
+ name,
303
+ local,
304
+ public: boolean(service.public, [...path, 'public']),
305
+ subdomain,
306
+ basicAuth,
307
+ logs: validateLogs(service.logs, [...path, 'logs']),
308
+ };
309
+ }
310
+ const LOG_PATH_RULE = 'must be the path of a log file, relative to the folder of this file or absolute, with a * at most in the file name.';
311
+ /** services.<name>.logs: a list of paths, or of mappings with path and name. */
312
+ function validateLogs(value, at) {
313
+ if (value === undefined) {
314
+ return [];
315
+ }
316
+ if (!Array.isArray(value)) {
317
+ throw new Problem(at, 'must be a list of log files, each a path or a mapping with path and name.');
318
+ }
319
+ const logs = [];
320
+ for (const [index, item] of value.entries()) {
321
+ let file = item;
322
+ let name;
323
+ if (isMapping(item)) {
324
+ const log = mapping(item, [...at, index], ['path', 'name'], 'a log file');
325
+ file = log.path;
326
+ name = log.name;
327
+ }
328
+ if (typeof file !== 'string' || file === '' || printable(file) !== file || path.dirname(file).includes('*')) {
329
+ throw new Problem(isMapping(item) ? [...at, index, 'path'] : [...at, index], LOG_PATH_RULE);
330
+ }
331
+ if (name !== undefined &&
332
+ (typeof name !== 'string' || name === '' || name.length > 255 || printable(name) !== name)) {
333
+ throw new Problem([...at, index, 'name'], 'must be a name of 1 to 255 characters without control characters.');
334
+ }
335
+ const named = typeof name === 'string' ? name : defaultLogName(file);
336
+ if (logs.some((log) => log.name === named)) {
337
+ throw new Problem([...at, index], `is named ${printable(named)} like another log file of this service; give it a name of its own with name:.`);
338
+ }
339
+ logs.push({ path: file, name: named });
340
+ }
341
+ return logs;
282
342
  }
283
343
  function isMapping(value) {
284
344
  return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date);
@@ -24,6 +24,8 @@ const ACCOUNT_REFUSALS = [
24
24
  ];
25
25
  /** 403 codes of the keys of a team whose sentence the control plane writes and the CLI prints as it is. */
26
26
  const TEAM_REFUSALS = ['team_plan_required', 'organisation_suspended'];
27
+ /** 403 codes of a relay token whose sentence the control plane writes and the CLI prints as it is. */
28
+ const RELAY_REFUSALS = [...TEAM_REFUSALS, 'team_key_not_registered'];
27
29
  /** Largest list of team keys that is read: about 15,000 keys. */
28
30
  const MAX_TEAM_ANSWER_BYTES = 1024 * 1024;
29
31
  /** How long the control plane may take to answer. */
@@ -34,6 +36,17 @@ const MAX_ANSWER_BYTES = 64 * 1024;
34
36
  const RELEASE = /^\d{1,5}\.\d{1,5}\.\d{1,5}$/;
35
37
  /** Longest connect token that is taken; the edge refuses longer ones unseen. */
36
38
  const MAX_TOKEN_LENGTH = 4096;
39
+ /** A custom domain as the control plane names it: lower case, at least three labels, no IP literal (phase 14) */
40
+ const CUSTOM_HOST = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?){2,}$/;
41
+ const NUMERIC_TLD = /\.\d+$/;
42
+ /** The statuses of a custom domain the control plane reports */
43
+ const DOMAIN_STATUSES = [
44
+ 'pending_dns',
45
+ 'pending_certificate',
46
+ 'active',
47
+ 'failed',
48
+ 'offline_plan',
49
+ ];
37
50
  export function createControlPlaneClient(options) {
38
51
  const { where, request, failure, malformed } = connect(options);
39
52
  return {
@@ -56,6 +69,7 @@ export function createControlPlaneClient(options) {
56
69
  : null,
57
70
  plan: isPlanName(json.plan) ? json.plan : null,
58
71
  edgeUrl: edgeOf(json.edgeUrl),
72
+ customDomains: customDomainsOf(json.customDomains),
59
73
  };
60
74
  },
61
75
  async connectToken(subdomain, signal) {
@@ -95,6 +109,7 @@ export function createControlPlaneClient(options) {
95
109
  latestVersion: typeof json.latestCliVersion === 'string' && RELEASE.test(json.latestCliVersion)
96
110
  ? json.latestCliVersion
97
111
  : null,
112
+ domains: hostsOf(json.domains),
98
113
  };
99
114
  },
100
115
  async teamKeys(peerKey, signal) {
@@ -124,6 +139,32 @@ export function createControlPlaneClient(options) {
124
139
  keys: json.keys.map((key) => key.toLowerCase()),
125
140
  };
126
141
  },
142
+ async relayToken(peerKey, signal) {
143
+ const { status, json } = await request('POST', '/api/v1/relay-tokens', { peerKey }, signal);
144
+ const code = isRecord(json) && typeof json.error === 'string' ? json.error : null;
145
+ if (status === 403 && code !== null && RELAY_REFUSALS.includes(code)) {
146
+ throw new HopwireError(`${controlPlaneMessage(json) ?? `The control plane at ${where} refused a relay token (403)`} (${code})`);
147
+ }
148
+ if (status === 404) {
149
+ throw new HopwireError(`The control plane at ${where} offers no relay (404); run the command without --relay.`);
150
+ }
151
+ if (status !== 200) {
152
+ throw failure(status, 'a relay token');
153
+ }
154
+ const expiresIn = isRecord(json) ? json.expiresIn : null;
155
+ if (!isRecord(json) ||
156
+ typeof json.token !== 'string' ||
157
+ !/^[\x21-\x7e]+$/.test(json.token) ||
158
+ json.token.length > MAX_TOKEN_LENGTH ||
159
+ typeof expiresIn !== 'number' ||
160
+ !Number.isInteger(expiresIn) ||
161
+ expiresIn < 1) {
162
+ throw malformed('a relay token');
163
+ }
164
+ // A duration and not a time of day, so the clock of this machine does not matter; never above the
165
+ // lifetime of a connect token, which the edge holds every token to
166
+ return { token: json.token, expiresInMs: Math.min(expiresIn, 300) * 1000 };
167
+ },
127
168
  };
128
169
  }
129
170
  /** A device code as the control plane makes it */
@@ -356,3 +397,32 @@ function edgeOf(value) {
356
397
  const url = parseEdgeUrl(value.trim());
357
398
  return url instanceof URL ? url : null;
358
399
  }
400
+ /** The hosts of a connect token answer: the valid ones, at most 5; anything else is ignored. */
401
+ function hostsOf(value) {
402
+ if (!Array.isArray(value)) {
403
+ return [];
404
+ }
405
+ const hosts = value.filter((host) => typeof host === 'string' && isCustomHost(host));
406
+ return [...new Set(hosts)].slice(0, 5);
407
+ }
408
+ /** The custom domains of GET /api/v1/me: entries that are not a valid host with a known status are left out. */
409
+ function customDomainsOf(value) {
410
+ if (!Array.isArray(value)) {
411
+ return [];
412
+ }
413
+ const found = [];
414
+ for (const entry of value) {
415
+ if (isRecord(entry) &&
416
+ typeof entry.host === 'string' &&
417
+ isCustomHost(entry.host) &&
418
+ typeof entry.subdomain === 'string' &&
419
+ isSubdomain(entry.subdomain) &&
420
+ DOMAIN_STATUSES.includes(entry.status)) {
421
+ found.push({ host: entry.host, subdomain: entry.subdomain, status: entry.status });
422
+ }
423
+ }
424
+ return found;
425
+ }
426
+ function isCustomHost(host) {
427
+ return host.length <= 253 && CUSTOM_HOST.test(host) && !NUMERIC_TLD.test(host);
428
+ }