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,390 @@
1
+ import * as crypto from 'node:crypto';
2
+ import { decodeJwt } from './jwt.js';
3
+ export function computePkceS256Challenge(codeVerifier) {
4
+ if (codeVerifier.length < 43 || codeVerifier.length > 128) {
5
+ throw new Error('RFC 7636 code_verifier length must be between 43 and 128 characters');
6
+ }
7
+ return crypto.createHash('sha256').update(codeVerifier, 'ascii').digest('base64url');
8
+ }
9
+ export function generatePkceBundle(options = {}) {
10
+ const len = Math.min(Math.max(Math.trunc(options.verifierLength ?? 64), 43), 128);
11
+ // RFC 7636 unreserved characters (base64url produces [A-Za-z0-9-_])
12
+ const codeVerifier = crypto.randomBytes(96).toString('base64url').slice(0, len);
13
+ const codeChallenge = computePkceS256Challenge(codeVerifier);
14
+ const state = crypto.randomBytes(18).toString('base64url');
15
+ const nonce = crypto.randomBytes(18).toString('base64url');
16
+ let authorizationUrl;
17
+ if (options.authorizationEndpoint && options.authorizationEndpoint.trim()) {
18
+ const u = new URL(options.authorizationEndpoint.trim());
19
+ u.searchParams.set('response_type', 'code');
20
+ if (options.clientId)
21
+ u.searchParams.set('client_id', options.clientId);
22
+ if (options.redirectUri)
23
+ u.searchParams.set('redirect_uri', options.redirectUri);
24
+ u.searchParams.set('scope', options.scope?.trim() || 'openid profile email');
25
+ u.searchParams.set('state', state);
26
+ u.searchParams.set('nonce', nonce);
27
+ u.searchParams.set('code_challenge', codeChallenge);
28
+ u.searchParams.set('code_challenge_method', 'S256');
29
+ if (options.audience)
30
+ u.searchParams.set('audience', options.audience);
31
+ authorizationUrl = u.toString();
32
+ }
33
+ return {
34
+ codeVerifier,
35
+ codeChallenge,
36
+ codeChallengeMethod: 'S256',
37
+ state,
38
+ nonce,
39
+ ...(authorizationUrl ? { authorizationUrl } : {}),
40
+ };
41
+ }
42
+ export function analyzeOAuthCallback(callbackUrl, expected = {}) {
43
+ const trimmed = callbackUrl.trim();
44
+ if (!trimmed)
45
+ throw new Error('Callback URL is required');
46
+ const parsed = new URL(trimmed.startsWith('http') ? trimmed : `https://callback.local/?${trimmed.replace(/^[?#]/, '')}`);
47
+ const params = new URLSearchParams(parsed.search);
48
+ if (parsed.hash && parsed.hash.length > 1) {
49
+ const hashParams = new URLSearchParams(parsed.hash.slice(1));
50
+ hashParams.forEach((v, k) => {
51
+ if (!params.has(k))
52
+ params.set(k, v);
53
+ });
54
+ }
55
+ const securityFindings = [];
56
+ const error = params.get('error') ?? undefined;
57
+ const errorDescription = params.get('error_description') ?? undefined;
58
+ const code = params.get('code') ?? undefined;
59
+ const state = params.get('state') ?? undefined;
60
+ const idTokenRaw = params.get('id_token') ?? undefined;
61
+ const accessTokenRaw = params.get('access_token') ?? undefined;
62
+ if (parsed.protocol === 'http:' && parsed.hostname !== 'localhost' && parsed.hostname !== '127.0.0.1') {
63
+ securityFindings.push({
64
+ severity: 'fail',
65
+ message: 'Non-localhost redirect URI uses plaintext HTTP instead of HTTPS.',
66
+ });
67
+ }
68
+ let stateMatches;
69
+ if (expected.state) {
70
+ stateMatches = state === expected.state;
71
+ securityFindings.push({
72
+ severity: stateMatches ? 'pass' : 'fail',
73
+ message: stateMatches
74
+ ? 'CSRF state parameter matches expected value.'
75
+ : 'CSRF WARNING: callback state does NOT match expected state!',
76
+ });
77
+ }
78
+ else if (!state) {
79
+ securityFindings.push({
80
+ severity: 'warn',
81
+ message: 'No "state" parameter present — CSRF protection cannot be verified.',
82
+ });
83
+ }
84
+ let pkceChallengeVerified;
85
+ if (expected.codeVerifier && expected.codeChallenge) {
86
+ try {
87
+ const computed = computePkceS256Challenge(expected.codeVerifier);
88
+ pkceChallengeVerified = computed === expected.codeChallenge;
89
+ securityFindings.push({
90
+ severity: pkceChallengeVerified ? 'pass' : 'fail',
91
+ message: pkceChallengeVerified
92
+ ? 'PKCE S256 code_verifier matches code_challenge.'
93
+ : 'PKCE mismatch: SHA256(code_verifier) does not equal code_challenge.',
94
+ });
95
+ }
96
+ catch (err) {
97
+ pkceChallengeVerified = false;
98
+ securityFindings.push({ severity: 'fail', message: err.message });
99
+ }
100
+ }
101
+ let decodedIdToken;
102
+ let nonceMatches;
103
+ if (idTokenRaw && idTokenRaw.split('.').length === 3) {
104
+ try {
105
+ decodedIdToken = decodeJwt(idTokenRaw);
106
+ if (expected.nonce) {
107
+ nonceMatches = decodedIdToken.payload.nonce === expected.nonce;
108
+ securityFindings.push({
109
+ severity: nonceMatches ? 'pass' : 'fail',
110
+ message: nonceMatches
111
+ ? 'OIDC id_token nonce matches expected value (replay protected).'
112
+ : 'OIDC WARNING: id_token nonce mismatch!',
113
+ });
114
+ }
115
+ }
116
+ catch {
117
+ securityFindings.push({ severity: 'warn', message: 'id_token present but could not be decoded as JWT.' });
118
+ }
119
+ }
120
+ let decodedAccessToken;
121
+ if (accessTokenRaw) {
122
+ if (parsed.hash.includes('access_token=')) {
123
+ securityFindings.push({
124
+ severity: 'warn',
125
+ message: 'Implicit Flow detected (access_token in URL fragment). Prefer Authorization Code + PKCE (S256).',
126
+ });
127
+ }
128
+ if (accessTokenRaw.split('.').length === 3) {
129
+ try {
130
+ decodedAccessToken = decodeJwt(accessTokenRaw);
131
+ }
132
+ catch {
133
+ // Opaque access token
134
+ }
135
+ }
136
+ }
137
+ if (code) {
138
+ securityFindings.push({ severity: 'pass', message: 'Authorization code received cleanly.' });
139
+ }
140
+ const hasFail = securityFindings.some((f) => f.severity === 'fail');
141
+ return {
142
+ valid: !error && !hasFail,
143
+ hasError: Boolean(error),
144
+ error,
145
+ errorDescription,
146
+ code,
147
+ state,
148
+ stateMatches,
149
+ tokenType: params.get('token_type') ?? undefined,
150
+ expiresIn: params.get('expires_in') ?? undefined,
151
+ scope: params.get('scope') ?? undefined,
152
+ decodedIdToken,
153
+ decodedAccessToken,
154
+ nonceMatches,
155
+ pkceChallengeVerified,
156
+ securityFindings,
157
+ };
158
+ }
159
+ const WIRE_TYPE_NAMES = {
160
+ 0: 'varint',
161
+ 1: 'fixed64',
162
+ 2: 'length-delimited',
163
+ 3: 'start-group',
164
+ 4: 'end-group',
165
+ 5: 'fixed32',
166
+ };
167
+ function parseProtoSchema(protoText) {
168
+ const cleaned = protoText.replace(/\/\/[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '');
169
+ const messages = new Map();
170
+ const msgRe = /\bmessage\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]*)\}/g;
171
+ let m;
172
+ while ((m = msgRe.exec(cleaned)) !== null) {
173
+ const msgName = m[1];
174
+ const body = m[2] ?? '';
175
+ const fields = new Map();
176
+ const fieldRe = /(?:(repeated|optional|required)\s+)?([A-Za-z0-9_.]+)\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(\d+)\s*(?:\[[^\]]*\])?\s*;/g;
177
+ let fm;
178
+ while ((fm = fieldRe.exec(body)) !== null) {
179
+ const num = Number(fm[4]);
180
+ fields.set(num, {
181
+ number: num,
182
+ name: fm[3],
183
+ type: fm[2],
184
+ repeated: fm[1] === 'repeated',
185
+ });
186
+ }
187
+ messages.set(msgName, { name: msgName, fields });
188
+ }
189
+ return messages;
190
+ }
191
+ function readVarint(buf, offset) {
192
+ let result = 0n;
193
+ let shift = 0n;
194
+ let pos = offset;
195
+ while (pos < buf.length) {
196
+ const byte = BigInt(buf[pos]);
197
+ result |= (byte & 0x7fn) << shift;
198
+ pos++;
199
+ if ((byte & 0x80n) === 0n) {
200
+ return { value: result, nextOffset: pos };
201
+ }
202
+ shift += 7n;
203
+ if (shift > 63n)
204
+ throw new Error(`Malformed varint (>10 bytes) at offset ${offset}`);
205
+ }
206
+ throw new Error(`Truncated varint at offset ${offset}`);
207
+ }
208
+ function decodeZigZag(n) {
209
+ return (n >> 1n) ^ -(n & 1n);
210
+ }
211
+ function isLikelyPrintableUtf8(buf) {
212
+ if (buf.length === 0)
213
+ return true;
214
+ const text = buf.toString('utf8');
215
+ if (text.includes('\uFFFD'))
216
+ return false;
217
+ let printable = 0;
218
+ for (let i = 0; i < text.length; i++) {
219
+ const c = text.charCodeAt(i);
220
+ if (c === 9 || c === 10 || c === 13 || (c >= 32 && c !== 127))
221
+ printable++;
222
+ }
223
+ return printable / text.length >= 0.9;
224
+ }
225
+ function bigIntToSafeJson(n) {
226
+ if (n >= BigInt(Number.MIN_SAFE_INTEGER) && n <= BigInt(Number.MAX_SAFE_INTEGER)) {
227
+ return Number(n);
228
+ }
229
+ return n.toString();
230
+ }
231
+ function decodeBufferInternal(buf, schemas, msgDef, depth = 0) {
232
+ if (depth > 8)
233
+ throw new Error('Protobuf nesting depth limit exceeded');
234
+ const fields = [];
235
+ let pos = 0;
236
+ while (pos < buf.length) {
237
+ const tagRes = readVarint(buf, pos);
238
+ pos = tagRes.nextOffset;
239
+ const tag = Number(tagRes.value);
240
+ const fieldNumber = tag >>> 3;
241
+ const wireType = tag & 0x07;
242
+ const wireTypeName = WIRE_TYPE_NAMES[wireType];
243
+ if (!wireTypeName || fieldNumber <= 0) {
244
+ throw new Error(`Invalid Protobuf tag (field=${fieldNumber}, wireType=${wireType}) at offset ${pos}`);
245
+ }
246
+ const def = msgDef?.fields.get(fieldNumber);
247
+ const entry = {
248
+ fieldNumber,
249
+ wireType,
250
+ wireTypeName,
251
+ ...(def ? { fieldName: def.name, schemaType: def.type } : {}),
252
+ value: null,
253
+ };
254
+ if (wireType === 0) {
255
+ const v = readVarint(buf, pos);
256
+ pos = v.nextOffset;
257
+ const unsigned = bigIntToSafeJson(v.value);
258
+ const zigZag = bigIntToSafeJson(decodeZigZag(v.value));
259
+ if (def?.type === 'bool') {
260
+ entry.value = v.value !== 0n;
261
+ }
262
+ else if (def?.type === 'sint32' || def?.type === 'sint64') {
263
+ entry.value = zigZag;
264
+ }
265
+ else {
266
+ entry.value = unsigned;
267
+ }
268
+ entry.alternatives = { uint: unsigned, sintZigZag: zigZag, bool: v.value !== 0n };
269
+ }
270
+ else if (wireType === 1) {
271
+ if (pos + 8 > buf.length)
272
+ throw new Error(`Truncated fixed64 at offset ${pos}`);
273
+ const sub = buf.subarray(pos, pos + 8);
274
+ pos += 8;
275
+ const dbl = sub.readDoubleLE(0);
276
+ const u64 = bigIntToSafeJson(sub.readBigUInt64LE(0));
277
+ const i64 = bigIntToSafeJson(sub.readBigInt64LE(0));
278
+ entry.value = def?.type === 'double' ? dbl : def?.type === 'sfixed64' ? i64 : u64;
279
+ entry.alternatives = { fixed64: u64, sfixed64: i64, double: dbl };
280
+ }
281
+ else if (wireType === 5) {
282
+ if (pos + 4 > buf.length)
283
+ throw new Error(`Truncated fixed32 at offset ${pos}`);
284
+ const sub = buf.subarray(pos, pos + 4);
285
+ pos += 4;
286
+ const flt = Math.round(sub.readFloatLE(0) * 1e6) / 1e6;
287
+ const u32 = sub.readUInt32LE(0);
288
+ const i32 = sub.readInt32LE(0);
289
+ entry.value = def?.type === 'float' ? flt : def?.type === 'sfixed32' ? i32 : u32;
290
+ entry.alternatives = { fixed32: u32, sfixed32: i32, float: flt };
291
+ }
292
+ else if (wireType === 2) {
293
+ const lenRes = readVarint(buf, pos);
294
+ pos = lenRes.nextOffset;
295
+ const len = Number(lenRes.value);
296
+ if (len < 0 || pos + len > buf.length) {
297
+ throw new Error(`Length-delimited field #${fieldNumber} overflows buffer (${len} bytes)`);
298
+ }
299
+ const slice = buf.subarray(pos, pos + len);
300
+ pos += len;
301
+ const subMsgDef = def ? schemas.get(def.type.split('.').pop() ?? '') : undefined;
302
+ if (subMsgDef) {
303
+ entry.nested = decodeBufferInternal(slice, schemas, subMsgDef, depth + 1);
304
+ entry.value = buildMappedObject(entry.nested);
305
+ }
306
+ else if (def?.type === 'string') {
307
+ entry.value = slice.toString('utf8');
308
+ }
309
+ else if (def?.type === 'bytes') {
310
+ entry.value = slice.toString('base64');
311
+ entry.alternatives = { hex: slice.toString('hex') };
312
+ }
313
+ else {
314
+ // Heuristic: try UTF-8 text first, else attempt embedded Protobuf submessage
315
+ if (isLikelyPrintableUtf8(slice) && slice.length > 0) {
316
+ entry.value = slice.toString('utf8');
317
+ entry.alternatives = { hex: slice.toString('hex'), base64: slice.toString('base64') };
318
+ }
319
+ else {
320
+ let nestedDecoded;
321
+ if (slice.length >= 2) {
322
+ try {
323
+ nestedDecoded = decodeBufferInternal(slice, schemas, undefined, depth + 1);
324
+ }
325
+ catch {
326
+ nestedDecoded = undefined;
327
+ }
328
+ }
329
+ if (nestedDecoded && nestedDecoded.length > 0) {
330
+ entry.nested = nestedDecoded;
331
+ entry.value = buildMappedObject(nestedDecoded);
332
+ }
333
+ else {
334
+ entry.value = slice.toString('hex');
335
+ entry.alternatives = { base64: slice.toString('base64'), bytes: slice.length };
336
+ }
337
+ }
338
+ }
339
+ }
340
+ else {
341
+ throw new Error(`Legacy Protobuf wireType ${wireType} (groups) is not supported`);
342
+ }
343
+ fields.push(entry);
344
+ }
345
+ return fields;
346
+ }
347
+ function buildMappedObject(fields) {
348
+ const out = {};
349
+ for (const f of fields) {
350
+ const key = f.fieldName ?? `field_${f.fieldNumber}`;
351
+ if (key in out) {
352
+ const prev = out[key];
353
+ out[key] = Array.isArray(prev) ? [...prev, f.value] : [prev, f.value];
354
+ }
355
+ else {
356
+ out[key] = f.value;
357
+ }
358
+ }
359
+ return out;
360
+ }
361
+ /**
362
+ * Decodes raw binary Protobuf payloads (hex or base64) into structured wire fields
363
+ * and optionally maps field numbers/types using a `.proto` message schema.
364
+ */
365
+ export function decodeProtobufWire(input, options = {}) {
366
+ const cleaned = input.replace(/\s+/g, '');
367
+ if (!cleaned)
368
+ throw new Error('Protobuf payload (hex or base64) is required');
369
+ const encOpt = options.encoding ?? 'auto';
370
+ const isHex = encOpt === 'hex' || (encOpt === 'auto' && cleaned.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(cleaned));
371
+ const inputEncoding = isHex ? 'hex' : 'base64';
372
+ const buf = Buffer.from(cleaned, inputEncoding);
373
+ if (buf.length === 0)
374
+ throw new Error('Decoded Protobuf buffer is empty');
375
+ if (buf.length > 1024 * 1024)
376
+ throw new Error('Protobuf payload exceeds 1 MB limit');
377
+ const schemas = options.protoSchema ? parseProtoSchema(options.protoSchema) : new Map();
378
+ let targetMsg;
379
+ if (schemas.size > 0) {
380
+ targetMsg = options.messageName ? schemas.get(options.messageName) : schemas.values().next().value;
381
+ }
382
+ const fields = decodeBufferInternal(buf, schemas, targetMsg);
383
+ return {
384
+ byteLength: buf.length,
385
+ inputEncoding,
386
+ fields,
387
+ mappedObject: buildMappedObject(fields),
388
+ ...(targetMsg ? { schemaMessage: targetMsg.name } : {}),
389
+ };
390
+ }
@@ -0,0 +1,27 @@
1
+ import type { MockRouteInput } from '../server/mock-store.js';
2
+ export interface OpenApiEndpoint {
3
+ method: string;
4
+ openApiPath: string;
5
+ mockPath: string;
6
+ operationId?: string;
7
+ summary: string;
8
+ tags: string[];
9
+ responseStatus: number;
10
+ sampleResponse: unknown;
11
+ sampleRequestBody?: unknown;
12
+ curlExample: string;
13
+ }
14
+ export interface ParsedOpenApiResult {
15
+ title: string;
16
+ version: string;
17
+ specVersion: string;
18
+ baseUrl: string;
19
+ endpointCount: number;
20
+ endpoints: OpenApiEndpoint[];
21
+ }
22
+ /**
23
+ * Parses an OpenAPI 3.x or Swagger 2.0 specification (JSON or YAML) and
24
+ * synthesizes live mock definitions + cURL snippets for every operation.
25
+ */
26
+ export declare function parseOpenApiSpec(rawInput: string): ParsedOpenApiResult;
27
+ export declare function openApiToMockRoutes(spec: ParsedOpenApiResult): MockRouteInput[];
@@ -0,0 +1,257 @@
1
+ import { parseYaml } from './converters.js';
2
+ import { generateCodeSnippets } from './curl.js';
3
+ import { isDangerousKey, safeJsonParse } from './security.js';
4
+ const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'];
5
+ function resolveJsonPointer(root, ref) {
6
+ if (!ref.startsWith('#/'))
7
+ return undefined;
8
+ const segments = ref
9
+ .slice(2)
10
+ .split('/')
11
+ .map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'));
12
+ let cur = root;
13
+ for (const seg of segments) {
14
+ if (isDangerousKey(seg))
15
+ return undefined;
16
+ if (!cur || typeof cur !== 'object' || Array.isArray(cur))
17
+ return undefined;
18
+ const obj = cur;
19
+ if (!Object.prototype.hasOwnProperty.call(obj, seg))
20
+ return undefined;
21
+ cur = obj[seg];
22
+ }
23
+ return cur;
24
+ }
25
+ function synthesizeExample(schema, root, depth = 0, visitedRefs = new Set()) {
26
+ if (depth > 10 || !schema || typeof schema !== 'object')
27
+ return null;
28
+ const s = schema;
29
+ if (typeof s.$ref === 'string') {
30
+ if (visitedRefs.has(s.$ref))
31
+ return { $circularRef: s.$ref };
32
+ const resolved = resolveJsonPointer(root, s.$ref);
33
+ if (!resolved)
34
+ return {};
35
+ const nextVisited = new Set(visitedRefs);
36
+ nextVisited.add(s.$ref);
37
+ return synthesizeExample(resolved, root, depth + 1, nextVisited);
38
+ }
39
+ if (s.example !== undefined)
40
+ return s.example;
41
+ if (s.default !== undefined)
42
+ return s.default;
43
+ if (Array.isArray(s.enum) && s.enum.length > 0)
44
+ return s.enum[0];
45
+ if (Array.isArray(s.allOf) && s.allOf.length > 0) {
46
+ const merged = {};
47
+ for (const part of s.allOf) {
48
+ const val = synthesizeExample(part, root, depth + 1, visitedRefs);
49
+ if (val && typeof val === 'object' && !Array.isArray(val)) {
50
+ Object.assign(merged, val);
51
+ }
52
+ }
53
+ return merged;
54
+ }
55
+ if (Array.isArray(s.oneOf) && s.oneOf.length > 0) {
56
+ return synthesizeExample(s.oneOf[0], root, depth + 1, visitedRefs);
57
+ }
58
+ if (Array.isArray(s.anyOf) && s.anyOf.length > 0) {
59
+ return synthesizeExample(s.anyOf[0], root, depth + 1, visitedRefs);
60
+ }
61
+ const rawType = Array.isArray(s.type) ? s.type[0] : s.type;
62
+ const type = typeof rawType === 'string' ? rawType : s.properties ? 'object' : s.items ? 'array' : 'string';
63
+ switch (type) {
64
+ case 'object': {
65
+ const out = {};
66
+ const props = (s.properties && typeof s.properties === 'object' ? s.properties : {});
67
+ for (const [k, propSchema] of Object.entries(props)) {
68
+ if (isDangerousKey(k))
69
+ continue;
70
+ out[k] = synthesizeExample(propSchema, root, depth + 1, visitedRefs);
71
+ }
72
+ return out;
73
+ }
74
+ case 'array':
75
+ return s.items ? [synthesizeExample(s.items, root, depth + 1, visitedRefs)] : [];
76
+ case 'integer':
77
+ return typeof s.minimum === 'number' ? Math.ceil(s.minimum) : 42;
78
+ case 'number':
79
+ return typeof s.minimum === 'number' ? s.minimum : 99.95;
80
+ case 'boolean':
81
+ return true;
82
+ case 'null':
83
+ return null;
84
+ case 'string':
85
+ default: {
86
+ const fmt = typeof s.format === 'string' ? s.format : '';
87
+ if (fmt === 'uuid')
88
+ return '{{uuid}}';
89
+ if (fmt === 'email')
90
+ return 'ada@devanvil.local';
91
+ if (fmt === 'date-time')
92
+ return '{{timestamp}}';
93
+ if (fmt === 'date')
94
+ return '2026-11-28';
95
+ if (fmt === 'uri' || fmt === 'url')
96
+ return 'https://api.devanvil.local/resource';
97
+ if (fmt === 'ipv4')
98
+ return '10.24.0.10';
99
+ return 'sample_string';
100
+ }
101
+ }
102
+ }
103
+ function extractMediaExample(mediaObj, root) {
104
+ if (!mediaObj || typeof mediaObj !== 'object')
105
+ return undefined;
106
+ const content = mediaObj;
107
+ const jsonMedia = (content['application/json'] ?? Object.values(content)[0]);
108
+ if (!jsonMedia || typeof jsonMedia !== 'object')
109
+ return undefined;
110
+ if (jsonMedia.example !== undefined)
111
+ return jsonMedia.example;
112
+ if (jsonMedia.examples && typeof jsonMedia.examples === 'object') {
113
+ const first = Object.values(jsonMedia.examples)[0];
114
+ if (first && first.value !== undefined)
115
+ return first.value;
116
+ }
117
+ if (jsonMedia.schema)
118
+ return synthesizeExample(jsonMedia.schema, root);
119
+ return undefined;
120
+ }
121
+ function toMockPath(openApiPath) {
122
+ return openApiPath.replace(/\{([^}]+)\}/g, ':$1');
123
+ }
124
+ /**
125
+ * Parses an OpenAPI 3.x or Swagger 2.0 specification (JSON or YAML) and
126
+ * synthesizes live mock definitions + cURL snippets for every operation.
127
+ */
128
+ export function parseOpenApiSpec(rawInput) {
129
+ const trimmed = rawInput.trim();
130
+ if (!trimmed)
131
+ throw new Error('OpenAPI specification input is empty');
132
+ if (Buffer.byteLength(trimmed, 'utf8') > 1_000_000) {
133
+ throw new Error('OpenAPI spec exceeds 1 MB safety limit');
134
+ }
135
+ let doc;
136
+ if (trimmed.startsWith('{')) {
137
+ doc = safeJsonParse(trimmed);
138
+ }
139
+ else {
140
+ try {
141
+ doc = parseYaml(trimmed);
142
+ }
143
+ catch {
144
+ doc = safeJsonParse(trimmed);
145
+ }
146
+ }
147
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) {
148
+ throw new Error('OpenAPI specification must parse to an object');
149
+ }
150
+ const root = doc;
151
+ const specVersion = String(root.openapi ?? root.swagger ?? '');
152
+ if (!specVersion) {
153
+ throw new Error('Missing "openapi" (3.x) or "swagger" (2.0) version field');
154
+ }
155
+ const info = (root.info && typeof root.info === 'object' ? root.info : {});
156
+ const title = typeof info.title === 'string' ? info.title : 'Untitled API';
157
+ const version = typeof info.version === 'string' ? info.version : '1.0.0';
158
+ let baseUrl = 'http://127.0.0.1:4321/mock';
159
+ if (Array.isArray(root.servers) && root.servers.length > 0) {
160
+ const firstServer = root.servers[0];
161
+ if (firstServer && typeof firstServer.url === 'string' && /^https?:\/\//i.test(firstServer.url)) {
162
+ baseUrl = firstServer.url.replace(/\/+$/, '');
163
+ }
164
+ }
165
+ const pathsObj = (root.paths && typeof root.paths === 'object' ? root.paths : {});
166
+ const endpoints = [];
167
+ for (const [openApiPath, pathItemRaw] of Object.entries(pathsObj)) {
168
+ if (!pathItemRaw || typeof pathItemRaw !== 'object')
169
+ continue;
170
+ const pathItem = pathItemRaw;
171
+ for (const methodLower of HTTP_METHODS) {
172
+ const opRaw = pathItem[methodLower];
173
+ if (!opRaw || typeof opRaw !== 'object')
174
+ continue;
175
+ const op = opRaw;
176
+ const method = methodLower.toUpperCase();
177
+ const mockPath = toMockPath(openApiPath);
178
+ // Find best 2xx response (or first numeric status)
179
+ const responses = (op.responses && typeof op.responses === 'object' ? op.responses : {});
180
+ const statusKeys = Object.keys(responses);
181
+ const chosenStatusKey = statusKeys.find((k) => /^2\d\d$/.test(k)) ??
182
+ statusKeys.find((k) => /^\d{3}$/.test(k)) ??
183
+ '200';
184
+ const responseStatus = /^\d{3}$/.test(chosenStatusKey) ? Number(chosenStatusKey) : 200;
185
+ const respObj = responses[chosenStatusKey];
186
+ let sampleResponse;
187
+ if (respObj && typeof respObj === 'object') {
188
+ if (respObj.content) {
189
+ sampleResponse = extractMediaExample(respObj.content, root);
190
+ }
191
+ else if (respObj.schema) {
192
+ // Swagger 2.0 style
193
+ sampleResponse = synthesizeExample(respObj.schema, root);
194
+ }
195
+ }
196
+ if (sampleResponse === undefined) {
197
+ sampleResponse = responseStatus === 204 ? '' : { ok: true, endpoint: openApiPath, timestamp: '{{timestamp}}' };
198
+ }
199
+ // Inject dynamic {{param.x}} placeholders into top-level matching id fields for instant realism
200
+ if (sampleResponse && typeof sampleResponse === 'object' && !Array.isArray(sampleResponse)) {
201
+ const paramMatches = Array.from(openApiPath.matchAll(/\{([^}]+)\}/g)).map((m) => m[1]);
202
+ const respRecord = sampleResponse;
203
+ for (const pName of paramMatches) {
204
+ if (pName in respRecord && typeof respRecord[pName] === 'string') {
205
+ respRecord[pName] = `{{param.${pName}}}`;
206
+ }
207
+ }
208
+ }
209
+ let sampleRequestBody;
210
+ const reqBody = op.requestBody;
211
+ if (reqBody && typeof reqBody === 'object' && reqBody.content) {
212
+ sampleRequestBody = extractMediaExample(reqBody.content, root);
213
+ }
214
+ const sampleUrl = `${baseUrl}${openApiPath.replace(/\{[^}]+\}/g, '42')}`;
215
+ const curlExample = generateCodeSnippets({
216
+ method,
217
+ url: sampleUrl,
218
+ headers: sampleRequestBody !== undefined ? { 'Content-Type': 'application/json' } : {},
219
+ body: sampleRequestBody !== undefined ? JSON.stringify(sampleRequestBody, null, 2) : '',
220
+ }).curl;
221
+ endpoints.push({
222
+ method,
223
+ openApiPath,
224
+ mockPath,
225
+ ...(typeof op.operationId === 'string' ? { operationId: op.operationId } : {}),
226
+ summary: typeof op.summary === 'string' ? op.summary : typeof op.description === 'string' ? op.description : `${method} ${openApiPath}`,
227
+ tags: Array.isArray(op.tags) ? op.tags.map(String) : [],
228
+ responseStatus,
229
+ sampleResponse,
230
+ ...(sampleRequestBody !== undefined ? { sampleRequestBody } : {}),
231
+ curlExample,
232
+ });
233
+ }
234
+ }
235
+ if (endpoints.length === 0) {
236
+ throw new Error('No HTTP operations found under "paths" in OpenAPI spec');
237
+ }
238
+ return {
239
+ title,
240
+ version,
241
+ specVersion,
242
+ baseUrl,
243
+ endpointCount: endpoints.length,
244
+ endpoints,
245
+ };
246
+ }
247
+ export function openApiToMockRoutes(spec) {
248
+ return spec.endpoints.map((ep) => ({
249
+ method: ep.method,
250
+ path: ep.mockPath,
251
+ status: ep.responseStatus,
252
+ headers: { 'Content-Type': 'application/json', 'X-Mock-Source': `OpenAPI:${spec.title}` },
253
+ body: typeof ep.sampleResponse === 'string' ? ep.sampleResponse : JSON.stringify(ep.sampleResponse, null, 2),
254
+ delayMs: 25,
255
+ enabled: true,
256
+ }));
257
+ }