@oxog/spark 1.1.0 → 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 -293
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1070 -956
  6. package/src/core/context.js +1100 -830
  7. package/src/core/middleware.js +305 -217
  8. package/src/index.js +183 -278
  9. package/src/middleware/body-parser.js +484 -526
  10. package/src/middleware/cache.js +179 -170
  11. package/src/middleware/compression.js +179 -182
  12. package/src/middleware/cors.js +178 -95
  13. package/src/middleware/health.js +221 -218
  14. package/src/middleware/logger.js +197 -194
  15. package/src/middleware/metrics.js +341 -327
  16. package/src/middleware/rate-limit.js +369 -319
  17. package/src/middleware/security.js +444 -332
  18. package/src/middleware/session.js +649 -529
  19. package/src/middleware/static.js +406 -299
  20. package/src/router/layer.js +199 -117
  21. package/src/router/route.js +151 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +147 -144
  24. package/src/utils/context-pool.js +85 -82
  25. package/src/utils/regex-validator.js +189 -176
  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 -957
  31. package/dist/core/context.js +0 -831
  32. package/dist/core/middleware.js +0 -218
  33. package/dist/core/request.js +0 -333
  34. package/dist/core/response.js +0 -375
  35. package/dist/index.js +0 -278
  36. package/dist/middleware/body-parser.js +0 -526
  37. package/dist/middleware/cache.js +0 -171
  38. package/dist/middleware/compression.js +0 -183
  39. package/dist/middleware/cors.js +0 -95
  40. package/dist/middleware/health.js +0 -219
  41. package/dist/middleware/index.js +0 -21
  42. package/dist/middleware/logger.js +0 -195
  43. package/dist/middleware/metrics.js +0 -328
  44. package/dist/middleware/rate-limit.js +0 -320
  45. package/dist/middleware/security.js +0 -333
  46. package/dist/middleware/session.js +0 -530
  47. package/dist/middleware/static.js +0 -299
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -117
  50. package/dist/router/route.js +0 -123
  51. package/dist/router/router.js +0 -756
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -145
  54. package/dist/utils/cache.js +0 -441
  55. package/dist/utils/context-pool.js +0 -83
  56. package/dist/utils/error-types.js +0 -132
  57. package/dist/utils/http.js +0 -413
  58. package/dist/utils/regex-validator.js +0 -177
  59. package/src/core/request.js +0 -333
  60. package/src/core/response.js +0 -375
  61. package/src/middleware/index.js +0 -21
  62. package/src/utils/cache.js +0 -441
  63. package/src/utils/error-types.js +0 -132
  64. package/src/utils/http.js +0 -413
@@ -1,218 +1,306 @@
1
- const bodyParser = require('../middleware/body-parser');
2
- const cors = require('../middleware/cors');
3
- const compression = require('../middleware/compression');
4
- const staticFiles = require('../middleware/static');
5
- const session = require('../middleware/session');
6
- const rateLimit = require('../middleware/rate-limit');
7
- const security = require('../middleware/security');
8
- const logger = require('../middleware/logger');
9
-
10
- function createMiddleware(app) {
11
- return {
12
- bodyParser: (options) => bodyParser(options),
13
- cors: (options) => cors(options),
14
- compression: (options) => compression(options),
15
- static: (root, options) => staticFiles(root, options),
16
- session: (options) => session(options),
17
- rateLimit: (options) => rateLimit(options),
18
- security: (options) => security(options),
19
- logger: (options) => logger(options),
20
-
21
- helmet: (options) => security(options),
22
-
23
- json: (options) => bodyParser({ ...options, type: 'json' }),
24
- urlencoded: (options) => bodyParser({ ...options, type: 'urlencoded' }),
25
- raw: (options) => bodyParser({ ...options, type: 'raw' }),
26
- text: (options) => bodyParser({ ...options, type: 'text' }),
27
-
28
- gzip: (options) => compression({ ...options, algorithm: 'gzip' }),
29
- deflate: (options) => compression({ ...options, algorithm: 'deflate' }),
30
- brotli: (options) => compression({ ...options, algorithm: 'br' }),
31
-
32
- basicAuth: (options) => {
33
- return async (ctx, next) => {
34
- const auth = ctx.get('authorization');
35
- if (!auth || !auth.startsWith('Basic ')) {
36
- ctx.set('WWW-Authenticate', 'Basic realm="Secure Area"');
37
- ctx.status(401).json({ error: 'Unauthorized' });
38
- return;
39
- }
40
-
41
- const credentials = Buffer.from(auth.slice(6), 'base64').toString();
42
- const [username, password] = credentials.split(':');
43
-
44
- if (options.users && options.users[username] === password) {
45
- ctx.user = { username };
46
- await next();
47
- } else if (options.verify && await options.verify(username, password)) {
48
- ctx.user = { username };
49
- await next();
50
- } else {
51
- ctx.set('WWW-Authenticate', 'Basic realm="Secure Area"');
52
- ctx.status(401).json({ error: 'Unauthorized' });
53
- }
54
- };
55
- },
56
-
57
- timeout: (ms) => {
58
- return async (ctx, next) => {
59
- const timeout = setTimeout(() => {
60
- if (!ctx.responded) {
61
- ctx.status(408).json({ error: 'Request Timeout' });
62
- }
63
- }, ms);
64
-
65
- try {
66
- await next();
67
- } finally {
68
- clearTimeout(timeout);
69
- }
70
- };
71
- },
72
-
73
- errorHandler: (handler) => {
74
- return async (ctx, next) => {
75
- try {
76
- await next();
77
- } catch (error) {
78
- if (handler) {
79
- await handler(error, ctx);
80
- } else {
81
- ctx.status(500).json({
82
- error: 'Internal Server Error',
83
- message: process.env.NODE_ENV === 'development' ? error.message : undefined
84
- });
85
- }
86
- }
87
- };
88
- },
89
-
90
- conditional: (condition, middleware) => {
91
- return async (ctx, next) => {
92
- if (typeof condition === 'function' ? condition(ctx) : condition) {
93
- await middleware(ctx, next);
94
- } else {
95
- await next();
96
- }
97
- };
98
- },
99
-
100
- compose: (...middlewares) => {
101
- return async (ctx, next) => {
102
- let index = 0;
103
-
104
- const dispatch = async (i) => {
105
- if (i >= middlewares.length) {
106
- return next();
107
- }
108
-
109
- const middleware = middlewares[i];
110
- return middleware(ctx, () => dispatch(i + 1));
111
- };
112
-
113
- return dispatch(0);
114
- };
115
- },
116
-
117
- unless: (condition, middleware) => {
118
- return async (ctx, next) => {
119
- if (typeof condition === 'function' ? !condition(ctx) : !condition) {
120
- await middleware(ctx, next);
121
- } else {
122
- await next();
123
- }
124
- };
125
- },
126
-
127
- skipIf: (condition) => {
128
- return async (ctx, next) => {
129
- if (typeof condition === 'function' ? condition(ctx) : condition) {
130
- await next();
131
- }
132
- };
133
- },
134
-
135
- cache: (options = {}) => {
136
- const { maxAge = 3600, private: isPrivate = false } = options;
137
-
138
- return async (ctx, next) => {
139
- await next();
140
-
141
- if (ctx.method === 'GET' && ctx.statusCode === 200) {
142
- const cacheControl = isPrivate ? 'private' : 'public';
143
- ctx.set('Cache-Control', `${cacheControl}, max-age=${maxAge}`);
144
- }
145
- };
146
- },
147
-
148
- etag: (options = {}) => {
149
- const crypto = require('crypto');
150
-
151
- return async (ctx, next) => {
152
- await next();
153
-
154
- if (ctx.method === 'GET' && ctx.statusCode === 200) {
155
- const body = ctx.res._getData ? ctx.res._getData() : '';
156
- const etag = crypto.createHash('md5').update(body).digest('hex');
157
-
158
- ctx.set('ETag', `"${etag}"`);
159
-
160
- if (ctx.get('if-none-match') === `"${etag}"`) {
161
- ctx.status(304).end();
162
- }
163
- }
164
- };
165
- },
166
-
167
- favicon: (path) => {
168
- const fs = require('fs');
169
- const favicon = fs.readFileSync(path);
170
-
171
- return async (ctx, next) => {
172
- if (ctx.path === '/favicon.ico') {
173
- ctx.set('Content-Type', 'image/x-icon');
174
- ctx.set('Cache-Control', 'public, max-age=86400');
175
- ctx.send(favicon);
176
- } else {
177
- await next();
178
- }
179
- };
180
- },
181
-
182
- responseTime: () => {
183
- return async (ctx, next) => {
184
- const start = Date.now();
185
- await next();
186
- const duration = Date.now() - start;
187
- ctx.set('X-Response-Time', `${duration}ms`);
188
- };
189
- },
190
-
191
- requestId: () => {
192
- const crypto = require('crypto');
193
-
194
- return async (ctx, next) => {
195
- const id = crypto.randomBytes(16).toString('hex');
196
- ctx.requestId = id;
197
- ctx.set('X-Request-ID', id);
198
- await next();
199
- };
200
- },
201
-
202
- healthCheck: (path = '/health') => {
203
- return async (ctx, next) => {
204
- if (ctx.path === path) {
205
- ctx.json({
206
- status: 'healthy',
207
- timestamp: new Date().toISOString(),
208
- uptime: process.uptime()
209
- });
210
- } else {
211
- await next();
212
- }
213
- };
214
- }
215
- };
216
- }
217
-
1
+ 'use strict';
2
+
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
+
218
306
  module.exports = { createMiddleware };