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,57 @@
|
|
|
1
|
+
import { rename, rm } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { storeError } from '../errors.js';
|
|
4
|
+
import { replaceIdentity } from '../identity.js';
|
|
5
|
+
import { ExchangeLog } from '../log.js';
|
|
6
|
+
import { rotateGuide } from '../output.js';
|
|
7
|
+
/**
|
|
8
|
+
* `hopwire rotate`: new keys for a data directory, for when a key went to the wrong person. The traffic log is
|
|
9
|
+
* copied, exchange by exchange, into a new log with a new key, and the identity is replaced, so neither the old log
|
|
10
|
+
* key nor the old peer key leads anywhere afterwards. The history stays; what somebody already replicated from the
|
|
11
|
+
* old log stays with them. No network connection is opened. A tunnel that runs on the directory holds its store,
|
|
12
|
+
* and the command then says to stop it first.
|
|
13
|
+
*/
|
|
14
|
+
export async function rotate(options) {
|
|
15
|
+
const current = path.join(options.dataDir, 'store');
|
|
16
|
+
const next = path.join(options.dataDir, 'store.rotating');
|
|
17
|
+
const retired = path.join(options.dataDir, 'store.retired');
|
|
18
|
+
// Opening the log takes the lock of the store: no tunnel runs on it while it is copied
|
|
19
|
+
const old = await ExchangeLog.open(current).catch((error) => {
|
|
20
|
+
throw storeError(error, options.dataDir);
|
|
21
|
+
});
|
|
22
|
+
let logKey;
|
|
23
|
+
let length;
|
|
24
|
+
try {
|
|
25
|
+
// What an earlier rotation left behind when it was cut short
|
|
26
|
+
await rm(next, { recursive: true, force: true });
|
|
27
|
+
await rm(retired, { recursive: true, force: true });
|
|
28
|
+
const copy = await ExchangeLog.open(next);
|
|
29
|
+
try {
|
|
30
|
+
for (let index = 0; index < old.length; index++) {
|
|
31
|
+
await copy.append(await old.get(index));
|
|
32
|
+
}
|
|
33
|
+
logKey = copy.key;
|
|
34
|
+
length = copy.length;
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
await copy.close();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
await old.close().catch(() => { });
|
|
42
|
+
await rm(next, { recursive: true, force: true }).catch(() => { });
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
await old.close();
|
|
46
|
+
// The old log leaves its place before the new one takes it; it is removed only once the new one is there
|
|
47
|
+
await rename(current, retired);
|
|
48
|
+
await rename(next, current);
|
|
49
|
+
await rm(retired, { recursive: true, force: true });
|
|
50
|
+
const identity = await replaceIdentity(options.dataDir);
|
|
51
|
+
options.print(`Rotated the keys of ${options.dataDir}; the old ones no longer lead anywhere`);
|
|
52
|
+
options.print(`Peer key ${identity.publicKey.toString('hex')}`);
|
|
53
|
+
options.print(`Traffic log ${logKey} (${length} exchanges)`);
|
|
54
|
+
for (const line of rotateGuide()) {
|
|
55
|
+
options.print(line);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { LOCAL_ENTRY_DEFAULT_PORT, RANDOM_SUBDOMAIN_BYTES, randomSubdomain } from '@hopwire/protocol';
|
|
3
|
+
import { HopwireError } from '../errors.js';
|
|
4
|
+
import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, agentLine, formatExchange, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, } from '../output.js';
|
|
5
|
+
import { startServing } from '../serve.js';
|
|
6
|
+
import { formatBridgeEvent } from './http.js';
|
|
7
|
+
/**
|
|
8
|
+
* `hopwire up`: every service of hopwire.yaml at once. All of them write to the one traffic log of the data
|
|
9
|
+
* directory and show up in one inspector; each has its own loopback entry point, a public one its own subdomain and
|
|
10
|
+
* connection to the edge, and with p2p.share teammates reach each by its name.
|
|
11
|
+
*/
|
|
12
|
+
export async function startUp(options) {
|
|
13
|
+
const { config } = options;
|
|
14
|
+
const entryPort = options.entryPort ?? LOCAL_ENTRY_DEFAULT_PORT;
|
|
15
|
+
const several = config.services.length > 1;
|
|
16
|
+
const width = Math.max(...config.services.map((service) => service.name.length));
|
|
17
|
+
const label = (name) => (several ? `${name.padEnd(width)} ` : '');
|
|
18
|
+
// Entry ports count up in the order of the file and leave out the port the file gives the inspector, which is
|
|
19
|
+
// bound last and would otherwise find its port taken by a service of the same file
|
|
20
|
+
let next = entryPort;
|
|
21
|
+
const services = config.services.map((service) => {
|
|
22
|
+
if (next === config.inspectorPort) {
|
|
23
|
+
next++;
|
|
24
|
+
}
|
|
25
|
+
const port = entryPort === 0 ? 0 : next++;
|
|
26
|
+
return {
|
|
27
|
+
name: service.name,
|
|
28
|
+
target: service.local,
|
|
29
|
+
// A port another program holds is no reason to fail: the startup lines say where each service listens
|
|
30
|
+
listenPort: port > 65535 ? 0 : port,
|
|
31
|
+
listenFallback: true,
|
|
32
|
+
public: publicOptions(service, config, options),
|
|
33
|
+
};
|
|
34
|
+
});
|
|
35
|
+
// The line about a tunnel --force stopped follows the startup lines: the mode stays the first line
|
|
36
|
+
const stopped = [];
|
|
37
|
+
const serving = await startServing({
|
|
38
|
+
services,
|
|
39
|
+
inspectPort: config.inspectorPort,
|
|
40
|
+
dataDir: options.dataDir,
|
|
41
|
+
force: options.force ?? false,
|
|
42
|
+
onHolderStopped: (line) => stopped.push(line),
|
|
43
|
+
share: config.share,
|
|
44
|
+
allow: config.allow ?? [],
|
|
45
|
+
team: options.team,
|
|
46
|
+
onTeamEvent: (event, organisation) => options.print(formatTeamEvent(event, organisation)),
|
|
47
|
+
bootstrap: options.bootstrap,
|
|
48
|
+
inspectorFiles: options.inspectorFiles,
|
|
49
|
+
agent: options.agent ?? false,
|
|
50
|
+
signal: options.signal,
|
|
51
|
+
listenOption: 'a free port',
|
|
52
|
+
inspectOption: 'inspector.port in hopwire.yaml',
|
|
53
|
+
onExchange: (exchange) => options.print(`${label(exchange.serviceName)}${formatExchange(exchange)}`),
|
|
54
|
+
onLogError: (name) => options.print(`${label(name)}Could not write to the traffic log; the request was still forwarded`),
|
|
55
|
+
onBridgeEvent: (name, event) => options.print(several ? `${formatBridgeEvent(event)} (service ${name})` : formatBridgeEvent(event)),
|
|
56
|
+
});
|
|
57
|
+
const access = serving.team === null
|
|
58
|
+
? config.allow === null
|
|
59
|
+
? null
|
|
60
|
+
: config.allow.length
|
|
61
|
+
: { team: serving.team.organisation, keys: serving.team.keys };
|
|
62
|
+
const [privateMode, bothModes] = serving.team === null ? [MODE_P2P, MODE_PUBLIC_P2P] : [MODE_P2P_TEAM, MODE_PUBLIC_P2P_TEAM];
|
|
63
|
+
options.print(`Config ${options.configFile} (${config.services.length === 1 ? '1 service' : `${config.services.length} services`})`);
|
|
64
|
+
for (const [index, service] of serving.services.entries()) {
|
|
65
|
+
const settings = config.services[index];
|
|
66
|
+
options.print(`Service ${service.name}`);
|
|
67
|
+
if (service.subdomain === null) {
|
|
68
|
+
options.print(serving.peerKey === null ? MODE_LOCAL : privateMode);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
options.print(serving.peerKey === null ? MODE_PUBLIC : bothModes);
|
|
72
|
+
}
|
|
73
|
+
options.print(`Forwarding ${service.url} -> ${service.target}`);
|
|
74
|
+
if (service.subdomain !== null) {
|
|
75
|
+
const url = service.publicUrl ?? `subdomain ${service.subdomain} (the edge did not report its URL)`;
|
|
76
|
+
options.print(`Public URL ${url}${settings?.basicAuth == null ? '' : ' (asks for the user and password of auth.basic)'}`);
|
|
77
|
+
if (service.usage !== null) {
|
|
78
|
+
options.print(formatUsage(service.usage));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
options.print(`Traffic log ${serving.logKey} (${serving.logLength} exchanges)`);
|
|
83
|
+
if (serving.peerKey !== null) {
|
|
84
|
+
options.print(`Peer key ${serving.peerKey}`);
|
|
85
|
+
options.print(shareNotice(access, 'p2p.allow in hopwire.yaml'));
|
|
86
|
+
}
|
|
87
|
+
options.print(`Inspector ${serving.inspectorUrl ?? ''}`);
|
|
88
|
+
if (serving.agentSocket !== null) {
|
|
89
|
+
const [first, ...rest] = serving.services;
|
|
90
|
+
options.print(agentLine(serving.agentSocket, first !== undefined && rest.length === 0 ? first.target : 'the local service of each exchange'));
|
|
91
|
+
}
|
|
92
|
+
for (const line of tunnelGuide({
|
|
93
|
+
services: serving.services.map((service, index) => ({
|
|
94
|
+
name: service.name,
|
|
95
|
+
url: service.url,
|
|
96
|
+
target: service.target,
|
|
97
|
+
publicUrl: service.publicUrl,
|
|
98
|
+
basicAuth: config.services[index]?.basicAuth != null,
|
|
99
|
+
stableUrl: options.connectTokens !== undefined,
|
|
100
|
+
})),
|
|
101
|
+
share: serving.peerKey === null
|
|
102
|
+
? null
|
|
103
|
+
: {
|
|
104
|
+
peerKey: serving.peerKey,
|
|
105
|
+
logKey: serving.logKey,
|
|
106
|
+
allowed: access,
|
|
107
|
+
restrictWith: 'p2p.allow in hopwire.yaml',
|
|
108
|
+
},
|
|
109
|
+
inspector: serving.inspectorUrl !== null,
|
|
110
|
+
widenWith: { share: 'p2p.share: true in hopwire.yaml', public: 'public: true on a service' },
|
|
111
|
+
})) {
|
|
112
|
+
options.print(line);
|
|
113
|
+
}
|
|
114
|
+
for (const line of stopped) {
|
|
115
|
+
options.print(line);
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
kind: 'up',
|
|
119
|
+
services: serving.services,
|
|
120
|
+
inspectorUrl: serving.inspectorUrl ?? '',
|
|
121
|
+
agentSocket: serving.agentSocket,
|
|
122
|
+
logKey: serving.logKey,
|
|
123
|
+
peerKey: serving.peerKey,
|
|
124
|
+
ended: serving.ended,
|
|
125
|
+
close: serving.close,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/** What the edge bridge of a public service needs; undefined for a service that is not public. */
|
|
129
|
+
function publicOptions(service, config, access) {
|
|
130
|
+
if (!service.public) {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
const { edgeUrl } = config;
|
|
134
|
+
const basicAuth = service.basicAuth === null ? {} : { basicAuth: service.basicAuth };
|
|
135
|
+
if (edgeUrl !== null && access.connectTokens !== undefined) {
|
|
136
|
+
// Without a subdomain in the file the tunnel gets the fixed URL of the organisation
|
|
137
|
+
return { edgeUrl, connectTokens: access.connectTokens, subdomain: service.subdomain, ...basicAuth };
|
|
138
|
+
}
|
|
139
|
+
if (edgeUrl === null || access.token === undefined) {
|
|
140
|
+
// The config module and the command line refuse both before anything is started
|
|
141
|
+
throw new HopwireError(`The service ${service.name} is public, which needs edge.url and a token.`);
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
edgeUrl,
|
|
145
|
+
token: access.token,
|
|
146
|
+
subdomain: service.subdomain ?? randomSubdomain(randomBytes(RANDOM_SUBDOMAIN_BYTES)),
|
|
147
|
+
...basicAuth,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { openOwnLog } from '../data-dir-holder.js';
|
|
2
|
+
import { HopwireError, listenError } from '../errors.js';
|
|
3
|
+
import { loadOrCreateIdentity } from '../identity.js';
|
|
4
|
+
import { startInspectorServer } from '../inspector-server.js';
|
|
5
|
+
import { createInterceptor } from '../interceptor.js';
|
|
6
|
+
import { REMOTE_LOG_BUDGET_BYTES } from '../log.js';
|
|
7
|
+
import { MODE_P2P, MODE_P2P_TEAM, formatExchange, printable, shortKey, watchGuide } from '../output.js';
|
|
8
|
+
import { INSPECTOR_FILES } from '../serve.js';
|
|
9
|
+
import { Supervisor, unlessAborted } from '../supervisor.js';
|
|
10
|
+
/**
|
|
11
|
+
* `hopwire watch <log-key>`: replicates a teammate's traffic log live into this machine's Corestore and shows it in
|
|
12
|
+
* the inspector next to the watcher's own log. Replays run through an interceptor of the watcher against
|
|
13
|
+
* --replay-target and land in the watcher's own log; the teammate's log is never written to.
|
|
14
|
+
*/
|
|
15
|
+
export async function startWatch(options) {
|
|
16
|
+
const logKey = options.logKey.toLowerCase();
|
|
17
|
+
/** What was started so far; closed in the order inspector, swarm and DHT, remote log, own log */
|
|
18
|
+
const supervisor = new Supervisor();
|
|
19
|
+
const close = supervisor.close;
|
|
20
|
+
/** Before every step that takes time: a start that was stopped goes no further */
|
|
21
|
+
const proceed = () => options.signal?.throwIfAborted();
|
|
22
|
+
/** The line about a tunnel --force stopped */
|
|
23
|
+
const stopped = [];
|
|
24
|
+
try {
|
|
25
|
+
proceed();
|
|
26
|
+
const identity = await loadOrCreateIdentity(options.dataDir);
|
|
27
|
+
const peerKey = identity.publicKey.toString('hex');
|
|
28
|
+
const { log: own, release } = await openOwnLog({
|
|
29
|
+
dataDir: options.dataDir,
|
|
30
|
+
force: options.force ?? false,
|
|
31
|
+
// after the startup lines: the mode stays the first line
|
|
32
|
+
print: (line) => stopped.push(line),
|
|
33
|
+
signal: options.signal,
|
|
34
|
+
});
|
|
35
|
+
supervisor.add('store', async () => {
|
|
36
|
+
await release();
|
|
37
|
+
await own.close();
|
|
38
|
+
});
|
|
39
|
+
if (logKey === own.key) {
|
|
40
|
+
throw new HopwireError('That is the key of the traffic log on this machine; hopwire watch takes the log key a teammate shared.');
|
|
41
|
+
}
|
|
42
|
+
const remote = await own.openRemote(logKey);
|
|
43
|
+
supervisor.add('store', () => remote.close());
|
|
44
|
+
proceed();
|
|
45
|
+
// Before the log is looked up: the sharer asks for the list when a key knocks that it does not know
|
|
46
|
+
const organisation = options.team === undefined
|
|
47
|
+
? null
|
|
48
|
+
: printable((await options.team.teamKeys(peerKey, options.signal)).organisation.name);
|
|
49
|
+
proceed();
|
|
50
|
+
const { JoinError, joinLog } = await import('../p2p.js');
|
|
51
|
+
const joined = await joinLog({
|
|
52
|
+
identity,
|
|
53
|
+
log: remote,
|
|
54
|
+
bootstrap: options.bootstrap,
|
|
55
|
+
signal: options.signal,
|
|
56
|
+
}).catch((error) => {
|
|
57
|
+
throw error instanceof JoinError
|
|
58
|
+
? joinError(error.code, logKey, peerKey, options.team !== undefined)
|
|
59
|
+
: error;
|
|
60
|
+
});
|
|
61
|
+
supervisor.add('p2p', () => joined.close());
|
|
62
|
+
// Up to 10 s for the sharer to say how long its log is; a start that is stopped does not wait for it
|
|
63
|
+
await unlessAborted(remote.follow(), options.signal);
|
|
64
|
+
if (remote.length === 0 && !joined.connected()) {
|
|
65
|
+
// A sharer with --team takes the connection and closes it when the key is not one of its team: said
|
|
66
|
+
// here, instead of an inspector that stays empty
|
|
67
|
+
throw joinError('no_connection', logKey, peerKey, options.team !== undefined);
|
|
68
|
+
}
|
|
69
|
+
// Replays keep the service name of the exchange they repeat
|
|
70
|
+
const interceptors = new Map();
|
|
71
|
+
const replayThrough = (serviceName) => {
|
|
72
|
+
if (options.replayTarget === null) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
let interceptor = interceptors.get(serviceName);
|
|
76
|
+
if (interceptor === undefined) {
|
|
77
|
+
interceptor = createInterceptor({
|
|
78
|
+
target: options.replayTarget,
|
|
79
|
+
serviceName,
|
|
80
|
+
log: own,
|
|
81
|
+
onExchange: (exchange) => options.print(formatExchange(exchange)),
|
|
82
|
+
onLogError: () => options.print('Could not write to the traffic log; the replay was still sent'),
|
|
83
|
+
});
|
|
84
|
+
interceptors.set(serviceName, interceptor);
|
|
85
|
+
}
|
|
86
|
+
return interceptor;
|
|
87
|
+
};
|
|
88
|
+
const status = {
|
|
89
|
+
mode: 'private',
|
|
90
|
+
services: [],
|
|
91
|
+
replayTarget: options.replayTarget?.origin ?? null,
|
|
92
|
+
logKey,
|
|
93
|
+
peerKey,
|
|
94
|
+
publicUrls: [],
|
|
95
|
+
watching: true,
|
|
96
|
+
};
|
|
97
|
+
const inspector = await startInspectorServer({
|
|
98
|
+
port: options.inspectPort,
|
|
99
|
+
staticDir: options.inspectorFiles ?? INSPECTOR_FILES,
|
|
100
|
+
sources: [
|
|
101
|
+
{ origin: 'remote', log: remote },
|
|
102
|
+
{ origin: 'own', log: own },
|
|
103
|
+
],
|
|
104
|
+
status: () => status,
|
|
105
|
+
replayThrough: (exchange) => replayThrough(exchange.serviceName),
|
|
106
|
+
}).catch((error) => {
|
|
107
|
+
throw listenError(error, options.inspectPort, 'inspector', '--inspect <port>');
|
|
108
|
+
});
|
|
109
|
+
supervisor.add('servers', () => inspector.close());
|
|
110
|
+
// Stopped at the last step: nothing is reported as running
|
|
111
|
+
proceed();
|
|
112
|
+
const stopPrinting = remote.subscribe((_index, exchange) => options.print(formatExchange(exchange)));
|
|
113
|
+
supervisor.add('servers', async () => stopPrinting());
|
|
114
|
+
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`));
|
|
115
|
+
options.print(organisation === null ? MODE_P2P : MODE_P2P_TEAM);
|
|
116
|
+
options.print(`Watching ${logKey} (${remote.length} exchanges)`);
|
|
117
|
+
options.print(`Peer key ${peerKey}`);
|
|
118
|
+
if (organisation !== null) {
|
|
119
|
+
options.print(`Team ${organisation}: this machine's key is registered there`);
|
|
120
|
+
}
|
|
121
|
+
options.print(options.replayTarget === null
|
|
122
|
+
? 'Replay off; start hopwire watch with --replay-target <url> to replay to a local service'
|
|
123
|
+
: `Replay to ${options.replayTarget.origin}`);
|
|
124
|
+
options.print(`Inspector ${inspector.url}`);
|
|
125
|
+
for (const line of watchGuide(options.replayTarget?.origin ?? null)) {
|
|
126
|
+
options.print(line);
|
|
127
|
+
}
|
|
128
|
+
for (const line of stopped) {
|
|
129
|
+
options.print(line);
|
|
130
|
+
}
|
|
131
|
+
return { kind: 'watch', inspectorUrl: inspector.url, logKey, peerKey, close };
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
await close().catch(() => { });
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** One sentence for a log that could not be joined: what happened and what to do. */
|
|
139
|
+
function joinError(code, logKey, ownKey, team) {
|
|
140
|
+
if (code === 'not_found') {
|
|
141
|
+
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).`);
|
|
142
|
+
}
|
|
143
|
+
return new HopwireError(team
|
|
144
|
+
? `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}.`
|
|
145
|
+
: `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.`);
|
|
146
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { parseDocument } from 'yaml';
|
|
3
|
+
import { INSPECTOR_DEFAULT_PORT, HOPWIRE_YAML_FILE, HOPWIRE_YAML_VERSION, isBasicCredentials, isPublicKeyHex, isReservableSubdomain, } from '@hopwire/protocol';
|
|
4
|
+
import { HopwireError } from './errors.js';
|
|
5
|
+
import { printable } from './output.js';
|
|
6
|
+
import { parseControlPlaneUrl, parseEdgeUrl, parseLocalTarget } from './urls.js';
|
|
7
|
+
/** A hopwire.yaml that cannot be used. `path` is the offending field, null when the file as a whole is at fault. */
|
|
8
|
+
export class ConfigError extends HopwireError {
|
|
9
|
+
file;
|
|
10
|
+
path;
|
|
11
|
+
constructor(file, path, problem) {
|
|
12
|
+
super(path === null ? `${file} ${problem}` : `${file}: ${path} ${problem}`);
|
|
13
|
+
this.file = file;
|
|
14
|
+
this.path = path;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** What a check found: the path of the field, and the rest of the sentence. */
|
|
18
|
+
class Problem {
|
|
19
|
+
path;
|
|
20
|
+
problem;
|
|
21
|
+
constructor(path, problem) {
|
|
22
|
+
this.path = path;
|
|
23
|
+
this.problem = problem;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const ROOT_KEYS = ['version', 'inspector', 'edge', 'controlPlane', 'p2p', 'services'];
|
|
27
|
+
const SERVICE_KEYS = ['local', 'public', 'subdomain', 'auth'];
|
|
28
|
+
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
|
+
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
|
+
/**
|
|
31
|
+
* Reads and validates a config file. `named` is true when the user chose the path with --config; `shown` is how
|
|
32
|
+
* the sentences name the file (the path itself unless the caller has a shorter one).
|
|
33
|
+
*/
|
|
34
|
+
export async function loadConfig(file, named, shown = file) {
|
|
35
|
+
let text;
|
|
36
|
+
try {
|
|
37
|
+
text = await readFile(file, 'utf8');
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
const code = typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : 'UNKNOWN';
|
|
41
|
+
if (code === 'ENOENT') {
|
|
42
|
+
throw new HopwireError(named
|
|
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>.`);
|
|
45
|
+
}
|
|
46
|
+
throw new HopwireError(`The config file ${shown} cannot be read (${code}); check that it is a readable file.`);
|
|
47
|
+
}
|
|
48
|
+
return parseConfig(text, shown);
|
|
49
|
+
}
|
|
50
|
+
/** Validates the text of a hopwire.yaml. Throws a ConfigError that names the offending field. */
|
|
51
|
+
export function parseConfig(text, file = HOPWIRE_YAML_FILE) {
|
|
52
|
+
// logLevel: the parser warns on stderr about a key that is a list or a mapping and quotes it; such a key is
|
|
53
|
+
// refused below, in the one sentence of this module
|
|
54
|
+
const document = parseDocument(text, { prettyErrors: true, uniqueKeys: true, logLevel: 'error' });
|
|
55
|
+
const [syntaxError] = document.errors;
|
|
56
|
+
if (syntaxError !== undefined) {
|
|
57
|
+
throw new ConfigError(file, null, `is not valid YAML: ${describeSyntaxError(syntaxError.message)}; correct the file and start again.`);
|
|
58
|
+
}
|
|
59
|
+
let value;
|
|
60
|
+
let ordered;
|
|
61
|
+
try {
|
|
62
|
+
value = document.toJS();
|
|
63
|
+
// The same once more with mappings as Maps, which keep the keys as YAML has them and in the order of the file
|
|
64
|
+
ordered = document.toJS({ mapAsMap: true });
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// Thrown while the document is resolved; its message names the alias, which is text from the file
|
|
68
|
+
throw new ConfigError(file, null, 'is not valid YAML: an alias (*name) has no anchor, or aliases are nested too deep; correct the file and start again.');
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
return validate(value, ordered);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error instanceof Problem) {
|
|
75
|
+
throw new ConfigError(file, error.path === null ? null : formatPath(error.path), error.problem);
|
|
76
|
+
}
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* What is wrong and where, from the message of the YAML parser: `<what> at line 4, column 9:` followed by lines that
|
|
82
|
+
* quote the file. Only the kind of problem and the position are kept: a quoted line, or a name the parser repeats
|
|
83
|
+
* after a colon, may be part of a password.
|
|
84
|
+
*/
|
|
85
|
+
function describeSyntaxError(message) {
|
|
86
|
+
const firstLine = message.split('\n')[0] ?? '';
|
|
87
|
+
const match = /^(.*?)( at line \d+, column \d+):?$/.exec(firstLine);
|
|
88
|
+
const what = (match?.[1] ?? firstLine).split(': ')[0] ?? '';
|
|
89
|
+
return printable(`${what === '' ? 'syntax error' : what}${match?.[2] ?? ''}`);
|
|
90
|
+
}
|
|
91
|
+
/** `value` is the file as plain objects, `ordered` the same with every mapping as a Map. */
|
|
92
|
+
function validate(value, ordered) {
|
|
93
|
+
if (value === null || value === undefined) {
|
|
94
|
+
throw new Problem(null, `is empty; it needs "version: ${HOPWIRE_YAML_VERSION}" and at least one service.`);
|
|
95
|
+
}
|
|
96
|
+
const root = mapping(value, [], ROOT_KEYS, 'the file');
|
|
97
|
+
if (root.version === undefined) {
|
|
98
|
+
throw new Problem(['version'], `is missing; add "version: ${HOPWIRE_YAML_VERSION}" to the file.`);
|
|
99
|
+
}
|
|
100
|
+
if (root.version !== HOPWIRE_YAML_VERSION) {
|
|
101
|
+
throw new Problem(['version'], `must be ${HOPWIRE_YAML_VERSION}, the only version of the format this tunnel reads.`);
|
|
102
|
+
}
|
|
103
|
+
let inspectorPort = INSPECTOR_DEFAULT_PORT;
|
|
104
|
+
if (root.inspector !== undefined) {
|
|
105
|
+
const inspector = mapping(root.inspector, ['inspector'], ['port'], 'inspector');
|
|
106
|
+
if (inspector.port !== undefined) {
|
|
107
|
+
const { port } = inspector;
|
|
108
|
+
if (typeof port !== 'number' || !Number.isInteger(port) || port < 0 || port > 65535) {
|
|
109
|
+
throw new Problem(['inspector', 'port'], 'must be a port number between 0 and 65535 (0 picks a free one).');
|
|
110
|
+
}
|
|
111
|
+
inspectorPort = port;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
let edgeUrl = null;
|
|
115
|
+
if (root.edge !== undefined) {
|
|
116
|
+
const edge = mapping(root.edge, ['edge'], ['url'], 'edge');
|
|
117
|
+
if (edge.url !== undefined) {
|
|
118
|
+
const parsed = typeof edge.url === 'string' ? parseEdgeUrl(edge.url) : 'malformed';
|
|
119
|
+
if (parsed === 'malformed') {
|
|
120
|
+
throw new Problem(['edge', 'url'], 'must be a ws:// or wss:// URL without a path, for example wss://edge.hwr.sh or ws://127.0.0.1:8787 for a local edge.');
|
|
121
|
+
}
|
|
122
|
+
if (parsed === 'insecure') {
|
|
123
|
+
throw new Problem(['edge', 'url'], 'must use wss:// unless the edge runs on this machine; over ws:// the token would travel unencrypted.');
|
|
124
|
+
}
|
|
125
|
+
edgeUrl = parsed;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
let controlPlaneUrl = null;
|
|
129
|
+
if (root.controlPlane !== undefined) {
|
|
130
|
+
const controlPlane = mapping(root.controlPlane, ['controlPlane'], ['url'], 'controlPlane');
|
|
131
|
+
if (controlPlane.url !== undefined) {
|
|
132
|
+
const parsed = typeof controlPlane.url === 'string' ? parseControlPlaneUrl(controlPlane.url) : 'malformed';
|
|
133
|
+
if (parsed === 'malformed') {
|
|
134
|
+
throw new Problem(['controlPlane', 'url'], 'must be an http:// or https:// URL without a path, for example https://hopwire.to.');
|
|
135
|
+
}
|
|
136
|
+
if (parsed === 'insecure') {
|
|
137
|
+
throw new Problem(['controlPlane', 'url'], 'must use https:// unless the control plane runs on this machine; over http:// the API token would travel unencrypted.');
|
|
138
|
+
}
|
|
139
|
+
controlPlaneUrl = parsed;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
let share = false;
|
|
143
|
+
let allow = null;
|
|
144
|
+
let team = false;
|
|
145
|
+
if (root.p2p !== undefined) {
|
|
146
|
+
const p2p = mapping(root.p2p, ['p2p'], ['share', 'allow', 'team'], 'p2p');
|
|
147
|
+
share = boolean(p2p.share, ['p2p', 'share']);
|
|
148
|
+
team = boolean(p2p.team, ['p2p', 'team']);
|
|
149
|
+
if (team && !share) {
|
|
150
|
+
throw new Problem(['p2p', 'team'], 'only works together with p2p.share: true; it decides who the shared services and the shared log are for.');
|
|
151
|
+
}
|
|
152
|
+
if (team && p2p.allow !== undefined) {
|
|
153
|
+
throw new Problem(['p2p', 'allow'], 'cannot be combined with p2p.team: the team is the list then; remove one of the two.');
|
|
154
|
+
}
|
|
155
|
+
if (p2p.allow !== undefined) {
|
|
156
|
+
if (!Array.isArray(p2p.allow)) {
|
|
157
|
+
throw new Problem(['p2p', 'allow'], 'must be a list of public keys, as "hopwire id" prints them.');
|
|
158
|
+
}
|
|
159
|
+
if (p2p.allow.length === 0) {
|
|
160
|
+
throw new Problem(['p2p', 'allow'], 'must list at least one public key; remove the key to let every teammate with the keys in.');
|
|
161
|
+
}
|
|
162
|
+
allow = p2p.allow.map((key, index) => {
|
|
163
|
+
if (typeof key !== 'string' || !isPublicKeyHex(key)) {
|
|
164
|
+
throw new Problem(['p2p', 'allow', index], 'must be a public key: 64 hexadecimal characters, as "hopwire id" prints them.');
|
|
165
|
+
}
|
|
166
|
+
return key.toLowerCase();
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (root.services === undefined) {
|
|
171
|
+
throw new Problem(['services'], 'is missing; add at least one service with its local URL.');
|
|
172
|
+
}
|
|
173
|
+
if (!isMapping(root.services)) {
|
|
174
|
+
throw new Problem(['services'], 'must be a mapping of service names to their settings.');
|
|
175
|
+
}
|
|
176
|
+
const settings = new Map(Object.entries(root.services));
|
|
177
|
+
const services = serviceNames(ordered).map((name) => validateService(name, settings.get(name)));
|
|
178
|
+
if (services.length === 0) {
|
|
179
|
+
throw new Problem(['services'], 'must name at least one service with its local URL.');
|
|
180
|
+
}
|
|
181
|
+
const subdomains = new Map();
|
|
182
|
+
for (const service of services) {
|
|
183
|
+
if (service.public && service.subdomain !== null) {
|
|
184
|
+
const other = subdomains.get(service.subdomain);
|
|
185
|
+
if (other !== undefined) {
|
|
186
|
+
throw new Problem(['services', service.name, 'subdomain'], `is also the subdomain of the service ${printable(other)}; a subdomain serves one service, so give each its own.`);
|
|
187
|
+
}
|
|
188
|
+
subdomains.set(service.subdomain, service.name);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (edgeUrl === null && services.some((service) => service.public)) {
|
|
192
|
+
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.');
|
|
193
|
+
}
|
|
194
|
+
return { inspectorPort, edgeUrl, controlPlaneUrl, share, allow, team, services };
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* The names of the services in the order of the file. The plain object cannot say: JavaScript lists keys that look
|
|
198
|
+
* like whole numbers first (`8080:` before `web:`), and `1` and "1", two keys for YAML, are one property of it, so
|
|
199
|
+
* the first of the two services would be dropped without a word. A name is the text of its key.
|
|
200
|
+
*/
|
|
201
|
+
function serviceNames(ordered) {
|
|
202
|
+
const services = ordered instanceof Map ? ordered.get('services') : undefined;
|
|
203
|
+
if (!(services instanceof Map)) {
|
|
204
|
+
throw new Problem(['services'], 'must be a mapping of service names to their settings.');
|
|
205
|
+
}
|
|
206
|
+
const names = [];
|
|
207
|
+
for (const key of services.keys()) {
|
|
208
|
+
if (typeof key === 'object' && key !== null) {
|
|
209
|
+
throw new Problem(['services'], 'has a key that is a list or a mapping; name each service with one plain word or number.');
|
|
210
|
+
}
|
|
211
|
+
const name = key === null ? '' : String(key);
|
|
212
|
+
if (names.includes(name)) {
|
|
213
|
+
throw new Problem(['services', name], 'is given twice; a number and the same number in quotes are one service name, so give each service its own.');
|
|
214
|
+
}
|
|
215
|
+
names.push(name);
|
|
216
|
+
}
|
|
217
|
+
return names;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* A name a service can have, in hopwire.yaml and as --name: 1 to 255 bytes (the limit of the connect preface, where a
|
|
221
|
+
* teammate asks for a service by its name) without control characters.
|
|
222
|
+
*/
|
|
223
|
+
export function isServiceName(name) {
|
|
224
|
+
return name !== '' && Buffer.byteLength(name) <= 255 && printable(name) === name;
|
|
225
|
+
}
|
|
226
|
+
function validateService(name, value) {
|
|
227
|
+
const path = ['services', name];
|
|
228
|
+
if (!isServiceName(name)) {
|
|
229
|
+
throw new Problem(path, 'is not a usable service name; use 1 to 255 bytes without control characters.');
|
|
230
|
+
}
|
|
231
|
+
const service = mapping(value, path, SERVICE_KEYS, 'a service');
|
|
232
|
+
if (service.local === undefined) {
|
|
233
|
+
throw new Problem([...path, 'local'], `is missing; it ${LOCAL_RULE}`);
|
|
234
|
+
}
|
|
235
|
+
const local = typeof service.local === 'string' ? parseLocalTarget(service.local) : null;
|
|
236
|
+
if (local === null) {
|
|
237
|
+
throw new Problem([...path, 'local'], LOCAL_RULE);
|
|
238
|
+
}
|
|
239
|
+
let subdomain = null;
|
|
240
|
+
if (service.subdomain !== undefined) {
|
|
241
|
+
if (typeof service.subdomain !== 'string' || !isReservableSubdomain(service.subdomain)) {
|
|
242
|
+
throw new Problem([...path, 'subdomain'], SUBDOMAIN_RULE);
|
|
243
|
+
}
|
|
244
|
+
subdomain = service.subdomain;
|
|
245
|
+
}
|
|
246
|
+
let basicAuth = null;
|
|
247
|
+
if (service.auth !== undefined) {
|
|
248
|
+
const auth = mapping(service.auth, [...path, 'auth'], ['basic'], 'auth');
|
|
249
|
+
if (auth.basic !== undefined) {
|
|
250
|
+
// The value is a credential: the sentence never repeats it
|
|
251
|
+
if (typeof auth.basic !== 'string' || !isBasicCredentials(auth.basic)) {
|
|
252
|
+
throw new Problem([...path, 'auth', 'basic'], 'must be user:password with a user that contains no colon, a password, no control characters and at most 512 bytes.');
|
|
253
|
+
}
|
|
254
|
+
basicAuth = auth.basic;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return { name, local, public: boolean(service.public, [...path, 'public']), subdomain, basicAuth };
|
|
258
|
+
}
|
|
259
|
+
function isMapping(value) {
|
|
260
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date);
|
|
261
|
+
}
|
|
262
|
+
/** A mapping that has no other keys than the ones the format knows. */
|
|
263
|
+
function mapping(value, path, allowed, what) {
|
|
264
|
+
if (!isMapping(value)) {
|
|
265
|
+
throw new Problem(path.length === 0 ? null : path, `must be a mapping with the ${allowed.length === 1 ? 'key' : 'keys'} ${list(allowed)}.`);
|
|
266
|
+
}
|
|
267
|
+
for (const key of Object.keys(value)) {
|
|
268
|
+
if (!allowed.includes(key)) {
|
|
269
|
+
throw new Problem([...path, key], `is not a key Hopwire knows; ${what} takes ${list(allowed)}.`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return value;
|
|
273
|
+
}
|
|
274
|
+
/** A boolean that defaults to false. YAML 1.2 knows true and false only: yes, on and 1 are not booleans. */
|
|
275
|
+
function boolean(value, path) {
|
|
276
|
+
if (value === undefined) {
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
if (typeof value !== 'boolean') {
|
|
280
|
+
throw new Problem(path, 'must be true or false.');
|
|
281
|
+
}
|
|
282
|
+
return value;
|
|
283
|
+
}
|
|
284
|
+
function list(names) {
|
|
285
|
+
return names.length === 1
|
|
286
|
+
? String(names[0])
|
|
287
|
+
: `${names.slice(0, -1).join(', ')} and ${String(names[names.length - 1])}`;
|
|
288
|
+
}
|
|
289
|
+
/** `services.api.local`, `p2p.allow[0]`; a name that is not a plain word is quoted: `services["my app"].local`. */
|
|
290
|
+
function formatPath(path) {
|
|
291
|
+
return path
|
|
292
|
+
.map((segment, index) => {
|
|
293
|
+
if (typeof segment === 'number') {
|
|
294
|
+
return `[${segment}]`;
|
|
295
|
+
}
|
|
296
|
+
if (/^[A-Za-z0-9_-]+$/.test(segment)) {
|
|
297
|
+
return index === 0 ? segment : `.${segment}`;
|
|
298
|
+
}
|
|
299
|
+
return `[${JSON.stringify(printable(segment))}]`;
|
|
300
|
+
})
|
|
301
|
+
.join('');
|
|
302
|
+
}
|