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.
@@ -0,0 +1,247 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import http from 'node:http';
3
+ import { isCapturedExchange } from '@hopwire/protocol';
4
+ import { HopwireError, errorCode } from './errors.js';
5
+ import { printable } from './output.js';
6
+ import { signHeaders, signedBy } from './signature.js';
7
+ export async function writeSnapshot(file, exchanges, now = Date.now()) {
8
+ const snapshot = { hopwire: 'snapshot', version: 1, createdAt: now, exchanges };
9
+ // Owner-only: the file holds headers and bodies as captured. Never over an existing file
10
+ try {
11
+ await writeFile(file, `${JSON.stringify(snapshot, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
12
+ }
13
+ catch (error) {
14
+ if (errorCode(error) === 'EEXIST') {
15
+ throw new HopwireError(`${printable(file)} exists already; name a new file, or remove that one first.`);
16
+ }
17
+ throw error;
18
+ }
19
+ }
20
+ /** Reads a snapshot file; one that is not exactly a snapshot is refused with one sentence. */
21
+ export async function readSnapshot(file) {
22
+ let text;
23
+ try {
24
+ text = await readFile(file, 'utf8');
25
+ }
26
+ catch (error) {
27
+ throw new HopwireError(errorCode(error) === 'ENOENT'
28
+ ? `${printable(file)} does not exist; write one with hopwire snapshot <file>.`
29
+ : `${printable(file)} cannot be read (${errorCode(error) ?? 'unknown error'}).`);
30
+ }
31
+ let parsed;
32
+ try {
33
+ parsed = JSON.parse(text);
34
+ }
35
+ catch {
36
+ throw new HopwireError(`${printable(file)} is not a snapshot of hopwire: it is not JSON.`);
37
+ }
38
+ if (typeof parsed !== 'object' ||
39
+ parsed === null ||
40
+ parsed.hopwire !== 'snapshot' ||
41
+ parsed.version !== 1 ||
42
+ !Array.isArray(parsed.exchanges)) {
43
+ throw new HopwireError(`${printable(file)} is not a snapshot of hopwire (version 1).`);
44
+ }
45
+ const exchanges = parsed.exchanges;
46
+ const bad = exchanges.findIndex((entry) => !isCapturedExchange(entry));
47
+ if (bad !== -1) {
48
+ throw new HopwireError(`${printable(file)}: exchange ${bad + 1} is not a request hopwire recorded.`);
49
+ }
50
+ return parsed;
51
+ }
52
+ /** Headers that describe the connection the request came in on; the new request has its own. */
53
+ const CONNECTION_HEADERS = new Set([
54
+ 'connection',
55
+ 'keep-alive',
56
+ 'transfer-encoding',
57
+ 'te',
58
+ 'upgrade',
59
+ 'proxy-connection',
60
+ 'content-length',
61
+ ]);
62
+ /** Largest answer read; the rest is cut. */
63
+ const ANSWER_LIMIT_BYTES = 8 * 1024 * 1024;
64
+ /** A request that sees no answer within this time counts as failed. */
65
+ const SEND_TIMEOUT_MS = 30_000;
66
+ /**
67
+ * Sends the request of an exchange to `target` (an http origin), with its method, path, headers and body; Host stays
68
+ * as recorded, as the tunnel forwards it. A secret for its provider signs it again at `signAt` (seconds).
69
+ */
70
+ export function send(exchange, target, options = {}) {
71
+ const { request } = exchange;
72
+ const body = Buffer.from(request.bodyBase64, 'base64');
73
+ let headers = request.headers.filter(([name]) => !CONNECTION_HEADERS.has(name.toLowerCase()));
74
+ if (options.secret !== undefined && signedBy(request.headers, options.secret.provider)) {
75
+ headers = signHeaders(headers, body, options.secret, options.signAt ?? Math.floor(Date.now() / 1000), options.wrongKey);
76
+ }
77
+ if (body.byteLength > 0 || !['GET', 'HEAD', 'DELETE', 'OPTIONS'].includes(request.method)) {
78
+ headers.push(['content-length', String(body.byteLength)]);
79
+ }
80
+ const started = performance.now();
81
+ return new Promise((resolve, reject) => {
82
+ const req = http.request({
83
+ host: target.hostname.replace(/^\[|\]$/g, ''),
84
+ port: target.port === '' ? 80 : Number(target.port),
85
+ method: request.method,
86
+ path: request.path,
87
+ headers: headers.flat(),
88
+ timeout: SEND_TIMEOUT_MS,
89
+ }, (res) => {
90
+ const chunks = [];
91
+ let size = 0;
92
+ res.on('data', (chunk) => {
93
+ size += chunk.byteLength;
94
+ if (size <= ANSWER_LIMIT_BYTES) {
95
+ chunks.push(chunk);
96
+ }
97
+ });
98
+ res.on('end', () => {
99
+ const raw = res.rawHeaders;
100
+ const answerHeaders = [];
101
+ for (let index = 0; index + 1 < raw.length; index += 2) {
102
+ answerHeaders.push([raw[index] ?? '', raw[index + 1] ?? '']);
103
+ }
104
+ resolve({
105
+ status: res.statusCode ?? 0,
106
+ headers: answerHeaders,
107
+ body: Buffer.concat(chunks),
108
+ durationMs: Math.round(performance.now() - started),
109
+ });
110
+ });
111
+ res.on('error', reject);
112
+ });
113
+ req.on('timeout', () => req.destroy(new HopwireError(`no answer within ${SEND_TIMEOUT_MS / 1000} s`)));
114
+ req.on('error', (error) => {
115
+ const code = errorCode(error);
116
+ reject(new HopwireError(code === 'ECONNREFUSED'
117
+ ? `nothing answers on ${target.origin}; is the service running?`
118
+ : error instanceof HopwireError
119
+ ? error.message
120
+ : `the request failed (${code ?? 'unknown error'})`));
121
+ });
122
+ req.end(body);
123
+ });
124
+ }
125
+ /**
126
+ * What differs between the recorded response and a new one; empty when they match. The status must be the same; a JSON
127
+ * body must have the same keys and types (and values with `strict`); another body is compared only with `strict`.
128
+ */
129
+ export function compareAnswer(recorded, answer, options) {
130
+ const differences = [];
131
+ if (recorded.status !== answer.status) {
132
+ differences.push(`status ${answer.status}, recorded ${recorded.status}`);
133
+ }
134
+ if (recorded.bodyTruncated) {
135
+ return differences;
136
+ }
137
+ const before = Buffer.from(recorded.bodyBase64, 'base64');
138
+ const was = parseJson(before);
139
+ const now = parseJson(answer.body);
140
+ if (was !== undefined && now !== undefined) {
141
+ differences.push(...compareJson(was, now, '', options));
142
+ }
143
+ else if (was !== undefined || now !== undefined) {
144
+ differences.push(was === undefined ? 'body is JSON now, was not' : 'body is no longer JSON');
145
+ }
146
+ else if (options.strict && !before.equals(answer.body)) {
147
+ differences.push('body differs');
148
+ }
149
+ return differences.slice(0, 8);
150
+ }
151
+ function parseJson(body) {
152
+ if (body.byteLength === 0) {
153
+ return undefined;
154
+ }
155
+ try {
156
+ return JSON.parse(body.toString('utf8'));
157
+ }
158
+ catch {
159
+ return undefined;
160
+ }
161
+ }
162
+ function kind(value) {
163
+ return value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
164
+ }
165
+ function compareJson(was, now, at, options) {
166
+ if (at !== '' && options.ignore.includes(at)) {
167
+ return [];
168
+ }
169
+ const name = at === '' ? 'body' : at;
170
+ if (kind(was) !== kind(now)) {
171
+ return [`${printable(name)} is ${kind(now)}, was ${kind(was)}`];
172
+ }
173
+ if (Array.isArray(was) && Array.isArray(now)) {
174
+ const out = [];
175
+ if (options.strict && was.length !== now.length) {
176
+ out.push(`${printable(name)} has ${now.length} items, had ${was.length}`);
177
+ }
178
+ // Items are compared by their shape: against the first recorded one
179
+ const sample = was[0];
180
+ if (sample !== undefined) {
181
+ for (const item of now.slice(0, 20)) {
182
+ out.push(...compareJson(sample, item, `${at}[]`, { ...options, strict: false }));
183
+ if (out.length > 0) {
184
+ break;
185
+ }
186
+ }
187
+ }
188
+ if (options.strict) {
189
+ for (const [index, item] of was.entries()) {
190
+ if (index < now.length) {
191
+ out.push(...compareJson(item, now[index], `${at}[]`, options));
192
+ }
193
+ }
194
+ }
195
+ return [...new Set(out)];
196
+ }
197
+ if (kind(was) === 'object') {
198
+ const before = was;
199
+ const after = now;
200
+ const out = [];
201
+ for (const key of Object.keys(before)) {
202
+ const child = at === '' ? key : `${at}.${key}`;
203
+ if (options.ignore.includes(child)) {
204
+ continue;
205
+ }
206
+ if (!(key in after)) {
207
+ out.push(`${printable(child)} is missing`);
208
+ }
209
+ else {
210
+ out.push(...compareJson(before[key], after[key], child, options));
211
+ }
212
+ }
213
+ for (const key of Object.keys(after)) {
214
+ const child = at === '' ? key : `${at}.${key}`;
215
+ if (!(key in before) && !options.ignore.includes(child)) {
216
+ out.push(`${printable(child)} is new`);
217
+ }
218
+ }
219
+ return out;
220
+ }
221
+ if (options.strict && was !== now) {
222
+ return [
223
+ `${printable(name)} is ${printable(JSON.stringify(now).slice(0, 40))}, was ${printable(JSON.stringify(was).slice(0, 40))}`,
224
+ ];
225
+ }
226
+ return [];
227
+ }
228
+ /**
229
+ * `http://127.0.0.1:3000`, `http://app:3000` (a service in CI) or a bare port: where verify, chaos and fix send to.
230
+ * An http origin without a path; the requests carry what was captured, so it is the user's own service.
231
+ */
232
+ export function parseTarget(value) {
233
+ const text = /^\d+$/.test(value) ? `http://127.0.0.1:${value}` : value;
234
+ let url;
235
+ try {
236
+ url = new URL(text);
237
+ }
238
+ catch {
239
+ return null;
240
+ }
241
+ return url.protocol === 'http:' &&
242
+ (url.pathname === '/' || url.pathname === '') &&
243
+ url.search === '' &&
244
+ url.username === ''
245
+ ? new URL(url.origin)
246
+ : null;
247
+ }
@@ -0,0 +1,12 @@
1
+ import { readFileSync } from 'node:fs';
2
+ /** The version of the package this file ships in; package.json lies next to `src` and `dist` alike. */
3
+ export function readVersion() {
4
+ const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
5
+ if (typeof manifest === 'object' &&
6
+ manifest !== null &&
7
+ 'version' in manifest &&
8
+ typeof manifest.version === 'string') {
9
+ return manifest.version;
10
+ }
11
+ throw new Error('package.json carries no version');
12
+ }
@@ -0,0 +1,91 @@
1
+ /** Bodies larger than this are not parsed for the event name: a row must never wait for a big JSON. */
2
+ const PARSE_LIMIT_BYTES = 256 * 1024;
3
+ /** Longest event name shown; a provider's own names are far shorter. */
4
+ const EVENT_MAX_LENGTH = 48;
5
+ /**
6
+ * The providers, each recognised by a header only it sends. The order matters where two could match: Svix carries
7
+ * the webhooks of several products (Clerk, Resend and others) and is named as itself.
8
+ */
9
+ const PROVIDERS = [
10
+ { provider: 'stripe', matches: (h) => h.has('stripe-signature'), event: (_h, body) => text(body()?.type) },
11
+ {
12
+ provider: 'github',
13
+ matches: (h) => h.has('x-github-event'),
14
+ event: (h, body) => joined(h.get('x-github-event'), text(body()?.action)),
15
+ },
16
+ { provider: 'gitlab', matches: (h) => h.has('x-gitlab-event'), event: (h) => text(h.get('x-gitlab-event')) },
17
+ { provider: 'shopify', matches: (h) => h.has('x-shopify-topic'), event: (h) => text(h.get('x-shopify-topic')) },
18
+ {
19
+ provider: 'slack',
20
+ matches: (h) => h.has('x-slack-signature'),
21
+ event: (_h, body) => {
22
+ const payload = body();
23
+ const inner = payload?.event;
24
+ return text(typeof inner === 'object' && inner !== null && 'type' in inner ? inner.type : payload?.type);
25
+ },
26
+ },
27
+ {
28
+ provider: 'linear',
29
+ matches: (h) => h.has('linear-signature') || h.has('linear-event'),
30
+ event: (h, body) => joined(text(body()?.type) ?? h.get('linear-event'), text(body()?.action)),
31
+ },
32
+ { provider: 'paddle', matches: (h) => h.has('paddle-signature'), event: (_h, body) => text(body()?.event_type) },
33
+ {
34
+ provider: 'paypal',
35
+ matches: (h) => h.has('paypal-transmission-id'),
36
+ event: (_h, body) => text(body()?.event_type),
37
+ },
38
+ { provider: 'twilio', matches: (h) => h.has('x-twilio-signature'), event: () => null },
39
+ {
40
+ provider: 'svix',
41
+ matches: (h) => h.has('svix-id') || h.has('webhook-id'),
42
+ event: (_h, body) => text(body()?.type),
43
+ },
44
+ ];
45
+ /**
46
+ * The webhook a request is, from its headers and, for the event name, its captured JSON body. Only what this machine
47
+ * captured is read; nothing is sent anywhere. Null for a request no provider's header marks.
48
+ */
49
+ export function recogniseWebhook(exchange) {
50
+ const headers = new Map(exchange.request.headers.map(([name, value]) => [name.toLowerCase(), value]));
51
+ const match = PROVIDERS.find((entry) => entry.matches(headers));
52
+ if (match === undefined) {
53
+ return null;
54
+ }
55
+ let parsed;
56
+ const body = () => {
57
+ parsed ??= jsonBody(exchange);
58
+ return parsed;
59
+ };
60
+ const event = match.event(headers, body);
61
+ return { provider: match.provider, event: event === null ? null : event.slice(0, EVENT_MAX_LENGTH) };
62
+ }
63
+ /** The request body as a JSON object; null when it is none, was cut by the capture, or is too large to parse here. */
64
+ function jsonBody(exchange) {
65
+ const { request } = exchange;
66
+ if (request.bodyTruncated ||
67
+ request.bodyBase64.length === 0 ||
68
+ (request.bodyBase64.length / 4) * 3 > PARSE_LIMIT_BYTES) {
69
+ return null;
70
+ }
71
+ try {
72
+ const value = JSON.parse(Buffer.from(request.bodyBase64, 'base64').toString('utf8'));
73
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
74
+ ? value
75
+ : null;
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
81
+ /** A non-empty string value, or null. */
82
+ function text(value) {
83
+ return typeof value === 'string' && value !== '' ? value : null;
84
+ }
85
+ /** "push", "pull_request.opened": the event and its action when there is one. */
86
+ function joined(event, action) {
87
+ if (event === null || event === undefined || event === '') {
88
+ return null;
89
+ }
90
+ return action === null ? event : `${event}.${action}`;
91
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hopwire",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "mcpName": "to.hopwire/hopwire",
5
5
  "description": "Record, share and replay the HTTP traffic of your local services: private P2P sharing with teammates, and public HTTPS URLs.",
6
6
  "license": "Apache-2.0",