devanvil 0.0.0-stage → 2.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 +21 -0
- package/README.ar.md +113 -0
- package/README.md +272 -2
- package/SECURITY.md +49 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +659 -0
- package/dist/core/contract-drift.d.ts +49 -0
- package/dist/core/contract-drift.js +302 -0
- package/dist/core/converters.d.ts +18 -0
- package/dist/core/converters.js +981 -0
- package/dist/core/cron.d.ts +33 -0
- package/dist/core/cron.js +306 -0
- package/dist/core/crypto.d.ts +59 -0
- package/dist/core/crypto.js +250 -0
- package/dist/core/curl.d.ts +17 -0
- package/dist/core/curl.js +170 -0
- package/dist/core/diff.d.ts +36 -0
- package/dist/core/diff.js +148 -0
- package/dist/core/encoding.d.ts +3 -0
- package/dist/core/encoding.js +143 -0
- package/dist/core/importers.d.ts +65 -0
- package/dist/core/importers.js +361 -0
- package/dist/core/jwt.d.ts +39 -0
- package/dist/core/jwt.js +256 -0
- package/dist/core/llm-tokens.d.ts +38 -0
- package/dist/core/llm-tokens.js +125 -0
- package/dist/core/log-analyzer.d.ts +30 -0
- package/dist/core/log-analyzer.js +155 -0
- package/dist/core/network.d.ts +72 -0
- package/dist/core/network.js +185 -0
- package/dist/core/oauth-protobuf.d.ts +74 -0
- package/dist/core/oauth-protobuf.js +390 -0
- package/dist/core/openapi.d.ts +27 -0
- package/dist/core/openapi.js +257 -0
- package/dist/core/pipeline.d.ts +28 -0
- package/dist/core/pipeline.js +154 -0
- package/dist/core/regex.d.ts +50 -0
- package/dist/core/regex.js +351 -0
- package/dist/core/runner.d.ts +53 -0
- package/dist/core/runner.js +250 -0
- package/dist/core/secrets.d.ts +87 -0
- package/dist/core/secrets.js +599 -0
- package/dist/core/security.d.ts +34 -0
- package/dist/core/security.js +284 -0
- package/dist/core/sql-explain.d.ts +50 -0
- package/dist/core/sql-explain.js +259 -0
- package/dist/core/tls.d.ts +44 -0
- package/dist/core/tls.js +166 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +31 -0
- package/dist/server/app.d.ts +31 -0
- package/dist/server/app.js +348 -0
- package/dist/server/http-proxy.d.ts +55 -0
- package/dist/server/http-proxy.js +364 -0
- package/dist/server/http-utils.d.ts +28 -0
- package/dist/server/http-utils.js +106 -0
- package/dist/server/load-tester.d.ts +53 -0
- package/dist/server/load-tester.js +134 -0
- package/dist/server/mcp.d.ts +35 -0
- package/dist/server/mcp.js +466 -0
- package/dist/server/mock-store.d.ts +38 -0
- package/dist/server/mock-store.js +197 -0
- package/dist/server/plugin-loader.d.ts +60 -0
- package/dist/server/plugin-loader.js +285 -0
- package/dist/server/recorder-store.d.ts +35 -0
- package/dist/server/recorder-store.js +146 -0
- package/dist/server/routes/network-routes.d.ts +3 -0
- package/dist/server/routes/network-routes.js +391 -0
- package/dist/server/routes/tools-routes.d.ts +3 -0
- package/dist/server/routes/tools-routes.js +292 -0
- package/dist/server/routes/workspace-routes.d.ts +3 -0
- package/dist/server/routes/workspace-routes.js +240 -0
- package/dist/server/webhook-store.d.ts +29 -0
- package/dist/server/webhook-store.js +90 -0
- package/dist/server/workspace-store.d.ts +91 -0
- package/dist/server/workspace-store.js +447 -0
- package/dist/server/ws-probe.d.ts +34 -0
- package/dist/server/ws-probe.js +283 -0
- package/dist/ui/app.js +274 -0
- package/dist/ui/favicon.svg +14 -0
- package/dist/ui/index.html +83 -0
- package/dist/ui/logo.png +0 -0
- package/dist/ui/styles.css +694 -0
- package/dist/ui/tools-data.js +704 -0
- package/dist/ui/tools-network.js +727 -0
- package/dist/ui/tools-ops.js +295 -0
- package/dist/ui/tools-pro.js +500 -0
- package/dist/ui/tools-security.js +389 -0
- package/dist/ui/tools-v12.js +745 -0
- package/dist/ui/tools-v13.js +321 -0
- package/dist/ui/tools-v20.js +563 -0
- package/dist/ui/tools-v21.js +395 -0
- package/package.json +75 -4
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import * as http from 'node:http';
|
|
2
|
+
import * as https from 'node:https';
|
|
3
|
+
import { brotliDecompressSync, gunzipSync, inflateSync } from 'node:zlib';
|
|
4
|
+
import { DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_DECOMPRESS_BYTES, validateProxyTargetUrl } from '../core/security.js';
|
|
5
|
+
const ALLOWED_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
6
|
+
const MAX_RESPONSE_BYTES = 5 * 1024 * 1024; // 5 MB
|
|
7
|
+
const MAX_REDIRECTS = 5;
|
|
8
|
+
const STRIPPED_REQ_HEADERS = new Set([
|
|
9
|
+
'host',
|
|
10
|
+
'connection',
|
|
11
|
+
'keep-alive',
|
|
12
|
+
'proxy-authenticate',
|
|
13
|
+
'proxy-authorization',
|
|
14
|
+
'te',
|
|
15
|
+
'trailer',
|
|
16
|
+
'transfer-encoding',
|
|
17
|
+
'upgrade',
|
|
18
|
+
'content-length',
|
|
19
|
+
]);
|
|
20
|
+
function decompressBody(raw, encodingHeader) {
|
|
21
|
+
const enc = (encodingHeader ?? '').toLowerCase().trim();
|
|
22
|
+
if (!enc || enc === 'identity')
|
|
23
|
+
return raw;
|
|
24
|
+
try {
|
|
25
|
+
if (enc === 'gzip' || enc === 'x-gzip') {
|
|
26
|
+
return gunzipSync(raw, { maxOutputLength: DEFAULT_MAX_DECOMPRESS_BYTES });
|
|
27
|
+
}
|
|
28
|
+
if (enc === 'deflate') {
|
|
29
|
+
return inflateSync(raw, { maxOutputLength: DEFAULT_MAX_DECOMPRESS_BYTES });
|
|
30
|
+
}
|
|
31
|
+
if (enc === 'br') {
|
|
32
|
+
return brotliDecompressSync(raw, { maxOutputLength: DEFAULT_MAX_DECOMPRESS_BYTES });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return raw;
|
|
37
|
+
}
|
|
38
|
+
return raw;
|
|
39
|
+
}
|
|
40
|
+
export async function executeProxyRequest(input, options = {}) {
|
|
41
|
+
const method = (input.method || 'GET').toUpperCase().trim();
|
|
42
|
+
if (!ALLOWED_METHODS.has(method)) {
|
|
43
|
+
throw new Error(`Unsupported HTTP method "${method}"`);
|
|
44
|
+
}
|
|
45
|
+
const bodyStr = input.body ?? '';
|
|
46
|
+
if (Buffer.byteLength(bodyStr, 'utf8') > DEFAULT_MAX_BODY_BYTES) {
|
|
47
|
+
throw new Error(`Request body exceeds ${DEFAULT_MAX_BODY_BYTES} byte limit`);
|
|
48
|
+
}
|
|
49
|
+
const timeoutMs = Math.min(Math.max(Number(input.timeoutMs ?? 15_000), 500), 30_000);
|
|
50
|
+
const followRedirects = input.followRedirects !== false;
|
|
51
|
+
let currentUrl = input.url.trim();
|
|
52
|
+
let currentMethod = method;
|
|
53
|
+
let currentBody = bodyStr;
|
|
54
|
+
let activeHeaders = input.headers && typeof input.headers === 'object' && !Array.isArray(input.headers)
|
|
55
|
+
? { ...input.headers }
|
|
56
|
+
: {};
|
|
57
|
+
let redirects = 0;
|
|
58
|
+
let totalDnsMs = 0;
|
|
59
|
+
const startedAt = performance.now();
|
|
60
|
+
while (true) {
|
|
61
|
+
const dnsStart = performance.now();
|
|
62
|
+
const target = await validateProxyTargetUrl(currentUrl, { allowPrivate: options.allowPrivate });
|
|
63
|
+
totalDnsMs += performance.now() - dnsStart;
|
|
64
|
+
const cleanHeaders = {};
|
|
65
|
+
for (const [k, v] of Object.entries(activeHeaders)) {
|
|
66
|
+
const lower = k.toLowerCase().trim();
|
|
67
|
+
if (!lower || STRIPPED_REQ_HEADERS.has(lower))
|
|
68
|
+
continue;
|
|
69
|
+
if (/[\r\n]/.test(k) || /[\r\n]/.test(String(v))) {
|
|
70
|
+
throw new Error(`Invalid CRLF characters in header "${k}"`);
|
|
71
|
+
}
|
|
72
|
+
cleanHeaders[k.trim()] = String(v);
|
|
73
|
+
}
|
|
74
|
+
if (!Object.keys(cleanHeaders).some((k) => k.toLowerCase() === 'user-agent')) {
|
|
75
|
+
cleanHeaders['User-Agent'] = 'DevAnvil/1.0 (Local-First Developer Studio)';
|
|
76
|
+
}
|
|
77
|
+
if (!Object.keys(cleanHeaders).some((k) => k.toLowerCase() === 'accept-encoding')) {
|
|
78
|
+
cleanHeaders['Accept-Encoding'] = 'gzip, deflate, br';
|
|
79
|
+
}
|
|
80
|
+
const sendBody = currentMethod !== 'GET' && currentMethod !== 'HEAD' && currentBody.length > 0;
|
|
81
|
+
const bodyBuf = sendBody ? Buffer.from(currentBody, 'utf8') : undefined;
|
|
82
|
+
if (bodyBuf) {
|
|
83
|
+
cleanHeaders['Content-Length'] = String(bodyBuf.length);
|
|
84
|
+
}
|
|
85
|
+
const hopResult = await new Promise((resolve, reject) => {
|
|
86
|
+
const transport = target.url.protocol === 'https:' ? https : http;
|
|
87
|
+
const reqStart = performance.now();
|
|
88
|
+
const req = transport.request({
|
|
89
|
+
protocol: target.url.protocol,
|
|
90
|
+
hostname: target.url.hostname,
|
|
91
|
+
port: target.url.port || (target.url.protocol === 'https:' ? 443 : 80),
|
|
92
|
+
path: `${target.url.pathname}${target.url.search}`,
|
|
93
|
+
method: currentMethod,
|
|
94
|
+
headers: cleanHeaders,
|
|
95
|
+
timeout: timeoutMs,
|
|
96
|
+
// Pin the already-validated IP address to eliminate DNS rebinding (TOCTOU)
|
|
97
|
+
lookup: ((_hostname, lookupOpts, cb) => {
|
|
98
|
+
if (typeof lookupOpts === 'function') {
|
|
99
|
+
lookupOpts(null, target.resolvedAddress, target.family);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (lookupOpts && lookupOpts.all) {
|
|
103
|
+
cb?.(null, [{ address: target.resolvedAddress, family: target.family }]);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
cb?.(null, target.resolvedAddress, target.family);
|
|
107
|
+
}),
|
|
108
|
+
}, (res) => {
|
|
109
|
+
const ttfbMs = performance.now() - reqStart;
|
|
110
|
+
const chunks = [];
|
|
111
|
+
let received = 0;
|
|
112
|
+
let truncated = false;
|
|
113
|
+
res.on('data', (chunk) => {
|
|
114
|
+
if (received + chunk.length > MAX_RESPONSE_BYTES) {
|
|
115
|
+
const remaining = Math.max(MAX_RESPONSE_BYTES - received, 0);
|
|
116
|
+
if (remaining > 0)
|
|
117
|
+
chunks.push(chunk.subarray(0, remaining));
|
|
118
|
+
truncated = true;
|
|
119
|
+
res.destroy();
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
chunks.push(chunk);
|
|
123
|
+
received += chunk.length;
|
|
124
|
+
});
|
|
125
|
+
const finish = () => {
|
|
126
|
+
const respHeaders = {};
|
|
127
|
+
for (const [hk, hv] of Object.entries(res.headers)) {
|
|
128
|
+
if (hv !== undefined) {
|
|
129
|
+
respHeaders[hk] = Array.isArray(hv) ? hv.join(', ') : String(hv);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
resolve({
|
|
133
|
+
status: res.statusCode ?? 0,
|
|
134
|
+
statusText: res.statusMessage ?? '',
|
|
135
|
+
headers: respHeaders,
|
|
136
|
+
rawBody: Buffer.concat(chunks),
|
|
137
|
+
truncated,
|
|
138
|
+
ttfbMs,
|
|
139
|
+
});
|
|
140
|
+
};
|
|
141
|
+
res.on('end', finish);
|
|
142
|
+
res.on('close', () => {
|
|
143
|
+
if (truncated)
|
|
144
|
+
finish();
|
|
145
|
+
});
|
|
146
|
+
res.on('error', (err) => {
|
|
147
|
+
if (truncated)
|
|
148
|
+
finish();
|
|
149
|
+
else
|
|
150
|
+
reject(err);
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
req.on('timeout', () => {
|
|
154
|
+
req.destroy(new Error(`Upstream request timed out after ${timeoutMs}ms`));
|
|
155
|
+
});
|
|
156
|
+
req.on('error', reject);
|
|
157
|
+
if (bodyBuf)
|
|
158
|
+
req.write(bodyBuf);
|
|
159
|
+
req.end();
|
|
160
|
+
});
|
|
161
|
+
const isRedirect = followRedirects &&
|
|
162
|
+
[301, 302, 303, 307, 308].includes(hopResult.status) &&
|
|
163
|
+
typeof hopResult.headers['location'] === 'string' &&
|
|
164
|
+
hopResult.headers['location'].length > 0;
|
|
165
|
+
if (isRedirect) {
|
|
166
|
+
redirects++;
|
|
167
|
+
if (redirects > MAX_REDIRECTS) {
|
|
168
|
+
throw new Error(`Exceeded maximum redirect hops (${MAX_REDIRECTS})`);
|
|
169
|
+
}
|
|
170
|
+
const nextUrlObj = new URL(hopResult.headers['location'], target.url);
|
|
171
|
+
// Strip sensitive credentials when redirected across origins
|
|
172
|
+
if (nextUrlObj.origin !== target.url.origin) {
|
|
173
|
+
const filtered = {};
|
|
174
|
+
for (const [hk, hv] of Object.entries(activeHeaders)) {
|
|
175
|
+
const lower = hk.toLowerCase();
|
|
176
|
+
if (lower !== 'authorization' && lower !== 'cookie' && lower !== 'proxy-authorization') {
|
|
177
|
+
filtered[hk] = hv;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
activeHeaders = filtered;
|
|
181
|
+
}
|
|
182
|
+
currentUrl = nextUrlObj.toString();
|
|
183
|
+
if (hopResult.status === 303 || ((hopResult.status === 301 || hopResult.status === 302) && currentMethod === 'POST')) {
|
|
184
|
+
currentMethod = 'GET';
|
|
185
|
+
currentBody = '';
|
|
186
|
+
}
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const decodedBuf = hopResult.truncated
|
|
190
|
+
? hopResult.rawBody
|
|
191
|
+
: decompressBody(hopResult.rawBody, hopResult.headers['content-encoding']);
|
|
192
|
+
const totalMs = performance.now() - startedAt;
|
|
193
|
+
return {
|
|
194
|
+
status: hopResult.status,
|
|
195
|
+
statusText: hopResult.statusText,
|
|
196
|
+
finalUrl: target.url.toString(),
|
|
197
|
+
redirects,
|
|
198
|
+
headers: hopResult.headers,
|
|
199
|
+
body: decodedBuf.toString('utf8'),
|
|
200
|
+
contentType: hopResult.headers['content-type'] ?? 'text/plain',
|
|
201
|
+
sizeBytes: decodedBuf.length,
|
|
202
|
+
truncated: hopResult.truncated,
|
|
203
|
+
timings: {
|
|
204
|
+
dnsValidateMs: Math.round(totalDnsMs * 100) / 100,
|
|
205
|
+
ttfbMs: Math.round(hopResult.ttfbMs * 100) / 100,
|
|
206
|
+
totalMs: Math.round(totalMs * 100) / 100,
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Connects to an SSE (Server-Sent Events) stream (e.g. AI LLM streaming APIs or live hooks)
|
|
213
|
+
* with the same SSRF + DNS-pinning guard, capturing events + Time-To-First-Token (TTFT).
|
|
214
|
+
*/
|
|
215
|
+
export async function executeSseStreamRequest(input, options = {}) {
|
|
216
|
+
const method = (input.method || 'GET').toUpperCase();
|
|
217
|
+
if (!ALLOWED_METHODS.has(method)) {
|
|
218
|
+
throw new Error(`Unsupported HTTP method: ${method}`);
|
|
219
|
+
}
|
|
220
|
+
const maxEvents = Math.min(Math.max(input.maxEvents ?? 40, 1), 200);
|
|
221
|
+
const maxDurationMs = Math.min(Math.max(input.maxDurationMs ?? 8_000, 500), 25_000);
|
|
222
|
+
const maxBytes = 2 * 1024 * 1024;
|
|
223
|
+
const target = await validateProxyTargetUrl(input.url, { allowPrivate: options.allowPrivate });
|
|
224
|
+
const headers = {};
|
|
225
|
+
for (const [k, v] of Object.entries(input.headers ?? {})) {
|
|
226
|
+
const lower = k.toLowerCase().trim();
|
|
227
|
+
if (!lower || STRIPPED_REQ_HEADERS.has(lower))
|
|
228
|
+
continue;
|
|
229
|
+
if (/[\r\n]/.test(k) || /[\r\n]/.test(String(v))) {
|
|
230
|
+
throw new Error(`Invalid CRLF characters in header "${k}"`);
|
|
231
|
+
}
|
|
232
|
+
headers[k.trim()] = String(v);
|
|
233
|
+
}
|
|
234
|
+
if (!Object.keys(headers).some((k) => k.toLowerCase() === 'accept')) {
|
|
235
|
+
headers['Accept'] = 'text/event-stream';
|
|
236
|
+
}
|
|
237
|
+
if (!Object.keys(headers).some((k) => k.toLowerCase() === 'user-agent')) {
|
|
238
|
+
headers['User-Agent'] = 'DevAnvil/1.2 (Local SSE Studio)';
|
|
239
|
+
}
|
|
240
|
+
let bodyBuf;
|
|
241
|
+
if (input.body && method !== 'GET' && method !== 'HEAD') {
|
|
242
|
+
bodyBuf = Buffer.from(input.body, 'utf8');
|
|
243
|
+
headers['Content-Length'] = String(bodyBuf.length);
|
|
244
|
+
}
|
|
245
|
+
const startedAt = performance.now();
|
|
246
|
+
const transport = target.url.protocol === 'https:' ? https : http;
|
|
247
|
+
const port = target.url.port ? Number(target.url.port) : target.url.protocol === 'https:' ? 443 : 80;
|
|
248
|
+
return new Promise((resolve, reject) => {
|
|
249
|
+
let settled = false;
|
|
250
|
+
let ttfbMs = 0;
|
|
251
|
+
let bytesReceived = 0;
|
|
252
|
+
let bufferText = '';
|
|
253
|
+
const events = [];
|
|
254
|
+
let stoppedReason = 'eof';
|
|
255
|
+
let status = 0;
|
|
256
|
+
let contentType = 'text/event-stream';
|
|
257
|
+
const finish = (reason, req) => {
|
|
258
|
+
if (settled)
|
|
259
|
+
return;
|
|
260
|
+
settled = true;
|
|
261
|
+
stoppedReason = reason;
|
|
262
|
+
clearTimeout(timer);
|
|
263
|
+
req.destroy();
|
|
264
|
+
resolve({
|
|
265
|
+
status,
|
|
266
|
+
contentType,
|
|
267
|
+
finalUrl: target.url.toString(),
|
|
268
|
+
ttfbMs: Math.round(ttfbMs * 100) / 100,
|
|
269
|
+
totalMs: Math.round((performance.now() - startedAt) * 100) / 100,
|
|
270
|
+
eventCount: events.length,
|
|
271
|
+
bytesReceived,
|
|
272
|
+
stoppedReason,
|
|
273
|
+
events,
|
|
274
|
+
});
|
|
275
|
+
};
|
|
276
|
+
const req = transport.request({
|
|
277
|
+
hostname: target.url.hostname,
|
|
278
|
+
port,
|
|
279
|
+
path: `${target.url.pathname}${target.url.search}`,
|
|
280
|
+
method,
|
|
281
|
+
headers,
|
|
282
|
+
lookup: ((_hostname, lookupOpts, cb) => {
|
|
283
|
+
if (typeof lookupOpts === 'function') {
|
|
284
|
+
lookupOpts(null, target.resolvedAddress, target.family);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (lookupOpts && lookupOpts.all) {
|
|
288
|
+
cb?.(null, [{ address: target.resolvedAddress, family: target.family }]);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
cb?.(null, target.resolvedAddress, target.family);
|
|
292
|
+
}),
|
|
293
|
+
}, (res) => {
|
|
294
|
+
status = res.statusCode ?? 0;
|
|
295
|
+
contentType = String(res.headers['content-type'] ?? 'text/event-stream');
|
|
296
|
+
ttfbMs = performance.now() - startedAt;
|
|
297
|
+
res.on('data', (chunk) => {
|
|
298
|
+
if (settled)
|
|
299
|
+
return;
|
|
300
|
+
bytesReceived += chunk.length;
|
|
301
|
+
if (bytesReceived > maxBytes) {
|
|
302
|
+
finish('max-bytes', req);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
bufferText += chunk.toString('utf8').replace(/\r\n/g, '\n');
|
|
306
|
+
let sep = bufferText.indexOf('\n\n');
|
|
307
|
+
while (sep !== -1) {
|
|
308
|
+
const rawFrame = bufferText.slice(0, sep);
|
|
309
|
+
bufferText = bufferText.slice(sep + 2);
|
|
310
|
+
sep = bufferText.indexOf('\n\n');
|
|
311
|
+
if (!rawFrame.trim())
|
|
312
|
+
continue;
|
|
313
|
+
let evName = 'message';
|
|
314
|
+
let evId;
|
|
315
|
+
const dataLines = [];
|
|
316
|
+
for (const line of rawFrame.split('\n')) {
|
|
317
|
+
if (line.startsWith(':'))
|
|
318
|
+
continue;
|
|
319
|
+
if (line.startsWith('event:'))
|
|
320
|
+
evName = line.slice(6).trim();
|
|
321
|
+
else if (line.startsWith('id:'))
|
|
322
|
+
evId = line.slice(3).trim();
|
|
323
|
+
else if (line.startsWith('data:'))
|
|
324
|
+
dataLines.push(line.slice(5).trimStart());
|
|
325
|
+
}
|
|
326
|
+
if (dataLines.length > 0) {
|
|
327
|
+
if (events.length === 0)
|
|
328
|
+
ttfbMs = performance.now() - startedAt;
|
|
329
|
+
events.push({
|
|
330
|
+
index: events.length + 1,
|
|
331
|
+
event: evName,
|
|
332
|
+
id: evId,
|
|
333
|
+
data: dataLines.join('\n'),
|
|
334
|
+
deltaMs: Math.round((performance.now() - startedAt) * 100) / 100,
|
|
335
|
+
});
|
|
336
|
+
if (events.length >= maxEvents) {
|
|
337
|
+
finish('max-events', req);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
res.on('end', () => finish('eof', req));
|
|
344
|
+
res.on('error', (err) => {
|
|
345
|
+
if (!settled) {
|
|
346
|
+
settled = true;
|
|
347
|
+
clearTimeout(timer);
|
|
348
|
+
reject(err);
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
});
|
|
352
|
+
const timer = setTimeout(() => finish('timeout', req), maxDurationMs);
|
|
353
|
+
req.on('error', (err) => {
|
|
354
|
+
if (!settled) {
|
|
355
|
+
settled = true;
|
|
356
|
+
clearTimeout(timer);
|
|
357
|
+
reject(err);
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
if (bodyBuf)
|
|
361
|
+
req.write(bodyBuf);
|
|
362
|
+
req.end();
|
|
363
|
+
});
|
|
364
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import type { MockStore } from './mock-store.js';
|
|
3
|
+
import type { PluginLoader } from './plugin-loader.js';
|
|
4
|
+
import type { RecorderStore } from './recorder-store.js';
|
|
5
|
+
import type { WebhookStore } from './webhook-store.js';
|
|
6
|
+
import type { WorkspaceStore } from './workspace-store.js';
|
|
7
|
+
export declare const CSP_BASE: string;
|
|
8
|
+
export declare const CSP_STRICT_FRAME: string;
|
|
9
|
+
export interface RouteContext {
|
|
10
|
+
version: string;
|
|
11
|
+
bindHost: string;
|
|
12
|
+
startedAt: number;
|
|
13
|
+
allowPrivateProxy: boolean;
|
|
14
|
+
denyIframe: boolean;
|
|
15
|
+
mockStore: MockStore;
|
|
16
|
+
webhookStore: WebhookStore;
|
|
17
|
+
workspaceStore: WorkspaceStore;
|
|
18
|
+
pluginLoader: PluginLoader;
|
|
19
|
+
recorderStore: RecorderStore;
|
|
20
|
+
}
|
|
21
|
+
export declare function asString(val: unknown, fallback?: string): string;
|
|
22
|
+
export declare function asOptionalString(val: unknown): string | undefined;
|
|
23
|
+
export declare function asOptionalNumber(val: unknown): number | undefined;
|
|
24
|
+
export declare function asStringMap(val: unknown): Record<string, string> | undefined;
|
|
25
|
+
export declare function applySecurityHeaders(res: ServerResponse, denyIframe: boolean): void;
|
|
26
|
+
export declare function sendJson(res: ServerResponse, status: number, payload: unknown, denyIframe: boolean): void;
|
|
27
|
+
export declare function readBody(req: IncomingMessage, maxBytes?: number): Promise<string>;
|
|
28
|
+
export declare function readJsonBody<T = Record<string, unknown>>(req: IncomingMessage): Promise<T>;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { DEFAULT_MAX_BODY_BYTES, safeJsonParse } from '../core/security.js';
|
|
2
|
+
export const CSP_BASE = [
|
|
3
|
+
"default-src 'self'",
|
|
4
|
+
"script-src 'self'",
|
|
5
|
+
"style-src 'self'",
|
|
6
|
+
"img-src 'self' data:",
|
|
7
|
+
"connect-src 'self'",
|
|
8
|
+
"font-src 'self'",
|
|
9
|
+
"object-src 'none'",
|
|
10
|
+
"base-uri 'self'",
|
|
11
|
+
"form-action 'self'",
|
|
12
|
+
].join('; ');
|
|
13
|
+
export const CSP_STRICT_FRAME = `${CSP_BASE}; frame-ancestors 'none'`;
|
|
14
|
+
export function asString(val, fallback = '') {
|
|
15
|
+
if (val === undefined || val === null)
|
|
16
|
+
return fallback;
|
|
17
|
+
if (typeof val !== 'string') {
|
|
18
|
+
throw Object.assign(new Error('Expected string input parameter'), { statusCode: 400 });
|
|
19
|
+
}
|
|
20
|
+
return val;
|
|
21
|
+
}
|
|
22
|
+
export function asOptionalString(val) {
|
|
23
|
+
if (val === undefined || val === null || val === '')
|
|
24
|
+
return undefined;
|
|
25
|
+
if (typeof val !== 'string') {
|
|
26
|
+
throw Object.assign(new Error('Expected string input parameter'), { statusCode: 400 });
|
|
27
|
+
}
|
|
28
|
+
return val;
|
|
29
|
+
}
|
|
30
|
+
export function asOptionalNumber(val) {
|
|
31
|
+
if (val === undefined || val === null || val === '')
|
|
32
|
+
return undefined;
|
|
33
|
+
const n = typeof val === 'number' ? val : Number(val);
|
|
34
|
+
if (!Number.isFinite(n)) {
|
|
35
|
+
throw Object.assign(new Error('Expected finite numeric parameter'), { statusCode: 400 });
|
|
36
|
+
}
|
|
37
|
+
return n;
|
|
38
|
+
}
|
|
39
|
+
export function asStringMap(val) {
|
|
40
|
+
if (val === undefined || val === null)
|
|
41
|
+
return undefined;
|
|
42
|
+
if (typeof val !== 'object' || Array.isArray(val)) {
|
|
43
|
+
throw Object.assign(new Error('Expected key-value map object'), { statusCode: 400 });
|
|
44
|
+
}
|
|
45
|
+
const out = {};
|
|
46
|
+
for (const [k, v] of Object.entries(val)) {
|
|
47
|
+
out[k] = String(v ?? '');
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
export function applySecurityHeaders(res, denyIframe) {
|
|
52
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
53
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
54
|
+
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=(), payment=()');
|
|
55
|
+
res.setHeader('Content-Security-Policy', denyIframe ? CSP_STRICT_FRAME : CSP_BASE);
|
|
56
|
+
if (denyIframe) {
|
|
57
|
+
res.setHeader('X-Frame-Options', 'DENY');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export function sendJson(res, status, payload, denyIframe) {
|
|
61
|
+
applySecurityHeaders(res, denyIframe);
|
|
62
|
+
const body = JSON.stringify(payload);
|
|
63
|
+
res.writeHead(status, {
|
|
64
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
65
|
+
'Cache-Control': 'no-store',
|
|
66
|
+
'Content-Length': Buffer.byteLength(body, 'utf8'),
|
|
67
|
+
});
|
|
68
|
+
res.end(body);
|
|
69
|
+
}
|
|
70
|
+
export async function readBody(req, maxBytes = DEFAULT_MAX_BODY_BYTES) {
|
|
71
|
+
return new Promise((resolveBody, rejectBody) => {
|
|
72
|
+
const chunks = [];
|
|
73
|
+
let total = 0;
|
|
74
|
+
let aborted = false;
|
|
75
|
+
req.on('data', (chunk) => {
|
|
76
|
+
if (aborted)
|
|
77
|
+
return;
|
|
78
|
+
total += chunk.length;
|
|
79
|
+
if (total > maxBytes) {
|
|
80
|
+
aborted = true;
|
|
81
|
+
rejectBody(Object.assign(new Error(`Payload exceeds maximum limit (${maxBytes} bytes)`), { statusCode: 413 }));
|
|
82
|
+
req.resume();
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
chunks.push(chunk);
|
|
86
|
+
});
|
|
87
|
+
req.on('end', () => {
|
|
88
|
+
if (!aborted)
|
|
89
|
+
resolveBody(Buffer.concat(chunks).toString('utf8'));
|
|
90
|
+
});
|
|
91
|
+
req.on('error', (err) => {
|
|
92
|
+
if (!aborted)
|
|
93
|
+
rejectBody(err);
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
export async function readJsonBody(req) {
|
|
98
|
+
const raw = await readBody(req);
|
|
99
|
+
if (!raw.trim())
|
|
100
|
+
return {};
|
|
101
|
+
const parsed = safeJsonParse(raw);
|
|
102
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
103
|
+
throw Object.assign(new Error('JSON request body must be an object'), { statusCode: 400 });
|
|
104
|
+
}
|
|
105
|
+
return parsed;
|
|
106
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export interface LoadTestThresholds {
|
|
2
|
+
maxP95Ms?: number;
|
|
3
|
+
minRps?: number;
|
|
4
|
+
maxErrorRatePct?: number;
|
|
5
|
+
}
|
|
6
|
+
export interface LoadTestInput {
|
|
7
|
+
method?: string;
|
|
8
|
+
url: string;
|
|
9
|
+
headers?: Record<string, string>;
|
|
10
|
+
body?: string;
|
|
11
|
+
totalRequests?: number;
|
|
12
|
+
concurrency?: number;
|
|
13
|
+
timeoutMs?: number;
|
|
14
|
+
thresholds?: LoadTestThresholds;
|
|
15
|
+
}
|
|
16
|
+
export interface LatencyBucket {
|
|
17
|
+
label: string;
|
|
18
|
+
count: number;
|
|
19
|
+
percent: number;
|
|
20
|
+
}
|
|
21
|
+
export interface LoadTestReport {
|
|
22
|
+
url: string;
|
|
23
|
+
method: string;
|
|
24
|
+
totalRequests: number;
|
|
25
|
+
concurrency: number;
|
|
26
|
+
completedRequests: number;
|
|
27
|
+
succeededRequests: number;
|
|
28
|
+
failedRequests: number;
|
|
29
|
+
totalDurationMs: number;
|
|
30
|
+
requestsPerSec: number;
|
|
31
|
+
throughputKbPerSec: number;
|
|
32
|
+
statusCodes: Record<string, number>;
|
|
33
|
+
latencyMs: {
|
|
34
|
+
min: number;
|
|
35
|
+
mean: number;
|
|
36
|
+
p50: number;
|
|
37
|
+
p90: number;
|
|
38
|
+
p95: number;
|
|
39
|
+
p99: number;
|
|
40
|
+
max: number;
|
|
41
|
+
};
|
|
42
|
+
histogram: LatencyBucket[];
|
|
43
|
+
sampleErrors: string[];
|
|
44
|
+
thresholdsPassed: boolean;
|
|
45
|
+
thresholdViolations: string[];
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Zero-dependency SSRF-guarded concurrent HTTP Load & Latency Benchmarker
|
|
49
|
+
* (lightweight offline alternative to k6 / autocannon).
|
|
50
|
+
*/
|
|
51
|
+
export declare function executeLoadTest(input: LoadTestInput, options?: {
|
|
52
|
+
allowPrivate?: boolean;
|
|
53
|
+
}): Promise<LoadTestReport>;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { executeProxyRequest } from './http-proxy.js';
|
|
2
|
+
function pct(sorted, p) {
|
|
3
|
+
if (sorted.length === 0)
|
|
4
|
+
return 0;
|
|
5
|
+
const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));
|
|
6
|
+
return Math.round(sorted[idx] * 10) / 10;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Zero-dependency SSRF-guarded concurrent HTTP Load & Latency Benchmarker
|
|
10
|
+
* (lightweight offline alternative to k6 / autocannon).
|
|
11
|
+
*/
|
|
12
|
+
export async function executeLoadTest(input, options = {}) {
|
|
13
|
+
const url = input.url.trim();
|
|
14
|
+
if (!url)
|
|
15
|
+
throw new Error('Target URL is required for load testing');
|
|
16
|
+
const method = (input.method ?? 'GET').toUpperCase();
|
|
17
|
+
const totalRequests = Math.min(Math.max(Math.trunc(input.totalRequests ?? 50), 1), 1000);
|
|
18
|
+
const concurrency = Math.min(Math.max(Math.trunc(input.concurrency ?? 10), 1), 50, totalRequests);
|
|
19
|
+
const timeoutMs = Math.min(Math.max(Math.trunc(input.timeoutMs ?? 8000), 500), 20_000);
|
|
20
|
+
const latencies = [];
|
|
21
|
+
const statusCodes = {};
|
|
22
|
+
const sampleErrors = [];
|
|
23
|
+
let totalBytes = 0;
|
|
24
|
+
let succeeded = 0;
|
|
25
|
+
let failed = 0;
|
|
26
|
+
let nextIdx = 0;
|
|
27
|
+
const startedAt = performance.now();
|
|
28
|
+
async function worker() {
|
|
29
|
+
while (true) {
|
|
30
|
+
const idx = nextIdx++;
|
|
31
|
+
if (idx >= totalRequests)
|
|
32
|
+
break;
|
|
33
|
+
const t0 = performance.now();
|
|
34
|
+
try {
|
|
35
|
+
const resp = await executeProxyRequest({
|
|
36
|
+
method,
|
|
37
|
+
url,
|
|
38
|
+
headers: input.headers,
|
|
39
|
+
body: input.body,
|
|
40
|
+
timeoutMs,
|
|
41
|
+
followRedirects: true,
|
|
42
|
+
}, { allowPrivate: options.allowPrivate });
|
|
43
|
+
const dt = performance.now() - t0;
|
|
44
|
+
latencies.push(dt);
|
|
45
|
+
totalBytes += resp.sizeBytes;
|
|
46
|
+
const codeKey = String(resp.status);
|
|
47
|
+
statusCodes[codeKey] = (statusCodes[codeKey] ?? 0) + 1;
|
|
48
|
+
if (resp.status >= 200 && resp.status < 400)
|
|
49
|
+
succeeded++;
|
|
50
|
+
else
|
|
51
|
+
failed++;
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
const dt = performance.now() - t0;
|
|
55
|
+
latencies.push(dt);
|
|
56
|
+
failed++;
|
|
57
|
+
statusCodes['ERR'] = (statusCodes['ERR'] ?? 0) + 1;
|
|
58
|
+
if (sampleErrors.length < 5) {
|
|
59
|
+
sampleErrors.push(err instanceof Error ? err.message : String(err));
|
|
60
|
+
}
|
|
61
|
+
// Fail fast if SSRF Guard blocks request on first attempt
|
|
62
|
+
if (idx === 0 && err instanceof Error && /SSRF Guard|Blocked protocol/i.test(err.message)) {
|
|
63
|
+
throw err;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
await Promise.all(Array.from({ length: concurrency }, () => worker()));
|
|
69
|
+
const totalDurationMs = Math.max(0.1, Math.round((performance.now() - startedAt) * 10) / 10);
|
|
70
|
+
latencies.sort((a, b) => a - b);
|
|
71
|
+
const sum = latencies.reduce((a, b) => a + b, 0);
|
|
72
|
+
const minVal = latencies[0] ?? 0;
|
|
73
|
+
const maxVal = latencies[latencies.length - 1] ?? 0;
|
|
74
|
+
// Build 6 clean histogram buckets
|
|
75
|
+
const bucketCount = 6;
|
|
76
|
+
const span = Math.max(maxVal - minVal, 1);
|
|
77
|
+
const step = span / bucketCount;
|
|
78
|
+
const counts = new Array(bucketCount).fill(0);
|
|
79
|
+
for (const v of latencies) {
|
|
80
|
+
const b = Math.min(bucketCount - 1, Math.floor((v - minVal) / step));
|
|
81
|
+
counts[b]++;
|
|
82
|
+
}
|
|
83
|
+
const histogram = counts.map((count, i) => {
|
|
84
|
+
const lo = Math.round((minVal + i * step) * 10) / 10;
|
|
85
|
+
const hi = Math.round((minVal + (i + 1) * step) * 10) / 10;
|
|
86
|
+
return {
|
|
87
|
+
label: `${lo}–${hi}ms`,
|
|
88
|
+
count,
|
|
89
|
+
percent: latencies.length ? Math.round((count / latencies.length) * 1000) / 10 : 0,
|
|
90
|
+
};
|
|
91
|
+
});
|
|
92
|
+
const requestsPerSec = Math.round((latencies.length / (totalDurationMs / 1000)) * 10) / 10;
|
|
93
|
+
const p95 = pct(latencies, 95);
|
|
94
|
+
const errorRatePct = latencies.length ? Math.round((failed / latencies.length) * 1000) / 10 : 0;
|
|
95
|
+
const thresholdViolations = [];
|
|
96
|
+
const th = input.thresholds;
|
|
97
|
+
if (th) {
|
|
98
|
+
if (th.maxP95Ms !== undefined && p95 > th.maxP95Ms) {
|
|
99
|
+
thresholdViolations.push(`P95 latency ${p95}ms exceeded threshold maxP95Ms=${th.maxP95Ms}ms`);
|
|
100
|
+
}
|
|
101
|
+
if (th.minRps !== undefined && requestsPerSec < th.minRps) {
|
|
102
|
+
thresholdViolations.push(`Throughput ${requestsPerSec} req/s dropped below minRps=${th.minRps}`);
|
|
103
|
+
}
|
|
104
|
+
if (th.maxErrorRatePct !== undefined && errorRatePct > th.maxErrorRatePct) {
|
|
105
|
+
thresholdViolations.push(`Error rate ${errorRatePct}% exceeded maxErrorRatePct=${th.maxErrorRatePct}%`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
url,
|
|
110
|
+
method,
|
|
111
|
+
totalRequests,
|
|
112
|
+
concurrency,
|
|
113
|
+
completedRequests: latencies.length,
|
|
114
|
+
succeededRequests: succeeded,
|
|
115
|
+
failedRequests: failed,
|
|
116
|
+
totalDurationMs,
|
|
117
|
+
requestsPerSec,
|
|
118
|
+
throughputKbPerSec: Math.round(((totalBytes / 1024) / (totalDurationMs / 1000)) * 10) / 10,
|
|
119
|
+
statusCodes,
|
|
120
|
+
latencyMs: {
|
|
121
|
+
min: Math.round(minVal * 10) / 10,
|
|
122
|
+
mean: latencies.length ? Math.round((sum / latencies.length) * 10) / 10 : 0,
|
|
123
|
+
p50: pct(latencies, 50),
|
|
124
|
+
p90: pct(latencies, 90),
|
|
125
|
+
p95,
|
|
126
|
+
p99: pct(latencies, 99),
|
|
127
|
+
max: Math.round(maxVal * 10) / 10,
|
|
128
|
+
},
|
|
129
|
+
histogram,
|
|
130
|
+
sampleErrors,
|
|
131
|
+
thresholdsPassed: thresholdViolations.length === 0,
|
|
132
|
+
thresholdViolations,
|
|
133
|
+
};
|
|
134
|
+
}
|