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.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.ar.md +113 -0
  3. package/README.md +272 -2
  4. package/SECURITY.md +49 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +659 -0
  7. package/dist/core/contract-drift.d.ts +49 -0
  8. package/dist/core/contract-drift.js +302 -0
  9. package/dist/core/converters.d.ts +18 -0
  10. package/dist/core/converters.js +981 -0
  11. package/dist/core/cron.d.ts +33 -0
  12. package/dist/core/cron.js +306 -0
  13. package/dist/core/crypto.d.ts +59 -0
  14. package/dist/core/crypto.js +250 -0
  15. package/dist/core/curl.d.ts +17 -0
  16. package/dist/core/curl.js +170 -0
  17. package/dist/core/diff.d.ts +36 -0
  18. package/dist/core/diff.js +148 -0
  19. package/dist/core/encoding.d.ts +3 -0
  20. package/dist/core/encoding.js +143 -0
  21. package/dist/core/importers.d.ts +65 -0
  22. package/dist/core/importers.js +361 -0
  23. package/dist/core/jwt.d.ts +39 -0
  24. package/dist/core/jwt.js +256 -0
  25. package/dist/core/llm-tokens.d.ts +38 -0
  26. package/dist/core/llm-tokens.js +125 -0
  27. package/dist/core/log-analyzer.d.ts +30 -0
  28. package/dist/core/log-analyzer.js +155 -0
  29. package/dist/core/network.d.ts +72 -0
  30. package/dist/core/network.js +185 -0
  31. package/dist/core/oauth-protobuf.d.ts +74 -0
  32. package/dist/core/oauth-protobuf.js +390 -0
  33. package/dist/core/openapi.d.ts +27 -0
  34. package/dist/core/openapi.js +257 -0
  35. package/dist/core/pipeline.d.ts +28 -0
  36. package/dist/core/pipeline.js +154 -0
  37. package/dist/core/regex.d.ts +50 -0
  38. package/dist/core/regex.js +351 -0
  39. package/dist/core/runner.d.ts +53 -0
  40. package/dist/core/runner.js +250 -0
  41. package/dist/core/secrets.d.ts +87 -0
  42. package/dist/core/secrets.js +599 -0
  43. package/dist/core/security.d.ts +34 -0
  44. package/dist/core/security.js +284 -0
  45. package/dist/core/sql-explain.d.ts +50 -0
  46. package/dist/core/sql-explain.js +259 -0
  47. package/dist/core/tls.d.ts +44 -0
  48. package/dist/core/tls.js +166 -0
  49. package/dist/index.d.ts +31 -0
  50. package/dist/index.js +31 -0
  51. package/dist/server/app.d.ts +31 -0
  52. package/dist/server/app.js +348 -0
  53. package/dist/server/http-proxy.d.ts +55 -0
  54. package/dist/server/http-proxy.js +364 -0
  55. package/dist/server/http-utils.d.ts +28 -0
  56. package/dist/server/http-utils.js +106 -0
  57. package/dist/server/load-tester.d.ts +53 -0
  58. package/dist/server/load-tester.js +134 -0
  59. package/dist/server/mcp.d.ts +35 -0
  60. package/dist/server/mcp.js +466 -0
  61. package/dist/server/mock-store.d.ts +38 -0
  62. package/dist/server/mock-store.js +197 -0
  63. package/dist/server/plugin-loader.d.ts +60 -0
  64. package/dist/server/plugin-loader.js +285 -0
  65. package/dist/server/recorder-store.d.ts +35 -0
  66. package/dist/server/recorder-store.js +146 -0
  67. package/dist/server/routes/network-routes.d.ts +3 -0
  68. package/dist/server/routes/network-routes.js +391 -0
  69. package/dist/server/routes/tools-routes.d.ts +3 -0
  70. package/dist/server/routes/tools-routes.js +292 -0
  71. package/dist/server/routes/workspace-routes.d.ts +3 -0
  72. package/dist/server/routes/workspace-routes.js +240 -0
  73. package/dist/server/webhook-store.d.ts +29 -0
  74. package/dist/server/webhook-store.js +90 -0
  75. package/dist/server/workspace-store.d.ts +91 -0
  76. package/dist/server/workspace-store.js +447 -0
  77. package/dist/server/ws-probe.d.ts +34 -0
  78. package/dist/server/ws-probe.js +283 -0
  79. package/dist/ui/app.js +274 -0
  80. package/dist/ui/favicon.svg +14 -0
  81. package/dist/ui/index.html +83 -0
  82. package/dist/ui/logo.png +0 -0
  83. package/dist/ui/styles.css +694 -0
  84. package/dist/ui/tools-data.js +704 -0
  85. package/dist/ui/tools-network.js +727 -0
  86. package/dist/ui/tools-ops.js +295 -0
  87. package/dist/ui/tools-pro.js +500 -0
  88. package/dist/ui/tools-security.js +389 -0
  89. package/dist/ui/tools-v12.js +745 -0
  90. package/dist/ui/tools-v13.js +321 -0
  91. package/dist/ui/tools-v20.js +563 -0
  92. package/dist/ui/tools-v21.js +395 -0
  93. package/package.json +75 -4
@@ -0,0 +1,146 @@
1
+ import * as crypto from 'node:crypto';
2
+ import { safeJsonParse } from '../core/security.js';
3
+ const MAX_RECORDED_ENTRIES = 100;
4
+ const SENSITIVE_HEADER_NAMES = new Set(['authorization', 'cookie', 'set-cookie', 'x-api-key', 'proxy-authorization']);
5
+ function redactHeaders(headers) {
6
+ const out = {};
7
+ for (const [k, v] of Object.entries(headers)) {
8
+ out[k] = SENSITIVE_HEADER_NAMES.has(k.toLowerCase()) ? '[REDACTED]' : v;
9
+ }
10
+ return out;
11
+ }
12
+ function inferJsonSchema(val, depth = 0) {
13
+ if (depth > 6 || val === null)
14
+ return { type: 'string', nullable: true };
15
+ if (Array.isArray(val)) {
16
+ return { type: 'array', items: val.length > 0 ? inferJsonSchema(val[0], depth + 1) : { type: 'string' } };
17
+ }
18
+ if (typeof val === 'boolean')
19
+ return { type: 'boolean', example: val };
20
+ if (typeof val === 'number')
21
+ return { type: Number.isInteger(val) ? 'integer' : 'number', example: val };
22
+ if (typeof val === 'string')
23
+ return { type: 'string', example: val.slice(0, 80) };
24
+ if (typeof val === 'object') {
25
+ const props = {};
26
+ const required = [];
27
+ for (const [k, v] of Object.entries(val)) {
28
+ props[k] = inferJsonSchema(v, depth + 1);
29
+ if (v !== null && v !== undefined)
30
+ required.push(k);
31
+ }
32
+ return { type: 'object', properties: props, ...(required.length ? { required } : {}) };
33
+ }
34
+ return { type: 'string' };
35
+ }
36
+ /**
37
+ * Bounded in-memory API Traffic Recorder.
38
+ * Captures proxied API Studio requests (with sensitive headers redacted) and exports them
39
+ * as Workspace Collections, Live Mock Routes, or an inferred OpenAPI 3.0.3 specification.
40
+ */
41
+ export class RecorderStore {
42
+ entries = [];
43
+ enabled = true;
44
+ isEnabled() {
45
+ return this.enabled;
46
+ }
47
+ setEnabled(flag) {
48
+ this.enabled = flag;
49
+ return this.enabled;
50
+ }
51
+ record(input) {
52
+ if (!this.enabled)
53
+ return null;
54
+ const entry = {
55
+ id: `rec_${crypto.randomBytes(4).toString('hex')}`,
56
+ recordedAt: new Date().toISOString(),
57
+ ...input,
58
+ requestHeaders: redactHeaders(input.requestHeaders),
59
+ responseBody: input.responseBody.slice(0, 128 * 1024),
60
+ };
61
+ this.entries.unshift(entry);
62
+ if (this.entries.length > MAX_RECORDED_ENTRIES) {
63
+ this.entries.length = MAX_RECORDED_ENTRIES;
64
+ }
65
+ return entry;
66
+ }
67
+ list() {
68
+ return [...this.entries];
69
+ }
70
+ clear() {
71
+ this.entries = [];
72
+ }
73
+ toSavedRequests() {
74
+ return this.entries.map((e) => ({
75
+ id: `req_${e.id}`,
76
+ name: `${e.method} ${e.pathname}`,
77
+ method: e.method,
78
+ url: e.url,
79
+ headers: { ...e.requestHeaders },
80
+ ...(e.requestBody ? { body: e.requestBody } : {}),
81
+ assertions: [{ type: 'status', expected: e.status }],
82
+ }));
83
+ }
84
+ toMockRoutes() {
85
+ const seen = new Set();
86
+ const routes = [];
87
+ for (const e of this.entries) {
88
+ const key = `${e.method}:${e.pathname}`;
89
+ if (seen.has(key))
90
+ continue;
91
+ seen.add(key);
92
+ routes.push({
93
+ method: e.method,
94
+ path: e.pathname || '/',
95
+ status: e.status,
96
+ headers: { 'Content-Type': e.responseContentType || 'application/json; charset=utf-8' },
97
+ body: e.responseBody,
98
+ });
99
+ }
100
+ return routes;
101
+ }
102
+ /**
103
+ * Infers a clean OpenAPI 3.0.3 JSON specification directly from captured live traffic!
104
+ */
105
+ inferOpenApiSpec(title = 'Recorded API Spec') {
106
+ const paths = {};
107
+ for (const e of this.entries) {
108
+ const pathKey = e.pathname || '/';
109
+ const methodKey = e.method.toLowerCase();
110
+ if (!paths[pathKey])
111
+ paths[pathKey] = {};
112
+ if (paths[pathKey][methodKey])
113
+ continue;
114
+ let schema = { type: 'string' };
115
+ try {
116
+ const parsed = safeJsonParse(e.responseBody);
117
+ schema = inferJsonSchema(parsed);
118
+ }
119
+ catch {
120
+ schema = { type: 'string' };
121
+ }
122
+ paths[pathKey][methodKey] = {
123
+ summary: `Recorded ${e.method} ${pathKey}`,
124
+ responses: {
125
+ [String(e.status)]: {
126
+ description: `Recorded HTTP ${e.status} response`,
127
+ content: {
128
+ [e.responseContentType.split(';')[0]?.trim() || 'application/json']: {
129
+ schema,
130
+ },
131
+ },
132
+ },
133
+ },
134
+ };
135
+ }
136
+ return {
137
+ openapi: '3.0.3',
138
+ info: {
139
+ title,
140
+ version: '1.0.0',
141
+ description: `Automatically inferred from ${this.entries.length} captured request(s) by DevAnvil Traffic Recorder.`,
142
+ },
143
+ paths,
144
+ };
145
+ }
146
+ }
@@ -0,0 +1,3 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type RouteContext } from '../http-utils.js';
3
+ export declare function handleNetworkRoutes(method: string, pathname: string, req: IncomingMessage, res: ServerResponse, ctx: RouteContext): Promise<boolean>;
@@ -0,0 +1,391 @@
1
+ import { checkOpenApiContractDrift } from '../../core/contract-drift.js';
2
+ import { generateCodeSnippets, parseCurlCommand } from '../../core/curl.js';
3
+ import { interpolateRequestWithEnv } from '../../core/importers.js';
4
+ import { openApiToMockRoutes, parseOpenApiSpec } from '../../core/openapi.js';
5
+ import { assertSafeChannelName, safeJsonParse } from '../../core/security.js';
6
+ import { inspectPemCertificates, inspectRemoteTls } from '../../core/tls.js';
7
+ import { executeProxyRequest, executeSseStreamRequest } from '../http-proxy.js';
8
+ import { applySecurityHeaders, asOptionalNumber, asOptionalString, asString, asStringMap, readJsonBody, sendJson, } from '../http-utils.js';
9
+ import { executeLoadTest } from '../load-tester.js';
10
+ import { executeWebSocketProbe, GRAPHQL_INTROSPECTION_QUERY } from '../ws-probe.js';
11
+ export async function handleNetworkRoutes(method, pathname, req, res, ctx) {
12
+ const { denyIframe, allowPrivateProxy, mockStore, webhookStore, workspaceStore, recorderStore } = ctx;
13
+ // API Studio Proxy (with optional Environment Interpolation + Record-to-Mock)
14
+ if (method === 'POST' && pathname === '/api/proxy') {
15
+ const body = await readJsonBody(req);
16
+ let reqMethod = asString(body.method, 'GET');
17
+ let targetUrl = asString(body.url);
18
+ let reqHeaders = asStringMap(body.headers) ?? {};
19
+ let reqBody = asString(body.body, '');
20
+ if (body.useEnvironment !== false) {
21
+ const activeEnv = workspaceStore.getActiveEnvironment();
22
+ if (activeEnv) {
23
+ const resolved = interpolateRequestWithEnv({ method: reqMethod, url: targetUrl, headers: reqHeaders, body: reqBody }, activeEnv.variables, { processEnv: process.env });
24
+ reqMethod = resolved.method;
25
+ targetUrl = resolved.url;
26
+ reqHeaders = resolved.headers;
27
+ reqBody = resolved.body;
28
+ }
29
+ }
30
+ if (!targetUrl) {
31
+ sendJson(res, 400, { error: 'Target URL is required' }, denyIframe);
32
+ return true;
33
+ }
34
+ const result = await executeProxyRequest({
35
+ method: reqMethod,
36
+ url: targetUrl,
37
+ headers: reqHeaders,
38
+ body: reqBody,
39
+ timeoutMs: asOptionalNumber(body.timeoutMs),
40
+ followRedirects: body.followRedirects !== false,
41
+ }, { allowPrivate: allowPrivateProxy });
42
+ // Auto-record proxied API traffic into bounded RecorderStore (sensitive headers redacted)
43
+ try {
44
+ const parsedFinal = new URL(result.finalUrl);
45
+ recorderStore.record({
46
+ method: reqMethod,
47
+ url: result.finalUrl,
48
+ pathname: parsedFinal.pathname || '/',
49
+ requestHeaders: reqHeaders,
50
+ ...(reqBody ? { requestBody: reqBody } : {}),
51
+ status: result.status,
52
+ responseContentType: result.contentType || 'application/json; charset=utf-8',
53
+ responseBody: result.body,
54
+ durationMs: result.timings.totalMs,
55
+ });
56
+ }
57
+ catch {
58
+ // Non-fatal recorder skip
59
+ }
60
+ let recordedMockPath;
61
+ if (body.recordAsMock === true) {
62
+ const parsedFinal = new URL(result.finalUrl);
63
+ const mockPath = parsedFinal.pathname || '/';
64
+ mockStore.create({
65
+ method: reqMethod,
66
+ path: mockPath,
67
+ status: result.status,
68
+ headers: { 'Content-Type': result.contentType || 'application/json; charset=utf-8' },
69
+ body: result.body,
70
+ });
71
+ workspaceStore.syncMocksAndPersist(mockStore.list());
72
+ recordedMockPath = `/mock${mockPath}`;
73
+ }
74
+ sendJson(res, 200, { ...result, ...(recordedMockPath ? { recordedMockPath } : {}) }, denyIframe);
75
+ return true;
76
+ }
77
+ // Live SSE Stream Tester Proxy (with TTFT & SSRF guard)
78
+ if (method === 'POST' && pathname === '/api/proxy/sse') {
79
+ const body = await readJsonBody(req);
80
+ let targetUrl = asString(body.url);
81
+ let reqHeaders = asStringMap(body.headers) ?? {};
82
+ let reqBody = asString(body.body, '');
83
+ const reqMethod = asString(body.method, 'GET');
84
+ if (body.useEnvironment !== false) {
85
+ const activeEnv = workspaceStore.getActiveEnvironment();
86
+ if (activeEnv) {
87
+ const resolved = interpolateRequestWithEnv({ method: reqMethod, url: targetUrl, headers: reqHeaders, body: reqBody }, activeEnv.variables, { processEnv: process.env });
88
+ targetUrl = resolved.url;
89
+ reqHeaders = resolved.headers;
90
+ reqBody = resolved.body;
91
+ }
92
+ }
93
+ if (!targetUrl) {
94
+ sendJson(res, 400, { error: 'Target SSE URL is required' }, denyIframe);
95
+ return true;
96
+ }
97
+ const result = await executeSseStreamRequest({
98
+ method: reqMethod,
99
+ url: targetUrl,
100
+ headers: reqHeaders,
101
+ body: reqBody,
102
+ maxEvents: asOptionalNumber(body.maxEvents),
103
+ maxDurationMs: asOptionalNumber(body.maxDurationMs),
104
+ }, { allowPrivate: allowPrivateProxy });
105
+ sendJson(res, 200, result, denyIframe);
106
+ return true;
107
+ }
108
+ // Live RFC 6455 WebSocket Probe (SSRF & DNS-pinning guarded)
109
+ if (method === 'POST' && pathname === '/api/proxy/ws') {
110
+ const body = await readJsonBody(req);
111
+ let targetUrl = asString(body.url);
112
+ let reqHeaders = asStringMap(body.headers) ?? {};
113
+ const activeEnv = body.useEnvironment !== false ? workspaceStore.getActiveEnvironment() : undefined;
114
+ if (activeEnv) {
115
+ const resolved = interpolateRequestWithEnv({ method: 'GET', url: targetUrl, headers: reqHeaders, body: '' }, activeEnv.variables, { processEnv: process.env });
116
+ targetUrl = resolved.url;
117
+ reqHeaders = resolved.headers;
118
+ }
119
+ const rawMessages = Array.isArray(body.messages)
120
+ ? body.messages.map((m) => String(m ?? ''))
121
+ : asOptionalString(body.message)
122
+ ? [asString(body.message)]
123
+ : [];
124
+ const result = await executeWebSocketProbe({
125
+ url: targetUrl,
126
+ headers: reqHeaders,
127
+ messages: rawMessages,
128
+ maxMessages: asOptionalNumber(body.maxMessages),
129
+ maxDurationMs: asOptionalNumber(body.maxDurationMs),
130
+ }, { allowPrivate: allowPrivateProxy });
131
+ sendJson(res, 200, result, denyIframe);
132
+ return true;
133
+ }
134
+ // GraphQL Studio Runner & Schema Introspection
135
+ if (method === 'POST' && pathname === '/api/graphql') {
136
+ const body = await readJsonBody(req);
137
+ let targetUrl = asString(body.url);
138
+ let reqHeaders = asStringMap(body.headers) ?? {};
139
+ const query = body.introspect === true ? GRAPHQL_INTROSPECTION_QUERY : asString(body.query);
140
+ if (!query.trim()) {
141
+ sendJson(res, 400, { error: 'GraphQL query is required' }, denyIframe);
142
+ return true;
143
+ }
144
+ let variables = undefined;
145
+ if (typeof body.variables === 'string' && body.variables.trim()) {
146
+ variables = safeJsonParse(body.variables);
147
+ }
148
+ else if (body.variables && typeof body.variables === 'object') {
149
+ variables = body.variables;
150
+ }
151
+ const activeEnv = body.useEnvironment !== false ? workspaceStore.getActiveEnvironment() : undefined;
152
+ if (activeEnv) {
153
+ const resolved = interpolateRequestWithEnv({ method: 'POST', url: targetUrl, headers: reqHeaders, body: '' }, activeEnv.variables, { processEnv: process.env });
154
+ targetUrl = resolved.url;
155
+ reqHeaders = resolved.headers;
156
+ }
157
+ const payload = JSON.stringify({
158
+ query,
159
+ ...(variables !== undefined ? { variables } : {}),
160
+ ...(asOptionalString(body.operationName) ? { operationName: asString(body.operationName) } : {}),
161
+ });
162
+ const result = await executeProxyRequest({
163
+ method: 'POST',
164
+ url: targetUrl,
165
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...reqHeaders },
166
+ body: payload,
167
+ timeoutMs: asOptionalNumber(body.timeoutMs),
168
+ }, { allowPrivate: allowPrivateProxy });
169
+ sendJson(res, 200, result, denyIframe);
170
+ return true;
171
+ }
172
+ // TLS / X.509 Certificate Inspector
173
+ if (method === 'POST' && pathname === '/api/tls/inspect-pem') {
174
+ const body = await readJsonBody(req);
175
+ const certificates = inspectPemCertificates(asString(body.pem));
176
+ sendJson(res, 200, { count: certificates.length, certificates }, denyIframe);
177
+ return true;
178
+ }
179
+ if (method === 'POST' && pathname === '/api/tls/inspect-remote') {
180
+ const body = await readJsonBody(req);
181
+ const report = await inspectRemoteTls(asString(body.target), {
182
+ port: asOptionalNumber(body.port),
183
+ allowPrivate: allowPrivateProxy,
184
+ timeoutMs: asOptionalNumber(body.timeoutMs),
185
+ });
186
+ sendJson(res, 200, report, denyIframe);
187
+ return true;
188
+ }
189
+ // HTTP Load & Latency Benchmarker (SSRF-guarded)
190
+ if (method === 'POST' && pathname === '/api/load-test') {
191
+ const body = await readJsonBody(req);
192
+ let reqMethod = asString(body.method, 'GET');
193
+ let targetUrl = asString(body.url);
194
+ let reqHeaders = asStringMap(body.headers) ?? {};
195
+ let reqBody = asString(body.body, '');
196
+ if (body.useEnvironment !== false) {
197
+ const activeEnv = workspaceStore.getActiveEnvironment();
198
+ if (activeEnv) {
199
+ const resolved = interpolateRequestWithEnv({ method: reqMethod, url: targetUrl, headers: reqHeaders, body: reqBody }, activeEnv.variables, { processEnv: process.env });
200
+ reqMethod = resolved.method;
201
+ targetUrl = resolved.url;
202
+ reqHeaders = resolved.headers;
203
+ reqBody = resolved.body;
204
+ }
205
+ }
206
+ const th = body.thresholds && typeof body.thresholds === 'object' && !Array.isArray(body.thresholds)
207
+ ? body.thresholds
208
+ : undefined;
209
+ const report = await executeLoadTest({
210
+ method: reqMethod,
211
+ url: targetUrl,
212
+ headers: reqHeaders,
213
+ body: reqBody,
214
+ totalRequests: asOptionalNumber(body.totalRequests),
215
+ concurrency: asOptionalNumber(body.concurrency),
216
+ timeoutMs: asOptionalNumber(body.timeoutMs),
217
+ ...(th
218
+ ? {
219
+ thresholds: {
220
+ maxP95Ms: asOptionalNumber(th.maxP95Ms),
221
+ minRps: asOptionalNumber(th.minRps),
222
+ maxErrorRatePct: asOptionalNumber(th.maxErrorRatePct),
223
+ },
224
+ }
225
+ : {}),
226
+ }, { allowPrivate: allowPrivateProxy });
227
+ sendJson(res, 200, report, denyIframe);
228
+ return true;
229
+ }
230
+ // OpenAPI Contract Drift Detector
231
+ if (method === 'POST' && pathname === '/api/contract/check') {
232
+ const body = await readJsonBody(req);
233
+ const report = checkOpenApiContractDrift({
234
+ spec: asString(body.spec),
235
+ method: asString(body.method, 'GET'),
236
+ path: asString(body.path, '/'),
237
+ status: asOptionalNumber(body.status) ?? 200,
238
+ body: asString(body.body, ''),
239
+ });
240
+ sendJson(res, 200, report, denyIframe);
241
+ return true;
242
+ }
243
+ // Live Traffic Recorder -> Collection / Mocks / Inferred OpenAPI 3.0.3
244
+ if (method === 'GET' && pathname === '/api/recorder') {
245
+ sendJson(res, 200, { enabled: recorderStore.isEnabled(), entries: recorderStore.list() }, denyIframe);
246
+ return true;
247
+ }
248
+ if (method === 'DELETE' && pathname === '/api/recorder') {
249
+ recorderStore.clear();
250
+ sendJson(res, 200, { cleared: true, entries: [] }, denyIframe);
251
+ return true;
252
+ }
253
+ if (method === 'POST' && pathname === '/api/recorder/toggle') {
254
+ const body = await readJsonBody(req);
255
+ const enabled = recorderStore.setEnabled(Boolean(body.enabled));
256
+ sendJson(res, 200, { enabled }, denyIframe);
257
+ return true;
258
+ }
259
+ if (method === 'POST' && pathname === '/api/recorder/export') {
260
+ const body = await readJsonBody(req);
261
+ const mode = asString(body.mode, 'openapi').toLowerCase();
262
+ if (mode === 'mocks') {
263
+ const routes = recorderStore.toMockRoutes();
264
+ const mounted = mockStore.importRoutes(routes, Boolean(body.replace));
265
+ workspaceStore.syncMocksAndPersist(mockStore.list());
266
+ sendJson(res, 201, { mode, mountedCount: mounted.length, routes: mockStore.list() }, denyIframe);
267
+ return true;
268
+ }
269
+ if (mode === 'collection') {
270
+ const name = asString(body.name, `Recorded Traffic (${new Date().toISOString().slice(0, 10)})`);
271
+ const collection = workspaceStore.addCollection(name, recorderStore.toSavedRequests());
272
+ sendJson(res, 201, { mode, collection, requestCount: collection.requests.length }, denyIframe);
273
+ return true;
274
+ }
275
+ const spec = recorderStore.inferOpenApiSpec(asString(body.title, 'Recorded API Spec'));
276
+ sendJson(res, 200, { mode: 'openapi', spec }, denyIframe);
277
+ return true;
278
+ }
279
+ // cURL parse & codegen
280
+ if (method === 'POST' && pathname === '/api/curl/parse') {
281
+ const body = await readJsonBody(req);
282
+ sendJson(res, 200, parseCurlCommand(asString(body.command)), denyIframe);
283
+ return true;
284
+ }
285
+ if (method === 'POST' && pathname === '/api/curl/generate') {
286
+ const body = await readJsonBody(req);
287
+ sendJson(res, 200, generateCodeSnippets({
288
+ method: asString(body.method, 'GET'),
289
+ url: asString(body.url, ''),
290
+ headers: asStringMap(body.headers) ?? {},
291
+ body: asString(body.body, ''),
292
+ }), denyIframe);
293
+ return true;
294
+ }
295
+ // Mock API CRUD + Bulk Import + OpenAPI Mount
296
+ if (method === 'GET' && pathname === '/api/mocks') {
297
+ sendJson(res, 200, { routes: mockStore.list() }, denyIframe);
298
+ return true;
299
+ }
300
+ if (method === 'POST' && pathname === '/api/mocks/import') {
301
+ const body = await readJsonBody(req);
302
+ if (!Array.isArray(body.routes)) {
303
+ sendJson(res, 400, { error: 'Expected "routes" array in import payload' }, denyIframe);
304
+ return true;
305
+ }
306
+ const imported = mockStore.importRoutes(body.routes, Boolean(body.replace));
307
+ workspaceStore.syncMocksAndPersist(mockStore.list());
308
+ sendJson(res, 201, { importedCount: imported.length, routes: mockStore.list() }, denyIframe);
309
+ return true;
310
+ }
311
+ if (method === 'POST' && pathname === '/api/mocks') {
312
+ const body = await readJsonBody(req);
313
+ const created = mockStore.create({
314
+ method: asString(body.method, 'GET'),
315
+ path: asString(body.path),
316
+ status: asOptionalNumber(body.status),
317
+ headers: asStringMap(body.headers),
318
+ body: asString(body.body, ''),
319
+ delayMs: asOptionalNumber(body.delayMs),
320
+ enabled: body.enabled !== false,
321
+ });
322
+ workspaceStore.syncMocksAndPersist(mockStore.list());
323
+ sendJson(res, 201, created, denyIframe);
324
+ return true;
325
+ }
326
+ if (pathname.startsWith('/api/mocks/')) {
327
+ const id = pathname.slice('/api/mocks/'.length);
328
+ if (method === 'PATCH' || method === 'PUT') {
329
+ const body = await readJsonBody(req);
330
+ const updated = mockStore.update(id, body);
331
+ workspaceStore.syncMocksAndPersist(mockStore.list());
332
+ sendJson(res, 200, updated, denyIframe);
333
+ return true;
334
+ }
335
+ if (method === 'DELETE') {
336
+ const deleted = mockStore.delete(id);
337
+ if (deleted)
338
+ workspaceStore.syncMocksAndPersist(mockStore.list());
339
+ sendJson(res, deleted ? 200 : 404, { deleted }, denyIframe);
340
+ return true;
341
+ }
342
+ }
343
+ if (method === 'POST' && pathname === '/api/openapi/parse') {
344
+ const body = await readJsonBody(req);
345
+ sendJson(res, 200, parseOpenApiSpec(asString(body.spec)), denyIframe);
346
+ return true;
347
+ }
348
+ if (method === 'POST' && pathname === '/api/openapi/mount') {
349
+ const body = await readJsonBody(req);
350
+ const parsed = parseOpenApiSpec(asString(body.spec));
351
+ const routes = openApiToMockRoutes(parsed);
352
+ const mounted = mockStore.importRoutes(routes, Boolean(body.replace));
353
+ workspaceStore.syncMocksAndPersist(mockStore.list());
354
+ sendJson(res, 201, { spec: parsed, mountedCount: mounted.length, routes: mockStore.list() }, denyIframe);
355
+ return true;
356
+ }
357
+ // Webhook Inspector & Live SSE Stream
358
+ if (method === 'GET' && pathname === '/api/webhooks') {
359
+ sendJson(res, 200, { channels: webhookStore.listChannels() }, denyIframe);
360
+ return true;
361
+ }
362
+ const webhookEventsMatch = /^\/api\/webhooks\/([^/]+)$/.exec(pathname);
363
+ if (webhookEventsMatch) {
364
+ const channel = assertSafeChannelName(decodeURIComponent(webhookEventsMatch[1]));
365
+ if (method === 'GET') {
366
+ sendJson(res, 200, { channel, events: webhookStore.list(channel) }, denyIframe);
367
+ return true;
368
+ }
369
+ if (method === 'DELETE') {
370
+ webhookStore.clear(channel);
371
+ sendJson(res, 200, { cleared: true, channel }, denyIframe);
372
+ return true;
373
+ }
374
+ }
375
+ const webhookStreamMatch = /^\/api\/webhooks\/([^/]+)\/stream$/.exec(pathname);
376
+ if (method === 'GET' && webhookStreamMatch) {
377
+ const channel = assertSafeChannelName(decodeURIComponent(webhookStreamMatch[1]));
378
+ applySecurityHeaders(res, denyIframe);
379
+ res.writeHead(200, {
380
+ 'Content-Type': 'text/event-stream; charset=utf-8',
381
+ 'Cache-Control': 'no-cache, no-transform',
382
+ Connection: 'keep-alive',
383
+ 'X-Accel-Buffering': 'no',
384
+ });
385
+ res.write(`event: connected\ndata: ${JSON.stringify({ channel, count: webhookStore.list(channel).length })}\n\n`);
386
+ const unsubscribe = webhookStore.subscribe(channel, res);
387
+ req.on('close', unsubscribe);
388
+ return true;
389
+ }
390
+ return false;
391
+ }
@@ -0,0 +1,3 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type RouteContext } from '../http-utils.js';
3
+ export declare function handleToolRoutes(method: string, pathname: string, urlObj: URL, req: IncomingMessage, res: ServerResponse, ctx: RouteContext): Promise<boolean>;