hopwire 0.1.8 → 0.1.9

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.
@@ -0,0 +1,329 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { access, readFile, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { isReservableSubdomain } from '@hopwire/protocol';
5
+ import { boundEdge, readAccount } from '../account.js';
6
+ import { renderConfig } from '../config-template.js';
7
+ import { isServiceName, parseConfig } from '../config.js';
8
+ import { HopwireError, UsageError, errorCode } from '../errors.js';
9
+ import { printable } from '../output.js';
10
+ import { parseLocalTarget } from '../urls.js';
11
+ /** Refusal of a target that exists; the file stays as it is. */
12
+ function exists(shown) {
13
+ return new HopwireError(`${shown} already exists; edit it, or remove it and run hopwire init again.`);
14
+ }
15
+ export const NO_TERMINAL = 'There is no terminal to ask on; pass the services with --service name=port and --yes, for example hopwire init --service web=3000 --yes';
16
+ const PUBLIC_NEEDS_LOGIN = 'Public URLs need an account: run hopwire login, then hopwire init again or set public: true in the file.';
17
+ export async function init(options) {
18
+ if (await present(options.file)) {
19
+ throw exists(options.shown);
20
+ }
21
+ const answers = options.flags === null ? await interview(options) : await fromFlags(options.flags, options.dataDir);
22
+ const text = renderConfig(answers);
23
+ // The parser of hopwire up decides; a refusal here is a fault of init and ends with its sentence
24
+ parseConfig(text, options.shown);
25
+ try {
26
+ // wx: a file that appeared while the questions were asked is not replaced
27
+ await writeFile(options.file, text, { flag: 'wx' });
28
+ }
29
+ catch (error) {
30
+ const code = errorCode(error);
31
+ if (code === 'EEXIST') {
32
+ throw exists(options.shown);
33
+ }
34
+ if (code === 'ENOENT') {
35
+ throw new HopwireError(`The directory of ${options.shown} does not exist; create it first.`);
36
+ }
37
+ throw new HopwireError(`${options.shown} cannot be written (${code}); check the permissions of its directory.`);
38
+ }
39
+ const names = answers.services.map((service) => printable(service.name));
40
+ options.print(`Wrote ${options.shown} (${names.length === 1 ? '1 service' : `${names.length} services`}: ${names.join(', ')})`);
41
+ if ((await (options.gitIgnores ?? gitIgnores)(options.file)) === false) {
42
+ options.print(`Git ${options.shown} is not ignored by git; add it to .gitignore before you put a password in auth.basic.`);
43
+ }
44
+ options.print(`Next hopwire up${options.named ? ` --config ${options.shown}` : ''}`);
45
+ }
46
+ async function present(file) {
47
+ try {
48
+ await access(file);
49
+ return true;
50
+ }
51
+ catch (error) {
52
+ if (errorCode(error) === 'ENOENT') {
53
+ return false;
54
+ }
55
+ throw new HopwireError(`${file} cannot be checked (${errorCode(error)}); check the permissions of its directory.`);
56
+ }
57
+ }
58
+ /** 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);
61
+ if (account === null) {
62
+ return 'logged-out';
63
+ }
64
+ const edgeUrl = await boundEdge(dataDir);
65
+ return edgeUrl === null ? 'no-edge' : { edgeUrl, controlPlaneUrl: account.controlPlaneUrl };
66
+ }
67
+ 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
+ // --- The flags ---
69
+ async function fromFlags(flags, dataDir) {
70
+ if (flags.services.length === 0) {
71
+ throw new UsageError('hopwire init --yes needs at least one --service name=port, for example --service web=3000');
72
+ }
73
+ const services = flags.services.map((value) => {
74
+ const separator = value.indexOf('=');
75
+ const name = separator < 0 ? '' : value.slice(0, separator);
76
+ if (separator < 0 || !isServiceName(name)) {
77
+ throw new UsageError('--service must be name=port or name=url, for example web=3000, with a name of 1 to 255 bytes without control characters');
78
+ }
79
+ const local = localTarget(value.slice(separator + 1));
80
+ if (local === null) {
81
+ 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
+ }
83
+ return { name, local, public: false, subdomain: null };
84
+ });
85
+ const byName = new Map();
86
+ for (const service of services) {
87
+ if (byName.has(service.name)) {
88
+ throw new UsageError(`--service ${printable(service.name)} is given twice; give each service its own name`);
89
+ }
90
+ byName.set(service.name, service);
91
+ }
92
+ for (const name of flags.public) {
93
+ const service = byName.get(name);
94
+ if (service === undefined) {
95
+ throw new UsageError(`--public ${printable(name)} names no service; name one given with --service`);
96
+ }
97
+ service.public = true;
98
+ }
99
+ const subdomains = new Set();
100
+ for (const value of flags.subdomains) {
101
+ const separator = value.indexOf('=');
102
+ const name = value.slice(0, Math.max(separator, 0));
103
+ const subdomain = value.slice(separator + 1);
104
+ const service = byName.get(name);
105
+ if (separator < 0 || service === undefined) {
106
+ throw new UsageError('--subdomain must be name=subdomain for a service given with --service and --public');
107
+ }
108
+ if (!service.public) {
109
+ throw new UsageError(`--subdomain ${printable(name)}=... only works together with --public ${printable(name)}`);
110
+ }
111
+ if (!isReservableSubdomain(subdomain)) {
112
+ throw new UsageError('--subdomain must name 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');
113
+ }
114
+ if (service.subdomain !== null || subdomains.has(subdomain)) {
115
+ throw new UsageError(`--subdomain is given twice for ${printable(name)} or for ${subdomain}; one subdomain serves one service`);
116
+ }
117
+ subdomains.add(subdomain);
118
+ service.subdomain = subdomain;
119
+ }
120
+ if (flags.team && !flags.share) {
121
+ throw new UsageError('--team only works together with --share');
122
+ }
123
+ if (flags.allowAgents && !flags.share) {
124
+ throw new UsageError('--allow-agents only works together with --share');
125
+ }
126
+ let edgeUrl = null;
127
+ let controlPlaneUrl = null;
128
+ if (flags.public.length > 0 || flags.team) {
129
+ const urls = await accountUrls(dataDir);
130
+ if (urls === 'logged-out') {
131
+ throw new HopwireError(flags.public.length > 0
132
+ ? '--public needs an account: run hopwire login first; nothing was written.'
133
+ : '--team needs an account in an organisation on the Team plan: run hopwire login first; nothing was written.');
134
+ }
135
+ if (flags.public.length > 0) {
136
+ if (urls === 'no-edge') {
137
+ throw new HopwireError(NO_EDGE);
138
+ }
139
+ edgeUrl = urls.edgeUrl;
140
+ controlPlaneUrl = urls.controlPlaneUrl;
141
+ }
142
+ }
143
+ return {
144
+ services,
145
+ edgeUrl,
146
+ controlPlaneUrl,
147
+ share: flags.share,
148
+ team: flags.team,
149
+ allowAgents: flags.allowAgents,
150
+ };
151
+ }
152
+ /** A port (`3000` becomes http://127.0.0.1:3000) or a loopback http URL without a path; null for anything else. */
153
+ export function localTarget(value) {
154
+ const trimmed = value.trim();
155
+ if (/^\d{1,5}$/.test(trimmed)) {
156
+ const port = Number(trimmed);
157
+ return port >= 1 && port <= 65535 ? new URL(`http://127.0.0.1:${port}`) : null;
158
+ }
159
+ return parseLocalTarget(trimmed);
160
+ }
161
+ // --- The questions ---
162
+ async function interview(options) {
163
+ const { ask, say } = options;
164
+ if (ask === undefined) {
165
+ throw new UsageError(NO_TERMINAL);
166
+ }
167
+ const question = async (text, fallback) => {
168
+ const answer = (await ask(fallback === null ? `${text} ` : `${text} [${fallback}] `)).trim();
169
+ return answer === '' && fallback !== null ? fallback : answer;
170
+ };
171
+ const yesNo = async (text) => {
172
+ for (;;) {
173
+ const answer = (await ask(`${text} [y/N] `)).trim().toLowerCase();
174
+ if (answer === '' || answer === 'n' || answer === 'no') {
175
+ return false;
176
+ }
177
+ if (answer === 'y' || answer === 'yes') {
178
+ return true;
179
+ }
180
+ say('Answer y or n.');
181
+ }
182
+ };
183
+ // Read once, before the first question: whether a service can be public at all
184
+ const urls = await accountUrls(options.dataDir);
185
+ const detected = await detectPort(options.cwd);
186
+ const services = [];
187
+ let toldAboutPublic = false;
188
+ do {
189
+ let name;
190
+ for (;;) {
191
+ name = await question('Name of the service', services.some((s) => s.name === 'web') ? null : 'web');
192
+ if (!isServiceName(name)) {
193
+ say('A service name is 1 to 255 bytes without control characters.');
194
+ }
195
+ else if (services.some((service) => service.name === name)) {
196
+ say(`There is a service ${printable(name)} already; give each service its own name.`);
197
+ }
198
+ else {
199
+ break;
200
+ }
201
+ }
202
+ let local;
203
+ for (;;) {
204
+ const answer = await question('Port or URL of the service on this machine', services.length === 0 && detected !== null ? String(detected) : null);
205
+ local = localTarget(answer);
206
+ if (local !== null) {
207
+ break;
208
+ }
209
+ 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
+ }
211
+ const service = { name, local, public: false, subdomain: null };
212
+ if (typeof urls === 'object') {
213
+ service.public = await yesNo('Serve it under a public URL?');
214
+ if (service.public) {
215
+ for (;;) {
216
+ const subdomain = await question('Subdomain (empty: the fixed URL of your organisation)', '');
217
+ if (subdomain === '') {
218
+ break;
219
+ }
220
+ if (!isReservableSubdomain(subdomain)) {
221
+ say('A subdomain is 3 to 63 lowercase letters, digits or hyphens, does not start or end with a hyphen, does not start with t- and is not a reserved name such as www or api.');
222
+ }
223
+ else if (services.some((other) => other.subdomain === subdomain)) {
224
+ say(`${subdomain} serves another service already; give each its own.`);
225
+ }
226
+ else {
227
+ service.subdomain = subdomain;
228
+ break;
229
+ }
230
+ }
231
+ }
232
+ }
233
+ else if (!toldAboutPublic) {
234
+ say(urls === 'logged-out' ? PUBLIC_NEEDS_LOGIN : NO_EDGE);
235
+ toldAboutPublic = true;
236
+ }
237
+ services.push(service);
238
+ } while (await yesNo('Another service?'));
239
+ const share = await yesNo('Share with teammates over P2P (hopwire watch, hopwire connect)?');
240
+ let team = false;
241
+ let allowAgents = false;
242
+ if (share) {
243
+ if (urls !== 'logged-out') {
244
+ team = await yesNo("Only machines of your organisation's members (Team plan)?");
245
+ }
246
+ say("What a teammate's coding agent reads goes to its model provider.");
247
+ allowAgents = await yesNo("Let teammates' coding agents read what is captured?");
248
+ }
249
+ const anyPublic = services.some((service) => service.public);
250
+ return {
251
+ services,
252
+ edgeUrl: anyPublic && typeof urls === 'object' ? urls.edgeUrl : null,
253
+ controlPlaneUrl: anyPublic && typeof urls === 'object' ? urls.controlPlaneUrl : null,
254
+ share,
255
+ team,
256
+ allowAgents,
257
+ };
258
+ }
259
+ // --- The port suggestion ---
260
+ /**
261
+ * The port suggested for the first service, never used with --yes: PORT=<n> in .env of the working directory (only
262
+ * that key is looked at), else an explicit port in the dev or start script of package.json. No port is probed.
263
+ */
264
+ export async function detectPort(cwd) {
265
+ const env = await readText(path.join(cwd, '.env'));
266
+ if (env !== null) {
267
+ const match = /^[ \t]*(?:export[ \t]+)?PORT[ \t]*=[ \t]*["']?(\d{1,5})["']?[ \t]*(?:#.*)?$/m.exec(env);
268
+ const port = validPort(match?.[1]);
269
+ if (port !== null) {
270
+ return port;
271
+ }
272
+ }
273
+ const manifest = await readText(path.join(cwd, 'package.json'));
274
+ if (manifest !== null) {
275
+ let scripts;
276
+ try {
277
+ scripts = JSON.parse(manifest).scripts;
278
+ }
279
+ catch {
280
+ return null;
281
+ }
282
+ if (typeof scripts === 'object' && scripts !== null) {
283
+ for (const key of ['dev', 'start']) {
284
+ const script = scripts[key];
285
+ if (typeof script !== 'string') {
286
+ continue;
287
+ }
288
+ const match = /(?:--port[= ]|(?:^|\s)-p\s+|(?:^|\s)PORT=)(\d{1,5})\b/.exec(script);
289
+ const port = validPort(match?.[1]);
290
+ if (port !== null) {
291
+ return port;
292
+ }
293
+ }
294
+ }
295
+ }
296
+ return null;
297
+ }
298
+ function validPort(value) {
299
+ const port = Number(value);
300
+ return value !== undefined && Number.isInteger(port) && port >= 1 && port <= 65535 ? port : null;
301
+ }
302
+ async function readText(file) {
303
+ try {
304
+ return await readFile(file, 'utf8');
305
+ }
306
+ catch {
307
+ return null;
308
+ }
309
+ }
310
+ // --- git ---
311
+ /**
312
+ * `git check-ignore -q`: exit 0 when the file is ignored, 1 when it is not; anything else (no work tree, no git) is
313
+ * null and prints no line. Runs locally; git contacts nothing for it.
314
+ */
315
+ export function gitIgnores(file) {
316
+ return new Promise((resolve) => {
317
+ execFile('git', ['check-ignore', '-q', '--', path.basename(file)], { cwd: path.dirname(file), timeout: 5000, windowsHide: true }, (error) => {
318
+ if (error === null) {
319
+ resolve(true);
320
+ }
321
+ else if (typeof error.code === 'number' && error.code === 1) {
322
+ resolve(false);
323
+ }
324
+ else {
325
+ resolve(null);
326
+ }
327
+ });
328
+ });
329
+ }
@@ -1,7 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { LOCAL_ENTRY_DEFAULT_PORT, RANDOM_SUBDOMAIN_BYTES, randomSubdomain } from '@hopwire/protocol';
3
3
  import { HopwireError } from '../errors.js';
4
- import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, AGENTS_ALLOWED_LINE, agentLine, agentOffLine, formatExchange, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, } from '../output.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
5
  import { startServing } from '../serve.js';
6
6
  import { formatBridgeEvent } from './http.js';
7
7
  /**
@@ -45,6 +45,8 @@ export async function startUp(options) {
45
45
  allow: config.allow ?? [],
46
46
  team: options.team,
47
47
  onTeamEvent: (event, organisation) => options.print(formatTeamEvent(event, organisation)),
48
+ relay: options.relay,
49
+ onRelayEvent: (event) => options.print(formatRelayEvent(event)),
48
50
  bootstrap: options.bootstrap,
49
51
  inspectorFiles: options.inspectorFiles,
50
52
  agent: options.agent,
@@ -85,6 +87,9 @@ export async function startUp(options) {
85
87
  if (serving.peerKey !== null) {
86
88
  options.print(`Peer key ${serving.peerKey}`);
87
89
  options.print(shareNotice(access, 'p2p.allow in hopwire.yaml'));
90
+ if (serving.relay !== null) {
91
+ options.print(relayLine(serving.relay.edgeUrl, serving.relay.problem));
92
+ }
88
93
  if (config.allowAgents) {
89
94
  options.print(AGENTS_ALLOWED_LINE);
90
95
  }
@@ -113,6 +118,7 @@ export async function startUp(options) {
113
118
  logKey: serving.logKey,
114
119
  allowed: access,
115
120
  restrictWith: 'p2p.allow in hopwire.yaml',
121
+ relay: serving.relay !== null,
116
122
  },
117
123
  inspector: serving.inspectorUrl !== null,
118
124
  widenWith: { share: 'p2p.share: true in hopwire.yaml', public: 'public: true on a service' },
@@ -6,7 +6,7 @@ import { agentsOnly, createInspectorApi } from '../inspector-api.js';
6
6
  import { startInspectorServer } from '../inspector-server.js';
7
7
  import { createInterceptor } from '../interceptor.js';
8
8
  import { REMOTE_LOG_BUDGET_BYTES } from '../log.js';
9
- import { MODE_P2P, MODE_P2P_TEAM, formatExchange, printable, shortKey, watchAgentLine, watchGuide } from '../output.js';
9
+ import { MODE_P2P, MODE_P2P_RELAYED, MODE_P2P_TEAM, formatExchange, printable, relayedLine, shortKey, watchAgentLine, watchGuide, } from '../output.js';
10
10
  import { INSPECTOR_FILES } from '../serve.js';
11
11
  import { Supervisor, unlessAborted } from '../supervisor.js';
12
12
  /**
@@ -49,15 +49,23 @@ export async function startWatch(options) {
49
49
  ? null
50
50
  : printable((await options.team.teamKeys(peerKey, options.signal)).organisation.name);
51
51
  proceed();
52
+ let relay;
53
+ if (options.relay !== undefined) {
54
+ // Loaded only here: without --relay nothing opens a relay socket
55
+ const { relaySetup } = await import('../relay.js');
56
+ relay = relaySetup(options.relay, peerKey);
57
+ }
52
58
  const { JoinError, joinLog } = await import('../p2p.js');
53
59
  const joined = await joinLog({
54
60
  identity,
55
61
  log: remote,
56
62
  bootstrap: options.bootstrap,
57
63
  signal: options.signal,
64
+ relay,
65
+ onRelayLost: (problem, limit) => options.print(limit ? `Limit ${problem}` : `Relay ${problem}; trying again`),
58
66
  }).catch((error) => {
59
67
  throw error instanceof JoinError
60
- ? joinError(error.code, logKey, peerKey, options.team !== undefined)
68
+ ? joinError(error.code, logKey, peerKey, options.team !== undefined, error.relayProblem)
61
69
  : error;
62
70
  });
63
71
  supervisor.add('p2p', () => joined.close());
@@ -131,12 +139,15 @@ export async function startWatch(options) {
131
139
  const stopPrinting = remote.subscribe((_index, exchange) => options.print(formatExchange(exchange)));
132
140
  supervisor.add('servers', async () => stopPrinting());
133
141
  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);
142
+ options.print(joined.relayed ? MODE_P2P_RELAYED : organisation === null ? MODE_P2P : MODE_P2P_TEAM);
135
143
  options.print(`Watching ${logKey} (${remote.length} exchanges)`);
136
144
  options.print(`Peer key ${peerKey}`);
137
145
  if (organisation !== null) {
138
146
  options.print(`Team ${organisation}: this machine's key is registered there`);
139
147
  }
148
+ if (joined.relayed && options.relay !== undefined) {
149
+ options.print(relayedLine(options.relay.edgeUrl));
150
+ }
140
151
  options.print(options.replayTarget === null
141
152
  ? 'Replay off; start hopwire watch with --replay-target <url> to replay to a local service'
142
153
  : `Replay to ${options.replayTarget.origin}`);
@@ -158,11 +169,16 @@ export async function startWatch(options) {
158
169
  }
159
170
  }
160
171
  /** One sentence for a log that could not be joined: what happened and what to do. */
161
- function joinError(code, logKey, ownKey, team) {
172
+ function joinError(code, logKey, ownKey, team, relayProblem = null) {
173
+ if (relayProblem !== null) {
174
+ return new HopwireError(code === 'not_found'
175
+ ? `Nobody shares the log ${shortKey(logKey)} on the DHT, and the relay did not connect either: ${relayProblem}.`
176
+ : `The sharer of the log ${shortKey(logKey)} was found but no direct connection came about, and the relay did not connect either: ${relayProblem}.`);
177
+ }
162
178
  if (code === 'not_found') {
163
179
  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
180
  }
165
181
  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.`);
182
+ ? `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}.`
183
+ : `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
184
  }
@@ -0,0 +1,70 @@
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
+ '',
27
+ ];
28
+ if (answers.edgeUrl !== null && answers.controlPlaneUrl !== null) {
29
+ 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}`, '');
30
+ }
31
+ else {
32
+ 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', '');
33
+ }
34
+ 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)}`);
35
+ if (answers.team) {
36
+ 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`);
37
+ }
38
+ else {
39
+ 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
+ }
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:');
42
+ answers.services.forEach((service, index) => {
43
+ if (index > 0) {
44
+ lines.push('');
45
+ }
46
+ lines.push(`${INDENT}${yamlKey(service.name)}:`, `${INDENT}${INDENT}# An http URL on this machine without a path.`);
47
+ lines.push(`${INDENT}${INDENT}local: ${service.local.origin}`);
48
+ if (!service.public) {
49
+ return;
50
+ }
51
+ lines.push(`${INDENT}${INDENT}public: true`);
52
+ if (service.subdomain !== null) {
53
+ lines.push(`${INDENT}${INDENT}# Reserved by your organisation in the control plane.`, `${INDENT}${INDENT}subdomain: ${service.subdomain}`);
54
+ }
55
+ else {
56
+ lines.push(`${INDENT}${INDENT}# Without a subdomain the fixed URL of your organisation is served. A subdomain it reserved:`, `${INDENT}${INDENT}# subdomain: my-app`);
57
+ }
58
+ 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`);
59
+ });
60
+ return `${lines.join('\n')}\n`;
61
+ }
62
+ /**
63
+ * A service name as a key of the mapping: plain when it is a plain word YAML reads as a string, otherwise in double
64
+ * quotes (a JSON string is a valid double-quoted YAML scalar). `true`, `null`, `8080` or `my app` are quoted.
65
+ */
66
+ function yamlKey(name) {
67
+ return /^[A-Za-z_][A-Za-z0-9_-]*$/.test(name) && !/^(true|false|null|yes|no|on|off|y|n)$/i.test(name)
68
+ ? name
69
+ : JSON.stringify(name);
70
+ }
package/dist/config.js CHANGED
@@ -41,7 +41,7 @@ export async function loadConfig(file, named, shown = file) {
41
41
  if (code === 'ENOENT') {
42
42
  throw new HopwireError(named
43
43
  ? `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>.`);
44
+ : `There is no ${HOPWIRE_YAML_FILE} in this directory; create one with hopwire init, or name a file with --config <path>.`);
45
45
  }
46
46
  throw new HopwireError(`The config file ${shown} cannot be read (${code}); check that it is a readable file.`);
47
47
  }
@@ -143,11 +143,16 @@ function validate(value, ordered) {
143
143
  let allow = null;
144
144
  let team = false;
145
145
  let allowAgents = false;
146
+ let relay = false;
146
147
  if (root.p2p !== undefined) {
147
- const p2p = mapping(root.p2p, ['p2p'], ['share', 'allow', 'team', 'allowAgents'], 'p2p');
148
+ const p2p = mapping(root.p2p, ['p2p'], ['share', 'allow', 'team', 'allowAgents', 'relay'], 'p2p');
148
149
  share = boolean(p2p.share, ['p2p', 'share']);
149
150
  team = boolean(p2p.team, ['p2p', 'team']);
150
151
  allowAgents = boolean(p2p.allowAgents, ['p2p', 'allowAgents']);
152
+ relay = boolean(p2p.relay, ['p2p', 'relay']);
153
+ if (relay && !team) {
154
+ throw new Problem(['p2p', 'relay'], 'needs p2p.team: true; the relay of the edge (Team plan) only pairs machines of one organisation.');
155
+ }
151
156
  if (allowAgents && !share) {
152
157
  throw new Problem(['p2p', 'allowAgents'], 'needs p2p.share: true; it lets the coding agents of teammates who watch the shared log read it.');
153
158
  }
@@ -212,6 +217,7 @@ function validate(value, ordered) {
212
217
  allow,
213
218
  team,
214
219
  allowAgents,
220
+ relay,
215
221
  agent,
216
222
  captureWebSocket,
217
223
  services,
@@ -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. */
@@ -124,6 +126,32 @@ export function createControlPlaneClient(options) {
124
126
  keys: json.keys.map((key) => key.toLowerCase()),
125
127
  };
126
128
  },
129
+ async relayToken(peerKey, signal) {
130
+ const { status, json } = await request('POST', '/api/v1/relay-tokens', { peerKey }, signal);
131
+ const code = isRecord(json) && typeof json.error === 'string' ? json.error : null;
132
+ if (status === 403 && code !== null && RELAY_REFUSALS.includes(code)) {
133
+ throw new HopwireError(`${controlPlaneMessage(json) ?? `The control plane at ${where} refused a relay token (403)`} (${code})`);
134
+ }
135
+ if (status === 404) {
136
+ throw new HopwireError(`The control plane at ${where} offers no relay (404); run the command without --relay.`);
137
+ }
138
+ if (status !== 200) {
139
+ throw failure(status, 'a relay token');
140
+ }
141
+ const expiresIn = isRecord(json) ? json.expiresIn : null;
142
+ if (!isRecord(json) ||
143
+ typeof json.token !== 'string' ||
144
+ !/^[\x21-\x7e]+$/.test(json.token) ||
145
+ json.token.length > MAX_TOKEN_LENGTH ||
146
+ typeof expiresIn !== 'number' ||
147
+ !Number.isInteger(expiresIn) ||
148
+ expiresIn < 1) {
149
+ throw malformed('a relay token');
150
+ }
151
+ // A duration and not a time of day, so the clock of this machine does not matter; never above the
152
+ // lifetime of a connect token, which the edge holds every token to
153
+ return { token: json.token, expiresInMs: Math.min(expiresIn, 300) * 1000 };
154
+ },
127
155
  };
128
156
  }
129
157
  /** A device code as the control plane makes it */
package/dist/main.js CHANGED
@@ -20,6 +20,7 @@ export async function main(proc) {
20
20
  env: proc.env,
21
21
  signal,
22
22
  promptSecret: proc.promptSecret,
23
+ promptLine: proc.promptLine,
23
24
  openBrowser: proc.openBrowser,
24
25
  input: proc.input,
25
26
  });
package/dist/output.js CHANGED
@@ -9,6 +9,34 @@ export const MODE_P2P = `Mode private (direct P2P: ${PRIVATE_CLAIM})`;
9
9
  * let in comes from the control plane of the user's account. The traffic still passes no server.
10
10
  */
11
11
  export const MODE_P2P_TEAM = 'Mode private (direct P2P with your team only: end-to-end encrypted, your traffic passes no server; the control plane of your account names the keys of the team)';
12
+ /**
13
+ * The mode line once a connection goes through the relay (--relay, Team plan, spec decision 136): neither "no account,
14
+ * no servers of ours" nor "your traffic passes no server" is said of it.
15
+ */
16
+ export const MODE_P2P_RELAYED = 'Mode private, relayed (P2P with your team through the relay of the Hopwire edge: end-to-end encrypted, the edge passes on bytes it cannot read; the control plane of your account names the keys of the team)';
17
+ /** The line of a sharer with --relay: what the relay is for and what the edge sees of it. */
18
+ export function relayLine(edgeUrl, problem) {
19
+ return problem === null
20
+ ? `Relay on: teammates without a direct connection reach this machine through the edge at ${edgeUrl.origin}; the edge sees addresses, your organisation, keys and byte counts, never content`
21
+ : `Relay not connected yet (${problem}); trying again, direct P2P works meanwhile`;
22
+ }
23
+ /** The line of watch or connect when the connection came through the relay. */
24
+ export function relayedLine(edgeUrl) {
25
+ return `Relay through the edge at ${edgeUrl.origin}: no direct connection came about; the edge sees addresses, your organisation, keys and byte counts, never content`;
26
+ }
27
+ /** One line for a change of the relay of a sharer; null for one that is not said. */
28
+ export function formatRelayEvent(event) {
29
+ switch (event.type) {
30
+ case 'ready':
31
+ return 'Relay connected to the edge';
32
+ case 'lost':
33
+ return `Relay ${event.problem}; trying again, direct P2P keeps working`;
34
+ case 'relayed':
35
+ return MODE_P2P_RELAYED;
36
+ case 'off':
37
+ return `Relay off: ${event.problem}`;
38
+ }
39
+ }
12
40
  /** First line of a tunnel with a public URL. Nothing of the private claim applies to it. */
13
41
  export const MODE_PUBLIC = 'Mode public (public URL through the edge; needs a token, requests pass through the edge)';
14
42
  /** First line of a tunnel that is public and shared with teammates at once. */
@@ -179,7 +207,7 @@ export function tunnelGuide(guide) {
179
207
  const [first] = services;
180
208
  const service = several && first !== undefined ? ` --service ${first.name}` : '';
181
209
  const team = share.allowed !== null && typeof share.allowed !== 'number' ? share.allowed.team : null;
182
- const flag = team === null ? '' : ' --team';
210
+ const flag = team === null ? '' : share.relay === true ? ' --team --relay' : ' --team';
183
211
  lines.push(' Send a teammate one or both keys, over a channel you trust:', ' The peer key, to call your service from their machine. They run', ` hopwire connect ${share.peerKey} --port 4141${service}${flag}`, ` and send requests to http://127.0.0.1:4141 (any free port works${several ? `; --service is one of ${services.map((entry) => entry.name).join(', ')}` : ''}).`, ' The log key, to watch this traffic live and replay it to their own service. They run', ` hopwire watch ${share.logKey} --replay-target http://127.0.0.1:3000${flag}`, ' with the address of the service on their machine.');
184
212
  if (team !== null) {
185
213
  lines.push(` Only machines of the members of ${printable(team)} get in. A teammate runs "hopwire login" in that organisation once; --team then registers their machine.`, ' A machine should no longer get in? Revoke its API token on the API tokens page, or remove the member from the team: it is cut off within about a minute.');