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,28 @@
1
+ export type PipelineOpId = 'trim' | 'uppercase' | 'lowercase' | 'reverse' | 'sort_lines' | 'unique_lines' | 'base64_encode' | 'base64_decode' | 'base64url_encode' | 'base64url_decode' | 'url_encode' | 'url_decode' | 'hex_encode' | 'hex_decode' | 'html_encode' | 'html_decode' | 'gzip_base64' | 'gunzip_base64' | 'json_pretty' | 'json_minify' | 'json_sort' | 'json_to_yaml' | 'yaml_to_json' | 'json_to_ts' | 'jsonpath' | 'sql_format' | 'jwt_decode' | 'redact_secrets' | 'sha256' | 'sha512' | 'regex_replace';
2
+ export interface PipelineStep {
3
+ op: PipelineOpId;
4
+ arg1?: string;
5
+ arg2?: string;
6
+ enabled?: boolean;
7
+ }
8
+ export interface PipelineTraceStep {
9
+ index: number;
10
+ op: PipelineOpId;
11
+ enabled: boolean;
12
+ output: string;
13
+ durationMs: number;
14
+ error?: string;
15
+ }
16
+ export interface PipelineResult {
17
+ output: string;
18
+ steps: PipelineTraceStep[];
19
+ succeeded: boolean;
20
+ }
21
+ export declare const PIPELINE_OPERATIONS: Array<{
22
+ id: PipelineOpId;
23
+ label: string;
24
+ category: string;
25
+ arg1Label?: string;
26
+ arg2Label?: string;
27
+ }>;
28
+ export declare function runPipeline(input: string, steps: PipelineStep[]): PipelineResult;
@@ -0,0 +1,154 @@
1
+ import { convertData, formatSql, queryJsonPath } from './converters.js';
2
+ import { hashText } from './crypto.js';
3
+ import { decodeText, encodeText } from './encoding.js';
4
+ import { decodeJwt } from './jwt.js';
5
+ import { testRegex } from './regex.js';
6
+ import { scanSecrets } from './secrets.js';
7
+ import { safeJsonParse } from './security.js';
8
+ export const PIPELINE_OPERATIONS = [
9
+ { id: 'trim', label: 'Trim Whitespace', category: 'Text' },
10
+ { id: 'uppercase', label: 'UPPERCASE', category: 'Text' },
11
+ { id: 'lowercase', label: 'lowercase', category: 'Text' },
12
+ { id: 'reverse', label: 'Reverse String', category: 'Text' },
13
+ { id: 'sort_lines', label: 'Sort Lines A-Z', category: 'Text' },
14
+ { id: 'unique_lines', label: 'Deduplicate Lines', category: 'Text' },
15
+ { id: 'regex_replace', label: 'Regex Replace', category: 'Text', arg1Label: 'Pattern', arg2Label: 'Replacement' },
16
+ { id: 'base64_encode', label: 'Base64 Encode', category: 'Encode' },
17
+ { id: 'base64_decode', label: 'Base64 Decode', category: 'Encode' },
18
+ { id: 'base64url_encode', label: 'Base64URL Encode', category: 'Encode' },
19
+ { id: 'base64url_decode', label: 'Base64URL Decode', category: 'Encode' },
20
+ { id: 'url_encode', label: 'URL Encode', category: 'Encode' },
21
+ { id: 'url_decode', label: 'URL Decode', category: 'Encode' },
22
+ { id: 'hex_encode', label: 'Hex Encode', category: 'Encode' },
23
+ { id: 'hex_decode', label: 'Hex Decode', category: 'Encode' },
24
+ { id: 'html_encode', label: 'HTML Escape', category: 'Encode' },
25
+ { id: 'html_decode', label: 'HTML Unescape', category: 'Encode' },
26
+ { id: 'gzip_base64', label: 'Gzip -> Base64', category: 'Compress' },
27
+ { id: 'gunzip_base64', label: 'Base64 -> Gunzip', category: 'Compress' },
28
+ { id: 'json_pretty', label: 'JSON Prettify', category: 'Data' },
29
+ { id: 'json_minify', label: 'JSON Minify', category: 'Data' },
30
+ { id: 'json_sort', label: 'JSON Sort Keys', category: 'Data' },
31
+ { id: 'json_to_yaml', label: 'JSON -> YAML', category: 'Data' },
32
+ { id: 'yaml_to_json', label: 'YAML -> JSON', category: 'Data' },
33
+ { id: 'json_to_ts', label: 'JSON -> TypeScript', category: 'Data' },
34
+ { id: 'jsonpath', label: 'JSONPath Extract', category: 'Data', arg1Label: 'Path (e.g. $.items[*].name)' },
35
+ { id: 'sql_format', label: 'SQL Format', category: 'Data' },
36
+ { id: 'jwt_decode', label: 'JWT Decode -> JSON', category: 'Security' },
37
+ { id: 'redact_secrets', label: 'Redact Secrets & API Keys', category: 'Security' },
38
+ { id: 'sha256', label: 'SHA-256 Digest', category: 'Crypto' },
39
+ { id: 'sha512', label: 'SHA-512 Digest', category: 'Crypto' },
40
+ ];
41
+ function runSingleStep(current, step) {
42
+ switch (step.op) {
43
+ case 'trim':
44
+ return current.trim();
45
+ case 'uppercase':
46
+ return current.toUpperCase();
47
+ case 'lowercase':
48
+ return current.toLowerCase();
49
+ case 'reverse':
50
+ return Array.from(current).reverse().join('');
51
+ case 'sort_lines':
52
+ return current.replace(/\r\n/g, '\n').split('\n').sort().join('\n');
53
+ case 'unique_lines':
54
+ return Array.from(new Set(current.replace(/\r\n/g, '\n').split('\n'))).join('\n');
55
+ case 'regex_replace': {
56
+ const pattern = step.arg1 ?? '';
57
+ if (!pattern)
58
+ return current;
59
+ const res = testRegex(pattern, 'g', current, { replacement: step.arg2 ?? '' });
60
+ return res.replaced ?? current;
61
+ }
62
+ case 'base64_encode':
63
+ return encodeText(current, 'base64');
64
+ case 'base64_decode':
65
+ return decodeText(current, 'base64');
66
+ case 'base64url_encode':
67
+ return encodeText(current, 'base64url');
68
+ case 'base64url_decode':
69
+ return decodeText(current, 'base64url');
70
+ case 'url_encode':
71
+ return encodeText(current, 'url');
72
+ case 'url_decode':
73
+ return decodeText(current, 'url');
74
+ case 'hex_encode':
75
+ return encodeText(current, 'hex');
76
+ case 'hex_decode':
77
+ return decodeText(current, 'hex');
78
+ case 'html_encode':
79
+ return encodeText(current, 'html');
80
+ case 'html_decode':
81
+ return decodeText(current, 'html');
82
+ case 'gzip_base64':
83
+ return encodeText(current, 'gzip-base64');
84
+ case 'gunzip_base64':
85
+ return decodeText(current, 'gzip-base64');
86
+ case 'json_pretty':
87
+ return convertData(current, 'json', 'json', { indent: 2 });
88
+ case 'json_minify':
89
+ return convertData(current, 'json', 'json', { minify: true });
90
+ case 'json_sort':
91
+ return convertData(current, 'json', 'json', { indent: 2, sortKeys: true });
92
+ case 'json_to_yaml':
93
+ return convertData(current, 'json', 'yaml');
94
+ case 'yaml_to_json':
95
+ return convertData(current, 'yaml', 'json', { indent: 2 });
96
+ case 'json_to_ts':
97
+ return convertData(current, 'json', 'typescript');
98
+ case 'jsonpath': {
99
+ const data = safeJsonParse(current);
100
+ const matches = queryJsonPath(data, step.arg1 || '$');
101
+ return JSON.stringify(matches.length === 1 ? matches[0] : matches, null, 2);
102
+ }
103
+ case 'sql_format':
104
+ return formatSql(current);
105
+ case 'jwt_decode':
106
+ return JSON.stringify(decodeJwt(current), null, 2);
107
+ case 'redact_secrets':
108
+ return scanSecrets(current).redactedText;
109
+ case 'sha256':
110
+ return hashText(current, 'sha256').hex;
111
+ case 'sha512':
112
+ return hashText(current, 'sha512').hex;
113
+ default:
114
+ throw new Error(`Unknown pipeline operation: ${String(step.op)}`);
115
+ }
116
+ }
117
+ export function runPipeline(input, steps) {
118
+ if (steps.length > 25) {
119
+ throw new Error('Pipeline step limit exceeded (max 25 steps)');
120
+ }
121
+ let current = input;
122
+ const trace = [];
123
+ for (let i = 0; i < steps.length; i++) {
124
+ const step = steps[i];
125
+ const enabled = step.enabled !== false;
126
+ if (!enabled) {
127
+ trace.push({ index: i, op: step.op, enabled: false, output: current, durationMs: 0 });
128
+ continue;
129
+ }
130
+ const start = performance.now();
131
+ try {
132
+ current = runSingleStep(current, step);
133
+ trace.push({
134
+ index: i,
135
+ op: step.op,
136
+ enabled: true,
137
+ output: current,
138
+ durationMs: Math.round((performance.now() - start) * 100) / 100,
139
+ });
140
+ }
141
+ catch (err) {
142
+ trace.push({
143
+ index: i,
144
+ op: step.op,
145
+ enabled: true,
146
+ output: current,
147
+ durationMs: Math.round((performance.now() - start) * 100) / 100,
148
+ error: err.message,
149
+ });
150
+ return { output: current, steps: trace, succeeded: false };
151
+ }
152
+ }
153
+ return { output: current, steps: trace, succeeded: true };
154
+ }
@@ -0,0 +1,50 @@
1
+ export interface ReDoSAnalysis {
2
+ risk: 'safe' | 'caution' | 'high';
3
+ findings: string[];
4
+ }
5
+ export interface RegexTokenExplanation {
6
+ token: string;
7
+ category: string;
8
+ description: string;
9
+ }
10
+ export interface RegexMatchItem {
11
+ index: number;
12
+ end: number;
13
+ match: string;
14
+ groups: string[];
15
+ namedGroups: Record<string, string>;
16
+ }
17
+ export interface RegexTestResult {
18
+ pattern: string;
19
+ flags: string;
20
+ matches: RegexMatchItem[];
21
+ matchCount: number;
22
+ truncated: boolean;
23
+ replaced?: string;
24
+ executionMs: number;
25
+ redos: ReDoSAnalysis;
26
+ explanation: RegexTokenExplanation[];
27
+ }
28
+ export declare const REGEX_PRESETS: Array<{
29
+ id: string;
30
+ name: string;
31
+ pattern: string;
32
+ flags: string;
33
+ sample: string;
34
+ }>;
35
+ /**
36
+ * Static heuristic detector for Catastrophic Backtracking (ReDoS) anti-patterns.
37
+ */
38
+ export declare function analyzeReDoS(pattern: string): ReDoSAnalysis;
39
+ /**
40
+ * Produces a readable token-by-token explanation of a regular expression.
41
+ */
42
+ export declare function explainRegex(pattern: string): RegexTokenExplanation[];
43
+ /**
44
+ * Safely tests a regular expression inside an isolated VM context with a hard 250ms timeout.
45
+ */
46
+ export declare function testRegex(pattern: string, flags: string, text: string, options?: {
47
+ replacement?: string;
48
+ timeoutMs?: number;
49
+ maxMatches?: number;
50
+ }): RegexTestResult;
@@ -0,0 +1,351 @@
1
+ import { Script } from 'node:vm';
2
+ export const REGEX_PRESETS = [
3
+ {
4
+ id: 'email',
5
+ name: 'Email Address',
6
+ pattern: '(?<user>[a-zA-Z0-9._%+-]+)@(?<domain>[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,})',
7
+ flags: 'g',
8
+ sample: 'Contact dev@devanvil.local or security.team+alerts@example.org for reports.',
9
+ },
10
+ {
11
+ id: 'semver',
12
+ name: 'Semantic Version (SemVer)',
13
+ pattern: 'v?(?<major>0|[1-9]\\d*)\\.(?<minor>0|[1-9]\\d*)\\.(?<patch>0|[1-9]\\d*)(?:-(?<prerelease>[0-9A-Za-z.-]+))?',
14
+ flags: 'g',
15
+ sample: 'Releases: v1.0.0, 2.14.3-beta.1, 0.9.0-rc.2',
16
+ },
17
+ {
18
+ id: 'ipv4',
19
+ name: 'IPv4 Address',
20
+ pattern: '\\b(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\b',
21
+ flags: 'g',
22
+ sample: 'Gateways: 192.168.1.1, 10.0.0.254, invalid 999.1.2.3, public 1.1.1.1',
23
+ },
24
+ {
25
+ id: 'uuid',
26
+ name: 'UUID (v1-v8)',
27
+ pattern: '\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}\\b',
28
+ flags: 'g',
29
+ sample: 'req_id=019374f1-52b0-7b1a-9a14-6b9e2d8c4a01 parent=550e8400-e29b-41d4-a716-446655440000',
30
+ },
31
+ {
32
+ id: 'iso8601',
33
+ name: 'ISO-8601 Timestamp',
34
+ pattern: '(?<date>\\d{4}-\\d{2}-\\d{2})T(?<time>\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)(?<tz>Z|[+-]\\d{2}:\\d{2})',
35
+ flags: 'g',
36
+ sample: 'Started at 2026-11-28T19:00:00Z, finished 2026-11-28T21:15:30.250+02:00',
37
+ },
38
+ {
39
+ id: 'url',
40
+ name: 'HTTP/HTTPS URL',
41
+ pattern: 'https?:\\/\\/[a-zA-Z0-9.-]+(?::\\d{1,5})?(?:\\/[^\\s"\'<>]*)?',
42
+ flags: 'g',
43
+ sample: 'Docs: https://github.com/abd77o/devanvil and http://api.example.com:8080/v1/health',
44
+ },
45
+ ];
46
+ /**
47
+ * Static heuristic detector for Catastrophic Backtracking (ReDoS) anti-patterns.
48
+ */
49
+ export function analyzeReDoS(pattern) {
50
+ const findings = [];
51
+ let risk = 'safe';
52
+ // Track group stack to detect nested quantifiers like (a+)+, (\w*)*, (a+b?){2,}
53
+ const stack = [];
54
+ let inCharClass = false;
55
+ for (let i = 0; i < pattern.length; i++) {
56
+ const ch = pattern[i];
57
+ if (ch === '\\') {
58
+ i++;
59
+ continue;
60
+ }
61
+ if (ch === '[' && !inCharClass) {
62
+ inCharClass = true;
63
+ continue;
64
+ }
65
+ if (ch === ']' && inCharClass) {
66
+ inCharClass = false;
67
+ continue;
68
+ }
69
+ if (inCharClass)
70
+ continue;
71
+ if (ch === '(') {
72
+ stack.push({ hasQuantifier: false, hasAlternation: false, content: '' });
73
+ }
74
+ else if (ch === ')') {
75
+ const group = stack.pop();
76
+ if (!group)
77
+ continue;
78
+ const next = pattern[i + 1];
79
+ const groupIsQuantified = next === '+' || next === '*' || next === '{';
80
+ if (groupIsQuantified && group.hasQuantifier) {
81
+ risk = 'high';
82
+ findings.push(`Nested quantifier detected in "(${group.content})${next}" — exponential backtracking risk (ReDoS).`);
83
+ }
84
+ if (groupIsQuantified && group.hasAlternation) {
85
+ const branches = group.content.split('|').map((b) => b.trim());
86
+ const duplicateOrPrefix = branches.some((b, idx) => branches.some((other, j) => idx !== j && b.length > 0 && (b === other || other.startsWith(b))));
87
+ if (duplicateOrPrefix) {
88
+ risk = 'high';
89
+ findings.push(`Overlapping quantified alternation "(${group.content})${next}" — can trigger exponential backtracking.`);
90
+ }
91
+ }
92
+ if (stack.length > 0 && (group.hasQuantifier || groupIsQuantified)) {
93
+ stack[stack.length - 1].hasQuantifier = true;
94
+ }
95
+ }
96
+ else {
97
+ if (stack.length > 0) {
98
+ const top = stack[stack.length - 1];
99
+ if (ch === '|')
100
+ top.hasAlternation = true;
101
+ if (ch === '+' || ch === '*' || ch === '{')
102
+ top.hasQuantifier = true;
103
+ if (top.content.length < 40)
104
+ top.content += ch;
105
+ }
106
+ }
107
+ }
108
+ // Adjacent unbounded greedy wildcards e.g. .*.* or .+.+
109
+ if (/\.\*[^\n]*\.\*|\.\+[^\n]*\.\+/.test(pattern)) {
110
+ if (risk === 'safe')
111
+ risk = 'caution';
112
+ findings.push('Multiple greedy ".*" / ".+" wildcards can cause quadratic O(n^2) backtracking on non-matching input.');
113
+ }
114
+ // Backreference inside quantifier e.g. (\w+)\1+
115
+ if (/\\[1-9][+*]|\\[1-9]\{/.test(pattern)) {
116
+ risk = 'high';
117
+ findings.push('Quantified backreference detected (e.g., \\1+) — super-polynomial matching complexity.');
118
+ }
119
+ if (findings.length === 0) {
120
+ findings.push('No common catastrophic backtracking (ReDoS) patterns detected.');
121
+ }
122
+ return { risk, findings };
123
+ }
124
+ /**
125
+ * Produces a readable token-by-token explanation of a regular expression.
126
+ */
127
+ export function explainRegex(pattern) {
128
+ const tokens = [];
129
+ let i = 0;
130
+ const ESCAPES = {
131
+ d: 'Any digit (0-9)',
132
+ D: 'Any non-digit character',
133
+ w: 'Any word character (a-z, A-Z, 0-9, _)',
134
+ W: 'Any non-word character',
135
+ s: 'Any whitespace character (space, tab, newline)',
136
+ S: 'Any non-whitespace character',
137
+ b: 'Word boundary',
138
+ B: 'Non-word boundary',
139
+ n: 'Newline character',
140
+ r: 'Carriage return',
141
+ t: 'Tab character',
142
+ };
143
+ while (i < pattern.length && tokens.length < 80) {
144
+ const ch = pattern[i];
145
+ if (ch === '\\' && i + 1 < pattern.length) {
146
+ const next = pattern[i + 1];
147
+ const tok = `\\${next}`;
148
+ const desc = ESCAPES[next] ?? (/[1-9]/.test(next) ? `Backreference to group #${next}` : `Escaped literal "${next}"`);
149
+ tokens.push({ token: tok, category: 'escape', description: desc });
150
+ i += 2;
151
+ }
152
+ else if (ch === '[') {
153
+ let j = i + 1;
154
+ while (j < pattern.length) {
155
+ if (pattern[j] === '\\')
156
+ j += 2;
157
+ else if (pattern[j] === ']')
158
+ break;
159
+ else
160
+ j++;
161
+ }
162
+ const cls = pattern.slice(i, j + 1);
163
+ const negated = cls.startsWith('[^');
164
+ tokens.push({
165
+ token: cls,
166
+ category: 'charClass',
167
+ description: negated ? `Any character NOT in set ${cls.slice(2, -1)}` : `Any character in set ${cls.slice(1, -1)}`,
168
+ });
169
+ i = j + 1;
170
+ }
171
+ else if (ch === '(') {
172
+ if (pattern.startsWith('(?:', i)) {
173
+ tokens.push({ token: '(?:', category: 'group', description: 'Start non-capturing group' });
174
+ i += 3;
175
+ }
176
+ else if (pattern.startsWith('(?=', i)) {
177
+ tokens.push({ token: '(?=', category: 'lookaround', description: 'Start positive lookahead' });
178
+ i += 3;
179
+ }
180
+ else if (pattern.startsWith('(?!', i)) {
181
+ tokens.push({ token: '(?!', category: 'lookaround', description: 'Start negative lookahead' });
182
+ i += 3;
183
+ }
184
+ else if (pattern.startsWith('(?<=', i)) {
185
+ tokens.push({ token: '(?<=', category: 'lookaround', description: 'Start positive lookbehind' });
186
+ i += 4;
187
+ }
188
+ else if (pattern.startsWith('(?<!', i)) {
189
+ tokens.push({ token: '(?<!', category: 'lookaround', description: 'Start negative lookbehind' });
190
+ i += 4;
191
+ }
192
+ else if (pattern.startsWith('(?<', i)) {
193
+ const end = pattern.indexOf('>', i + 3);
194
+ if (end !== -1) {
195
+ const name = pattern.slice(i + 3, end);
196
+ tokens.push({ token: pattern.slice(i, end + 1), category: 'group', description: `Start named capturing group "${name}"` });
197
+ i = end + 1;
198
+ }
199
+ else {
200
+ tokens.push({ token: '(', category: 'group', description: 'Start capturing group' });
201
+ i++;
202
+ }
203
+ }
204
+ else {
205
+ tokens.push({ token: '(', category: 'group', description: 'Start capturing group' });
206
+ i++;
207
+ }
208
+ }
209
+ else if (ch === ')') {
210
+ tokens.push({ token: ')', category: 'group', description: 'End group' });
211
+ i++;
212
+ }
213
+ else if (ch === '{') {
214
+ const m = /^\{(\d+)(?:,(\d*))?\}\??/.exec(pattern.slice(i));
215
+ if (m) {
216
+ const lazy = m[0].endsWith('?') ? ' (lazy)' : '';
217
+ const desc = m[2] === undefined
218
+ ? `Exactly ${m[1]} times${lazy}`
219
+ : m[2] === ''
220
+ ? `${m[1]} or more times${lazy}`
221
+ : `Between ${m[1]} and ${m[2]} times${lazy}`;
222
+ tokens.push({ token: m[0], category: 'quantifier', description: desc });
223
+ i += m[0].length;
224
+ }
225
+ else {
226
+ tokens.push({ token: '{', category: 'literal', description: 'Literal "{"' });
227
+ i++;
228
+ }
229
+ }
230
+ else if (ch === '*' || ch === '+' || ch === '?') {
231
+ const lazy = pattern[i + 1] === '?';
232
+ const tok = lazy ? `${ch}?` : ch;
233
+ const base = ch === '*' ? '0 or more times' : ch === '+' ? '1 or more times' : 'Optional (0 or 1 time)';
234
+ tokens.push({ token: tok, category: 'quantifier', description: lazy ? `${base} (lazy)` : base });
235
+ i += lazy ? 2 : 1;
236
+ }
237
+ else if (ch === '^') {
238
+ tokens.push({ token: '^', category: 'anchor', description: 'Start of string (or line with /m)' });
239
+ i++;
240
+ }
241
+ else if (ch === '$') {
242
+ tokens.push({ token: '$', category: 'anchor', description: 'End of string (or line with /m)' });
243
+ i++;
244
+ }
245
+ else if (ch === '|') {
246
+ tokens.push({ token: '|', category: 'alternation', description: 'OR (alternation branch)' });
247
+ i++;
248
+ }
249
+ else if (ch === '.') {
250
+ tokens.push({ token: '.', category: 'wildcard', description: 'Any character (except newline unless /s)' });
251
+ i++;
252
+ }
253
+ else {
254
+ let lit = ch;
255
+ i++;
256
+ while (i < pattern.length && !'\\[](){}*+?^$|.'.includes(pattern[i])) {
257
+ lit += pattern[i];
258
+ i++;
259
+ }
260
+ tokens.push({ token: lit, category: 'literal', description: `Literal text "${lit}"` });
261
+ }
262
+ }
263
+ return tokens;
264
+ }
265
+ const VALID_FLAGS = new Set(['g', 'i', 'm', 's', 'u', 'd']);
266
+ // Pre-compiled VM script avoids re-parsing runner source on every regex test call
267
+ const REGEX_RUNNER_SCRIPT = new Script(`
268
+ const re = new RegExp(pattern, flags);
269
+ const out = [];
270
+ if (flags.includes('g')) {
271
+ let m;
272
+ while ((m = re.exec(text)) !== null) {
273
+ out.push({
274
+ index: m.index,
275
+ end: m.index + m[0].length,
276
+ match: m[0],
277
+ groups: Array.prototype.slice.call(m, 1).map(g => g === undefined ? '' : String(g)),
278
+ namedGroups: m.groups ? Object.assign({}, m.groups) : {}
279
+ });
280
+ if (out.length >= maxMatches) {
281
+ result.truncated = true;
282
+ break;
283
+ }
284
+ if (m[0].length === 0) re.lastIndex++;
285
+ }
286
+ } else {
287
+ const m = re.exec(text);
288
+ if (m) {
289
+ out.push({
290
+ index: m.index,
291
+ end: m.index + m[0].length,
292
+ match: m[0],
293
+ groups: Array.prototype.slice.call(m, 1).map(g => g === undefined ? '' : String(g)),
294
+ namedGroups: m.groups ? Object.assign({}, m.groups) : {}
295
+ });
296
+ }
297
+ }
298
+ result.matches = out;
299
+ if (typeof replacement === 'string') {
300
+ result.replaced = text.replace(new RegExp(pattern, flags), replacement);
301
+ }
302
+ `);
303
+ /**
304
+ * Safely tests a regular expression inside an isolated VM context with a hard 250ms timeout.
305
+ */
306
+ export function testRegex(pattern, flags, text, options = {}) {
307
+ if (pattern.length > 2000) {
308
+ throw new Error('Regex pattern exceeds 2,000 character safety limit');
309
+ }
310
+ if (text.length > 250_000) {
311
+ throw new Error('Test input exceeds 250,000 character safety limit');
312
+ }
313
+ const sanitizedFlags = Array.from(new Set(flags.split('').filter((f) => VALID_FLAGS.has(f)))).join('');
314
+ // Validate regex syntax upfront
315
+ new RegExp(pattern, sanitizedFlags);
316
+ const redos = analyzeReDoS(pattern);
317
+ const explanation = explainRegex(pattern);
318
+ const timeoutMs = Math.min(Math.max(options.timeoutMs ?? 250, 20), 1000);
319
+ const maxMatches = Math.min(Math.max(options.maxMatches ?? 500, 1), 2000);
320
+ const start = performance.now();
321
+ const sandbox = {
322
+ pattern,
323
+ flags: sanitizedFlags,
324
+ text,
325
+ replacement: options.replacement,
326
+ maxMatches,
327
+ result: { matches: [], truncated: false, replaced: undefined },
328
+ };
329
+ try {
330
+ REGEX_RUNNER_SCRIPT.runInNewContext(sandbox, { timeout: timeoutMs });
331
+ }
332
+ catch (err) {
333
+ const msg = err.message || '';
334
+ if (msg.includes('timed out')) {
335
+ throw new Error(`Regex execution aborted after ${timeoutMs}ms (possible ReDoS catastrophic backtracking)`);
336
+ }
337
+ throw err;
338
+ }
339
+ const executionMs = Math.round((performance.now() - start) * 100) / 100;
340
+ return {
341
+ pattern,
342
+ flags: sanitizedFlags,
343
+ matches: sandbox.result.matches,
344
+ matchCount: sandbox.result.matches.length,
345
+ truncated: sandbox.result.truncated,
346
+ ...(sandbox.result.replaced !== undefined ? { replaced: sandbox.result.replaced } : {}),
347
+ executionMs,
348
+ redos,
349
+ explanation,
350
+ };
351
+ }
@@ -0,0 +1,53 @@
1
+ import { type RequestAssertion, type SavedApiRequest } from './importers.js';
2
+ export interface AssertionResult {
3
+ type: RequestAssertion['type'];
4
+ target?: string;
5
+ expected?: string | number | boolean;
6
+ actual?: unknown;
7
+ passed: boolean;
8
+ message: string;
9
+ }
10
+ export interface RequestRunResult {
11
+ requestId: string;
12
+ name: string;
13
+ method: string;
14
+ resolvedUrl: string;
15
+ status?: number;
16
+ latencyMs: number;
17
+ passed: boolean;
18
+ error?: string;
19
+ assertions: AssertionResult[];
20
+ extracted?: Record<string, string>;
21
+ }
22
+ export interface CollectionRunReport {
23
+ collectionName: string;
24
+ environmentName?: string;
25
+ startedAt: string;
26
+ totalDurationMs: number;
27
+ totalRequests: number;
28
+ passedRequests: number;
29
+ failedRequests: number;
30
+ passed: boolean;
31
+ results: RequestRunResult[];
32
+ }
33
+ /**
34
+ * Executes all requests in a DevAnvil Collection sequentially with active environment &
35
+ * optional `{{env.*}}` interpolation, SSRF protection, and declarative assertions.
36
+ * Zero-dependency alternative to Newman for local & CI API testing.
37
+ */
38
+ export declare function runCollection(collection: {
39
+ name: string;
40
+ requests: SavedApiRequest[];
41
+ }, options?: {
42
+ environmentName?: string;
43
+ variables?: Record<string, string>;
44
+ processEnv?: Record<string, string | undefined>;
45
+ allowPrivate?: boolean;
46
+ timeoutMs?: number;
47
+ stopOnFailure?: boolean;
48
+ }): Promise<CollectionRunReport>;
49
+ /**
50
+ * Formats a DevAnvil CollectionRunReport into standard JUnit XML for GitHub Actions,
51
+ * GitLab CI, Azure DevOps, and Jenkins test result panels.
52
+ */
53
+ export declare function formatRunReportAsJunitXml(report: CollectionRunReport): string;