devanvil 0.0.0-stage → 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 (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 +664 -0
  7. package/dist/core/contract-drift.d.ts +49 -0
  8. package/dist/core/contract-drift.js +312 -0
  9. package/dist/core/converters.d.ts +18 -0
  10. package/dist/core/converters.js +989 -0
  11. package/dist/core/cron.d.ts +33 -0
  12. package/dist/core/cron.js +309 -0
  13. package/dist/core/crypto.d.ts +59 -0
  14. package/dist/core/crypto.js +260 -0
  15. package/dist/core/curl.d.ts +17 -0
  16. package/dist/core/curl.js +174 -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 +269 -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 +396 -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 +360 -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 +603 -0
  43. package/dist/core/security.d.ts +34 -0
  44. package/dist/core/security.js +301 -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 +169 -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 +359 -0
  53. package/dist/server/http-proxy.d.ts +55 -0
  54. package/dist/server/http-proxy.js +373 -0
  55. package/dist/server/http-utils.d.ts +28 -0
  56. package/dist/server/http-utils.js +118 -0
  57. package/dist/server/load-tester.d.ts +53 -0
  58. package/dist/server/load-tester.js +137 -0
  59. package/dist/server/mcp.d.ts +35 -0
  60. package/dist/server/mcp.js +470 -0
  61. package/dist/server/mock-store.d.ts +38 -0
  62. package/dist/server/mock-store.js +238 -0
  63. package/dist/server/plugin-loader.d.ts +61 -0
  64. package/dist/server/plugin-loader.js +305 -0
  65. package/dist/server/recorder-store.d.ts +35 -0
  66. package/dist/server/recorder-store.js +147 -0
  67. package/dist/server/routes/network-routes.d.ts +3 -0
  68. package/dist/server/routes/network-routes.js +441 -0
  69. package/dist/server/routes/tools-routes.d.ts +3 -0
  70. package/dist/server/routes/tools-routes.js +299 -0
  71. package/dist/server/routes/workspace-routes.d.ts +3 -0
  72. package/dist/server/routes/workspace-routes.js +262 -0
  73. package/dist/server/webhook-store.d.ts +29 -0
  74. package/dist/server/webhook-store.js +100 -0
  75. package/dist/server/workspace-store.d.ts +91 -0
  76. package/dist/server/workspace-store.js +448 -0
  77. package/dist/server/ws-probe.d.ts +34 -0
  78. package/dist/server/ws-probe.js +291 -0
  79. package/dist/ui/app.js +290 -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 +719 -0
  85. package/dist/ui/tools-network.js +769 -0
  86. package/dist/ui/tools-ops.js +299 -0
  87. package/dist/ui/tools-pro.js +500 -0
  88. package/dist/ui/tools-security.js +397 -0
  89. package/dist/ui/tools-v12.js +765 -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 +411 -0
  93. package/package.json +75 -4
@@ -0,0 +1,299 @@
1
+ import { convertData, formatSql, queryJsonPath } from '../../core/converters.js';
2
+ import { describeCron, getNextCronRuns, parseTimestamp } from '../../core/cron.js';
3
+ import { decryptAesGcm, deriveKey, encryptAesGcm, generateApiKey, generateAsymmetricKeyPair, generateNanoId, generatePassword, generateUlid, generateUuidV4, generateUuidV7, hashText, hmacText, } from '../../core/crypto.js';
4
+ import { diffJsonSemantic, diffText } from '../../core/diff.js';
5
+ import { decodeText, encodeText } from '../../core/encoding.js';
6
+ import { decodeJwt, signJwt, verifyJwt } from '../../core/jwt.js';
7
+ import { analyzeLlmText, compactContextText } from '../../core/llm-tokens.js';
8
+ import { analyzeLogs } from '../../core/log-analyzer.js';
9
+ import { calculateCidr, checkColorContrast, HTTP_STATUS_CODES, parseChmod, parseHexColor, } from '../../core/network.js';
10
+ import { analyzeOAuthCallback, decodeProtobufWire, generatePkceBundle } from '../../core/oauth-protobuf.js';
11
+ import { PIPELINE_OPERATIONS, runPipeline } from '../../core/pipeline.js';
12
+ import { REGEX_PRESETS, testRegex } from '../../core/regex.js';
13
+ import { analyzeEnvFile, scanSecrets } from '../../core/secrets.js';
14
+ import { safeJsonParse } from '../../core/security.js';
15
+ import { analyzeSqlExplain } from '../../core/sql-explain.js';
16
+ import { asOptionalNumber, asOptionalString, asString, readJsonBody, sendJson, } from '../http-utils.js';
17
+ export async function handleToolRoutes(method, pathname, urlObj, req, res, ctx) {
18
+ const { denyIframe } = ctx;
19
+ // SQL EXPLAIN ANALYZE Visualizer & Log Analyzer
20
+ if (method === 'POST' && pathname === '/api/sql/explain') {
21
+ const body = await readJsonBody(req);
22
+ sendJson(res, 200, analyzeSqlExplain(asString(body.input)), denyIframe);
23
+ return true;
24
+ }
25
+ if (method === 'POST' && pathname === '/api/logs/analyze') {
26
+ const body = await readJsonBody(req);
27
+ sendJson(res, 200, analyzeLogs(asString(body.input)), denyIframe);
28
+ return true;
29
+ }
30
+ // OAuth 2.0 / OIDC PKCE Studio & Protobuf Binary Wire Inspector
31
+ if (method === 'POST' && pathname === '/api/oauth/pkce') {
32
+ const body = await readJsonBody(req);
33
+ sendJson(res, 200, generatePkceBundle({
34
+ verifierLength: asOptionalNumber(body.verifierLength),
35
+ authorizationEndpoint: asOptionalString(body.authorizationEndpoint),
36
+ clientId: asOptionalString(body.clientId),
37
+ redirectUri: asOptionalString(body.redirectUri),
38
+ scope: asOptionalString(body.scope),
39
+ audience: asOptionalString(body.audience),
40
+ }), denyIframe);
41
+ return true;
42
+ }
43
+ if (method === 'POST' && pathname === '/api/oauth/analyze-callback') {
44
+ const body = await readJsonBody(req);
45
+ sendJson(res, 200, analyzeOAuthCallback(asString(body.callbackUrl), {
46
+ state: asOptionalString(body.expectedState),
47
+ nonce: asOptionalString(body.expectedNonce),
48
+ codeVerifier: asOptionalString(body.codeVerifier),
49
+ codeChallenge: asOptionalString(body.codeChallenge),
50
+ }), denyIframe);
51
+ return true;
52
+ }
53
+ if (method === 'POST' && pathname === '/api/protobuf/decode') {
54
+ const body = await readJsonBody(req);
55
+ const enc = asString(body.encoding, 'auto').toLowerCase();
56
+ sendJson(res, 200, decodeProtobufWire(asString(body.input), {
57
+ encoding: enc === 'hex' || enc === 'base64' ? enc : 'auto',
58
+ protoSchema: asOptionalString(body.protoSchema),
59
+ messageName: asOptionalString(body.messageName),
60
+ }), denyIframe);
61
+ return true;
62
+ }
63
+ // Secret Scanner & .env Validator
64
+ if (method === 'POST' && pathname === '/api/secrets/scan') {
65
+ const body = await readJsonBody(req);
66
+ sendJson(res, 200, scanSecrets(asString(body.input), {
67
+ checkHighEntropy: body.checkHighEntropy !== false,
68
+ entropyThreshold: asOptionalNumber(body.entropyThreshold),
69
+ }), denyIframe);
70
+ return true;
71
+ }
72
+ if (method === 'POST' && pathname === '/api/secrets/env') {
73
+ const body = await readJsonBody(req);
74
+ sendJson(res, 200, analyzeEnvFile(asString(body.env), asOptionalString(body.example)), denyIframe);
75
+ return true;
76
+ }
77
+ // LLM Token & Context Budget Studio
78
+ if (method === 'POST' && pathname === '/api/llm/analyze') {
79
+ const body = await readJsonBody(req);
80
+ sendJson(res, 200, analyzeLlmText(asString(body.input)), denyIframe);
81
+ return true;
82
+ }
83
+ if (method === 'POST' && pathname === '/api/llm/compact') {
84
+ const body = await readJsonBody(req);
85
+ sendJson(res, 200, compactContextText(asString(body.input), {
86
+ stripLineComments: Boolean(body.stripLineComments),
87
+ minifyJson: Boolean(body.minifyJson),
88
+ }), denyIframe);
89
+ return true;
90
+ }
91
+ // JWT Studio
92
+ if (method === 'POST' && pathname === '/api/jwt/decode') {
93
+ const body = await readJsonBody(req);
94
+ sendJson(res, 200, decodeJwt(asString(body.token)), denyIframe);
95
+ return true;
96
+ }
97
+ if (method === 'POST' && pathname === '/api/jwt/sign') {
98
+ const body = await readJsonBody(req);
99
+ const payload = body.payload && typeof body.payload === 'object' && !Array.isArray(body.payload)
100
+ ? body.payload
101
+ : {};
102
+ const token = signJwt(payload, asString(body.secret), {
103
+ alg: asOptionalString(body.alg),
104
+ expiresInSeconds: asOptionalNumber(body.expiresInSeconds),
105
+ });
106
+ sendJson(res, 200, { token, decoded: decodeJwt(token) }, denyIframe);
107
+ return true;
108
+ }
109
+ if (method === 'POST' && pathname === '/api/jwt/verify') {
110
+ const body = await readJsonBody(req);
111
+ sendJson(res, 200, verifyJwt(asString(body.token), asString(body.secret), {
112
+ allowedAlgorithms: Array.isArray(body.allowedAlgorithms)
113
+ ? body.allowedAlgorithms.filter((x) => typeof x === 'string').slice(0, 10)
114
+ : undefined,
115
+ clockToleranceSec: asOptionalNumber(body.clockToleranceSec),
116
+ }), denyIframe);
117
+ return true;
118
+ }
119
+ if (method === 'POST' && pathname === '/api/jwt/keypair') {
120
+ const body = await readJsonBody(req);
121
+ sendJson(res, 200, generateAsymmetricKeyPair(body.type === 'rsa' ? 'rsa' : 'ec'), denyIframe);
122
+ return true;
123
+ }
124
+ // Data Converters, JSONPath, SQL, Diff
125
+ if (method === 'POST' && pathname === '/api/convert') {
126
+ const body = await readJsonBody(req);
127
+ const output = convertData(asString(body.input), asString(body.from, 'json'), asString(body.to, 'yaml'), {
128
+ indent: asOptionalNumber(body.indent),
129
+ sortKeys: Boolean(body.sortKeys),
130
+ minify: Boolean(body.minify),
131
+ });
132
+ sendJson(res, 200, { output }, denyIframe);
133
+ return true;
134
+ }
135
+ if (method === 'POST' && pathname === '/api/jsonpath') {
136
+ const body = await readJsonBody(req);
137
+ const parsed = safeJsonParse(asString(body.input, '{}'));
138
+ const matches = queryJsonPath(parsed, asString(body.expression, '$'));
139
+ sendJson(res, 200, { count: matches.length, matches }, denyIframe);
140
+ return true;
141
+ }
142
+ if (method === 'POST' && pathname === '/api/sql/format') {
143
+ const body = await readJsonBody(req);
144
+ sendJson(res, 200, { formatted: formatSql(asString(body.sql)) }, denyIframe);
145
+ return true;
146
+ }
147
+ if (method === 'POST' && pathname === '/api/diff') {
148
+ const body = await readJsonBody(req);
149
+ if (body.mode === 'json') {
150
+ sendJson(res, 200, diffJsonSemantic(asString(body.left, '{}'), asString(body.right, '{}')), denyIframe);
151
+ }
152
+ else {
153
+ sendJson(res, 200, diffText(asString(body.left), asString(body.right)), denyIframe);
154
+ }
155
+ return true;
156
+ }
157
+ // Regex Lab
158
+ if (method === 'GET' && pathname === '/api/regex/presets') {
159
+ sendJson(res, 200, { presets: REGEX_PRESETS }, denyIframe);
160
+ return true;
161
+ }
162
+ if (method === 'POST' && pathname === '/api/regex/test') {
163
+ const body = await readJsonBody(req);
164
+ sendJson(res, 200, testRegex(asString(body.pattern), asString(body.flags, 'g'), asString(body.text), {
165
+ replacement: asOptionalString(body.replacement),
166
+ }), denyIframe);
167
+ return true;
168
+ }
169
+ // Crypto, Hashing, Encoding & IDs
170
+ if (method === 'POST' && pathname === '/api/crypto/hash') {
171
+ const body = await readJsonBody(req);
172
+ const algo = asString(body.algorithm, 'sha256');
173
+ const secret = asOptionalString(body.hmacSecret);
174
+ sendJson(res, 200, secret ? hmacText(asString(body.input), secret, algo) : hashText(asString(body.input), algo), denyIframe);
175
+ return true;
176
+ }
177
+ if (method === 'POST' && pathname === '/api/crypto/aes') {
178
+ const body = await readJsonBody(req);
179
+ const output = body.mode === 'decrypt'
180
+ ? decryptAesGcm(asString(body.input), asString(body.passphrase))
181
+ : encryptAesGcm(asString(body.input), asString(body.passphrase));
182
+ sendJson(res, 200, { output }, denyIframe);
183
+ return true;
184
+ }
185
+ if (method === 'POST' && pathname === '/api/crypto/kdf') {
186
+ const body = await readJsonBody(req);
187
+ sendJson(res, 200, deriveKey(asString(body.password), {
188
+ kdf: body.kdf === 'pbkdf2' ? 'pbkdf2' : 'scrypt',
189
+ saltHex: asOptionalString(body.saltHex),
190
+ iterations: asOptionalNumber(body.iterations),
191
+ }), denyIframe);
192
+ return true;
193
+ }
194
+ if (method === 'POST' && pathname === '/api/crypto/password') {
195
+ const body = await readJsonBody(req);
196
+ const count = Math.min(Math.max(Math.floor(asOptionalNumber(body.count) ?? 1), 1), 20);
197
+ const items = Array.from({ length: count }, () => generatePassword({
198
+ length: asOptionalNumber(body.length),
199
+ uppercase: body.uppercase !== false,
200
+ lowercase: body.lowercase !== false,
201
+ numbers: body.numbers !== false,
202
+ symbols: body.symbols !== false,
203
+ excludeAmbiguous: Boolean(body.excludeAmbiguous),
204
+ }));
205
+ sendJson(res, 200, { items }, denyIframe);
206
+ return true;
207
+ }
208
+ if (method === 'POST' && pathname === '/api/crypto/ids') {
209
+ const body = await readJsonBody(req);
210
+ const count = Math.min(Math.max(Math.floor(asOptionalNumber(body.count) ?? 5), 1), 50);
211
+ const kind = asString(body.kind, 'uuidv7');
212
+ const size = asOptionalNumber(body.size) ?? 21;
213
+ const prefix = asString(body.prefix, 'da_live');
214
+ const ids = Array.from({ length: count }, () => {
215
+ if (kind === 'uuidv4')
216
+ return generateUuidV4();
217
+ if (kind === 'ulid')
218
+ return generateUlid();
219
+ if (kind === 'nanoid')
220
+ return generateNanoId(size);
221
+ if (kind === 'apikey')
222
+ return generateApiKey(prefix);
223
+ return generateUuidV7();
224
+ });
225
+ sendJson(res, 200, { kind, ids }, denyIframe);
226
+ return true;
227
+ }
228
+ if (method === 'POST' && pathname === '/api/encode') {
229
+ const body = await readJsonBody(req);
230
+ const codec = asString(body.codec, 'base64');
231
+ const output = body.mode === 'decode' ? decodeText(asString(body.input), codec) : encodeText(asString(body.input), codec);
232
+ sendJson(res, 200, { output }, denyIframe);
233
+ return true;
234
+ }
235
+ // Pipeline / Recipes
236
+ if (method === 'GET' && pathname === '/api/pipeline/ops') {
237
+ sendJson(res, 200, { operations: PIPELINE_OPERATIONS }, denyIframe);
238
+ return true;
239
+ }
240
+ if (method === 'POST' && pathname === '/api/pipeline/run') {
241
+ const body = await readJsonBody(req);
242
+ if (body.steps !== undefined && !Array.isArray(body.steps)) {
243
+ sendJson(res, 400, { error: 'Pipeline "steps" must be an array' }, denyIframe);
244
+ return true;
245
+ }
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);
252
+ return true;
253
+ }
254
+ // Cron & Timestamp
255
+ if (method === 'POST' && pathname === '/api/cron') {
256
+ const body = await readJsonBody(req);
257
+ const expr = asString(body.expression, '*/15 * * * *');
258
+ sendJson(res, 200, { ...getNextCronRuns(expr, asOptionalNumber(body.count) ?? 10), description: describeCron(expr) }, denyIframe);
259
+ return true;
260
+ }
261
+ if (method === 'POST' && pathname === '/api/timestamp') {
262
+ const body = await readJsonBody(req);
263
+ sendJson(res, 200, parseTimestamp(asString(body.input, 'now')), denyIframe);
264
+ return true;
265
+ }
266
+ // Network, Chmod, Color, HTTP Status
267
+ if (method === 'POST' && pathname === '/api/utils/cidr') {
268
+ const body = await readJsonBody(req);
269
+ sendJson(res, 200, calculateCidr(asString(body.cidr, '192.168.1.0/24')), denyIframe);
270
+ return true;
271
+ }
272
+ if (method === 'POST' && pathname === '/api/utils/chmod') {
273
+ const body = await readJsonBody(req);
274
+ sendJson(res, 200, parseChmod(asString(body.mode, '755')), denyIframe);
275
+ return true;
276
+ }
277
+ if (method === 'POST' && pathname === '/api/utils/color') {
278
+ const body = await readJsonBody(req);
279
+ const bg = asOptionalString(body.background);
280
+ if (bg) {
281
+ sendJson(res, 200, checkColorContrast(asString(body.foreground, '#FFFFFF'), bg), denyIframe);
282
+ }
283
+ else {
284
+ sendJson(res, 200, parseHexColor(asString(body.foreground, '#F59E0B')), denyIframe);
285
+ }
286
+ return true;
287
+ }
288
+ if (method === 'GET' && pathname === '/api/utils/http-statuses') {
289
+ const q = (urlObj.searchParams.get('q') ?? '').trim().toLowerCase();
290
+ const filtered = q
291
+ ? HTTP_STATUS_CODES.filter((s) => String(s.code).includes(q) ||
292
+ s.title.toLowerCase().includes(q) ||
293
+ s.description.toLowerCase().includes(q))
294
+ : HTTP_STATUS_CODES;
295
+ sendJson(res, 200, { statuses: filtered }, denyIframe);
296
+ return true;
297
+ }
298
+ return false;
299
+ }
@@ -0,0 +1,3 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type RouteContext } from '../http-utils.js';
3
+ export declare function handleWorkspaceAndPluginRoutes(method: string, pathname: string, req: IncomingMessage, res: ServerResponse, ctx: RouteContext): Promise<boolean>;
@@ -0,0 +1,262 @@
1
+ import { importHarArchive, importHttpFile, importPostmanCollection, } from '../../core/importers.js';
2
+ import { formatRunReportAsJunitXml, runCollection } from '../../core/runner.js';
3
+ import { safeJsonParse } from '../../core/security.js';
4
+ import { asOptionalNumber, asOptionalString, asString, asStringMap, readJsonBody, sendJson, } from '../http-utils.js';
5
+ export async function handleWorkspaceAndPluginRoutes(method, pathname, req, res, ctx) {
6
+ const { denyIframe, allowPrivateProxy, mockStore, workspaceStore, pluginLoader } = ctx;
7
+ // Zero-Trust Sandboxed Local Plugins (~/.devanvil/plugins) — Worker Thread + VM isolation + CRUD
8
+ if (method === 'GET' && pathname === '/api/plugins') {
9
+ sendJson(res, 200, {
10
+ pluginsDir: pluginLoader.getPluginsDir(),
11
+ isolation: 'worker_threads+vm',
12
+ plugins: pluginLoader.listPlugins(),
13
+ }, denyIframe);
14
+ return true;
15
+ }
16
+ if (method === 'POST' && pathname === '/api/plugins/scaffold') {
17
+ const body = await readJsonBody(req);
18
+ const created = pluginLoader.scaffoldPlugin(asString(body.id));
19
+ sendJson(res, 201, { created, plugins: pluginLoader.listPlugins() }, denyIframe);
20
+ return true;
21
+ }
22
+ const pluginRunMatch = /^\/api\/plugins\/([^/]+)\/run$/.exec(pathname);
23
+ if (method === 'POST' && pluginRunMatch) {
24
+ const pluginId = decodeURIComponent(pluginRunMatch[1]);
25
+ const body = await readJsonBody(req);
26
+ const opts = body.options && typeof body.options === 'object' && !Array.isArray(body.options)
27
+ ? body.options
28
+ : {};
29
+ const result = await pluginLoader.runPluginAsync(pluginId, asString(body.input), opts, asOptionalNumber(body.timeoutMs));
30
+ sendJson(res, 200, result, denyIframe);
31
+ return true;
32
+ }
33
+ const pluginSourceMatch = /^\/api\/plugins\/([^/]+)\/source$/.exec(pathname);
34
+ if (pluginSourceMatch) {
35
+ const pluginId = decodeURIComponent(pluginSourceMatch[1]);
36
+ if (method === 'GET') {
37
+ sendJson(res, 200, pluginLoader.readPluginSource(pluginId), denyIframe);
38
+ return true;
39
+ }
40
+ if (method === 'PUT' || method === 'POST') {
41
+ const body = await readJsonBody(req);
42
+ sendJson(res, 200, pluginLoader.savePluginSource(pluginId, asString(body.code)), denyIframe);
43
+ return true;
44
+ }
45
+ }
46
+ const pluginItemMatch = /^\/api\/plugins\/([^/]+)$/.exec(pathname);
47
+ if (method === 'DELETE' && pluginItemMatch) {
48
+ const pluginId = decodeURIComponent(pluginItemMatch[1]);
49
+ const deleted = pluginLoader.deletePlugin(pluginId);
50
+ sendJson(res, deleted ? 200 : 404, { deleted, plugins: pluginLoader.listPlugins() }, denyIframe);
51
+ return true;
52
+ }
53
+ // Git-Native Workspace, Environments, Collections & Importers
54
+ if (method === 'GET' && pathname === '/api/workspace') {
55
+ sendJson(res, 200, {
56
+ persistent: workspaceStore.isPersistent(),
57
+ filePath: workspaceStore.getFilePath() ?? null,
58
+ localOverridesPath: workspaceStore.getLocalOverridesPath() ?? null,
59
+ secretWarnings: workspaceStore.auditWorkspaceSecrets(),
60
+ workspace: workspaceStore.getSnapshot(mockStore.list()),
61
+ }, denyIframe);
62
+ return true;
63
+ }
64
+ if (method === 'POST' && pathname === '/api/workspace/export-encrypted') {
65
+ const body = await readJsonBody(req);
66
+ const bundle = workspaceStore.exportEncryptedBundle(asString(body.passphrase), mockStore.list());
67
+ sendJson(res, 200, { bundle }, denyIframe);
68
+ return true;
69
+ }
70
+ if (method === 'POST' && pathname === '/api/workspace/import-encrypted') {
71
+ const body = await readJsonBody(req);
72
+ const raw = typeof body.bundle === 'string' ? body.bundle : JSON.stringify(body.bundle ?? {});
73
+ const loaded = workspaceStore.importEncryptedBundle(raw, asString(body.passphrase));
74
+ if (loaded.mockRoutes.length > 0) {
75
+ mockStore.importRoutes(loaded.mockRoutes, Boolean(body.replaceMocks));
76
+ }
77
+ sendJson(res, 200, {
78
+ workspace: workspaceStore.getSnapshot(mockStore.list()),
79
+ secretWarnings: workspaceStore.auditWorkspaceSecrets(),
80
+ }, denyIframe);
81
+ return true;
82
+ }
83
+ if (method === 'POST' && pathname === '/api/workspace/run') {
84
+ const body = await readJsonBody(req);
85
+ const snap = workspaceStore.getSnapshot(mockStore.list());
86
+ const colId = asOptionalString(body.collectionId);
87
+ const col = colId ? snap.collections.find((c) => c.id === colId || c.name === colId) : snap.collections[0];
88
+ if (!col) {
89
+ sendJson(res, 404, { error: 'Collection not found in workspace' }, denyIframe);
90
+ return true;
91
+ }
92
+ const envId = asOptionalString(body.environmentId);
93
+ const activeEnv = envId
94
+ ? snap.environments.find((e) => e.id === envId || e.name === envId)
95
+ : workspaceStore.getActiveEnvironment();
96
+ const report = await runCollection(col, {
97
+ environmentName: activeEnv?.name,
98
+ variables: activeEnv?.variables ?? {},
99
+ processEnv: process.env,
100
+ allowPrivate: allowPrivateProxy,
101
+ timeoutMs: asOptionalNumber(body.timeoutMs),
102
+ stopOnFailure: Boolean(body.stopOnFailure),
103
+ });
104
+ sendJson(res, 200, {
105
+ report,
106
+ ...(body.includeJunit === true ? { junitXml: formatRunReportAsJunitXml(report) } : {}),
107
+ }, denyIframe);
108
+ return true;
109
+ }
110
+ if (method === 'POST' && pathname === '/api/workspace/import') {
111
+ const body = await readJsonBody(req);
112
+ const raw = typeof body.json === 'string' ? body.json : JSON.stringify(body.workspace ?? body);
113
+ const loaded = workspaceStore.importWorkspaceJson(raw);
114
+ if (loaded.mockRoutes.length > 0) {
115
+ mockStore.importRoutes(loaded.mockRoutes, Boolean(body.replaceMocks));
116
+ }
117
+ sendJson(res, 200, {
118
+ workspace: workspaceStore.getSnapshot(mockStore.list()),
119
+ secretWarnings: workspaceStore.auditWorkspaceSecrets(),
120
+ }, denyIframe);
121
+ return true;
122
+ }
123
+ if (method === 'POST' && pathname === '/api/workspace/environments') {
124
+ const body = await readJsonBody(req);
125
+ const env = workspaceStore.upsertEnvironment({
126
+ id: asOptionalString(body.id),
127
+ name: asString(body.name),
128
+ variables: asStringMap(body.variables) ?? {},
129
+ });
130
+ sendJson(res, 201, {
131
+ environment: env,
132
+ workspace: workspaceStore.getSnapshot(mockStore.list()),
133
+ secretWarnings: workspaceStore.auditWorkspaceSecrets(),
134
+ }, denyIframe);
135
+ return true;
136
+ }
137
+ if (method === 'POST' && pathname === '/api/workspace/environments/active') {
138
+ const body = await readJsonBody(req);
139
+ const env = workspaceStore.setActiveEnvironment(asString(body.id));
140
+ sendJson(res, 200, { activeEnvironment: env }, denyIframe);
141
+ return true;
142
+ }
143
+ if (method === 'DELETE' && pathname.startsWith('/api/workspace/environments/')) {
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
+ }
152
+ const deleted = workspaceStore.deleteEnvironment(id);
153
+ sendJson(res, deleted ? 200 : 404, { deleted }, denyIframe);
154
+ return true;
155
+ }
156
+ // Update or delete a single request inside a collection (Assertions & Request Chaining editor!)
157
+ const reqItemMatch = /^\/api\/workspace\/collections\/([^/]+)\/requests\/([^/]+)$/.exec(pathname);
158
+ if (reqItemMatch) {
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
+ }
169
+ if (method === 'PUT' || method === 'PATCH') {
170
+ const body = await readJsonBody(req);
171
+ const updated = workspaceStore.updateRequestInCollection(colId, reqId, {
172
+ name: asOptionalString(body.name),
173
+ method: asOptionalString(body.method),
174
+ url: asOptionalString(body.url),
175
+ headers: body.headers ? asStringMap(body.headers) : undefined,
176
+ body: typeof body.body === 'string' ? body.body : undefined,
177
+ notes: asOptionalString(body.notes),
178
+ assertions: Array.isArray(body.assertions) ? body.assertions : undefined,
179
+ extract: Array.isArray(body.extract) ? body.extract : undefined,
180
+ });
181
+ sendJson(res, 200, { request: updated, workspace: workspaceStore.getSnapshot(mockStore.list()) }, denyIframe);
182
+ return true;
183
+ }
184
+ if (method === 'DELETE') {
185
+ const deleted = workspaceStore.deleteRequestFromCollection(colId, reqId);
186
+ sendJson(res, deleted ? 200 : 404, { deleted, workspace: workspaceStore.getSnapshot(mockStore.list()) }, denyIframe);
187
+ return true;
188
+ }
189
+ }
190
+ if (method === 'POST' && pathname === '/api/workspace/collections') {
191
+ const body = await readJsonBody(req);
192
+ if (body.request && typeof body.request === 'object') {
193
+ const r = body.request;
194
+ const saved = workspaceStore.saveRequestToCollection(asOptionalString(body.collectionId), {
195
+ name: asString(r.name, `${asString(r.method, 'GET')} ${asString(r.url)}`),
196
+ method: asString(r.method, 'GET'),
197
+ url: asString(r.url),
198
+ headers: asStringMap(r.headers) ?? {},
199
+ body: asOptionalString(r.body),
200
+ assertions: Array.isArray(r.assertions) ? r.assertions : undefined,
201
+ extract: Array.isArray(r.extract) ? r.extract : undefined,
202
+ });
203
+ sendJson(res, 201, { request: saved, workspace: workspaceStore.getSnapshot(mockStore.list()) }, denyIframe);
204
+ return true;
205
+ }
206
+ const col = workspaceStore.addCollection(asString(body.name, 'New Collection'), Array.isArray(body.requests) ? body.requests : []);
207
+ sendJson(res, 201, { collection: col, workspace: workspaceStore.getSnapshot(mockStore.list()) }, denyIframe);
208
+ return true;
209
+ }
210
+ if (method === 'DELETE' && pathname.startsWith('/api/workspace/collections/')) {
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
+ }
219
+ const deleted = workspaceStore.deleteCollection(id);
220
+ sendJson(res, deleted ? 200 : 404, { deleted }, denyIframe);
221
+ return true;
222
+ }
223
+ if (method === 'POST' && pathname === '/api/import/collection') {
224
+ const body = await readJsonBody(req);
225
+ const raw = asString(body.input);
226
+ const fmt = asString(body.format, 'auto').toLowerCase();
227
+ let imported;
228
+ if (fmt === 'postman')
229
+ imported = importPostmanCollection(raw);
230
+ else if (fmt === 'har')
231
+ imported = importHarArchive(raw);
232
+ else if (fmt === 'http')
233
+ imported = importHttpFile(raw);
234
+ else {
235
+ const trimmed = raw.trim();
236
+ if (trimmed.startsWith('{')) {
237
+ const probe = safeJsonParse(trimmed);
238
+ imported = probe && 'log' in probe ? importHarArchive(trimmed) : importPostmanCollection(trimmed);
239
+ }
240
+ else {
241
+ imported = importHttpFile(trimmed);
242
+ }
243
+ }
244
+ const collection = workspaceStore.addCollection(imported.collectionName, imported.requests);
245
+ let mountedMocksCount = 0;
246
+ if (body.mountMocks === true && imported.mockRoutes.length > 0) {
247
+ const mounted = mockStore.importRoutes(imported.mockRoutes, false);
248
+ mountedMocksCount = mounted.length;
249
+ workspaceStore.syncMocksAndPersist(mockStore.list());
250
+ }
251
+ sendJson(res, 201, {
252
+ format: imported.format,
253
+ collection,
254
+ importedRequestsCount: imported.requests.length,
255
+ availableMocksCount: imported.mockRoutes.length,
256
+ mountedMocksCount,
257
+ warnings: imported.warnings,
258
+ }, denyIframe);
259
+ return true;
260
+ }
261
+ return false;
262
+ }
@@ -0,0 +1,29 @@
1
+ import type { ServerResponse } from 'node:http';
2
+ export interface WebhookEvent {
3
+ id: string;
4
+ channel: string;
5
+ receivedAt: string;
6
+ method: string;
7
+ path: string;
8
+ query: Record<string, string>;
9
+ headers: Record<string, string>;
10
+ body: string;
11
+ contentType: string;
12
+ sizeBytes: number;
13
+ remoteAddress: string;
14
+ }
15
+ export declare class WebhookStore {
16
+ private channels;
17
+ private listeners;
18
+ capture(input: Omit<WebhookEvent, 'id' | 'receivedAt'>): WebhookEvent;
19
+ list(rawChannel: string): WebhookEvent[];
20
+ listChannels(): Array<{
21
+ channel: string;
22
+ count: number;
23
+ lastReceivedAt?: string;
24
+ }>;
25
+ clear(rawChannel: string): void;
26
+ totalListeners(): number;
27
+ subscribe(rawChannel: string, res: ServerResponse): () => void;
28
+ private broadcast;
29
+ }