hopwire 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +8 -0
- package/README.md +29 -2
- package/dist/account.js +168 -0
- package/dist/agent/redact.js +101 -0
- package/dist/agent/summary.js +32 -0
- package/dist/agent-socket.js +93 -0
- package/dist/bin.js +22 -0
- package/dist/body-capture.js +28 -0
- package/dist/browser.js +42 -0
- package/dist/cli.js +674 -0
- package/dist/commands/connect.js +221 -0
- package/dist/commands/doctor.js +107 -0
- package/dist/commands/http.js +108 -0
- package/dist/commands/login.js +133 -0
- package/dist/commands/mcp.js +69 -0
- package/dist/commands/rotate.js +57 -0
- package/dist/commands/up.js +149 -0
- package/dist/commands/watch.js +146 -0
- package/dist/config.js +302 -0
- package/dist/control-plane-client.js +300 -0
- package/dist/data-dir-holder.js +178 -0
- package/dist/edge-bridge.js +1031 -0
- package/dist/errors.js +53 -0
- package/dist/identity.js +134 -0
- package/dist/inspector/THIRD-PARTY-NOTICES.txt +330 -0
- package/dist/inspector/assets/index-BvwyMIFs.css +2 -0
- package/dist/inspector/assets/index-Ctrz3UJp.js +2 -0
- package/dist/inspector/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/inspector/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
- package/dist/inspector/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/inspector/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
- package/dist/inspector/assets/space-grotesk-latin-400-normal-CJ-V5oYT.woff2 +0 -0
- package/dist/inspector/assets/space-grotesk-latin-500-normal-lFbtlQH6.woff2 +0 -0
- package/dist/inspector/assets/space-grotesk-latin-ext-400-normal-CfP_5XZW.woff2 +0 -0
- package/dist/inspector/assets/space-grotesk-latin-ext-500-normal-DUe3BAxM.woff2 +0 -0
- package/dist/inspector/favicon.svg +1 -0
- package/dist/inspector/index.html +16 -0
- package/dist/inspector-api.js +508 -0
- package/dist/inspector-server.js +150 -0
- package/dist/interceptor.js +480 -0
- package/dist/log.js +393 -0
- package/dist/main.js +37 -0
- package/dist/mcp/body.js +134 -0
- package/dist/mcp/client.js +169 -0
- package/dist/mcp/jsonrpc.js +170 -0
- package/dist/mcp/tools.js +715 -0
- package/dist/output.js +249 -0
- package/dist/p2p-stream.js +226 -0
- package/dist/p2p.js +389 -0
- package/dist/prompt.js +62 -0
- package/dist/proxy-server.js +252 -0
- package/dist/serve.js +234 -0
- package/dist/style.js +60 -0
- package/dist/supervisor.js +146 -0
- package/dist/team-keys.js +129 -0
- package/dist/update-notice.js +67 -0
- package/dist/urls.js +45 -0
- package/dist/websocket.js +99 -0
- package/node_modules/@hopwire/protocol/LICENSE +201 -0
- package/node_modules/@hopwire/protocol/NOTICE +8 -0
- package/node_modules/@hopwire/protocol/dist/basic-auth.d.ts +9 -0
- package/node_modules/@hopwire/protocol/dist/basic-auth.js +21 -0
- package/node_modules/@hopwire/protocol/dist/constants.d.ts +91 -0
- package/node_modules/@hopwire/protocol/dist/constants.js +89 -0
- package/node_modules/@hopwire/protocol/dist/exchange.d.ts +54 -0
- package/node_modules/@hopwire/protocol/dist/exchange.js +71 -0
- package/node_modules/@hopwire/protocol/dist/frames.d.ts +177 -0
- package/node_modules/@hopwire/protocol/dist/frames.js +191 -0
- package/node_modules/@hopwire/protocol/dist/headers.d.ts +20 -0
- package/node_modules/@hopwire/protocol/dist/headers.js +58 -0
- package/node_modules/@hopwire/protocol/dist/index.d.ts +10 -0
- package/node_modules/@hopwire/protocol/dist/index.js +10 -0
- package/node_modules/@hopwire/protocol/dist/inspector.d.ts +46 -0
- package/node_modules/@hopwire/protocol/dist/inspector.js +42 -0
- package/node_modules/@hopwire/protocol/dist/p2p.d.ts +52 -0
- package/node_modules/@hopwire/protocol/dist/p2p.js +119 -0
- package/node_modules/@hopwire/protocol/dist/plan.d.ts +104 -0
- package/node_modules/@hopwire/protocol/dist/plan.js +180 -0
- package/node_modules/@hopwire/protocol/dist/subdomain.d.ts +10 -0
- package/node_modules/@hopwire/protocol/dist/subdomain.js +30 -0
- package/node_modules/@hopwire/protocol/dist/websocket.d.ts +70 -0
- package/node_modules/@hopwire/protocol/dist/websocket.js +113 -0
- package/node_modules/@hopwire/protocol/package.json +13 -0
- package/package.json +38 -5
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { once } from 'node:events';
|
|
2
|
+
import net, {} from 'node:net';
|
|
3
|
+
import { HopwireError, listenError } from '../errors.js';
|
|
4
|
+
import { loadOrCreateIdentity } from '../identity.js';
|
|
5
|
+
import { MODE_P2P, MODE_P2P_TEAM, connectGuide, printable, shortKey } from '../output.js';
|
|
6
|
+
import { Supervisor, unlessAborted } from '../supervisor.js';
|
|
7
|
+
/**
|
|
8
|
+
* `hopwire connect <peer-key> --port <p>`: a loopback listener whose every TCP connection becomes one end-to-end
|
|
9
|
+
* encrypted HyperDHT stream into the teammate's interceptor. A first stream is opened before the listener, so a
|
|
10
|
+
* wrong key, a refusal or a failed hole punch is reported at once instead of on the first request.
|
|
11
|
+
*/
|
|
12
|
+
export async function startConnect(options) {
|
|
13
|
+
options.signal?.throwIfAborted();
|
|
14
|
+
const identity = await loadOrCreateIdentity(options.dataDir);
|
|
15
|
+
const ownKey = identity.publicKey.toString('hex');
|
|
16
|
+
let organisation = null;
|
|
17
|
+
if (options.team !== undefined) {
|
|
18
|
+
// Before any connection to the peer: the sharer asks for the list when a key knocks that it does not know
|
|
19
|
+
const team = await options.team.teamKeys(ownKey, options.signal);
|
|
20
|
+
organisation = printable(team.organisation.name);
|
|
21
|
+
if (!team.keys.includes(options.peerKey)) {
|
|
22
|
+
throw new HopwireError(`No member of ${organisation} has registered the key ${shortKey(options.peerKey)}; check the key, and that your teammate shares with --team (or p2p.team in hopwire.yaml) from an account in that organisation. Without --team this command connects to any key.`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const { PeerConnectError, createPeerConnector } = await import('../p2p.js');
|
|
26
|
+
options.signal?.throwIfAborted();
|
|
27
|
+
const connector = createPeerConnector({
|
|
28
|
+
identity,
|
|
29
|
+
peerKey: options.peerKey,
|
|
30
|
+
service: options.service,
|
|
31
|
+
bootstrap: options.bootstrap,
|
|
32
|
+
});
|
|
33
|
+
// Closed in the order of every command: the listener and its connections, then the DHT node
|
|
34
|
+
const supervisor = new Supervisor();
|
|
35
|
+
supervisor.add('p2p', () => connector.close());
|
|
36
|
+
try {
|
|
37
|
+
try {
|
|
38
|
+
// A start that is stopped does not wait for the peer: closing the connector ends the stream
|
|
39
|
+
const probe = await unlessAborted(connector.open(), options.signal);
|
|
40
|
+
probe.destroy();
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
throw error instanceof PeerConnectError ? connectError(error.code, options, ownKey) : error;
|
|
44
|
+
}
|
|
45
|
+
const clients = new Set();
|
|
46
|
+
/** Hosts whose refusal was said already: one line each, and no more than a few */
|
|
47
|
+
const refused = new Set();
|
|
48
|
+
const server = net.createServer({ allowHalfOpen: true }, (client) => {
|
|
49
|
+
clients.add(client);
|
|
50
|
+
client.once('close', () => clients.delete(client));
|
|
51
|
+
const port = server.address().port;
|
|
52
|
+
admit(client, answeredHosts(port, options.allowHosts ?? []), () => bridge(client, connector, (error) => {
|
|
53
|
+
// The client only sees a closed connection; the reason is said here
|
|
54
|
+
const code = error instanceof PeerConnectError ? error.code : 'UNKNOWN';
|
|
55
|
+
options.print(connectError(code, options, ownKey).message);
|
|
56
|
+
}), (host) => {
|
|
57
|
+
const shown = printableHost(host);
|
|
58
|
+
if (!refused.has(shown) && refused.size < REFUSALS_SAID) {
|
|
59
|
+
refused.add(shown);
|
|
60
|
+
options.print(`Refused a request for the host ${shown}: this port only answers 127.0.0.1:${port} and localhost:${port}. If you sent it yourself, start hopwire connect with --allow-host ${shown}.`);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
server.listen(options.port, '127.0.0.1');
|
|
65
|
+
try {
|
|
66
|
+
await once(server, 'listening');
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
throw listenError(error, options.port, 'local end of the tunnel', '--port <port>');
|
|
70
|
+
}
|
|
71
|
+
supervisor.add('servers', async () => {
|
|
72
|
+
server.close();
|
|
73
|
+
for (const client of clients) {
|
|
74
|
+
client.destroy();
|
|
75
|
+
}
|
|
76
|
+
await once(server, 'close');
|
|
77
|
+
});
|
|
78
|
+
// Stopped at the last step: nothing is reported as running
|
|
79
|
+
options.signal?.throwIfAborted();
|
|
80
|
+
const url = `http://127.0.0.1:${server.address().port}`;
|
|
81
|
+
options.print(organisation === null ? MODE_P2P : MODE_P2P_TEAM);
|
|
82
|
+
options.print(`Forwarding ${url} -> peer ${options.peerKey}${options.service === null ? '' : ` (service ${options.service})`}`);
|
|
83
|
+
options.print(`Peer key ${ownKey}`);
|
|
84
|
+
if (organisation !== null) {
|
|
85
|
+
options.print(`Team ${organisation}: the peer is a machine of a member, and this machine's key is registered there`);
|
|
86
|
+
}
|
|
87
|
+
// What reaches the peer is recorded there (spec decision 112): said before anything is sent
|
|
88
|
+
options.print(CONNECT_RECORDING_NOTICE);
|
|
89
|
+
for (const line of connectGuide(url)) {
|
|
90
|
+
options.print(line);
|
|
91
|
+
}
|
|
92
|
+
return { kind: 'connect', url, peerKey: ownKey, close: supervisor.close };
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
await supervisor.close().catch(() => { });
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** The line `hopwire connect` prints: the peer records what is sent to its service (spec decision 112). */
|
|
100
|
+
export const CONNECT_RECORDING_NOTICE = 'Notice The peer records everything you send through this connection in its traffic log, headers, cookies, form fields and passwords included, and can share that log with others.';
|
|
101
|
+
/** The head of a request is read up to this size to find its Host; the teammate's side takes no larger one */
|
|
102
|
+
const REQUEST_HEAD_MAX_BYTES = 64 * 1024;
|
|
103
|
+
/** Refused hosts that get a line of their own per run */
|
|
104
|
+
const REFUSALS_SAID = 5;
|
|
105
|
+
/** The Host values the listener on `port` answers: its loopback names, and what --allow-host named. */
|
|
106
|
+
function answeredHosts(port, allowHosts) {
|
|
107
|
+
const hosts = new Set();
|
|
108
|
+
for (const name of ['127.0.0.1', 'localhost', '[::1]', ...allowHosts]) {
|
|
109
|
+
hosts.add(name);
|
|
110
|
+
if (!/:\d+$/.test(name)) {
|
|
111
|
+
hosts.add(`${name}:${port}`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (port !== 80) {
|
|
115
|
+
// Without a port a Host means port 80
|
|
116
|
+
for (const name of ['127.0.0.1', 'localhost', '[::1]']) {
|
|
117
|
+
hosts.delete(name);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return hosts;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Reads the head of the first request of a connection and lets the connection through when its Host is one the
|
|
124
|
+
* listener answers. Everything that reaches this port goes to the teammate's service under this machine's key, and
|
|
125
|
+
* a web page can reach the port from the browser: with a name of its own that it points at 127.0.0.1 (DNS
|
|
126
|
+
* rebinding) the browser would hand it the answers as well. Such a request names that host, never the loopback
|
|
127
|
+
* address, and is answered 403 here. A browser opens a connection per host, so the first request speaks for the
|
|
128
|
+
* connection. A request without a Host is not a browser's and passes.
|
|
129
|
+
*/
|
|
130
|
+
function admit(client, answered, proceed, refuse) {
|
|
131
|
+
client.on('error', () => { });
|
|
132
|
+
let head = Buffer.alloc(0);
|
|
133
|
+
const onData = (chunk) => {
|
|
134
|
+
head = Buffer.concat([head, chunk]);
|
|
135
|
+
const end = head.indexOf('\r\n\r\n');
|
|
136
|
+
if (end === -1 && head.length < REQUEST_HEAD_MAX_BYTES) {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
client.off('data', onData);
|
|
140
|
+
client.pause();
|
|
141
|
+
const host = hostOf(head.subarray(0, end === -1 ? head.length : end).toString('latin1'));
|
|
142
|
+
if (host !== null && !answered.has(host)) {
|
|
143
|
+
refuse(host);
|
|
144
|
+
client.end('HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n' +
|
|
145
|
+
"Hopwire: this port forwards to a teammate's service and only answers requests made to its own loopback address\n");
|
|
146
|
+
client.once('finish', () => client.destroy());
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
// The peer gets the bytes as they came
|
|
150
|
+
client.unshift(head);
|
|
151
|
+
proceed();
|
|
152
|
+
};
|
|
153
|
+
client.on('data', onData);
|
|
154
|
+
}
|
|
155
|
+
/** The value of the first Host header of a request head, in lower case; null when it has none. */
|
|
156
|
+
function hostOf(head) {
|
|
157
|
+
for (const line of head.split('\r\n').slice(1)) {
|
|
158
|
+
const match = /^host[ \t]*:(.*)$/i.exec(line);
|
|
159
|
+
if (match !== null) {
|
|
160
|
+
return (match[1] ?? '').trim().toLowerCase();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
/** A host as it is printed: what a name can consist of, and not longer than a name is. */
|
|
166
|
+
function printableHost(host) {
|
|
167
|
+
return host.replace(/[^a-z0-9.:[\]_-]/g, '?').slice(0, 80) || '?';
|
|
168
|
+
}
|
|
169
|
+
/** Joins one accepted TCP connection with one stream to the peer, byte for byte in both directions. */
|
|
170
|
+
function bridge(client, connector, onUnreachable) {
|
|
171
|
+
client.on('error', () => { });
|
|
172
|
+
// Nothing is read from the client until the peer accepted the stream
|
|
173
|
+
client.pause();
|
|
174
|
+
connector.open().then((peer) => {
|
|
175
|
+
if (client.destroyed) {
|
|
176
|
+
peer.destroy();
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
client.pipe(peer);
|
|
180
|
+
peer.pipe(client);
|
|
181
|
+
client.once('close', () => peer.destroy());
|
|
182
|
+
peer.once('close', () => {
|
|
183
|
+
if (peer.readableEnded && client.writableEnded && !client.writableFinished) {
|
|
184
|
+
// The peer ended cleanly: its last bytes go out to the client before the socket is closed
|
|
185
|
+
client.once('finish', () => client.destroy());
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
client.destroy();
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}, (error) => {
|
|
192
|
+
client.destroy();
|
|
193
|
+
onUnreachable(error);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
/** One sentence for a stream that could not be opened: what happened and what to do. */
|
|
197
|
+
function connectError(code, options, ownKey) {
|
|
198
|
+
const peer = shortKey(options.peerKey);
|
|
199
|
+
switch (code) {
|
|
200
|
+
case 'PEER_NOT_FOUND':
|
|
201
|
+
return new HopwireError(`No peer with the key ${peer} was found; check the key, your network connection and that your teammate's tunnel is running and shared (--share, or p2p.share in hopwire.yaml).`);
|
|
202
|
+
case 'unknown_service':
|
|
203
|
+
return new HopwireError(`The peer has no service named "${options.service ?? ''}"; ask your teammate for the name it was started with (--name, or the service name in hopwire.yaml).`);
|
|
204
|
+
case 'service_required':
|
|
205
|
+
return new HopwireError('The peer runs several services; choose one with --service <name>.');
|
|
206
|
+
case 'busy':
|
|
207
|
+
return new HopwireError(`The peer ${peer} has as many connections open as it accepts; close some of yours or try again later.`);
|
|
208
|
+
case 'bad_preface':
|
|
209
|
+
case 'bad_reply':
|
|
210
|
+
return new HopwireError('The peer did not understand this connect request; make sure both sides run the same version of Hopwire.');
|
|
211
|
+
case 'timeout':
|
|
212
|
+
return new HopwireError(`The peer ${peer} did not answer in time; check your connection and try again.`);
|
|
213
|
+
case 'PEER_CONNECTION_FAILED':
|
|
214
|
+
return new HopwireError(options.team === undefined
|
|
215
|
+
? `The peer ${peer} was found but did not accept the connection; if your teammate uses --allow, it has to list this machine's key ${ownKey}. If your teammate shares with --team, run this command with --team.`
|
|
216
|
+
: `The peer ${peer} was found but did not accept the connection; if your teammate uses --allow instead of --team, it has to list this machine's key ${ownKey}. Otherwise try again in a minute.`);
|
|
217
|
+
default:
|
|
218
|
+
// Hole punching failed in one of its ways; V1 has no relay to fall back to
|
|
219
|
+
return new HopwireError(`No direct connection to the peer ${peer} was possible (${code}); Hopwire has no relay, so try again from another network.`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { access, stat } from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { HOPWIRE_YAML_FILE } from '@hopwire/protocol';
|
|
5
|
+
import { accountFile, boundEdge, readAccount } from '../account.js';
|
|
6
|
+
import { loadConfig } from '../config.js';
|
|
7
|
+
import { errorCode } from '../errors.js';
|
|
8
|
+
import { printable } from '../output.js';
|
|
9
|
+
/**
|
|
10
|
+
* `hopwire doctor`: a report about this installation, for the user to read and, when they choose, to paste into a
|
|
11
|
+
* bug report. It is printed and sent nowhere. It holds no key, no token and no traffic: only versions, whether the
|
|
12
|
+
* files of the data directory are there and who can read them, where the machine is logged in, and whether the
|
|
13
|
+
* hopwire.yaml of the working directory can be used.
|
|
14
|
+
*
|
|
15
|
+
* Without --network it opens no connection at all. With --network it joins the DHT for a moment (the public one:
|
|
16
|
+
* its nodes see the IP address of this machine, as with --share) and says whether this network lets two machines
|
|
17
|
+
* connect directly, which is what private mode needs.
|
|
18
|
+
*/
|
|
19
|
+
export async function doctor(options) {
|
|
20
|
+
const { print, dataDir } = options;
|
|
21
|
+
print(`Hopwire ${options.version}`);
|
|
22
|
+
print(`Node.js ${process.version}`);
|
|
23
|
+
print(`System ${process.platform} ${process.arch} (${os.release()})`);
|
|
24
|
+
print(`Data dir ${printable(dataDir)} (${await entry(dataDir, 0o700)})`);
|
|
25
|
+
print(`Identity ${await entry(path.join(dataDir, 'identity.json'), 0o600, 'none yet; the first tunnel or hopwire id creates it')}`);
|
|
26
|
+
print(`Traffic log ${await entry(path.join(dataDir, 'store'), 0o700, 'none yet; the first tunnel creates it')}`);
|
|
27
|
+
print(`Account ${await account(dataDir)}`);
|
|
28
|
+
print(`Config ${await config(options.cwd)}`);
|
|
29
|
+
print(`Network ${options.network ? await network(options) : NOT_CHECKED}`);
|
|
30
|
+
print('');
|
|
31
|
+
print(options.network
|
|
32
|
+
? 'Nothing was sent to us. The network check joined the DHT for a moment; its nodes saw the IP address of this machine.'
|
|
33
|
+
: 'Nothing was sent anywhere: this report was put together on this machine without a network connection.');
|
|
34
|
+
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.');
|
|
35
|
+
}
|
|
36
|
+
const NOT_CHECKED = 'not checked. hopwire doctor --network tests whether this network allows direct P2P connections; for that it joins the public DHT, whose nodes see your IP address';
|
|
37
|
+
/** Whether a file or directory is there, and whether others than its owner can get at it. */
|
|
38
|
+
async function entry(file, expected, missing = 'missing') {
|
|
39
|
+
let mode;
|
|
40
|
+
try {
|
|
41
|
+
mode = (await stat(file)).mode & 0o777;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
return errorCode(error) === 'ENOENT' ? missing : `cannot be read (${errorCode(error)})`;
|
|
45
|
+
}
|
|
46
|
+
if (process.platform === 'win32') {
|
|
47
|
+
// Windows has no owner, group and other bits to report
|
|
48
|
+
return 'present';
|
|
49
|
+
}
|
|
50
|
+
const shown = mode.toString(8).padStart(4, '0');
|
|
51
|
+
return (mode & 0o077) === 0
|
|
52
|
+
? `present, mode ${shown}`
|
|
53
|
+
: `present, mode ${shown}: others on this machine can get at it; it should be ${expected.toString(8).padStart(4, '0')}`;
|
|
54
|
+
}
|
|
55
|
+
/** Where the machine is logged in. The API token is never part of the answer. */
|
|
56
|
+
async function account(dataDir) {
|
|
57
|
+
try {
|
|
58
|
+
const stored = await readAccount(dataDir);
|
|
59
|
+
if (stored === null) {
|
|
60
|
+
return 'not logged in (only public mode needs an account)';
|
|
61
|
+
}
|
|
62
|
+
const edge = await boundEdge(dataDir);
|
|
63
|
+
const file = await entry(accountFile(dataDir), 0o600);
|
|
64
|
+
return printable(`logged in at ${stored.controlPlaneUrl.origin}, edge ${edge === null ? 'not bound yet' : edge.origin}; config.json ${file}`);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
return `config.json cannot be used: ${message(error)}`;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** The hopwire.yaml of the working directory, checked the way hopwire up checks it. */
|
|
71
|
+
async function config(cwd) {
|
|
72
|
+
const file = path.join(cwd, HOPWIRE_YAML_FILE);
|
|
73
|
+
try {
|
|
74
|
+
await access(file);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return `no ${HOPWIRE_YAML_FILE} in this directory (only hopwire up needs one)`;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const loaded = await loadConfig(file, false, HOPWIRE_YAML_FILE);
|
|
81
|
+
const services = loaded.services.length;
|
|
82
|
+
const open = loaded.services.filter((service) => service.public).length;
|
|
83
|
+
return `${HOPWIRE_YAML_FILE} can be used: ${services} ${services === 1 ? 'service' : 'services'}, ${open} public, P2P sharing ${loaded.share ? (loaded.team ? 'on, for your team only' : 'on') : 'off'}`;
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
return `${HOPWIRE_YAML_FILE} cannot be used: ${message(error)}`;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** What the DHT says about the network this machine is on. */
|
|
90
|
+
async function network(options) {
|
|
91
|
+
// Loaded only for --network: the one module that creates a DHT node
|
|
92
|
+
const { probeNetwork } = await import('../p2p.js');
|
|
93
|
+
const found = await probeNetwork({ bootstrap: options.bootstrap, signal: options.signal });
|
|
94
|
+
if (found === 'unreachable') {
|
|
95
|
+
return 'the DHT could not be reached within 15 seconds; private mode with teammates (--share, connect, watch) will not work from this network. A tunnel on this machine alone and public mode do not need the DHT';
|
|
96
|
+
}
|
|
97
|
+
if (found === 'open') {
|
|
98
|
+
return 'direct P2P works: this machine can be reached from outside without hole punching';
|
|
99
|
+
}
|
|
100
|
+
if (found === 'consistent') {
|
|
101
|
+
return 'direct P2P should work: this network keeps one outside port per connection, which is what hole punching needs';
|
|
102
|
+
}
|
|
103
|
+
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. There is no relay; public mode works from here';
|
|
104
|
+
}
|
|
105
|
+
function message(error) {
|
|
106
|
+
return printable(error instanceof Error ? error.message : String(error));
|
|
107
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, agentLine, formatExchange, formatLimitReached, formatMeteredUsage, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, } from '../output.js';
|
|
2
|
+
import { startServing } from '../serve.js';
|
|
3
|
+
export { INSPECTOR_FILES } from '../serve.js';
|
|
4
|
+
/**
|
|
5
|
+
* `hopwire http <port>`: forwards a loopback listener to one local service, logs every exchange and shows it in the
|
|
6
|
+
* inspector. With --share teammates can reach the service and replicate the log over Holepunch; with --public the
|
|
7
|
+
* edge serves it under a public URL. Without either nothing but loopback is opened.
|
|
8
|
+
*/
|
|
9
|
+
export async function startHttpTunnel(options) {
|
|
10
|
+
const target = new URL(`http://127.0.0.1:${options.port}`);
|
|
11
|
+
const allow = options.allow ?? [];
|
|
12
|
+
// The line about a tunnel --force stopped follows the startup lines: the mode stays the first line
|
|
13
|
+
const stopped = [];
|
|
14
|
+
const serving = await startServing({
|
|
15
|
+
services: [{ name: options.serviceName, target, listenPort: options.listenPort, public: options.public }],
|
|
16
|
+
inspectPort: options.inspectPort,
|
|
17
|
+
dataDir: options.dataDir,
|
|
18
|
+
force: options.force ?? false,
|
|
19
|
+
onHolderStopped: (line) => stopped.push(line),
|
|
20
|
+
share: options.share ?? false,
|
|
21
|
+
allow,
|
|
22
|
+
team: options.team,
|
|
23
|
+
onTeamEvent: (event, organisation) => options.print(formatTeamEvent(event, organisation)),
|
|
24
|
+
bootstrap: options.bootstrap,
|
|
25
|
+
inspectorFiles: options.inspectorFiles,
|
|
26
|
+
agent: options.agent ?? false,
|
|
27
|
+
signal: options.signal,
|
|
28
|
+
listenOption: '--listen <port>',
|
|
29
|
+
inspectOption: '--inspect <port> or run with --no-inspect',
|
|
30
|
+
onExchange: (exchange) => options.print(formatExchange(exchange)),
|
|
31
|
+
onLogError: () => options.print('Could not write to the traffic log; the request was still forwarded'),
|
|
32
|
+
onBridgeEvent: (_service, event) => options.print(formatBridgeEvent(event)),
|
|
33
|
+
});
|
|
34
|
+
const { inspectorUrl, agentSocket, logKey, peerKey, ended, close } = serving;
|
|
35
|
+
const url = serving.services[0]?.url ?? '';
|
|
36
|
+
const publicUrl = serving.services[0]?.publicUrl ?? null;
|
|
37
|
+
const subdomain = serving.services[0]?.subdomain ?? '';
|
|
38
|
+
const usage = serving.services[0]?.usage ?? null;
|
|
39
|
+
const access = serving.team === null
|
|
40
|
+
? allow.length > 0
|
|
41
|
+
? allow.length
|
|
42
|
+
: null
|
|
43
|
+
: { team: serving.team.organisation, keys: serving.team.keys };
|
|
44
|
+
if (options.public === undefined) {
|
|
45
|
+
options.print(peerKey === null ? MODE_LOCAL : serving.team === null ? MODE_P2P : MODE_P2P_TEAM);
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
options.print(peerKey === null ? MODE_PUBLIC : serving.team === null ? MODE_PUBLIC_P2P : MODE_PUBLIC_P2P_TEAM);
|
|
49
|
+
}
|
|
50
|
+
options.print(`Forwarding ${url} -> ${target.origin}`);
|
|
51
|
+
if (options.public !== undefined) {
|
|
52
|
+
options.print(`Public URL ${publicUrl ?? `subdomain ${subdomain} (the edge did not report its URL)`}`);
|
|
53
|
+
if (usage !== null) {
|
|
54
|
+
options.print(formatUsage(usage));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
options.print(`Traffic log ${logKey} (${serving.logLength} exchanges)`);
|
|
58
|
+
if (peerKey !== null) {
|
|
59
|
+
options.print(`Peer key ${peerKey}`);
|
|
60
|
+
options.print(shareNotice(access));
|
|
61
|
+
}
|
|
62
|
+
if (inspectorUrl !== null) {
|
|
63
|
+
options.print(`Inspector ${inspectorUrl}`);
|
|
64
|
+
}
|
|
65
|
+
if (agentSocket !== null) {
|
|
66
|
+
options.print(agentLine(agentSocket, target.origin));
|
|
67
|
+
}
|
|
68
|
+
for (const line of tunnelGuide({
|
|
69
|
+
services: [
|
|
70
|
+
{
|
|
71
|
+
name: options.serviceName,
|
|
72
|
+
url,
|
|
73
|
+
target: target.origin,
|
|
74
|
+
publicUrl,
|
|
75
|
+
stableUrl: options.public?.connectTokens !== undefined,
|
|
76
|
+
},
|
|
77
|
+
],
|
|
78
|
+
share: peerKey === null
|
|
79
|
+
? null
|
|
80
|
+
: {
|
|
81
|
+
peerKey,
|
|
82
|
+
logKey,
|
|
83
|
+
allowed: access,
|
|
84
|
+
restrictWith: '--allow <their key>',
|
|
85
|
+
},
|
|
86
|
+
inspector: inspectorUrl !== null,
|
|
87
|
+
widenWith: { share: '--share', public: '--public' },
|
|
88
|
+
})) {
|
|
89
|
+
options.print(line);
|
|
90
|
+
}
|
|
91
|
+
for (const line of stopped) {
|
|
92
|
+
options.print(line);
|
|
93
|
+
}
|
|
94
|
+
return { kind: 'http', url, inspectorUrl, agentSocket, logKey, peerKey, publicUrl, ended, close };
|
|
95
|
+
}
|
|
96
|
+
/** One line for a change of the connection to the edge, or for a daily limit of the plan that was reached. */
|
|
97
|
+
export function formatBridgeEvent(event) {
|
|
98
|
+
switch (event.type) {
|
|
99
|
+
case 'reconnected':
|
|
100
|
+
return 'Edge connected again; the public URL is served';
|
|
101
|
+
case 'disconnected':
|
|
102
|
+
return `Edge connection lost; the public URL is offline, next attempt in ${(event.retryInMs / 1000).toFixed(1)} s`;
|
|
103
|
+
case 'limit_reached':
|
|
104
|
+
return formatLimitReached(event.meter);
|
|
105
|
+
case 'metered_usage':
|
|
106
|
+
return formatMeteredUsage(event.metered);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { DEFAULT_CONTROL_PLANE_URL, accountFile, isApiToken, readControlPlaneUrl, removeAccount, writeAccount, } from '../account.js';
|
|
2
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
3
|
+
import { HopwireError, TemporaryError } from '../errors.js';
|
|
4
|
+
import { LOGIN_NEXT, printable } from '../output.js';
|
|
5
|
+
/**
|
|
6
|
+
* `hopwire login`: gets an API token, asks the control plane whose it is, and stores it with the URL of the control
|
|
7
|
+
* plane in config.json of the data directory (mode 0600). The token comes from HOPWIRE_TOKEN, else from a hidden
|
|
8
|
+
* prompt with --token, else from the browser login: the control plane shows a page where the user signs in, types
|
|
9
|
+
* the code printed here and approves, and then hands this CLI a new token. The control plane is the one of --api,
|
|
10
|
+
* else the one of an earlier login on this data directory, else the hosted one (DEFAULT_CONTROL_PLANE_URL). Nothing
|
|
11
|
+
* is stored unless the control plane accepted the token. The token is never printed.
|
|
12
|
+
*/
|
|
13
|
+
export async function login(options) {
|
|
14
|
+
const controlPlaneUrl = options.apiUrl ?? (await storedUrl(options.dataDir)) ?? new URL(DEFAULT_CONTROL_PLANE_URL);
|
|
15
|
+
const fromEnv = (options.token ?? '').trim();
|
|
16
|
+
const apiToken = fromEnv ||
|
|
17
|
+
(options.paste
|
|
18
|
+
? (await ask(options.promptSecret, options.signal)).trim()
|
|
19
|
+
: await browserLogin(controlPlaneUrl, options));
|
|
20
|
+
if (!isApiToken(apiToken)) {
|
|
21
|
+
throw new HopwireError('That is not an API token: one starts with hw_ and has 43 characters; copy it from the API tokens page of the control plane right after creating it.');
|
|
22
|
+
}
|
|
23
|
+
// Loaded only here and for a public tunnel of a logged-in user: nothing else contacts the control plane
|
|
24
|
+
const { createControlPlaneClient } = await import('../control-plane-client.js');
|
|
25
|
+
const { email, organisation, plan, edgeUrl } = await createControlPlaneClient({
|
|
26
|
+
url: controlPlaneUrl,
|
|
27
|
+
apiToken,
|
|
28
|
+
}).me(options.signal);
|
|
29
|
+
// 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
|
+
// The address comes from another machine: nothing of it reaches the terminal as an escape sequence
|
|
32
|
+
options.print(`Logged in ${printable(email)} at ${controlPlaneUrl.origin}`);
|
|
33
|
+
if (organisation !== null) {
|
|
34
|
+
options.print(`Organisation ${printable(organisation.name)}${plan === null ? '' : ` (${plan} plan)`}; the token acts in this organisation`);
|
|
35
|
+
}
|
|
36
|
+
if (edgeUrl !== null) {
|
|
37
|
+
options.print(`Edge ${edgeUrl.origin} (public tunnels of this account go there)`);
|
|
38
|
+
}
|
|
39
|
+
options.print(`Token stored in ${accountFile(options.dataDir)} (readable for this user only)`);
|
|
40
|
+
for (const line of LOGIN_NEXT) {
|
|
41
|
+
options.print(line);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* `hopwire logout`: removes the stored token from this machine. The URL of the control plane stays in the file, so
|
|
46
|
+
* the next `hopwire login` needs no --api. The token itself stays valid at the control plane until it is revoked
|
|
47
|
+
* there; the control plane is not contacted.
|
|
48
|
+
*/
|
|
49
|
+
export async function logout(options) {
|
|
50
|
+
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`);
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
options.print(`Logged out no token was stored in ${file}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** 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) => {
|
|
61
|
+
if (error instanceof HopwireError) {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
throw error;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
async function ask(promptSecret, signal) {
|
|
68
|
+
if (promptSecret === undefined) {
|
|
69
|
+
throw noTerminal();
|
|
70
|
+
}
|
|
71
|
+
return promptSecret('API token (input is hidden): ', signal);
|
|
72
|
+
}
|
|
73
|
+
/** Without a terminal nobody is there to paste a token or approve a code; a script would wait in vain. */
|
|
74
|
+
function noTerminal() {
|
|
75
|
+
return new HopwireError('hopwire login has no terminal to ask for the API token on; pass it in the environment variable HOPWIRE_TOKEN.');
|
|
76
|
+
}
|
|
77
|
+
/** Waits, until the signal fires; then rejects with the signal's reason, as everything that stops on it does. */
|
|
78
|
+
async function pause(ms, signal) {
|
|
79
|
+
try {
|
|
80
|
+
await sleep(ms, undefined, { signal });
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
signal?.throwIfAborted();
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** Added to the wait between two questions when the control plane says they come too often (429). */
|
|
88
|
+
const SLOW_DOWN_MS = 5_000;
|
|
89
|
+
/** The longest wait between two questions */
|
|
90
|
+
const MAX_INTERVAL_MS = 30_000;
|
|
91
|
+
/**
|
|
92
|
+
* The browser login: the control plane starts it and names a code, the user approves that code on the page /cli-login
|
|
93
|
+
* of the control plane, and the CLI asks every few seconds until it gets the new API token, the login is denied or
|
|
94
|
+
* the code expires. The page is opened in the browser unless --no-browser, over SSH or without a display; its URL
|
|
95
|
+
* and the code are printed either way, so it can be opened on any device.
|
|
96
|
+
*/
|
|
97
|
+
async function browserLogin(controlPlaneUrl, options) {
|
|
98
|
+
if (options.promptSecret === undefined) {
|
|
99
|
+
throw noTerminal();
|
|
100
|
+
}
|
|
101
|
+
const wait = options.wait ?? pause;
|
|
102
|
+
const { createLoginClient } = await import('../control-plane-client.js');
|
|
103
|
+
const client = createLoginClient({ url: controlPlaneUrl });
|
|
104
|
+
const started = await client.start(options.signal);
|
|
105
|
+
const deadline = Date.now() + started.expiresInSeconds * 1000;
|
|
106
|
+
const page = new URL('/cli-login', controlPlaneUrl).href;
|
|
107
|
+
const minutes = Math.round(started.expiresInSeconds / 60);
|
|
108
|
+
options.print(`Sign in ${page}`);
|
|
109
|
+
options.print(`Code ${started.userCode} (type it on that page; it works for ${minutes} minutes)`);
|
|
110
|
+
const opened = !options.noBrowser && (options.openBrowser?.(page) ?? false);
|
|
111
|
+
options.print(opened
|
|
112
|
+
? 'Browser opened; sign in if asked, type the code and approve'
|
|
113
|
+
: 'Browser not opened; open the page on any device, sign in, type the code and approve');
|
|
114
|
+
options.print('Waiting for the approval (Ctrl+C stops; hopwire login --token pastes a token instead)');
|
|
115
|
+
let interval = started.intervalSeconds * 1000;
|
|
116
|
+
while (Date.now() < deadline) {
|
|
117
|
+
await wait(interval, options.signal);
|
|
118
|
+
try {
|
|
119
|
+
const answer = await client.poll(started.deviceCode, options.signal);
|
|
120
|
+
if (answer.state === 'approved') {
|
|
121
|
+
return answer.apiToken;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
// Asked too often, or the control plane is out of reach for a moment: ask again, more slowly
|
|
126
|
+
if (!(error instanceof TemporaryError)) {
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
interval = Math.min(interval + SLOW_DOWN_MS, MAX_INTERVAL_MS);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
throw new HopwireError('The code expired before it was approved; run hopwire login again.');
|
|
133
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createAgentClient } from '../mcp/client.js';
|
|
2
|
+
import { MESSAGE_LIMIT_BYTES, createMcpServer } from '../mcp/jsonrpc.js';
|
|
3
|
+
/**
|
|
4
|
+
* `hopwire mcp`: a stdio MCP server for coding agents on this machine. It reaches a tunnel started with --agent
|
|
5
|
+
* through the agent socket of the data directory. It opens no TCP connection, never opens the traffic log and writes
|
|
6
|
+
* no file; standard output carries JSON-RPC and nothing else.
|
|
7
|
+
*/
|
|
8
|
+
export function startMcp(options) {
|
|
9
|
+
const server = createMcpServer({
|
|
10
|
+
client: createAgentClient(options.dataDir),
|
|
11
|
+
dataDir: options.dataDir,
|
|
12
|
+
readOnly: options.readOnly,
|
|
13
|
+
version: options.version,
|
|
14
|
+
send: (message) => options.print(JSON.stringify(message)),
|
|
15
|
+
now: options.now,
|
|
16
|
+
});
|
|
17
|
+
const input = options.input;
|
|
18
|
+
input.setEncoding('utf8');
|
|
19
|
+
let buffer = '';
|
|
20
|
+
let dropping = false;
|
|
21
|
+
const onData = (chunk) => {
|
|
22
|
+
buffer += chunk.toString();
|
|
23
|
+
let at;
|
|
24
|
+
while ((at = buffer.indexOf('\n')) !== -1) {
|
|
25
|
+
const line = buffer.slice(0, at);
|
|
26
|
+
buffer = buffer.slice(at + 1);
|
|
27
|
+
if (dropping) {
|
|
28
|
+
// The rest of a line that was too long
|
|
29
|
+
dropping = false;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
server.receive(line);
|
|
33
|
+
}
|
|
34
|
+
if (Buffer.byteLength(buffer) > MESSAGE_LIMIT_BYTES) {
|
|
35
|
+
buffer = '';
|
|
36
|
+
dropping = true;
|
|
37
|
+
server.receive('{');
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
input.on('data', onData);
|
|
41
|
+
let finish = () => { };
|
|
42
|
+
const finished = new Promise((resolve) => {
|
|
43
|
+
finish = resolve;
|
|
44
|
+
});
|
|
45
|
+
const end = () => {
|
|
46
|
+
if (buffer !== '' && !dropping) {
|
|
47
|
+
server.receive(buffer);
|
|
48
|
+
}
|
|
49
|
+
buffer = '';
|
|
50
|
+
// Calls still running answer first
|
|
51
|
+
void server.drain().then(finish);
|
|
52
|
+
};
|
|
53
|
+
input.once('end', end);
|
|
54
|
+
input.once('close', end);
|
|
55
|
+
return {
|
|
56
|
+
kind: 'mcp',
|
|
57
|
+
finished,
|
|
58
|
+
async close() {
|
|
59
|
+
input.off('data', onData);
|
|
60
|
+
input.off('end', end);
|
|
61
|
+
input.off('close', end);
|
|
62
|
+
await server.close();
|
|
63
|
+
// Standard input is not read any more, so it does not keep the process alive
|
|
64
|
+
if ('pause' in input && typeof input.pause === 'function') {
|
|
65
|
+
input.pause();
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|