hopwire 0.3.0 → 0.5.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
+ }