@oxog/spark 1.1.1 → 1.2.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 (64) hide show
  1. package/CHANGELOG.md +632 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1068 -956
  6. package/src/core/context.js +1098 -830
  7. package/src/core/middleware.js +303 -217
  8. package/src/index.js +183 -280
  9. package/src/middleware/body-parser.js +482 -526
  10. package/src/middleware/cache.js +177 -170
  11. package/src/middleware/compression.js +177 -182
  12. package/src/middleware/cors.js +176 -95
  13. package/src/middleware/health.js +219 -218
  14. package/src/middleware/logger.js +195 -194
  15. package/src/middleware/metrics.js +339 -327
  16. package/src/middleware/rate-limit.js +367 -319
  17. package/src/middleware/security.js +442 -332
  18. package/src/middleware/session.js +647 -529
  19. package/src/middleware/static.js +404 -299
  20. package/src/router/layer.js +197 -117
  21. package/src/router/route.js +149 -123
  22. package/src/router/router.js +703 -755
  23. package/src/utils/async-handler.js +145 -147
  24. package/src/utils/context-pool.js +83 -82
  25. package/src/utils/regex-validator.js +187 -163
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +536 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -959
  31. package/dist/core/context.js +0 -833
  32. package/dist/core/middleware.js +0 -220
  33. package/dist/core/request.js +0 -335
  34. package/dist/core/response.js +0 -377
  35. package/dist/index.js +0 -280
  36. package/dist/middleware/body-parser.js +0 -528
  37. package/dist/middleware/cache.js +0 -173
  38. package/dist/middleware/compression.js +0 -185
  39. package/dist/middleware/cors.js +0 -97
  40. package/dist/middleware/health.js +0 -221
  41. package/dist/middleware/index.js +0 -23
  42. package/dist/middleware/logger.js +0 -197
  43. package/dist/middleware/metrics.js +0 -330
  44. package/dist/middleware/rate-limit.js +0 -322
  45. package/dist/middleware/security.js +0 -335
  46. package/dist/middleware/session.js +0 -532
  47. package/dist/middleware/static.js +0 -301
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -119
  50. package/dist/router/route.js +0 -125
  51. package/dist/router/router.js +0 -758
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -150
  54. package/dist/utils/cache.js +0 -443
  55. package/dist/utils/context-pool.js +0 -85
  56. package/dist/utils/error-types.js +0 -134
  57. package/dist/utils/http.js +0 -415
  58. package/dist/utils/regex-validator.js +0 -166
  59. package/src/core/request.js +0 -335
  60. package/src/core/response.js +0 -377
  61. package/src/middleware/index.js +0 -23
  62. package/src/utils/cache.js +0 -443
  63. package/src/utils/error-types.js +0 -134
  64. package/src/utils/http.js +0 -415
@@ -1,166 +1,190 @@
1
1
  'use strict';
2
2
 
3
- const MAX_PATTERN_LENGTH = 1000;
4
- const MAX_CAPTURE_GROUPS = 10;
5
- const DANGEROUS_PATTERNS = [
6
- /(\w+\+)+\w+/, // Potential catastrophic backtracking
7
- /(\w+\*)+\w+/, // Potential catastrophic backtracking
8
- /(a+)+b/, // Classic ReDoS pattern
9
- /(\d+)+\w/, // Numeric ReDoS pattern
10
- ];
11
-
12
- class RegexValidator {
13
- static isComplexPattern(pattern) {
14
- if (typeof pattern !== 'string') return false;
15
-
16
- // Check pattern length
17
- if (pattern.length > MAX_PATTERN_LENGTH) {
18
- return true;
19
- }
20
-
21
- // Count capture groups
22
- const captureGroups = pattern.match(/\([^)]*\)/g) || [];
23
- if (captureGroups.length > MAX_CAPTURE_GROUPS) {
24
- return true;
25
- }
26
-
27
- // Check for nested quantifiers
28
- if (/(\+|\*|\{[^}]+\}){2,}/.test(pattern)) {
29
- return true;
30
- }
31
-
32
- // Check for dangerous patterns
33
- for (const dangerous of DANGEROUS_PATTERNS) {
34
- if (dangerous.test(pattern)) {
35
- return true;
36
- }
37
- }
38
-
39
- return false;
40
- }
41
-
42
- static sanitizePattern(pattern) {
43
- if (typeof pattern !== 'string') return pattern;
44
-
45
- // Limit pattern length
46
- if (pattern.length > MAX_PATTERN_LENGTH) {
47
- pattern = pattern.substring(0, MAX_PATTERN_LENGTH);
48
- }
49
-
50
- // Replace potentially dangerous quantifiers
51
- pattern = pattern.replace(/(\+|\*){2,}/g, '$1');
52
- pattern = pattern.replace(/\{(\d+),?\}/g, (match, num) => {
53
- const limit = parseInt(num);
54
- return limit > 100 ? '{0,100}' : match;
55
- });
56
-
57
- return pattern;
58
- }
59
-
60
- static testPerformance(pattern, testString = 'a'.repeat(100)) {
61
- if (!(pattern instanceof RegExp)) {
62
- try {
63
- pattern = new RegExp(pattern);
64
- } catch (e) {
65
- return { safe: false, error: e.message };
66
- }
67
- }
68
-
69
- const startTime = process.hrtime.bigint();
70
- const timeout = 100; // 100ms timeout
71
-
72
- try {
73
- // Simple synchronous test with time check
74
- const result = pattern.test(testString);
75
- const endTime = process.hrtime.bigint();
76
- const duration = Number(endTime - startTime) / 1e6; // Convert to milliseconds
77
-
78
- return {
79
- safe: duration < timeout,
80
- duration,
81
- pattern: pattern.source,
82
- result
83
- };
84
- } catch (error) {
85
- return { safe: false, error: error.message };
86
- }
87
- }
88
- }
89
-
90
- // Regex cache with complexity checking
91
- class SafeRegexCache {
92
- constructor(maxSize = 1000) {
93
- this.cache = new Map();
94
- this.maxSize = maxSize;
95
- }
96
-
97
- get(pattern, flags = '') {
98
- const key = `${pattern}:${flags}`;
99
-
100
- if (this.cache.has(key)) {
101
- const entry = this.cache.get(key);
102
- entry.lastAccess = Date.now();
103
- return entry.regex;
104
- }
105
-
106
- // Validate pattern before creating regex
107
- if (RegexValidator.isComplexPattern(pattern)) {
108
- pattern = RegexValidator.sanitizePattern(pattern);
109
- }
110
-
111
- try {
112
- const regex = new RegExp(pattern, flags);
113
-
114
- // Test performance before caching
115
- const perfTest = RegexValidator.testPerformance(regex);
116
- if (!perfTest.safe) {
117
- throw new Error(`Unsafe regex pattern: ${perfTest.error}`);
118
- }
119
-
120
- // Add to cache
121
- if (this.cache.size >= this.maxSize) {
122
- this.evictOldest();
123
- }
124
-
125
- this.cache.set(key, {
126
- regex,
127
- lastAccess: Date.now(),
128
- pattern,
129
- flags
130
- });
131
-
132
- return regex;
133
- } catch (error) {
134
- throw new Error(`Invalid regex pattern: ${error.message}`);
135
- }
136
- }
137
-
138
- evictOldest() {
139
- let oldest = null;
140
- let oldestTime = Infinity;
141
-
142
- for (const [key, entry] of this.cache.entries()) {
143
- if (entry.lastAccess < oldestTime) {
144
- oldest = key;
145
- oldestTime = entry.lastAccess;
146
- }
147
- }
148
-
149
- if (oldest) {
150
- this.cache.delete(oldest);
151
- }
152
- }
153
-
154
- clear() {
155
- this.cache.clear();
156
- }
157
-
158
- get size() {
159
- return this.cache.size;
160
- }
161
- }
162
-
163
- module.exports = {
164
- RegexValidator,
165
- SafeRegexCache
3
+ const MAX_PATTERN_LENGTH = 1000;
4
+ const MAX_CAPTURE_GROUPS = 10;
5
+ // SECURITY: Use safe patterns to detect dangerous regex (avoid ReDoS in validator itself)
6
+ // Previous patterns like /(\w+\+)+\w+/ could themselves cause ReDoS
7
+ const DANGEROUS_PATTERNS = [
8
+ /\(\w\+\+\)\+/, // Nested quantifiers with word chars: (\w+)+
9
+ /\(\w\+\*\)\+/, // Nested quantifiers: (\w*)+
10
+ /\(a\+\)\+b/, // Classic ReDoS pattern: (a+)+b
11
+ /\(\d\+\)\+/, // Numeric nested quantifiers: (\d+)+
12
+ ];
13
+
14
+ class RegexValidator {
15
+ static isComplexPattern(pattern) {
16
+ if (typeof pattern !== 'string') return false;
17
+
18
+ // Check pattern length
19
+ if (pattern.length > MAX_PATTERN_LENGTH) {
20
+ return true;
21
+ }
22
+
23
+ // Count capture groups (excluding non-capturing groups like (?:...))
24
+ // SECURITY: Avoid lookbehind (?<!...) for older Node.js compatibility
25
+ // Match opening parens that are not escaped and not followed by ?
26
+ let captureGroups = 0;
27
+ for (let i = 0; i < pattern.length; i++) {
28
+ if (pattern[i] === '(' && (i === 0 || pattern[i - 1] !== '\\')) {
29
+ if (i + 1 >= pattern.length || pattern[i + 1] !== '?') {
30
+ captureGroups++;
31
+ }
32
+ }
33
+ }
34
+ if (captureGroups > MAX_CAPTURE_GROUPS) {
35
+ return true;
36
+ }
37
+
38
+ // Check for nested quantifiers
39
+ if (/(\+|\*|\{[^}]+\}){2,}/.test(pattern)) {
40
+ return true;
41
+ }
42
+
43
+ // Check for dangerous patterns
44
+ for (const dangerous of DANGEROUS_PATTERNS) {
45
+ if (dangerous.test(pattern)) {
46
+ return true;
47
+ }
48
+ }
49
+
50
+ return false;
51
+ }
52
+
53
+ static sanitizePattern(pattern) {
54
+ if (typeof pattern !== 'string') return pattern;
55
+
56
+ // Limit pattern length
57
+ if (pattern.length > MAX_PATTERN_LENGTH) {
58
+ pattern = pattern.substring(0, MAX_PATTERN_LENGTH);
59
+ }
60
+
61
+ // SECURITY: Removed dangerous quantifier replacement that changes semantics
62
+ // The pattern /(\+|\*){2,}/g would incorrectly change '++' to '+',
63
+ // which alters regex meaning (++ is literal, + is quantifier)
64
+ // Instead, reject patterns with excessive nested quantifiers during validation
65
+
66
+ // Limit quantifier ranges to prevent ReDoS
67
+ pattern = pattern.replace(/\{(\d+),?\}/g, (match, num) => {
68
+ const limit = parseInt(num, 10);
69
+ return limit > 100 ? '{0,100}' : match;
70
+ });
71
+
72
+ return pattern;
73
+ }
74
+
75
+ static testPerformance(pattern, testString = 'a'.repeat(100)) {
76
+ if (!(pattern instanceof RegExp)) {
77
+ try {
78
+ pattern = new RegExp(pattern);
79
+ } catch (e) {
80
+ return { safe: false, error: e.message };
81
+ }
82
+ }
83
+
84
+ const startTime = process.hrtime.bigint();
85
+ const timeout = 100; // 100ms timeout
86
+
87
+ try {
88
+ // Simple synchronous test with time check
89
+ const result = pattern.test(testString);
90
+ const endTime = process.hrtime.bigint();
91
+ const duration = Number(endTime - startTime) / 1e6; // Convert to milliseconds
92
+
93
+ return {
94
+ safe: duration < timeout,
95
+ duration,
96
+ pattern: pattern.source,
97
+ result
98
+ };
99
+ } catch (error) {
100
+ return { safe: false, error: error.message };
101
+ }
102
+ }
103
+ }
104
+
105
+ // Regex cache with complexity checking
106
+ class SafeRegexCache {
107
+ constructor(maxSize = 1000) {
108
+ this.cache = new Map();
109
+ this.maxSize = maxSize;
110
+ }
111
+
112
+ get(pattern, flags = '') {
113
+ const key = `${pattern}:${flags}`;
114
+
115
+ if (this.cache.has(key)) {
116
+ const entry = this.cache.get(key);
117
+ entry.lastAccess = Date.now();
118
+ return entry.regex;
119
+ }
120
+
121
+ // SECURITY: Validate regex flags before creating RegExp
122
+ // Valid flags are: g (global), i (ignoreCase), m (multiline), s (dotAll), u (unicode), y (sticky)
123
+ const validFlags = new Set(['g', 'i', 'm', 's', 'u', 'y']);
124
+ for (const flag of flags) {
125
+ if (!validFlags.has(flag)) {
126
+ throw new Error(`Invalid regex flag: "${flag}". Valid flags are: g, i, m, s, u, y`);
127
+ }
128
+ }
129
+
130
+ // Validate pattern before creating regex
131
+ if (RegexValidator.isComplexPattern(pattern)) {
132
+ pattern = RegexValidator.sanitizePattern(pattern);
133
+ }
134
+
135
+ try {
136
+ const regex = new RegExp(pattern, flags);
137
+
138
+ // Test performance before caching
139
+ const perfTest = RegexValidator.testPerformance(regex);
140
+ if (!perfTest.safe) {
141
+ throw new Error(`Unsafe regex pattern: ${perfTest.error}`);
142
+ }
143
+
144
+ // Add to cache
145
+ if (this.cache.size >= this.maxSize) {
146
+ this.evictOldest();
147
+ }
148
+
149
+ this.cache.set(key, {
150
+ regex,
151
+ lastAccess: Date.now(),
152
+ pattern,
153
+ flags
154
+ });
155
+
156
+ return regex;
157
+ } catch (error) {
158
+ throw new Error(`Invalid regex pattern: ${error.message}`);
159
+ }
160
+ }
161
+
162
+ evictOldest() {
163
+ let oldest = null;
164
+ let oldestTime = Infinity;
165
+
166
+ for (const [key, entry] of this.cache.entries()) {
167
+ if (entry.lastAccess < oldestTime) {
168
+ oldest = key;
169
+ oldestTime = entry.lastAccess;
170
+ }
171
+ }
172
+
173
+ if (oldest) {
174
+ this.cache.delete(oldest);
175
+ }
176
+ }
177
+
178
+ clear() {
179
+ this.cache.clear();
180
+ }
181
+
182
+ get size() {
183
+ return this.cache.size;
184
+ }
185
+ }
186
+
187
+ module.exports = {
188
+ RegexValidator,
189
+ SafeRegexCache
166
190
  };
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Safe JSON parsing with depth and size validation
3
+ * Prevents DoS attacks via deeply nested objects or extremely large payloads
4
+ */
5
+
6
+ /**
7
+ * Parse JSON with security validations
8
+ * @param {string} text - JSON string to parse
9
+ * @param {Object} options - Parsing options
10
+ * @param {number} options.maxDepth - Maximum nesting depth (default: 20)
11
+ * @param {number} options.maxSize - Maximum JSON string size in bytes (default: 1MB)
12
+ * @param {Function} [options.reviver] - JSON.parse reviver
13
+ * @returns {*} Parsed JSON object
14
+ * @throws {Error} If validation fails or parsing errors
15
+ */
16
+ function safeJSONParse(text, options = {}) {
17
+ const maxDepth = options.maxDepth || 20;
18
+ const maxSize = options.maxSize || 1024 * 1024; // 1MB default
19
+
20
+ // SECURITY: Validate size before parsing to prevent memory exhaustion
21
+ if (typeof text !== 'string') {
22
+ throw new Error('JSON input must be a string');
23
+ }
24
+
25
+ if (text.length > maxSize) {
26
+ throw new Error(`JSON payload too large: ${text.length} bytes exceeds maximum ${maxSize} bytes`);
27
+ }
28
+
29
+ // SECURITY: Validate depth to prevent stack overflow from deeply nested objects
30
+ // Count maximum nesting level by tracking bracket/brace depth
31
+ let depth = 0;
32
+ let maxDepthFound = 0;
33
+ let inString = false;
34
+ let escaped = false;
35
+
36
+ for (let i = 0; i < text.length; i++) {
37
+ const char = text[i];
38
+
39
+ if (escaped) {
40
+ escaped = false;
41
+ continue;
42
+ }
43
+
44
+ if (char === '\\') {
45
+ escaped = true;
46
+ continue;
47
+ }
48
+
49
+ if (char === '"') {
50
+ inString = !inString;
51
+ continue;
52
+ }
53
+
54
+ if (inString) {
55
+ continue;
56
+ }
57
+
58
+ if (char === '{' || char === '[') {
59
+ depth++;
60
+ if (depth > maxDepthFound) {
61
+ maxDepthFound = depth;
62
+ }
63
+ if (depth > maxDepth) {
64
+ throw new Error(`JSON nesting depth ${depth} exceeds maximum allowed depth ${maxDepth}`);
65
+ }
66
+ } else if (char === '}' || char === ']') {
67
+ depth--;
68
+ }
69
+ }
70
+
71
+ // Parse the JSON after validation
72
+ try {
73
+ return options.reviver ? JSON.parse(text, options.reviver) : JSON.parse(text);
74
+ } catch (error) {
75
+ throw new Error(`Invalid JSON: ${error.message}`);
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Stringify JSON with size validation
81
+ * @param {*} value - Value to stringify
82
+ * @param {Object} options - Stringify options
83
+ * @param {number} options.maxSize - Maximum output size (default: 1MB)
84
+ * @returns {string} JSON string
85
+ * @throws {Error} If output exceeds size limit
86
+ */
87
+ function safeJSONStringify(value, options = {}) {
88
+ const maxSize = options.maxSize || 1024 * 1024; // 1MB default
89
+
90
+ try {
91
+ const result = JSON.stringify(value);
92
+
93
+ if (result.length > maxSize) {
94
+ throw new Error(`JSON output too large: ${result.length} bytes exceeds maximum ${maxSize} bytes`);
95
+ }
96
+
97
+ return result;
98
+ } catch (error) {
99
+ // Handle circular references
100
+ if (error.message && error.message.includes('circular')) {
101
+ throw new Error('Cannot stringify circular JSON structure');
102
+ }
103
+ throw error;
104
+ }
105
+ }
106
+
107
+ module.exports = {
108
+ safeJSONParse,
109
+ safeJSONStringify
110
+ };