devanvil 2.1.0 → 2.1.1

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 (41) hide show
  1. package/SECURITY.md +4 -4
  2. package/dist/cli.js +6 -1
  3. package/dist/core/contract-drift.js +15 -5
  4. package/dist/core/converters.js +25 -17
  5. package/dist/core/cron.js +6 -3
  6. package/dist/core/crypto.js +11 -1
  7. package/dist/core/curl.js +5 -1
  8. package/dist/core/diff.js +2 -2
  9. package/dist/core/encoding.js +1 -1
  10. package/dist/core/jwt.js +21 -8
  11. package/dist/core/oauth-protobuf.js +16 -10
  12. package/dist/core/regex.js +13 -4
  13. package/dist/core/secrets.js +11 -7
  14. package/dist/core/security.js +20 -3
  15. package/dist/core/tls.js +5 -2
  16. package/dist/server/app.d.ts +1 -1
  17. package/dist/server/app.js +17 -6
  18. package/dist/server/http-proxy.js +19 -10
  19. package/dist/server/http-utils.js +15 -3
  20. package/dist/server/load-tester.js +3 -0
  21. package/dist/server/mcp.d.ts +1 -1
  22. package/dist/server/mcp.js +8 -4
  23. package/dist/server/mock-store.js +54 -13
  24. package/dist/server/plugin-loader.d.ts +2 -1
  25. package/dist/server/plugin-loader.js +21 -1
  26. package/dist/server/recorder-store.js +2 -1
  27. package/dist/server/routes/network-routes.js +54 -4
  28. package/dist/server/routes/tools-routes.js +9 -2
  29. package/dist/server/routes/workspace-routes.js +26 -4
  30. package/dist/server/webhook-store.js +12 -2
  31. package/dist/server/workspace-store.js +4 -3
  32. package/dist/server/ws-probe.js +8 -0
  33. package/dist/ui/app.js +20 -4
  34. package/dist/ui/styles.css +2 -2
  35. package/dist/ui/tools-data.js +42 -27
  36. package/dist/ui/tools-network.js +70 -28
  37. package/dist/ui/tools-ops.js +16 -12
  38. package/dist/ui/tools-security.js +30 -22
  39. package/dist/ui/tools-v12.js +34 -14
  40. package/dist/ui/tools-v21.js +26 -10
  41. package/package.json +1 -1
@@ -15,7 +15,7 @@ import { handleToolRoutes } from './routes/tools-routes.js';
15
15
  import { handleWorkspaceAndPluginRoutes } from './routes/workspace-routes.js';
16
16
  import { WebhookStore } from './webhook-store.js';
17
17
  import { WorkspaceStore } from './workspace-store.js';
18
- export const DEVANVIL_VERSION = '2.1.0';
18
+ export const DEVANVIL_VERSION = '2.1.1';
19
19
  const MIME_TYPES = {
20
20
  '.html': 'text/html; charset=utf-8',
21
21
  '.css': 'text/css; charset=utf-8',
@@ -108,7 +108,16 @@ export function createDevAnvilServer(options = {}) {
108
108
  async function handleRequest(req, res) {
109
109
  const method = (req.method ?? 'GET').toUpperCase();
110
110
  const rawUrl = req.url ?? '/';
111
- const urlObj = new URL(rawUrl, `http://${req.headers.host || 'localhost'}`);
111
+ // Parse against a constant local origin and normalize leading slashes to prevent protocol-relative or malformed Host errors
112
+ const normalizedRawUrl = rawUrl.startsWith('//') ? `/${rawUrl.replace(/^\/+/, '')}` : rawUrl.startsWith('/') ? rawUrl : `/${rawUrl}`;
113
+ let urlObj;
114
+ try {
115
+ urlObj = new URL(normalizedRawUrl, 'http://localhost');
116
+ }
117
+ catch {
118
+ sendJson(res, 400, { error: 'Malformed request URL' }, denyIframe);
119
+ return;
120
+ }
112
121
  const pathname = urlObj.pathname;
113
122
  // 1. Live Mock API Server: /mock/*
114
123
  if (pathname === '/mock' || pathname.startsWith('/mock/')) {
@@ -131,11 +140,13 @@ export function createDevAnvilServer(options = {}) {
131
140
  if (matched.route.delayMs > 0) {
132
141
  await new Promise((r) => setTimeout(r, matched.route.delayMs));
133
142
  }
143
+ // Set custom mock headers first, then re-apply security headers so mock routes can never weaken CSP/XFO/nosniff
144
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
145
+ for (const [hk, hv] of Object.entries(matched.route.headers)) {
146
+ res.setHeader(hk, hv);
147
+ }
134
148
  applySecurityHeaders(res, denyIframe);
135
- res.writeHead(matched.route.status, {
136
- 'Content-Type': 'application/json; charset=utf-8',
137
- ...matched.route.headers,
138
- });
149
+ res.writeHead(matched.route.status);
139
150
  res.end(matched.renderedBody);
140
151
  return;
141
152
  }
@@ -63,16 +63,17 @@ export async function executeProxyRequest(input, options = {}) {
63
63
  totalDnsMs += performance.now() - dnsStart;
64
64
  const cleanHeaders = {};
65
65
  for (const [k, v] of Object.entries(activeHeaders)) {
66
- const lower = k.toLowerCase().trim();
66
+ const trimmedKey = k.trim();
67
+ const lower = trimmedKey.toLowerCase();
67
68
  if (!lower || STRIPPED_REQ_HEADERS.has(lower))
68
69
  continue;
69
- if (/[\r\n]/.test(k) || /[\r\n]/.test(String(v))) {
70
- throw new Error(`Invalid CRLF characters in header "${k}"`);
70
+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(trimmedKey) || /[\r\n\0]/.test(String(v))) {
71
+ throw new Error(`Invalid CRLF or illegal characters in header "${k}"`);
71
72
  }
72
- cleanHeaders[k.trim()] = String(v);
73
+ cleanHeaders[trimmedKey] = String(v);
73
74
  }
74
75
  if (!Object.keys(cleanHeaders).some((k) => k.toLowerCase() === 'user-agent')) {
75
- cleanHeaders['User-Agent'] = 'DevAnvil/1.0 (Local-First Developer Studio)';
76
+ cleanHeaders['User-Agent'] = 'DevAnvil/2.1.1 (Local-First Developer Studio)';
76
77
  }
77
78
  if (!Object.keys(cleanHeaders).some((k) => k.toLowerCase() === 'accept-encoding')) {
78
79
  cleanHeaders['Accept-Encoding'] = 'gzip, deflate, br';
@@ -122,7 +123,11 @@ export async function executeProxyRequest(input, options = {}) {
122
123
  chunks.push(chunk);
123
124
  received += chunk.length;
124
125
  });
126
+ let finished = false;
125
127
  const finish = () => {
128
+ if (finished)
129
+ return;
130
+ finished = true;
126
131
  const respHeaders = {};
127
132
  for (const [hk, hv] of Object.entries(res.headers)) {
128
133
  if (hv !== undefined) {
@@ -223,23 +228,27 @@ export async function executeSseStreamRequest(input, options = {}) {
223
228
  const target = await validateProxyTargetUrl(input.url, { allowPrivate: options.allowPrivate });
224
229
  const headers = {};
225
230
  for (const [k, v] of Object.entries(input.headers ?? {})) {
226
- const lower = k.toLowerCase().trim();
231
+ const trimmedKey = k.trim();
232
+ const lower = trimmedKey.toLowerCase();
227
233
  if (!lower || STRIPPED_REQ_HEADERS.has(lower))
228
234
  continue;
229
- if (/[\r\n]/.test(k) || /[\r\n]/.test(String(v))) {
230
- throw new Error(`Invalid CRLF characters in header "${k}"`);
235
+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(trimmedKey) || /[\r\n\0]/.test(String(v))) {
236
+ throw new Error(`Invalid CRLF or illegal characters in header "${k}"`);
231
237
  }
232
- headers[k.trim()] = String(v);
238
+ headers[trimmedKey] = String(v);
233
239
  }
234
240
  if (!Object.keys(headers).some((k) => k.toLowerCase() === 'accept')) {
235
241
  headers['Accept'] = 'text/event-stream';
236
242
  }
237
243
  if (!Object.keys(headers).some((k) => k.toLowerCase() === 'user-agent')) {
238
- headers['User-Agent'] = 'DevAnvil/1.2 (Local SSE Studio)';
244
+ headers['User-Agent'] = 'DevAnvil/2.1.1 (Local SSE Studio)';
239
245
  }
240
246
  let bodyBuf;
241
247
  if (input.body && method !== 'GET' && method !== 'HEAD') {
242
248
  bodyBuf = Buffer.from(input.body, 'utf8');
249
+ if (bodyBuf.byteLength > DEFAULT_MAX_BODY_BYTES) {
250
+ throw new Error(`SSE request body exceeds ${DEFAULT_MAX_BODY_BYTES} byte limit`);
251
+ }
243
252
  headers['Content-Length'] = String(bodyBuf.length);
244
253
  }
245
254
  const startedAt = performance.now();
@@ -1,4 +1,4 @@
1
- import { DEFAULT_MAX_BODY_BYTES, safeJsonParse } from '../core/security.js';
1
+ import { DEFAULT_MAX_BODY_BYTES, isDangerousKey, safeJsonParse } from '../core/security.js';
2
2
  export const CSP_BASE = [
3
3
  "default-src 'self'",
4
4
  "script-src 'self'",
@@ -44,6 +44,8 @@ export function asStringMap(val) {
44
44
  }
45
45
  const out = {};
46
46
  for (const [k, v] of Object.entries(val)) {
47
+ if (isDangerousKey(k))
48
+ continue;
47
49
  out[k] = String(v ?? '');
48
50
  }
49
51
  return out;
@@ -85,12 +87,22 @@ export async function readBody(req, maxBytes = DEFAULT_MAX_BODY_BYTES) {
85
87
  chunks.push(chunk);
86
88
  });
87
89
  req.on('end', () => {
88
- if (!aborted)
90
+ if (!aborted) {
91
+ aborted = true;
89
92
  resolveBody(Buffer.concat(chunks).toString('utf8'));
93
+ }
94
+ });
95
+ req.on('aborted', () => {
96
+ if (!aborted) {
97
+ aborted = true;
98
+ rejectBody(Object.assign(new Error('Request aborted before completion'), { statusCode: 400 }));
99
+ }
90
100
  });
91
101
  req.on('error', (err) => {
92
- if (!aborted)
102
+ if (!aborted) {
103
+ aborted = true;
93
104
  rejectBody(err);
105
+ }
94
106
  });
95
107
  });
96
108
  }
@@ -1,3 +1,4 @@
1
+ import { validateProxyTargetUrl } from '../core/security.js';
1
2
  import { executeProxyRequest } from './http-proxy.js';
2
3
  function pct(sorted, p) {
3
4
  if (sorted.length === 0)
@@ -18,6 +19,8 @@ export async function executeLoadTest(input, options = {}) {
18
19
  const concurrency = Math.min(Math.max(Math.trunc(input.concurrency ?? 10), 1), 50, totalRequests);
19
20
  const timeoutMs = Math.min(Math.max(Math.trunc(input.timeoutMs ?? 8000), 500), 20_000);
20
21
  const latencies = [];
22
+ // Pre-validate URL against SSRF guard once before spawning concurrent workers
23
+ await validateProxyTargetUrl(url, { allowPrivate: options.allowPrivate });
21
24
  const statusCodes = {};
22
25
  const sampleErrors = [];
23
26
  let totalBytes = 0;
@@ -20,7 +20,7 @@ export interface JsonRpcResponse {
20
20
  };
21
21
  }
22
22
  export declare const MCP_PROTOCOL_VERSION = "2024-11-05";
23
- export declare const MCP_SERVER_VERSION = "2.1.0";
23
+ export declare const MCP_SERVER_VERSION = "2.1.1";
24
24
  export declare const MCP_TOOLS: McpToolDefinition[];
25
25
  export declare function executeMcpTool(name: string, rawArgs: Record<string, unknown> | undefined): unknown;
26
26
  /**
@@ -15,7 +15,7 @@ import { safeJsonParse } from '../core/security.js';
15
15
  import { analyzeSqlExplain } from '../core/sql-explain.js';
16
16
  import { inspectPemCertificates } from '../core/tls.js';
17
17
  export const MCP_PROTOCOL_VERSION = '2024-11-05';
18
- export const MCP_SERVER_VERSION = '2.1.0';
18
+ export const MCP_SERVER_VERSION = '2.1.1';
19
19
  export const MCP_TOOLS = [
20
20
  {
21
21
  name: 'devanvil_scan_secrets',
@@ -256,10 +256,14 @@ export function executeMcpTool(name, rawArgs) {
256
256
  }
257
257
  case 'devanvil_regex_test':
258
258
  return testRegex(reqString(args, 'pattern'), typeof args.flags === 'string' ? args.flags : 'g', reqString(args, 'text'));
259
- case 'devanvil_convert_data':
259
+ case 'devanvil_convert_data': {
260
+ const rawTo = reqString(args, 'to');
261
+ const isMinified = rawTo === 'json-minified';
262
+ const normalizedTo = (isMinified ? 'json' : rawTo === 'json-schema' ? 'jsonschema' : rawTo);
260
263
  return {
261
- output: convertData(reqString(args, 'input'), reqString(args, 'from'), reqString(args, 'to')),
264
+ output: convertData(reqString(args, 'input'), reqString(args, 'from'), normalizedTo, isMinified ? { minify: true } : undefined),
262
265
  };
266
+ }
263
267
  case 'devanvil_semantic_diff': {
264
268
  const left = reqString(args, 'left');
265
269
  const right = reqString(args, 'right');
@@ -438,7 +442,7 @@ export function startMcpStdioServer() {
438
442
  }
439
443
  let parsed;
440
444
  try {
441
- parsed = safeJsonParse(line);
445
+ parsed = safeJsonParse(line, 4 * 1024 * 1024);
442
446
  }
443
447
  catch {
444
448
  const resp = {
@@ -18,15 +18,54 @@ function safeDecodeSegment(seg) {
18
18
  return seg;
19
19
  }
20
20
  }
21
+ const VALID_HTTP_HEADER_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
22
+ const BLOCKED_MOCK_HEADERS = new Set([
23
+ 'content-security-policy',
24
+ 'content-security-policy-report-only',
25
+ 'x-frame-options',
26
+ 'x-content-type-options',
27
+ 'strict-transport-security',
28
+ 'referrer-policy',
29
+ 'permissions-policy',
30
+ 'cross-origin-opener-policy',
31
+ 'cross-origin-embedder-policy',
32
+ 'set-cookie',
33
+ 'transfer-encoding',
34
+ 'content-length',
35
+ 'connection',
36
+ 'keep-alive',
37
+ 'upgrade',
38
+ 'te',
39
+ 'trailer',
40
+ 'host',
41
+ ]);
21
42
  function sanitizeHeadersMap(headers) {
22
43
  const clean = {};
23
44
  for (const [k, v] of Object.entries(headers ?? {})) {
24
- if (k.trim() && !/[\r\n]/.test(k) && !/[\r\n]/.test(String(v))) {
25
- clean[k.trim()] = String(v);
26
- }
45
+ const key = k.trim();
46
+ if (!key || !VALID_HTTP_HEADER_TOKEN.test(key))
47
+ continue;
48
+ if (BLOCKED_MOCK_HEADERS.has(key.toLowerCase()))
49
+ continue;
50
+ const val = String(v);
51
+ if (/[\r\n\0]/.test(val))
52
+ continue;
53
+ clean[key] = val;
27
54
  }
28
55
  return clean;
29
56
  }
57
+ function sanitizeStatus(raw, fallback) {
58
+ const n = typeof raw === 'number' ? raw : Number(raw);
59
+ if (!Number.isFinite(n))
60
+ throw new Error('Mock status must be a valid HTTP status code (100-599)');
61
+ return Math.min(Math.max(Math.floor(n), 100), 599);
62
+ }
63
+ function sanitizeDelay(raw, fallback) {
64
+ const n = typeof raw === 'number' ? raw : Number(raw);
65
+ if (!Number.isFinite(n))
66
+ return fallback;
67
+ return Math.min(Math.max(Math.floor(n), 0), 5000);
68
+ }
30
69
  function matchRoutePath(pattern, actualPath) {
31
70
  const patSegs = pattern.split('/').filter(Boolean);
32
71
  const actSegs = actualPath.split('/').filter(Boolean);
@@ -87,8 +126,8 @@ export class MockStore {
87
126
  throw new Error(`Invalid HTTP method "${method}"`);
88
127
  }
89
128
  const path = normalizeMockPath(input.path);
90
- const status = Math.min(Math.max(Math.floor(input.status ?? 200), 100), 599);
91
- const delayMs = Math.min(Math.max(Math.floor(input.delayMs ?? 0), 0), 5000);
129
+ const status = input.status !== undefined ? sanitizeStatus(input.status, 200) : 200;
130
+ const delayMs = input.delayMs !== undefined ? sanitizeDelay(input.delayMs, 0) : 0;
92
131
  const headers = sanitizeHeadersMap(input.headers ?? { 'Content-Type': 'application/json' });
93
132
  const route = {
94
133
  id: generateUuidV7(),
@@ -96,7 +135,7 @@ export class MockStore {
96
135
  path,
97
136
  status,
98
137
  headers,
99
- body: input.body ?? '',
138
+ body: typeof input.body === 'string' ? input.body : String(input.body ?? ''),
100
139
  delayMs,
101
140
  enabled: input.enabled !== false,
102
141
  hits: 0,
@@ -110,16 +149,18 @@ export class MockStore {
110
149
  if (idx === -1)
111
150
  throw new Error('Mock route not found');
112
151
  const current = this.routes[idx];
113
- const method = patch.method !== undefined ? patch.method.toUpperCase().trim() : current.method;
152
+ const method = patch.method !== undefined
153
+ ? (typeof patch.method === 'string' ? patch.method.toUpperCase().trim() : '')
154
+ : current.method;
114
155
  if (!VALID_MOCK_METHODS.has(method))
115
156
  throw new Error(`Invalid HTTP method "${method}"`);
116
157
  const updated = {
117
158
  ...current,
118
159
  method,
119
- path: patch.path !== undefined ? normalizeMockPath(patch.path) : current.path,
120
- status: patch.status !== undefined ? Math.min(Math.max(Math.floor(patch.status), 100), 599) : current.status,
121
- delayMs: patch.delayMs !== undefined ? Math.min(Math.max(Math.floor(patch.delayMs), 0), 5000) : current.delayMs,
122
- body: patch.body !== undefined ? patch.body : current.body,
160
+ path: patch.path !== undefined ? normalizeMockPath(String(patch.path)) : current.path,
161
+ status: patch.status !== undefined ? sanitizeStatus(patch.status, current.status) : current.status,
162
+ delayMs: patch.delayMs !== undefined ? sanitizeDelay(patch.delayMs, current.delayMs) : current.delayMs,
163
+ body: patch.body !== undefined ? String(patch.body) : current.body,
123
164
  enabled: patch.enabled !== undefined ? Boolean(patch.enabled) : current.enabled,
124
165
  headers: patch.headers !== undefined ? sanitizeHeadersMap(patch.headers) : current.headers,
125
166
  };
@@ -185,11 +226,11 @@ export class MockStore {
185
226
  return ctx.path;
186
227
  if (token.startsWith('param.')) {
187
228
  const key = token.slice(6);
188
- return ctx.params[key] ?? '';
229
+ return Object.prototype.hasOwnProperty.call(ctx.params, key) ? (ctx.params[key] ?? '') : '';
189
230
  }
190
231
  if (token.startsWith('query.')) {
191
232
  const key = token.slice(6);
192
- return ctx.query[key] ?? '';
233
+ return Object.prototype.hasOwnProperty.call(ctx.query, key) ? (ctx.query[key] ?? '') : '';
193
234
  }
194
235
  return match;
195
236
  });
@@ -47,9 +47,10 @@ export declare class PluginLoader {
47
47
  * Uses primitive-only JSON boundaries + `codeGeneration: { strings: false, wasm: false }`.
48
48
  */
49
49
  runPlugin(pluginId: string, input: string, options?: Record<string, unknown>): PluginRunResult;
50
+ private activeWorkers;
50
51
  /**
51
52
  * Asynchronous hardened Worker Thread + VM sandbox execution (used by HTTP Server).
52
- * Guarantees non-blocking event loop, empty worker env, capped V8 heap, and hard terminate on timeout.
53
+ * Guarantees non-blocking event loop, empty worker env, capped V8 heap, concurrency cap, and hard terminate on timeout.
53
54
  */
54
55
  runPluginAsync(pluginId: string, input: string, options?: Record<string, unknown>, timeoutMs?: number): Promise<PluginRunResult>;
55
56
  scaffoldPlugin(rawId: string): {
@@ -87,6 +87,11 @@ export class PluginLoader {
87
87
  if (lstat.isSymbolicLink() || !lstat.isFile()) {
88
88
  throw new Error('Plugin entry must be a regular non-symlink file');
89
89
  }
90
+ const realRoot = fs.realpathSync(this.pluginsDir);
91
+ const realCode = fs.realpathSync(codePath);
92
+ if (!realCode.startsWith(`${realRoot}${path.sep}`)) {
93
+ throw new Error('Blocked symlinked plugin directory escape');
94
+ }
90
95
  if (lstat.size > MAX_PLUGIN_CODE_BYTES) {
91
96
  throw new Error(`Plugin code exceeds ${MAX_PLUGIN_CODE_BYTES} byte safety limit`);
92
97
  }
@@ -111,6 +116,9 @@ export class PluginLoader {
111
116
  if (!fs.existsSync(manifestPath))
112
117
  continue;
113
118
  try {
119
+ const mStat = fs.lstatSync(manifestPath);
120
+ if (mStat.isSymbolicLink() || !mStat.isFile() || mStat.size > 32_768)
121
+ continue;
114
122
  const raw = safeJsonParse(fs.readFileSync(manifestPath, 'utf8'));
115
123
  const id = typeof raw.id === 'string' ? raw.id.trim() : '';
116
124
  if (!VALID_PLUGIN_ID.test(id))
@@ -193,18 +201,26 @@ export class PluginLoader {
193
201
  isolation: 'vm',
194
202
  };
195
203
  }
204
+ activeWorkers = 0;
196
205
  /**
197
206
  * Asynchronous hardened Worker Thread + VM sandbox execution (used by HTTP Server).
198
- * Guarantees non-blocking event loop, empty worker env, capped V8 heap, and hard terminate on timeout.
207
+ * Guarantees non-blocking event loop, empty worker env, capped V8 heap, concurrency cap, and hard terminate on timeout.
199
208
  */
200
209
  async runPluginAsync(pluginId, input, options = {}, timeoutMs = PLUGIN_TIMEOUT_MS) {
210
+ if (this.activeWorkers >= 4) {
211
+ throw new Error('Too many concurrent plugin executions (max 4); please retry shortly');
212
+ }
201
213
  const { plugin, codePath } = this.resolveSafePlugin(pluginId);
202
214
  const code = fs.readFileSync(codePath, 'utf8');
203
215
  const cappedTimeout = Math.min(Math.max(Math.trunc(timeoutMs), 50), 2000);
204
216
  const wrapped = buildSandboxedScript(code, JSON.stringify(String(input)), JSON.stringify(options ?? {}));
205
217
  const t0 = performance.now();
218
+ this.activeWorkers++;
206
219
  return new Promise((resolve, reject) => {
207
220
  let settled = false;
221
+ const release = () => {
222
+ this.activeWorkers = Math.max(0, this.activeWorkers - 1);
223
+ };
208
224
  const worker = new Worker(WORKER_RUNNER_CODE, {
209
225
  eval: true,
210
226
  env: {},
@@ -223,6 +239,7 @@ export class PluginLoader {
223
239
  if (settled)
224
240
  return;
225
241
  settled = true;
242
+ release();
226
243
  void worker.terminate();
227
244
  reject(new Error(`Plugin "${plugin.id}" timed out after ${cappedTimeout}ms and was terminated`));
228
245
  }, cappedTimeout + WORKER_KILL_BUFFER_MS);
@@ -232,6 +249,7 @@ export class PluginLoader {
232
249
  return;
233
250
  settled = true;
234
251
  clearTimeout(killTimer);
252
+ release();
235
253
  void worker.terminate();
236
254
  if (!msg.ok) {
237
255
  reject(new Error(msg.error || 'Plugin execution failed'));
@@ -249,6 +267,7 @@ export class PluginLoader {
249
267
  return;
250
268
  settled = true;
251
269
  clearTimeout(killTimer);
270
+ release();
252
271
  void worker.terminate();
253
272
  reject(err);
254
273
  });
@@ -257,6 +276,7 @@ export class PluginLoader {
257
276
  return;
258
277
  settled = true;
259
278
  clearTimeout(killTimer);
279
+ release();
260
280
  reject(new Error(`Plugin worker exited unexpectedly (code ${exitCode})`));
261
281
  });
262
282
  });
@@ -2,10 +2,11 @@ import * as crypto from 'node:crypto';
2
2
  import { safeJsonParse } from '../core/security.js';
3
3
  const MAX_RECORDED_ENTRIES = 100;
4
4
  const SENSITIVE_HEADER_NAMES = new Set(['authorization', 'cookie', 'set-cookie', 'x-api-key', 'proxy-authorization']);
5
+ const SENSITIVE_HEADER_RE = /(?:auth|token|secret|api[-_]?key|password|session|cookie)/i;
5
6
  function redactHeaders(headers) {
6
7
  const out = {};
7
8
  for (const [k, v] of Object.entries(headers)) {
8
- out[k] = SENSITIVE_HEADER_NAMES.has(k.toLowerCase()) ? '[REDACTED]' : v;
9
+ out[k] = SENSITIVE_HEADER_NAMES.has(k.toLowerCase()) || SENSITIVE_HEADER_RE.test(k) ? '[REDACTED]' : v;
9
10
  }
10
11
  return out;
11
12
  }
@@ -324,10 +324,44 @@ export async function handleNetworkRoutes(method, pathname, req, res, ctx) {
324
324
  return true;
325
325
  }
326
326
  if (pathname.startsWith('/api/mocks/')) {
327
- const id = pathname.slice('/api/mocks/'.length);
327
+ let id;
328
+ try {
329
+ id = decodeURIComponent(pathname.slice('/api/mocks/'.length));
330
+ }
331
+ catch {
332
+ sendJson(res, 400, { error: 'Malformed mock route id' }, denyIframe);
333
+ return true;
334
+ }
328
335
  if (method === 'PATCH' || method === 'PUT') {
329
336
  const body = await readJsonBody(req);
330
- const updated = mockStore.update(id, body);
337
+ const patch = {};
338
+ if (body.method !== undefined)
339
+ patch.method = asString(body.method);
340
+ if (body.path !== undefined)
341
+ patch.path = asString(body.path);
342
+ if (body.status !== undefined) {
343
+ const s = asOptionalNumber(body.status);
344
+ if (s === undefined) {
345
+ sendJson(res, 400, { error: 'Mock "status" must be a finite HTTP status code (100-599)' }, denyIframe);
346
+ return true;
347
+ }
348
+ patch.status = s;
349
+ }
350
+ if (body.delayMs !== undefined) {
351
+ const d = asOptionalNumber(body.delayMs);
352
+ if (d === undefined) {
353
+ sendJson(res, 400, { error: 'Mock "delayMs" must be a finite number (0-5000)' }, denyIframe);
354
+ return true;
355
+ }
356
+ patch.delayMs = d;
357
+ }
358
+ if (body.headers !== undefined)
359
+ patch.headers = asStringMap(body.headers);
360
+ if (body.body !== undefined)
361
+ patch.body = asString(body.body);
362
+ if (body.enabled !== undefined)
363
+ patch.enabled = Boolean(body.enabled);
364
+ const updated = mockStore.update(id, patch);
331
365
  workspaceStore.syncMocksAndPersist(mockStore.list());
332
366
  sendJson(res, 200, updated, denyIframe);
333
367
  return true;
@@ -361,7 +395,15 @@ export async function handleNetworkRoutes(method, pathname, req, res, ctx) {
361
395
  }
362
396
  const webhookEventsMatch = /^\/api\/webhooks\/([^/]+)$/.exec(pathname);
363
397
  if (webhookEventsMatch) {
364
- const channel = assertSafeChannelName(decodeURIComponent(webhookEventsMatch[1]));
398
+ let rawCh;
399
+ try {
400
+ rawCh = decodeURIComponent(webhookEventsMatch[1]);
401
+ }
402
+ catch {
403
+ sendJson(res, 400, { error: 'Malformed webhook channel name' }, denyIframe);
404
+ return true;
405
+ }
406
+ const channel = assertSafeChannelName(rawCh);
365
407
  if (method === 'GET') {
366
408
  sendJson(res, 200, { channel, events: webhookStore.list(channel) }, denyIframe);
367
409
  return true;
@@ -374,7 +416,15 @@ export async function handleNetworkRoutes(method, pathname, req, res, ctx) {
374
416
  }
375
417
  const webhookStreamMatch = /^\/api\/webhooks\/([^/]+)\/stream$/.exec(pathname);
376
418
  if (method === 'GET' && webhookStreamMatch) {
377
- const channel = assertSafeChannelName(decodeURIComponent(webhookStreamMatch[1]));
419
+ let rawCh;
420
+ try {
421
+ rawCh = decodeURIComponent(webhookStreamMatch[1]);
422
+ }
423
+ catch {
424
+ sendJson(res, 400, { error: 'Malformed webhook channel name' }, denyIframe);
425
+ return true;
426
+ }
427
+ const channel = assertSafeChannelName(rawCh);
378
428
  applySecurityHeaders(res, denyIframe);
379
429
  res.writeHead(200, {
380
430
  'Content-Type': 'text/event-stream; charset=utf-8',
@@ -109,7 +109,9 @@ export async function handleToolRoutes(method, pathname, urlObj, req, res, ctx)
109
109
  if (method === 'POST' && pathname === '/api/jwt/verify') {
110
110
  const body = await readJsonBody(req);
111
111
  sendJson(res, 200, verifyJwt(asString(body.token), asString(body.secret), {
112
- allowedAlgorithms: Array.isArray(body.allowedAlgorithms) ? body.allowedAlgorithms : undefined,
112
+ allowedAlgorithms: Array.isArray(body.allowedAlgorithms)
113
+ ? body.allowedAlgorithms.filter((x) => typeof x === 'string').slice(0, 10)
114
+ : undefined,
113
115
  clockToleranceSec: asOptionalNumber(body.clockToleranceSec),
114
116
  }), denyIframe);
115
117
  return true;
@@ -241,7 +243,12 @@ export async function handleToolRoutes(method, pathname, urlObj, req, res, ctx)
241
243
  sendJson(res, 400, { error: 'Pipeline "steps" must be an array' }, denyIframe);
242
244
  return true;
243
245
  }
244
- sendJson(res, 200, runPipeline(asString(body.input), body.steps ?? []), denyIframe);
246
+ const rawSteps = (body.steps ?? []);
247
+ if (rawSteps.some((s) => !s || typeof s !== 'object' || Array.isArray(s) || typeof s.op !== 'string')) {
248
+ sendJson(res, 400, { error: 'Each pipeline step must be an object with a string "op" field' }, denyIframe);
249
+ return true;
250
+ }
251
+ sendJson(res, 200, runPipeline(asString(body.input), rawSteps), denyIframe);
245
252
  return true;
246
253
  }
247
254
  // Cron & Timestamp
@@ -141,7 +141,14 @@ export async function handleWorkspaceAndPluginRoutes(method, pathname, req, res,
141
141
  return true;
142
142
  }
143
143
  if (method === 'DELETE' && pathname.startsWith('/api/workspace/environments/')) {
144
- const id = pathname.slice('/api/workspace/environments/'.length);
144
+ let id;
145
+ try {
146
+ id = decodeURIComponent(pathname.slice('/api/workspace/environments/'.length));
147
+ }
148
+ catch {
149
+ sendJson(res, 400, { error: 'Malformed environment id' }, denyIframe);
150
+ return true;
151
+ }
145
152
  const deleted = workspaceStore.deleteEnvironment(id);
146
153
  sendJson(res, deleted ? 200 : 404, { deleted }, denyIframe);
147
154
  return true;
@@ -149,8 +156,16 @@ export async function handleWorkspaceAndPluginRoutes(method, pathname, req, res,
149
156
  // Update or delete a single request inside a collection (Assertions & Request Chaining editor!)
150
157
  const reqItemMatch = /^\/api\/workspace\/collections\/([^/]+)\/requests\/([^/]+)$/.exec(pathname);
151
158
  if (reqItemMatch) {
152
- const colId = decodeURIComponent(reqItemMatch[1]);
153
- const reqId = decodeURIComponent(reqItemMatch[2]);
159
+ let colId;
160
+ let reqId;
161
+ try {
162
+ colId = decodeURIComponent(reqItemMatch[1]);
163
+ reqId = decodeURIComponent(reqItemMatch[2]);
164
+ }
165
+ catch {
166
+ sendJson(res, 400, { error: 'Malformed collection or request id' }, denyIframe);
167
+ return true;
168
+ }
154
169
  if (method === 'PUT' || method === 'PATCH') {
155
170
  const body = await readJsonBody(req);
156
171
  const updated = workspaceStore.updateRequestInCollection(colId, reqId, {
@@ -193,7 +208,14 @@ export async function handleWorkspaceAndPluginRoutes(method, pathname, req, res,
193
208
  return true;
194
209
  }
195
210
  if (method === 'DELETE' && pathname.startsWith('/api/workspace/collections/')) {
196
- const id = pathname.slice('/api/workspace/collections/'.length);
211
+ let id;
212
+ try {
213
+ id = decodeURIComponent(pathname.slice('/api/workspace/collections/'.length));
214
+ }
215
+ catch {
216
+ sendJson(res, 400, { error: 'Malformed collection id' }, denyIframe);
217
+ return true;
218
+ }
197
219
  const deleted = workspaceStore.deleteCollection(id);
198
220
  sendJson(res, deleted ? 200 : 404, { deleted }, denyIframe);
199
221
  return true;
@@ -64,7 +64,12 @@ export class WebhookStore {
64
64
  set.add(res);
65
65
  const heartbeat = setInterval(() => {
66
66
  if (!res.writableEnded) {
67
- res.write(': heartbeat\n\n');
67
+ try {
68
+ res.write(': heartbeat\n\n');
69
+ }
70
+ catch {
71
+ set?.delete(res);
72
+ }
68
73
  }
69
74
  }, 20_000);
70
75
  heartbeat.unref();
@@ -83,7 +88,12 @@ export class WebhookStore {
83
88
  const frame = `event: ${eventName}\ndata: ${JSON.stringify(payload)}\n\n`;
84
89
  for (const res of set) {
85
90
  if (!res.writableEnded) {
86
- res.write(frame);
91
+ try {
92
+ res.write(frame);
93
+ }
94
+ catch {
95
+ set.delete(res);
96
+ }
87
97
  }
88
98
  }
89
99
  }
@@ -439,9 +439,10 @@ export class WorkspaceStore {
439
439
  return;
440
440
  const dir = path.dirname(this.filePath);
441
441
  fs.mkdirSync(dir, { recursive: true });
442
- // Atomic write-temp-then-rename to prevent partial/corrupted JSON files
443
- const tmpPath = `${this.filePath}.${process.pid}.tmp`;
444
- fs.writeFileSync(tmpPath, `${JSON.stringify(this.data, null, 2)}\n`, 'utf8');
442
+ // Atomic write-temp-then-rename with unpredictable suffix & restricted owner-only permissions
443
+ const suffix = crypto.randomBytes(6).toString('hex');
444
+ const tmpPath = `${this.filePath}.${process.pid}.${suffix}.tmp`;
445
+ fs.writeFileSync(tmpPath, `${JSON.stringify(this.data, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
445
446
  fs.renameSync(tmpPath, this.filePath);
446
447
  }
447
448
  }