hopwire 0.2.1 → 0.4.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/dist/bin.js +142 -6
- package/dist/cli.js +164 -14
- package/dist/commands/chaos.js +186 -0
- package/dist/commands/fix.js +177 -0
- package/dist/commands/http.js +5 -2
- package/dist/commands/snapshot.js +81 -0
- package/dist/commands/up.js +5 -2
- package/dist/commands/verify.js +64 -0
- package/dist/commands/watch.js +12 -4
- package/dist/config-template.js +1 -0
- package/dist/config.js +22 -1
- package/dist/curl.js +59 -0
- package/dist/errors.js +3 -0
- package/dist/inspector/assets/{index-CIOfyIbK.js → index-CdyIIKdA.js} +1 -1
- package/dist/inspector/index.html +1 -1
- package/dist/live.js +226 -0
- package/dist/main.js +17 -4
- package/dist/output.js +19 -0
- package/dist/p2p.js +59 -1
- package/dist/serve.js +27 -1
- package/dist/shapes.js +216 -0
- package/dist/shortcuts.js +242 -0
- package/dist/signature.js +207 -0
- package/dist/style.js +6 -0
- package/dist/terminal.js +671 -0
- package/dist/traffic.js +247 -0
- package/dist/version.js +12 -0
- package/dist/webhook.js +91 -0
- package/package.json +1 -1
package/dist/p2p.js
CHANGED
|
@@ -36,6 +36,11 @@ const MAX_STREAMS = 64;
|
|
|
36
36
|
const MAX_STREAMS_PER_PEER = 16;
|
|
37
37
|
/** Keeps a relayed replication from being taken for idle by the edge while the log has nothing new. */
|
|
38
38
|
const RELAY_KEEPALIVE_MS = 30_000;
|
|
39
|
+
/**
|
|
40
|
+
* A teammate's `hopwire connect` opens and closes streams as its HTTP connections come and go; it counts as gone only
|
|
41
|
+
* when it held none for this long.
|
|
42
|
+
*/
|
|
43
|
+
const PEER_GONE_MS = 15_000;
|
|
39
44
|
/**
|
|
40
45
|
* `--share`: answers `hopwire connect` on the identity key (p2pConnect) and
|
|
41
46
|
* announces the traffic log for `hopwire watch` (logReplication). With an
|
|
@@ -95,6 +100,56 @@ export async function startSharing(options) {
|
|
|
95
100
|
/** Streams held, from their arrival to their close, refused ones not counted: in total and per public key */
|
|
96
101
|
let held = 0;
|
|
97
102
|
const heldPerPeer = new Map();
|
|
103
|
+
const onPeerEvent = options.onPeerEvent ?? (() => { });
|
|
104
|
+
/** Streams of `hopwire connect` per key, and the timers that say a key is gone */
|
|
105
|
+
const connected = new Map();
|
|
106
|
+
const goneTimers = new Map();
|
|
107
|
+
const connectedStream = (peer, socket) => {
|
|
108
|
+
const timer = goneTimers.get(peer);
|
|
109
|
+
if (timer !== undefined) {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
goneTimers.delete(peer);
|
|
112
|
+
}
|
|
113
|
+
const before = connected.get(peer) ?? 0;
|
|
114
|
+
connected.set(peer, before + 1);
|
|
115
|
+
if (before === 0 && timer === undefined) {
|
|
116
|
+
onPeerEvent({ type: 'connected', key: peer });
|
|
117
|
+
}
|
|
118
|
+
socket.once('close', () => {
|
|
119
|
+
const left = (connected.get(peer) ?? 1) - 1;
|
|
120
|
+
connected.set(peer, left);
|
|
121
|
+
if (left === 0) {
|
|
122
|
+
const gone = setTimeout(() => {
|
|
123
|
+
goneTimers.delete(peer);
|
|
124
|
+
if ((connected.get(peer) ?? 0) === 0) {
|
|
125
|
+
connected.delete(peer);
|
|
126
|
+
onPeerEvent({ type: 'disconnected', key: peer });
|
|
127
|
+
}
|
|
128
|
+
}, PEER_GONE_MS);
|
|
129
|
+
gone.unref();
|
|
130
|
+
goneTimers.set(peer, gone);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
};
|
|
134
|
+
/** Replications per watching key */
|
|
135
|
+
const watching = new Map();
|
|
136
|
+
const watchedBy = (peer, connection) => {
|
|
137
|
+
const before = watching.get(peer) ?? 0;
|
|
138
|
+
watching.set(peer, before + 1);
|
|
139
|
+
if (before === 0) {
|
|
140
|
+
onPeerEvent({ type: 'watching', key: peer });
|
|
141
|
+
}
|
|
142
|
+
connection.once('close', () => {
|
|
143
|
+
const left = (watching.get(peer) ?? 1) - 1;
|
|
144
|
+
if (left === 0) {
|
|
145
|
+
watching.delete(peer);
|
|
146
|
+
onPeerEvent({ type: 'stopped_watching', key: peer });
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
watching.set(peer, left);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
};
|
|
98
153
|
const accept = async (stream) => {
|
|
99
154
|
const socket = toNodeDuplex(stream);
|
|
100
155
|
sockets.add(socket);
|
|
@@ -156,6 +211,7 @@ export async function startSharing(options) {
|
|
|
156
211
|
return;
|
|
157
212
|
}
|
|
158
213
|
socket.write(encodeP2pPrefaceReply({ ok: true }));
|
|
214
|
+
connectedStream(peer, socket);
|
|
159
215
|
// From here on the stream is an HTTP/1.1 connection of the in-process server
|
|
160
216
|
watchdogs.set(socket, watchHttpConnection(socket, timeouts));
|
|
161
217
|
servers.get(chosen.name)?.emit('connection', socket);
|
|
@@ -175,11 +231,12 @@ export async function startSharing(options) {
|
|
|
175
231
|
connection.destroy();
|
|
176
232
|
return;
|
|
177
233
|
}
|
|
234
|
+
const peer = connection.remotePublicKey.toString('hex');
|
|
178
235
|
if (admission === null) {
|
|
236
|
+
watchedBy(peer, connection);
|
|
179
237
|
log.replicate(connection);
|
|
180
238
|
return;
|
|
181
239
|
}
|
|
182
|
-
const peer = connection.remotePublicKey.toString('hex');
|
|
183
240
|
void admission.admits(peer).then((admitted) => {
|
|
184
241
|
if (connection.destroyed) {
|
|
185
242
|
return;
|
|
@@ -189,6 +246,7 @@ export async function startSharing(options) {
|
|
|
189
246
|
return;
|
|
190
247
|
}
|
|
191
248
|
track(peer, connection);
|
|
249
|
+
watchedBy(peer, connection);
|
|
192
250
|
log.replicate(connection);
|
|
193
251
|
});
|
|
194
252
|
};
|
package/dist/serve.js
CHANGED
|
@@ -9,6 +9,7 @@ import { createInterceptor } from './interceptor.js';
|
|
|
9
9
|
import { openOwnLog } from './data-dir-holder.js';
|
|
10
10
|
import { InFlightExchanges, followLogFile } from './log-follow.js';
|
|
11
11
|
import { createProxyServer } from './proxy-server.js';
|
|
12
|
+
import { ShapeBook } from './shapes.js';
|
|
12
13
|
import { Supervisor } from './supervisor.js';
|
|
13
14
|
/**
|
|
14
15
|
* What `hopwire http` (one service) and `hopwire up` (the services of hopwire.yaml) have in common: one traffic log,
|
|
@@ -46,6 +47,30 @@ export async function startServing(options) {
|
|
|
46
47
|
supervisor.add('store', () => local.close());
|
|
47
48
|
}
|
|
48
49
|
const shareLogs = options.share && options.shareLogs === true;
|
|
50
|
+
// Payload drift: the shapes of earlier webhooks, kept in the data directory; saved a moment after a change
|
|
51
|
+
const shapes = await ShapeBook.open(options.dataDir);
|
|
52
|
+
let saving = null;
|
|
53
|
+
const saveShapes = () => {
|
|
54
|
+
saving = null;
|
|
55
|
+
void shapes.save().catch(() => { });
|
|
56
|
+
};
|
|
57
|
+
supervisor.add('servers', async () => {
|
|
58
|
+
if (saving !== null) {
|
|
59
|
+
clearTimeout(saving);
|
|
60
|
+
await shapes.save().catch(() => { });
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
const onExchange = (exchange) => {
|
|
64
|
+
options.onExchange(exchange);
|
|
65
|
+
const drift = shapes.observe(exchange);
|
|
66
|
+
if (drift !== null) {
|
|
67
|
+
options.onDrift?.(drift);
|
|
68
|
+
}
|
|
69
|
+
if (exchange.source !== 'replay' && saving === null) {
|
|
70
|
+
saving = setTimeout(saveShapes, 2000);
|
|
71
|
+
saving.unref();
|
|
72
|
+
}
|
|
73
|
+
};
|
|
49
74
|
const interceptors = new Map();
|
|
50
75
|
const inFlight = new Map();
|
|
51
76
|
const services = [];
|
|
@@ -63,7 +88,7 @@ export async function startServing(options) {
|
|
|
63
88
|
logRequestId: options.logRequestId === true && tracked !== undefined,
|
|
64
89
|
allowAgents: options.share && options.allowAgents === true,
|
|
65
90
|
captureWebSocketMessages: options.captureWebSocketMessages ?? true,
|
|
66
|
-
onExchange
|
|
91
|
+
onExchange,
|
|
67
92
|
onLogError: () => {
|
|
68
93
|
if (!storeClosing) {
|
|
69
94
|
options.onLogError(service.name);
|
|
@@ -156,6 +181,7 @@ export async function startServing(options) {
|
|
|
156
181
|
signal: options.signal,
|
|
157
182
|
relay: relaySetup,
|
|
158
183
|
onRelayEvent: options.onRelayEvent,
|
|
184
|
+
onPeerEvent: options.onPeerEvent,
|
|
159
185
|
});
|
|
160
186
|
supervisor.add('p2p', () => sharing.close());
|
|
161
187
|
peerKey = sharing.peerKey;
|
package/dist/shapes.js
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { printable } from './output.js';
|
|
4
|
+
import { recogniseWebhook } from './webhook.js';
|
|
5
|
+
/**
|
|
6
|
+
* Payload drift: the shape of the JSON bodies of each provider's events, as this machine saw them, and a line when a
|
|
7
|
+
* new body of the same event differs: a field never seen, a field that was always there and is missing, a field whose
|
|
8
|
+
* type changed. Only paths and types are kept, never values, in shapes.json of the data directory.
|
|
9
|
+
*/
|
|
10
|
+
/** How deep into a body paths are followed, and how many of one body are kept. */
|
|
11
|
+
const MAX_DEPTH = 6;
|
|
12
|
+
const MAX_PATHS = 500;
|
|
13
|
+
/** Samples needed before something counts as new, and before a missing field counts as missing. */
|
|
14
|
+
const NEW_AFTER = 3;
|
|
15
|
+
const MISSING_AFTER = 5;
|
|
16
|
+
/** Bodies larger than this are not read for their shape. */
|
|
17
|
+
const PARSE_LIMIT_BYTES = 1024 * 1024;
|
|
18
|
+
/** Events kept in the file; the ones seen least recently go first. */
|
|
19
|
+
const MAX_EVENTS = 500;
|
|
20
|
+
/** The paths of a JSON value with their types: `data.object.id` -> string; array items share `items[]`. */
|
|
21
|
+
export function shapeOf(value) {
|
|
22
|
+
const paths = new Map();
|
|
23
|
+
const walk = (node, at, depth) => {
|
|
24
|
+
if (paths.size >= MAX_PATHS) {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const type = typeOf(node);
|
|
28
|
+
if (at !== '') {
|
|
29
|
+
paths.set(at, type);
|
|
30
|
+
}
|
|
31
|
+
if (depth >= MAX_DEPTH) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (type === 'object') {
|
|
35
|
+
for (const [key, child] of Object.entries(node)) {
|
|
36
|
+
walk(child, at === '' ? key : `${at}.${key}`, depth + 1);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
else if (type === 'array') {
|
|
40
|
+
for (const item of node) {
|
|
41
|
+
walk(item, `${at}[]`, depth + 1);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
walk(value, '', 0);
|
|
46
|
+
return paths;
|
|
47
|
+
}
|
|
48
|
+
function typeOf(value) {
|
|
49
|
+
if (value === null) {
|
|
50
|
+
return 'null';
|
|
51
|
+
}
|
|
52
|
+
if (Array.isArray(value)) {
|
|
53
|
+
return 'array';
|
|
54
|
+
}
|
|
55
|
+
const type = typeof value;
|
|
56
|
+
return type === 'object' || type === 'string' || type === 'number' || type === 'boolean' ? type : 'null';
|
|
57
|
+
}
|
|
58
|
+
/** The book of shapes of one data directory. */
|
|
59
|
+
export class ShapeBook {
|
|
60
|
+
file;
|
|
61
|
+
events;
|
|
62
|
+
constructor(file, events) {
|
|
63
|
+
this.file = file;
|
|
64
|
+
this.events = events;
|
|
65
|
+
}
|
|
66
|
+
/** Opens shapes.json of the data directory; a missing or unreadable file starts an empty book. */
|
|
67
|
+
static async open(dataDir) {
|
|
68
|
+
const file = path.join(dataDir, 'shapes.json');
|
|
69
|
+
const events = new Map();
|
|
70
|
+
try {
|
|
71
|
+
const parsed = JSON.parse(await readFile(file, 'utf8'));
|
|
72
|
+
if (typeof parsed === 'object' && parsed !== null && 'events' in parsed) {
|
|
73
|
+
const stored = parsed.events;
|
|
74
|
+
if (typeof stored === 'object' && stored !== null) {
|
|
75
|
+
for (const [key, shape] of Object.entries(stored)) {
|
|
76
|
+
if (isEventShape(shape)) {
|
|
77
|
+
events.set(key, shape);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
// No book yet, or one that cannot be read: start again
|
|
85
|
+
}
|
|
86
|
+
return new ShapeBook(file, events);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Takes in one exchange: a drift when the body of a known event differs from what was seen before, else null. The
|
|
90
|
+
* body is learned either way.
|
|
91
|
+
*/
|
|
92
|
+
observe(exchange) {
|
|
93
|
+
if (exchange.source === 'replay') {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const webhook = recogniseWebhook(exchange);
|
|
97
|
+
if (webhook === null || webhook.event === null) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
const body = jsonBody(exchange);
|
|
101
|
+
if (body === null) {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
const now = exchange.timestamp;
|
|
105
|
+
const shape = shapeOf(body);
|
|
106
|
+
const key = `${webhook.provider} ${webhook.event}`;
|
|
107
|
+
const known = this.events.get(key);
|
|
108
|
+
const drift = known === undefined ? null : compare(webhook.provider, webhook.event, known, shape);
|
|
109
|
+
const entry = known ?? { samples: 0, firstSeen: now, lastSeen: now, paths: {} };
|
|
110
|
+
entry.samples += 1;
|
|
111
|
+
entry.lastSeen = now;
|
|
112
|
+
for (const [at, type] of shape) {
|
|
113
|
+
const seen = entry.paths[at] ?? { count: 0, types: [] };
|
|
114
|
+
seen.count += 1;
|
|
115
|
+
if (!seen.types.includes(type)) {
|
|
116
|
+
seen.types.push(type);
|
|
117
|
+
}
|
|
118
|
+
entry.paths[at] = seen;
|
|
119
|
+
}
|
|
120
|
+
this.events.delete(key);
|
|
121
|
+
this.events.set(key, entry);
|
|
122
|
+
while (this.events.size > MAX_EVENTS) {
|
|
123
|
+
const oldest = this.events.keys().next().value;
|
|
124
|
+
if (oldest === undefined) {
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
this.events.delete(oldest);
|
|
128
|
+
}
|
|
129
|
+
return drift;
|
|
130
|
+
}
|
|
131
|
+
/** Writes the book: to a temporary file first, so a crash never leaves half of it. */
|
|
132
|
+
async save() {
|
|
133
|
+
await mkdir(path.dirname(this.file), { recursive: true });
|
|
134
|
+
const temporary = `${this.file}.${process.pid}.tmp`;
|
|
135
|
+
await writeFile(temporary, JSON.stringify({ version: 1, events: Object.fromEntries(this.events) }), {
|
|
136
|
+
mode: 0o600,
|
|
137
|
+
});
|
|
138
|
+
await rename(temporary, this.file);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function compare(provider, event, known, shape) {
|
|
142
|
+
const added = [];
|
|
143
|
+
const missing = [];
|
|
144
|
+
const retyped = [];
|
|
145
|
+
if (known.samples >= NEW_AFTER) {
|
|
146
|
+
for (const [at, type] of shape) {
|
|
147
|
+
const seen = known.paths[at];
|
|
148
|
+
if (seen === undefined) {
|
|
149
|
+
// Under a new object or array only its top is named
|
|
150
|
+
if (!added.some((parent) => at.startsWith(`${parent}.`) || at.startsWith(`${parent}[]`))) {
|
|
151
|
+
added.push(at);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
else if (!seen.types.includes(type) && !(type === 'null' || seen.types.includes('null'))) {
|
|
155
|
+
retyped.push({ path: at, was: [...seen.types], now: type });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (known.samples >= MISSING_AFTER) {
|
|
160
|
+
for (const [at, seen] of Object.entries(known.paths)) {
|
|
161
|
+
if (seen.count === known.samples && !shape.has(at)) {
|
|
162
|
+
if (!missing.some((parent) => at.startsWith(`${parent}.`) || at.startsWith(`${parent}[]`))) {
|
|
163
|
+
missing.push(at);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (added.length === 0 && missing.length === 0 && retyped.length === 0) {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
return { provider, event, added, missing, retyped, samples: known.samples, since: known.firstSeen };
|
|
172
|
+
}
|
|
173
|
+
function jsonBody(exchange) {
|
|
174
|
+
const { request } = exchange;
|
|
175
|
+
if (request.bodyTruncated ||
|
|
176
|
+
request.bodyBase64.length === 0 ||
|
|
177
|
+
(request.bodyBase64.length / 4) * 3 > PARSE_LIMIT_BYTES) {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
const value = JSON.parse(Buffer.from(request.bodyBase64, 'base64').toString('utf8'));
|
|
182
|
+
return typeof value === 'object' && value !== null ? value : null;
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function isEventShape(value) {
|
|
189
|
+
if (typeof value !== 'object' || value === null) {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
const shape = value;
|
|
193
|
+
return (typeof shape.samples === 'number' &&
|
|
194
|
+
typeof shape.firstSeen === 'number' &&
|
|
195
|
+
typeof shape.lastSeen === 'number' &&
|
|
196
|
+
typeof shape.paths === 'object' &&
|
|
197
|
+
shape.paths !== null);
|
|
198
|
+
}
|
|
199
|
+
/** Longest list of paths a drift line names; the rest are counted. */
|
|
200
|
+
const LISTED = 4;
|
|
201
|
+
/** The line of a drift, as hopwire prints it. */
|
|
202
|
+
export function formatDrift(drift) {
|
|
203
|
+
const list = (paths) => paths.length <= LISTED
|
|
204
|
+
? paths.join(', ')
|
|
205
|
+
: `${paths.slice(0, LISTED).join(', ')} and ${paths.length - LISTED} more`;
|
|
206
|
+
const parts = [
|
|
207
|
+
...(drift.added.length > 0 ? [`new ${list(drift.added)}`] : []),
|
|
208
|
+
...(drift.missing.length > 0 ? [`missing ${list(drift.missing)}`] : []),
|
|
209
|
+
...drift.retyped
|
|
210
|
+
.slice(0, LISTED)
|
|
211
|
+
.map((entry) => `${entry.path} is now ${entry.now} (was ${entry.was.join(' or ')})`),
|
|
212
|
+
];
|
|
213
|
+
const day = new Date(drift.since).toISOString().slice(0, 10);
|
|
214
|
+
// Provider, event and paths come from a request: nothing in them may reach the terminal as an escape sequence
|
|
215
|
+
return `Drift ${printable(`${drift.provider} ${drift.event}: ${parts.join('; ')}`)} (against ${drift.samples} earlier ${drift.samples === 1 ? 'request' : 'requests'} since ${day})`;
|
|
216
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { curlCommand } from './curl.js';
|
|
3
|
+
import { mainPublicUrl, printable } from './output.js';
|
|
4
|
+
/** The keys act on tunnels that show exchanges: http, up and watch. Connect and mcp keep the terminal as it is. */
|
|
5
|
+
export function shortcutTarget(running) {
|
|
6
|
+
switch (running.kind) {
|
|
7
|
+
case 'http':
|
|
8
|
+
return { inspectorUrl: running.inspectorUrl, publicUrl: running.publicUrl, entry: () => running.url };
|
|
9
|
+
case 'up': {
|
|
10
|
+
const published = running.services.find((service) => service.publicUrl !== null);
|
|
11
|
+
return {
|
|
12
|
+
inspectorUrl: running.inspectorUrl,
|
|
13
|
+
publicUrl: published === undefined ? null : mainPublicUrl(published.publicUrl, published.customDomains),
|
|
14
|
+
entry: (name) => running.services.find((service) => service.name === name)?.url ?? null,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
case 'watch':
|
|
18
|
+
return { inspectorUrl: running.inspectorUrl, publicUrl: null, entry: () => running.replayTarget };
|
|
19
|
+
default:
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const CTRL_C = '\u0003';
|
|
24
|
+
/** The keys in a chunk of terminal input: an arrow arrives as one escape sequence, Escape alone as ESC. */
|
|
25
|
+
export function keysOf(chunk) {
|
|
26
|
+
const keys = [];
|
|
27
|
+
for (let index = 0; index < chunk.length;) {
|
|
28
|
+
// eslint-disable-next-line no-control-regex -- an escape sequence starts with ESC
|
|
29
|
+
const sequence = /^\u001b\[[0-9;]*[A-Za-z~]/.exec(chunk.slice(index));
|
|
30
|
+
if (sequence !== null) {
|
|
31
|
+
keys.push(sequence[0]);
|
|
32
|
+
index += sequence[0].length;
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
keys.push(chunk[index] ?? '');
|
|
36
|
+
index += 1;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return keys;
|
|
40
|
+
}
|
|
41
|
+
/** What ? lists. */
|
|
42
|
+
export const KEYS_HELP = '\u2191\u2193 pick a request, enter shows it, i opens it in the inspector, r replays it, y copies it as curl, o inspector, c copy the public URL, q quit';
|
|
43
|
+
/**
|
|
44
|
+
* Reads single keys while a tunnel runs: o opens the inspector, c copies the public URL, r replays the newest
|
|
45
|
+
* request, q and Ctrl+C stop. The terminal is put in raw mode for it, so Ctrl+C reaches here as a key and is turned
|
|
46
|
+
* into the same SIGINT as before. Returns what gives the terminal back.
|
|
47
|
+
*/
|
|
48
|
+
export function startShortcuts(input, actions) {
|
|
49
|
+
if (input.isTTY !== true || input.setRawMode === undefined) {
|
|
50
|
+
return () => { };
|
|
51
|
+
}
|
|
52
|
+
const setRawMode = input.setRawMode.bind(input);
|
|
53
|
+
const { target, say } = actions;
|
|
54
|
+
const onData = (chunk) => {
|
|
55
|
+
for (const key of keysOf(chunk)) {
|
|
56
|
+
switch (key) {
|
|
57
|
+
case '\u001b[A':
|
|
58
|
+
actions.move?.(-1);
|
|
59
|
+
break;
|
|
60
|
+
case '\u001b[B':
|
|
61
|
+
actions.move?.(1);
|
|
62
|
+
break;
|
|
63
|
+
case '\u001b':
|
|
64
|
+
actions.unpick?.();
|
|
65
|
+
break;
|
|
66
|
+
case '\r':
|
|
67
|
+
case '\n':
|
|
68
|
+
if (actions.details !== undefined && !actions.details()) {
|
|
69
|
+
say('No request has come in yet.', true);
|
|
70
|
+
}
|
|
71
|
+
break;
|
|
72
|
+
case 'y': {
|
|
73
|
+
const picked = actions.lastExchange();
|
|
74
|
+
const base = picked === null ? null : target.entry(picked.serviceName);
|
|
75
|
+
if (picked === null) {
|
|
76
|
+
say('No request has come in yet.', true);
|
|
77
|
+
}
|
|
78
|
+
else if (base === null) {
|
|
79
|
+
say('There is nowhere on this machine to send it: start with --replay-target.', true);
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
const copy = curlCommand(picked, base);
|
|
83
|
+
void actions.copy(copy.command).then((how) => {
|
|
84
|
+
const notes = [
|
|
85
|
+
...(copy.credentials.length > 0
|
|
86
|
+
? [`it carries ${copy.credentials.join(', ')}; mind where you paste it`]
|
|
87
|
+
: []),
|
|
88
|
+
...(copy.bodyLeftOut === null ? [] : [`no body: ${copy.bodyLeftOut}`]),
|
|
89
|
+
];
|
|
90
|
+
say(`${how === 'copied' ? 'Copied' : 'Sent to the clipboard of the terminal:'} curl for ${printable(picked.request.method)} ${printable(picked.request.path)} to ${base}${notes.length > 0 ? ` (${notes.join('; ')})` : ''}`);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
case 'i': {
|
|
96
|
+
const picked = actions.lastExchange();
|
|
97
|
+
if (target.inspectorUrl === null) {
|
|
98
|
+
say('There is no inspector in this run (--no-inspect).', true);
|
|
99
|
+
}
|
|
100
|
+
else if (picked === null) {
|
|
101
|
+
say('No request has come in yet.', true);
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
// The inspector opens the exchange named after the #; the fragment never leaves the browser
|
|
105
|
+
const url = `${target.inspectorUrl}/#exchange=${encodeURIComponent(picked.id)}`;
|
|
106
|
+
if (!actions.openBrowser(url)) {
|
|
107
|
+
say(`Open ${url} in your browser.`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
case CTRL_C:
|
|
113
|
+
case 'q':
|
|
114
|
+
actions.interrupt();
|
|
115
|
+
return;
|
|
116
|
+
case 'o':
|
|
117
|
+
if (target.inspectorUrl === null) {
|
|
118
|
+
say('There is no inspector in this run (--no-inspect).', true);
|
|
119
|
+
}
|
|
120
|
+
else if (actions.openBrowser(`${target.inspectorUrl}/`)) {
|
|
121
|
+
say('Opened the inspector in your browser.');
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
say(`Open ${target.inspectorUrl}/ in your browser.`);
|
|
125
|
+
}
|
|
126
|
+
break;
|
|
127
|
+
case 'c':
|
|
128
|
+
if (target.publicUrl === null) {
|
|
129
|
+
say('This tunnel has no public URL.', true);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
const url = target.publicUrl;
|
|
133
|
+
void actions
|
|
134
|
+
.copy(url)
|
|
135
|
+
.then((how) => say(how === 'copied' ? `Copied ${url}` : `Sent ${url} to the clipboard of the terminal`));
|
|
136
|
+
}
|
|
137
|
+
break;
|
|
138
|
+
case 'r': {
|
|
139
|
+
const last = actions.lastExchange();
|
|
140
|
+
if (target.inspectorUrl === null) {
|
|
141
|
+
say('Replay needs the inspector; this run has none (--no-inspect).', true);
|
|
142
|
+
}
|
|
143
|
+
else if (last === null) {
|
|
144
|
+
say('No request has come in yet.', true);
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
void actions.replay(target.inspectorUrl, last).then((problem) => {
|
|
148
|
+
if (problem !== null) {
|
|
149
|
+
say(`Replay failed: ${problem}`, true);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
case '?':
|
|
156
|
+
case 'h':
|
|
157
|
+
say(KEYS_HELP);
|
|
158
|
+
break;
|
|
159
|
+
default:
|
|
160
|
+
break;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
setRawMode(true);
|
|
165
|
+
input.setEncoding('utf8');
|
|
166
|
+
input.resume();
|
|
167
|
+
input.on('data', onData);
|
|
168
|
+
const restore = () => {
|
|
169
|
+
input.off('data', onData);
|
|
170
|
+
setRawMode(false);
|
|
171
|
+
input.pause();
|
|
172
|
+
process.off('exit', restore);
|
|
173
|
+
};
|
|
174
|
+
process.once('exit', restore);
|
|
175
|
+
return restore;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Sends a request of the log again through the inspector of this run, as its Replay button does. The new exchange
|
|
179
|
+
* shows up as a row of its own; only a refusal comes back here, as the inspector's sentence.
|
|
180
|
+
*/
|
|
181
|
+
export async function replayThroughInspector(inspectorUrl, exchange) {
|
|
182
|
+
try {
|
|
183
|
+
const response = await fetch(`${inspectorUrl}/api/replay/${encodeURIComponent(exchange.id)}`, {
|
|
184
|
+
method: 'POST',
|
|
185
|
+
headers: { 'content-type': 'application/json' },
|
|
186
|
+
body: '{}',
|
|
187
|
+
});
|
|
188
|
+
if (response.ok) {
|
|
189
|
+
await response.arrayBuffer();
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
const answer = await response.json().catch(() => null);
|
|
193
|
+
return typeof answer === 'object' &&
|
|
194
|
+
answer !== null &&
|
|
195
|
+
'message' in answer &&
|
|
196
|
+
typeof answer.message === 'string'
|
|
197
|
+
? answer.message
|
|
198
|
+
: `the inspector answered ${response.status}`;
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
return 'the inspector did not answer';
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Puts a text on the clipboard with the tool of the operating system (pbcopy, clip, wl-copy, xclip). Without one, or
|
|
206
|
+
* over SSH, it asks the terminal to do it (OSC 52), which most terminals do; the answer says which way it went.
|
|
207
|
+
*/
|
|
208
|
+
export async function copyToClipboard(text, writeTerminal, env = process.env, platform = process.platform) {
|
|
209
|
+
const command = clipboardCommand(env, platform);
|
|
210
|
+
if (command !== null && (await pipeTo(command, text))) {
|
|
211
|
+
return 'copied';
|
|
212
|
+
}
|
|
213
|
+
writeTerminal(`\u001b]52;c;${Buffer.from(text).toString('base64')}\u0007`);
|
|
214
|
+
return 'terminal';
|
|
215
|
+
}
|
|
216
|
+
function clipboardCommand(env, platform) {
|
|
217
|
+
if (platform === 'darwin') {
|
|
218
|
+
return env.SSH_CONNECTION ? null : ['pbcopy', []];
|
|
219
|
+
}
|
|
220
|
+
if (platform === 'win32') {
|
|
221
|
+
return ['clip', []];
|
|
222
|
+
}
|
|
223
|
+
if (env.WAYLAND_DISPLAY) {
|
|
224
|
+
return ['wl-copy', []];
|
|
225
|
+
}
|
|
226
|
+
return env.DISPLAY ? ['xclip', ['-selection', 'clipboard']] : null;
|
|
227
|
+
}
|
|
228
|
+
/** Runs a command with the text on its standard input; true when it exited with 0. Never through a shell. */
|
|
229
|
+
function pipeTo([command, args], text) {
|
|
230
|
+
return new Promise((resolve) => {
|
|
231
|
+
try {
|
|
232
|
+
const child = spawn(command, args, { stdio: ['pipe', 'ignore', 'ignore'] });
|
|
233
|
+
child.on('error', () => resolve(false));
|
|
234
|
+
child.on('close', (code) => resolve(code === 0));
|
|
235
|
+
child.stdin.on('error', () => { });
|
|
236
|
+
child.stdin.end(text);
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
resolve(false);
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
}
|