@oxog/spark 1.1.1 → 1.3.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 +656 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +90 -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 +705 -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 +538 -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,220 +1,306 @@
1
1
  'use strict';
2
2
 
3
- const bodyParser = require('../middleware/body-parser');
4
- const cors = require('../middleware/cors');
5
- const compression = require('../middleware/compression');
6
- const staticFiles = require('../middleware/static');
7
- const session = require('../middleware/session');
8
- const rateLimit = require('../middleware/rate-limit');
9
- const security = require('../middleware/security');
10
- const logger = require('../middleware/logger');
11
-
12
- function createMiddleware(app) {
13
- return {
14
- bodyParser: (options) => bodyParser(options),
15
- cors: (options) => cors(options),
16
- compression: (options) => compression(options),
17
- static: (root, options) => staticFiles(root, options),
18
- session: (options) => session(options),
19
- rateLimit: (options) => rateLimit(options),
20
- security: (options) => security(options),
21
- logger: (options) => logger(options),
22
-
23
- helmet: (options) => security(options),
24
-
25
- json: (options) => bodyParser({ ...options, type: 'json' }),
26
- urlencoded: (options) => bodyParser({ ...options, type: 'urlencoded' }),
27
- raw: (options) => bodyParser({ ...options, type: 'raw' }),
28
- text: (options) => bodyParser({ ...options, type: 'text' }),
29
-
30
- gzip: (options) => compression({ ...options, algorithm: 'gzip' }),
31
- deflate: (options) => compression({ ...options, algorithm: 'deflate' }),
32
- brotli: (options) => compression({ ...options, algorithm: 'br' }),
33
-
34
- basicAuth: (options) => {
35
- return async (ctx, next) => {
36
- const auth = ctx.get('authorization');
37
- if (!auth || !auth.startsWith('Basic ')) {
38
- ctx.set('WWW-Authenticate', 'Basic realm="Secure Area"');
39
- ctx.status(401).json({ error: 'Unauthorized' });
40
- return;
41
- }
42
-
43
- const credentials = Buffer.from(auth.slice(6), 'base64').toString();
44
- const [username, password] = credentials.split(':');
45
-
46
- if (options.users && options.users[username] === password) {
47
- ctx.user = { username };
48
- await next();
49
- } else if (options.verify && await options.verify(username, password)) {
50
- ctx.user = { username };
51
- await next();
52
- } else {
53
- ctx.set('WWW-Authenticate', 'Basic realm="Secure Area"');
54
- ctx.status(401).json({ error: 'Unauthorized' });
55
- }
56
- };
57
- },
58
-
59
- timeout: (ms) => {
60
- return async (ctx, next) => {
61
- const timeout = setTimeout(() => {
62
- if (!ctx.responded) {
63
- ctx.status(408).json({ error: 'Request Timeout' });
64
- }
65
- }, ms);
66
-
67
- try {
68
- await next();
69
- } finally {
70
- clearTimeout(timeout);
71
- }
72
- };
73
- },
74
-
75
- errorHandler: (handler) => {
76
- return async (ctx, next) => {
77
- try {
78
- await next();
79
- } catch (error) {
80
- if (handler) {
81
- await handler(error, ctx);
82
- } else {
83
- ctx.status(500).json({
84
- error: 'Internal Server Error',
85
- message: process.env.NODE_ENV === 'development' ? error.message : undefined
86
- });
87
- }
88
- }
89
- };
90
- },
91
-
92
- conditional: (condition, middleware) => {
93
- return async (ctx, next) => {
94
- if (typeof condition === 'function' ? condition(ctx) : condition) {
95
- await middleware(ctx, next);
96
- } else {
97
- await next();
98
- }
99
- };
100
- },
101
-
102
- compose: (...middlewares) => {
103
- return async (ctx, next) => {
104
- let index = 0;
105
-
106
- const dispatch = async (i) => {
107
- if (i >= middlewares.length) {
108
- return next();
109
- }
110
-
111
- const middleware = middlewares[i];
112
- return middleware(ctx, () => dispatch(i + 1));
113
- };
114
-
115
- return dispatch(0);
116
- };
117
- },
118
-
119
- unless: (condition, middleware) => {
120
- return async (ctx, next) => {
121
- if (typeof condition === 'function' ? !condition(ctx) : !condition) {
122
- await middleware(ctx, next);
123
- } else {
124
- await next();
125
- }
126
- };
127
- },
128
-
129
- skipIf: (condition) => {
130
- return async (ctx, next) => {
131
- if (typeof condition === 'function' ? condition(ctx) : condition) {
132
- await next();
133
- }
134
- };
135
- },
136
-
137
- cache: (options = {}) => {
138
- const { maxAge = 3600, private: isPrivate = false } = options;
139
-
140
- return async (ctx, next) => {
141
- await next();
142
-
143
- if (ctx.method === 'GET' && ctx.statusCode === 200) {
144
- const cacheControl = isPrivate ? 'private' : 'public';
145
- ctx.set('Cache-Control', `${cacheControl}, max-age=${maxAge}`);
146
- }
147
- };
148
- },
149
-
150
- etag: (options = {}) => {
151
- const crypto = require('crypto');
152
-
153
- return async (ctx, next) => {
154
- await next();
155
-
156
- if (ctx.method === 'GET' && ctx.statusCode === 200) {
157
- const body = ctx.res._getData ? ctx.res._getData() : '';
158
- const etag = crypto.createHash('md5').update(body).digest('hex');
159
-
160
- ctx.set('ETag', `"${etag}"`);
161
-
162
- if (ctx.get('if-none-match') === `"${etag}"`) {
163
- ctx.status(304).end();
164
- }
165
- }
166
- };
167
- },
168
-
169
- favicon: (path) => {
170
- const fs = require('fs');
171
- const favicon = fs.readFileSync(path);
172
-
173
- return async (ctx, next) => {
174
- if (ctx.path === '/favicon.ico') {
175
- ctx.set('Content-Type', 'image/x-icon');
176
- ctx.set('Cache-Control', 'public, max-age=86400');
177
- ctx.send(favicon);
178
- } else {
179
- await next();
180
- }
181
- };
182
- },
183
-
184
- responseTime: () => {
185
- return async (ctx, next) => {
186
- const start = Date.now();
187
- await next();
188
- const duration = Date.now() - start;
189
- ctx.set('X-Response-Time', `${duration}ms`);
190
- };
191
- },
192
-
193
- requestId: () => {
194
- const crypto = require('crypto');
195
-
196
- return async (ctx, next) => {
197
- const id = crypto.randomBytes(16).toString('hex');
198
- ctx.requestId = id;
199
- ctx.set('X-Request-ID', id);
200
- await next();
201
- };
202
- },
203
-
204
- healthCheck: (path = '/health') => {
205
- return async (ctx, next) => {
206
- if (ctx.path === path) {
207
- ctx.json({
208
- status: 'healthy',
209
- timestamp: new Date().toISOString(),
210
- uptime: process.uptime()
211
- });
212
- } else {
213
- await next();
214
- }
215
- };
216
- }
217
- };
218
- }
219
-
3
+ const crypto = require('crypto');
4
+ const bodyParser = require('../middleware/body-parser');
5
+ const cors = require('../middleware/cors');
6
+ const compression = require('../middleware/compression');
7
+ const staticFiles = require('../middleware/static');
8
+ const session = require('../middleware/session');
9
+ const rateLimit = require('../middleware/rate-limit');
10
+ const security = require('../middleware/security');
11
+ const logger = require('../middleware/logger');
12
+
13
+ function createMiddleware(_app) {
14
+ return {
15
+ bodyParser: (options) => bodyParser(options),
16
+ cors: (options) => cors(options),
17
+ compression: (options) => compression(options),
18
+ static: (root, options) => staticFiles(root, options),
19
+ session: (options) => session(options),
20
+ rateLimit: (options) => rateLimit(options),
21
+ security: (options) => security(options),
22
+ logger: (options) => logger(options),
23
+
24
+ helmet: (options) => security(options),
25
+
26
+ json: (options) => bodyParser({ ...options, type: 'json' }),
27
+ urlencoded: (options) => bodyParser({ ...options, type: 'urlencoded' }),
28
+ raw: (options) => bodyParser({ ...options, type: 'raw' }),
29
+ text: (options) => bodyParser({ ...options, type: 'text' }),
30
+
31
+ gzip: (options) => compression({ ...options, algorithm: 'gzip' }),
32
+ deflate: (options) => compression({ ...options, algorithm: 'deflate' }),
33
+ brotli: (options) => compression({ ...options, algorithm: 'br' }),
34
+
35
+ basicAuth: (options) => {
36
+ return async (ctx, next) => {
37
+ const auth = ctx.get('authorization');
38
+ if (!auth || !auth.startsWith('Basic ')) {
39
+ ctx.set('WWW-Authenticate', 'Basic realm="Secure Area"');
40
+ ctx.status(401).json({ error: 'Unauthorized' });
41
+ return;
42
+ }
43
+
44
+ const credentials = Buffer.from(auth.slice(6), 'base64').toString();
45
+ const [username, password] = credentials.split(':');
46
+
47
+ // SECURITY FIX (BUG-SEC-006): Prevent username enumeration via timing attacks
48
+ // Always perform the same operations regardless of username existence
49
+ let authenticated = false;
50
+
51
+ // Use a dummy password for timing-safe comparison when user doesn't exist
52
+ const dummyPassword = 'dummy_password_to_prevent_timing_attack_1234567890';
53
+
54
+ if (options.users) {
55
+ // Get the expected password (or dummy if user doesn't exist)
56
+ const expectedPassword = options.users[username] || dummyPassword;
57
+ const userExists = Object.prototype.hasOwnProperty.call(options.users, username);
58
+
59
+ try {
60
+ // SECURITY: Always perform timing-safe comparison, even for non-existent users
61
+ // This prevents timing attacks that could enumerate valid usernames
62
+ const maxLen = Math.max(password.length, expectedPassword.length);
63
+ const passwordBuf = Buffer.from(password.padEnd(maxLen, '\0'));
64
+ const expectedBuf = Buffer.from(expectedPassword.padEnd(maxLen, '\0'));
65
+
66
+ const passwordMatches = crypto.timingSafeEqual(passwordBuf, expectedBuf) &&
67
+ password.length === expectedPassword.length;
68
+
69
+ // Only set authenticated if BOTH user exists AND password matches
70
+ authenticated = userExists && passwordMatches;
71
+ } catch (err) {
72
+ // Length mismatch or other error - not authenticated
73
+ authenticated = false;
74
+ }
75
+ }
76
+
77
+ if (authenticated) {
78
+ ctx.user = { username };
79
+ await next();
80
+ } else if (options.verify) {
81
+ // SECURITY: Even with custom verify, perform dummy operation if needed
82
+ // to maintain constant timing
83
+ const verifyResult = await options.verify(username, password);
84
+ if (verifyResult) {
85
+ ctx.user = { username };
86
+ await next();
87
+ return;
88
+ }
89
+ }
90
+
91
+ // SECURITY: Add small random delay to further prevent timing attacks
92
+ // This makes it harder to measure timing differences
93
+ if (!authenticated) {
94
+ await new Promise(resolve => setTimeout(resolve, Math.random() * 10));
95
+ }
96
+
97
+ if (!authenticated) {
98
+ ctx.set('WWW-Authenticate', 'Basic realm="Secure Area"');
99
+ ctx.status(401).json({ error: 'Unauthorized' });
100
+ }
101
+ };
102
+ },
103
+
104
+ timeout: (ms) => {
105
+ return async (ctx, next) => {
106
+ const timeout = setTimeout(() => {
107
+ if (!ctx.responded) {
108
+ ctx.status(408).json({ error: 'Request Timeout' });
109
+ }
110
+ }, ms);
111
+
112
+ try {
113
+ await next();
114
+ } finally {
115
+ clearTimeout(timeout);
116
+ }
117
+ };
118
+ },
119
+
120
+ errorHandler: (handler) => {
121
+ return async (ctx, next) => {
122
+ try {
123
+ await next();
124
+ } catch (error) {
125
+ if (handler) {
126
+ await handler(error, ctx);
127
+ } else {
128
+ ctx.status(500).json({
129
+ error: 'Internal Server Error',
130
+ message: process.env.NODE_ENV === 'development' ? error.message : undefined
131
+ });
132
+ }
133
+ }
134
+ };
135
+ },
136
+
137
+ conditional: (condition, middleware) => {
138
+ return async (ctx, next) => {
139
+ if (typeof condition === 'function' ? condition(ctx) : condition) {
140
+ await middleware(ctx, next);
141
+ } else {
142
+ await next();
143
+ }
144
+ };
145
+ },
146
+
147
+ compose: (...middlewares) => {
148
+ return async (ctx, next) => {
149
+ const dispatch = async (i) => {
150
+ if (i >= middlewares.length) {
151
+ return next();
152
+ }
153
+
154
+ const middleware = middlewares[i];
155
+ return middleware(ctx, () => dispatch(i + 1));
156
+ };
157
+
158
+ return dispatch(0);
159
+ };
160
+ },
161
+
162
+ unless: (condition, middleware) => {
163
+ return async (ctx, next) => {
164
+ if (typeof condition === 'function' ? !condition(ctx) : !condition) {
165
+ await middleware(ctx, next);
166
+ } else {
167
+ await next();
168
+ }
169
+ };
170
+ },
171
+
172
+ skipIf: (condition) => {
173
+ return async (ctx, next) => {
174
+ if (typeof condition === 'function' ? condition(ctx) : condition) {
175
+ await next();
176
+ }
177
+ };
178
+ },
179
+
180
+ cache: (options = {}) => {
181
+ const { maxAge = 3600, private: isPrivate = false } = options;
182
+
183
+ return async (ctx, next) => {
184
+ await next();
185
+
186
+ if (ctx.method === 'GET' && ctx.statusCode === 200) {
187
+ const cacheControl = isPrivate ? 'private' : 'public';
188
+ ctx.set('Cache-Control', `${cacheControl}, max-age=${maxAge}`);
189
+ }
190
+ };
191
+ },
192
+
193
+ etag: (_options = {}) => {
194
+ const crypto = require('crypto');
195
+
196
+ return async (ctx, next) => {
197
+ // BUG FIX: Intercept response body to generate ETag
198
+ // The previous implementation used ctx.res._getData() which doesn't exist
199
+ // on real Node.js response objects (only in mock objects)
200
+
201
+ let responseBody = null;
202
+ const originalSend = ctx.send;
203
+ const originalJson = ctx.json;
204
+
205
+ // Intercept send() to capture body
206
+ ctx.send = function(data) {
207
+ responseBody = data;
208
+ return originalSend.call(this, data);
209
+ };
210
+
211
+ // Intercept json() to capture body
212
+ ctx.json = function(data) {
213
+ responseBody = JSON.stringify(data);
214
+ return originalJson.call(this, data);
215
+ };
216
+
217
+ await next();
218
+
219
+ // Generate ETag if we captured a body
220
+ if (ctx.method === 'GET' && ctx.statusCode === 200 && responseBody) {
221
+ const bodyStr = typeof responseBody === 'string' ? responseBody : String(responseBody);
222
+ // SECURITY: Use SHA-256 instead of MD5 for cryptographic strength
223
+ const etag = crypto.createHash('sha256').update(bodyStr).digest('hex').substring(0, 32);
224
+
225
+ ctx.set('ETag', `"${etag}"`);
226
+
227
+ // Check if client's ETag matches (conditional GET)
228
+ if (ctx.get('if-none-match') === `"${etag}"`) {
229
+ ctx.status(304).end();
230
+ }
231
+ }
232
+ };
233
+ },
234
+
235
+ favicon: (path) => {
236
+ // BUG FIX: Use async file reading to avoid blocking event loop
237
+ const fs = require('fs').promises;
238
+ let favicon = null;
239
+ let loading = null;
240
+
241
+ // Start loading favicon asynchronously
242
+ loading = fs.readFile(path).then(data => {
243
+ favicon = data;
244
+ loading = null;
245
+ }).catch(err => {
246
+ console.error('Failed to load favicon:', err.message);
247
+ loading = null;
248
+ });
249
+
250
+ return async (ctx, next) => {
251
+ if (ctx.path === '/favicon.ico') {
252
+ // Wait for favicon to load if still loading
253
+ if (loading) {
254
+ await loading;
255
+ }
256
+
257
+ if (favicon) {
258
+ ctx.set('Content-Type', 'image/x-icon');
259
+ ctx.set('Cache-Control', 'public, max-age=86400');
260
+ ctx.send(favicon);
261
+ } else {
262
+ ctx.status(404).send('Favicon not found');
263
+ }
264
+ } else {
265
+ await next();
266
+ }
267
+ };
268
+ },
269
+
270
+ responseTime: () => {
271
+ return async (ctx, next) => {
272
+ const start = Date.now();
273
+ await next();
274
+ const duration = Date.now() - start;
275
+ ctx.set('X-Response-Time', `${duration}ms`);
276
+ };
277
+ },
278
+
279
+ requestId: () => {
280
+ const crypto = require('crypto');
281
+
282
+ return async (ctx, next) => {
283
+ const id = crypto.randomBytes(16).toString('hex');
284
+ ctx.requestId = id;
285
+ ctx.set('X-Request-ID', id);
286
+ await next();
287
+ };
288
+ },
289
+
290
+ healthCheck: (path = '/health') => {
291
+ return async (ctx, next) => {
292
+ if (ctx.path === path) {
293
+ ctx.json({
294
+ status: 'healthy',
295
+ timestamp: new Date().toISOString(),
296
+ uptime: process.uptime()
297
+ });
298
+ } else {
299
+ await next();
300
+ }
301
+ };
302
+ }
303
+ };
304
+ }
305
+
220
306
  module.exports = { createMiddleware };