@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
package/CHANGELOG.md CHANGED
@@ -1,294 +1,633 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file.
4
-
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
-
8
- ## [1.1.1] - 2025-07-17
9
-
10
- ### ๐Ÿ”ง Production Validation & Bug Fixes
11
-
12
- #### Fixed
13
- - **Router Middleware Bug**: Fixed critical bug where Route HTTP methods only accepted single handlers instead of multiple handlers for middleware composition
14
- - Updated all HTTP methods (get, post, put, delete, etc.) to accept rest parameters (...handlers)
15
- - Fixed middleware chain execution for route-specific middleware
16
- - Ensured proper request flow through middleware stack
17
- - **Session Auto-Save**: Fixed session authentication issues where sessions were being saved after response was sent
18
- - Implemented auto-save functionality in session proxy
19
- - Session data now saves immediately when modified
20
- - Session cookies are set properly during the request lifecycle
21
- - **Port Handling**: Fixed port 0 handling for dynamic port allocation
22
- - Changed from falsy check to explicit undefined check
23
- - Enables proper testing with dynamic port assignment
24
- - **Memory Leak Prevention**: Fixed EventEmitter memory leak warnings in validation tests
25
- - Increased max listeners limit for test environments
26
- - Optimized test iteration counts to prevent memory buildup
27
-
28
- #### Added
29
- - **Complete Production Pipeline**: Comprehensive validation and release preparation system
30
- - 20+ validation checks covering all aspects of production readiness
31
- - Automated testing for all 4 example applications
32
- - Performance benchmarking (4000+ req/sec validated)
33
- - Security vulnerability scanning
34
- - Package size optimization (reduced from 236KB to 65KB)
35
- - Memory leak detection and prevention
36
- - Cross-platform compatibility testing
37
- - **Enhanced Test Coverage**: Achieved 100% test success rate across all components
38
- - Complete test suite for all example applications
39
- - Integration tests for ecommerce API with session authentication
40
- - Unit tests for all middleware components
41
- - Performance and stress testing
42
- - **TypeScript Definitions**: Cleaned and optimized TypeScript definitions
43
- - Self-contained definitions without Node.js dependencies
44
- - Accurate interfaces matching actual implementation
45
- - Fixed method signatures (setCookie vs cookie)
46
- - Enhanced SessionOptions and RateLimitOptions interfaces
47
-
48
- #### Changed
49
- - **Documentation Overhaul**: Completely rewrote all documentation from scratch
50
- - Clean, modern README.md with focused feature highlights
51
- - Comprehensive API Reference with detailed examples
52
- - Step-by-step Getting Started guide with complete tutorials
53
- - Extensive Middleware Guide with advanced patterns and best practices
54
- - Removed unnecessary debug and temporary documentation files
55
- - **Package Optimization**: Streamlined package contents
56
- - Removed debug files and temporary validation artifacts
57
- - Cleaned up development-only files
58
- - Optimized bundle size for production deployment
59
-
60
- #### Improved
61
- - **Error Handling**: Enhanced error messages and validation feedback
62
- - **Performance**: Optimized request handling and middleware execution
63
- - **Security**: Validated all security features are working correctly
64
- - **Reliability**: Extensive testing ensures production-ready stability
65
-
66
- ---
67
-
68
- ## [1.1.0] - 2025-07-16
69
-
70
- ### ๐Ÿ”’ Security Enhancements
71
-
72
- #### Added
73
- - **Path Traversal Protection**: Comprehensive protection against directory traversal attacks in static file middleware
74
- - URL normalization and validation
75
- - Path containment verification
76
- - Malformed URL error handling
77
- - **ReDoS Protection**: Regular Expression Denial of Service protection
78
- - SafeRegexCache with performance testing
79
- - RegexValidator for pattern complexity analysis
80
- - Automatic pattern sanitization for unsafe expressions
81
- - **Header/Cookie Injection Protection**: Prevention of CRLF injection attacks
82
- - Header value validation against null bytes and CRLF characters
83
- - Cookie value sanitization
84
- - Header length limits (8192 characters max)
85
- - **Enhanced Input Validation**: Improved parameter and URL validation throughout the framework
86
-
87
- ### ๐Ÿ›ก๏ธ Memory Management & Performance
88
-
89
- #### Added
90
- - **Memory Leak Protection**: Comprehensive cleanup mechanisms
91
- - Automatic interval cleanup during shutdown
92
- - Cleanup handler registration system
93
- - Graceful shutdown with timeout handling
94
- - **Object Pooling**: Context object reuse for better memory efficiency
95
- - Context.init() and Context.reset() methods
96
- - Reduced garbage collection pressure
97
- - **Buffer Optimizations**: Enhanced memory usage in request handling
98
- - Stream processing improvements
99
- - Optimized string operations
100
-
101
- ### ๐Ÿšจ Error Handling Improvements
102
-
103
- #### Added
104
- - **Advanced Error Handler**: Comprehensive error handling system
105
- - Custom error types with status codes
106
- - AsyncHandler for automatic promise error catching
107
- - Structured error responses with proper HTTP status codes
108
- - Development vs production error detail handling
109
- - **Common HTTP Errors**: Pre-defined error creators
110
- - BadRequest, Unauthorized, Forbidden, NotFound
111
- - MethodNotAllowed, Conflict, TooManyRequests
112
- - InternalServerError, ServiceUnavailable, etc.
113
-
114
- #### Fixed
115
- - **Error Propagation**: Proper error handling through middleware chain
116
- - **Response Formatting**: Consistent error response structure
117
- - **Status Code Handling**: Correct HTTP status codes for different error types
118
-
119
- ### ๐Ÿ”ง Framework Enhancements
120
-
121
- #### Added
122
- - **Enhanced Router**: Improved routing capabilities
123
- - Better path parameter extraction
124
- - Improved route matching performance
125
- - Support for router mounting with path prefixes
126
- - **Middleware Improvements**: Enhanced middleware system
127
- - Better error handling in middleware chain
128
- - Cleanup handler support for middleware
129
- - Improved middleware execution flow
130
-
131
- #### Fixed
132
- - **Case Sensitivity**: Fixed HTTP method handling case sensitivity issues
133
- - **Route Parameters**: Improved parameter extraction and URL decoding
134
- - **Router Mounting**: Fixed app.use() with router and path prefix functionality
135
-
136
- ### ๐Ÿ“ฆ TypeScript & API Improvements
137
-
138
- #### Added
139
- - **Enhanced Type Definitions**: Improved TypeScript support
140
- - Better generic type constraints
141
- - More precise interface definitions
142
- - Enhanced IDE autocomplete support
143
-
144
- ### ๐Ÿงช Testing & Quality
145
-
146
- #### Added
147
- - **Comprehensive Integration Tests**: Full framework testing suite
148
- - Security feature testing
149
- - Memory leak testing
150
- - Error handling validation
151
- - Performance testing
152
- - CORS and middleware testing
153
-
154
- #### Fixed
155
- - **Test Suite**: Stable and reliable testing framework
156
- - **Error Test Coverage**: Complete error handling test coverage
157
-
158
- ### ๐Ÿ”„ Developer Experience
159
-
160
- #### Changed
161
- - **Package.json**: Updated scripts and metadata
162
- - Version bump to 1.1.0
163
- - Updated description highlighting security features
164
- - Added security-related keywords
165
- - Updated test scripts
166
- - **Documentation**: Enhanced code documentation
167
- - Comprehensive JSDoc comments
168
- - Security feature documentation
169
- - API usage examples
170
-
171
- ### ๐Ÿ—๏ธ Internal Improvements
172
-
173
- #### Added
174
- - **Graceful Shutdown**: Proper application shutdown handling
175
- - Signal handling (SIGTERM, SIGINT, SIGBREAK)
176
- - Cleanup handler execution
177
- - Connection draining
178
- - **Error Logging**: Enhanced error logging with context
179
- - **Development Mode**: Better development experience with detailed error reporting
180
-
181
- #### Changed
182
- - **Code Organization**: Improved file structure and module organization
183
- - **Performance Optimizations**: Various micro-optimizations throughout the codebase
184
-
185
- ---
186
-
187
- ## [1.0.0] - 2025-07-15
188
-
189
- ### ๐ŸŽ‰ Initial Release as @oxog/spark
190
-
191
- #### Added
192
- - โœจ Production-ready with comprehensive test suite (434+ tests)
193
- - ๐Ÿ›ก๏ธ Security hardened with OWASP Top 10 compliance
194
- - โšก Blazing fast performance (42,000+ req/sec)
195
- - ๐Ÿ“ Complete TypeScript definitions
196
- - ๐ŸŽฏ Zero dependencies - built on Node.js core
197
- - ๐Ÿ”’ Secure defaults (CORS disabled, CSRF enabled)
198
- - ๐Ÿ’พ Multiple session stores (Memory, File)
199
- - ๐Ÿšฆ Advanced rate limiting strategies
200
- - ๐Ÿ—œ๏ธ Built-in compression support
201
- - ๐Ÿ“Š Comprehensive middleware suite
202
- - ๐Ÿ”ง Developer-friendly with hot reload
203
- - ๐Ÿ“ˆ Production monitoring ready
204
-
205
- #### Security
206
- - ๐Ÿ” Removed all hardcoded secrets
207
- - ๐Ÿ›ก๏ธ Fixed path traversal vulnerabilities
208
- - ๐Ÿ”’ Enhanced CSRF protection
209
- - โœ… Input validation on all user inputs
210
- - ๐Ÿšซ Secure session management
211
-
212
- #### Performance
213
- - ๐Ÿ’จ Sub-millisecond latency (p50: 0.8ms)
214
- - ๐Ÿš€ High throughput (42K+ requests/second)
215
- - ๐Ÿ’พ Low memory footprint (38MB baseline)
216
- - ๐Ÿ“‰ Efficient per-connection memory (<0.1KB)
217
-
218
- #### Developer Experience
219
- - ๐Ÿ› ๏ธ Complete build tooling
220
- - ๐Ÿ“‹ ESLint configuration
221
- - ๐Ÿ“ Comprehensive documentation
222
- - ๐Ÿ’ก Working examples (e-commerce API)
223
- - ๐Ÿงช Extensive test coverage (98.7%)
224
-
225
- ---
226
-
227
- ## Security Advisories
228
-
229
- ### [1.1.0] Security Improvements
230
- - **CVE-2024-SPARK-001**: Fixed path traversal vulnerability in static middleware
231
- - **CVE-2024-SPARK-002**: Added ReDoS protection for regex operations
232
- - **CVE-2024-SPARK-003**: Prevented header/cookie injection attacks
233
- - **CVE-2024-SPARK-004**: Enhanced input validation across all components
234
-
235
- ### Recommendations
236
- - **Upgrade immediately** from version 1.0.0 to 1.1.0 for security fixes
237
- - **Review configurations** to ensure security features are properly enabled
238
- - **Test applications** with the new security features enabled
239
- - **Monitor logs** for any security-related events
240
-
241
- ---
242
-
243
- ## Migration Guide
244
-
245
- ### From 1.0.0 to 1.1.0
246
-
247
- #### Breaking Changes
248
- - None. Version 1.1.0 is fully backward compatible with 1.0.0
249
-
250
- #### New Features Available
251
- 1. **Enhanced Error Handling**:
252
- ```javascript
253
- const { errorHandling } = require('@oxog/spark');
254
-
255
- // Use async handler for automatic error catching
256
- app.get('/users/:id', errorHandling.asyncHandler(async (ctx) => {
257
- const user = await findUser(ctx.params.id);
258
- if (!user) {
259
- throw errorHandling.errors.notFound('User not found');
260
- }
261
- ctx.json(user);
262
- }));
263
- ```
264
-
265
- 2. **Security Features** (automatically enabled):
266
- - Path traversal protection in static middleware
267
- - ReDoS protection in routing
268
- - Header injection protection
269
- - Memory leak protection
270
-
271
- 3. **Graceful Shutdown**:
272
- ```javascript
273
- app.onShutdown(async () => {
274
- await database.close();
275
- console.log('Database connection closed');
276
- });
277
- ```
278
-
279
- #### Recommended Actions
280
- 1. Update package.json to version 1.1.0
281
- 2. Review error handling and consider using new asyncHandler
282
- 3. Test security features in your environment
283
- 4. Add graceful shutdown handlers for your resources
284
-
285
- ---
286
-
287
- ### Links
288
- - ๐Ÿ“ฆ NPM: https://www.npmjs.com/package/@oxog/spark
289
- - ๐Ÿ™ GitHub: https://github.com/ersinkoc/spark
290
- - ๐Ÿ“š Documentation: https://github.com/ersinkoc/spark/tree/main/docs
291
-
292
- ---
293
-
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.2.0] - 2026-11-30
9
+
10
+ This release includes the changes listed under 1.1.2, which was never published
11
+ to npm (the last published version is 1.1.1). The test and coverage figures
12
+ quoted for 1.1.2 came from scripts that printed fixed results; this release
13
+ replaces them with a real test suite (145 tests against real HTTP servers,
14
+ enforced coverage thresholds).
15
+
16
+ ### Fixed
17
+
18
+ - **Routing**: any `router.use(fn)` middleware broke every route registered after it
19
+ (the router overwrote `ctx.path` with the matched prefix), so `router.group()` never
20
+ matched either. Middleware mounted with `router.use(path, fn)` now sees the path
21
+ below the prefix, and later layers see the full path.
22
+ - **Routing**: `HEAD` requests to `GET` routes returned 404; they are now answered by
23
+ the `GET` handlers (without a body).
24
+ - **Routing**: `app.use('/api', ...)` and `router.use('/api', ...)` also matched
25
+ `/apiary`; prefixes now match whole path segments.
26
+ - **Routing**: after a handler threw, later matching routes still ran (and could answer
27
+ 200); errors now skip the remaining layers and reach the error handler.
28
+ - **Routing**: malformed percent-encoding in a route parameter (`/users/%E0%A4%A`)
29
+ answered 500; it now answers 400.
30
+ - **Routing**: `router.get()`/`post()`/... returned a `Route`, so chaining
31
+ `router.get(a, h).get(b, h)` threw; they now return the router, as the type
32
+ definitions already said. Routes registered with a trailing slash (`/a/`) now also
33
+ match `/a` unless the router is strict.
34
+ - **Routing**: `app.options(path, handler)` and `router.options(path, handler)` threw
35
+ `TypeError` because the `options` configuration property hid the method; both work
36
+ now and `app.options.port` etc. still read the configuration.
37
+ - **Requests**: a request whose Host header cannot form a URL never got a response
38
+ (and caused an unhandled rejection); it now gets 400.
39
+ - **Errors**: an error whose `status` is not a valid 4xx/5xx code left the request
40
+ hanging; it now answers 500.
41
+ - **Body parser**: errors thrown by later middleware or handlers were caught and
42
+ answered as `400 Bad Request` with the internal error message; they now reach the
43
+ application error handler (500, message hidden in production).
44
+ - **Body parser**: `bodyParser.json()` (and the other fixed-type parsers) rejected every
45
+ bodiless `POST`/`DELETE` and every request of another content type with 400; they now
46
+ skip requests without a body or with a different Content-Type.
47
+ - **Body parser**: `limit` given as a string (`'10kb'`, as the type definitions allow)
48
+ was ignored, so no limit applied; size strings are now parsed.
49
+ - **Body parser**: chunked bodies over the limit answered 400 (multipart/raw reset the
50
+ connection); every oversized body now answers 413 and closes the connection.
51
+ - **Body parser**: multipart uploads corrupted binary files (bytes >= 0x80 were
52
+ re-encoded as UTF-8) and mangled non-ASCII field values; files are now byte-exact and
53
+ fields are decoded as UTF-8. Part headers are matched case-insensitively.
54
+ - **Body parser**: the documented `inflate` option was not implemented; gzip, deflate
55
+ and br request bodies are now decompressed, with the size limit applied after
56
+ decompression (other encodings answer 415).
57
+ - **Static files**: files inside dot-directories were served (`/.git/config`,
58
+ `/.ssh/id_rsa`); every path segment is now checked against the `dotfiles` policy.
59
+ - **Static files**: Range requests answered 200 without `Content-Range`; they now
60
+ answer 206 with correct headers, and unsatisfiable ranges answer 416.
61
+ - **Static files**: files were read fully into memory; they are now streamed with
62
+ backpressure, and client disconnects destroy the file stream.
63
+ - **Rate limiting**: the window never reset, so a client that reached `max` was blocked
64
+ until the process restarted; `X-RateLimit-Reset` was always "now" and `Retry-After`
65
+ was the full window. All three are fixed. The documented `skip` option now works.
66
+ - **CSRF**: tokens were not bound to the client (every token was valid for every user)
67
+ and a token sent only as a cookie was accepted, which browsers attach to cross-site
68
+ requests. Each client now gets its own secret (in the session, or in an HttpOnly
69
+ SameSite=Strict `_csrf` cookie) and tokens are only read from the `x-csrf-token`
70
+ header or `_csrf` body field. Use `ctx.csrfToken()` to issue tokens.
71
+ - **CORS**: responses whose `Access-Control-Allow-Origin` depends on the request did not
72
+ send `Vary: Origin` (shared caches could serve one origin's response to another);
73
+ `origin: true` with `credentials: true` failed every request with 500 instead of
74
+ failing at setup; `origin: true` logged a warning on every request; a function origin
75
+ returning `true` sent `Access-Control-Allow-Origin: true`; all OPTIONS requests were
76
+ swallowed even when not preflights.
77
+ - **Compression**: never compressed `GET` responses (it read the request's
78
+ Content-Type); `compression.gzip()` could send Brotli; `Vary` replaced `Vary: Origin`.
79
+ - **Sessions**: passing any `cookie` option (e.g. `{ maxAge }`) dropped the default
80
+ `HttpOnly`, `SameSite=Lax` and `Path=/` flags, making the session cookie readable by
81
+ scripts. The defaults are now kept.
82
+ - **Sessions**: `MemoryStore` timers kept the process alive for up to `maxAge` (24 h by
83
+ default) after `close()`, and a `maxAge` above ~24.8 days expired sessions
84
+ immediately. Timers are unref'd and capped; expiry is checked on read.
85
+ - **Sessions**: a failing store left the request hanging with an unhandled rejection;
86
+ it now answers 500. `destroy()` clears the cookie with the session cookie's path.
87
+ - **Cookies**: `maxAge` is documented in milliseconds but was sent as `Max-Age` seconds
88
+ unchanged (a "1 hour" cookie lived 41 days); it is now converted to seconds.
89
+ `clearCookie()` now sends `Max-Age=0`.
90
+ - **Redirects**: protocol-relative (`//evil.com`) and backslash (`/\evil.com`) targets
91
+ bypassed the external-redirect check; the `settings` option documented for
92
+ `allowedRedirectDomains`/`allowOpenRedirects`/`trustProxy` was never read, so external
93
+ redirects were impossible to allow. Redirects to the request's own host (http -> https)
94
+ are allowed.
95
+ - **Shutdown**: `close()` left a 10-second timer that kept the process alive, did not
96
+ close idle keep-alive connections on older Node versions, and never terminated hung
97
+ requests. It now closes idle connections immediately, lets in-flight requests finish
98
+ (answering with `Connection: close`), and destroys what is left after
99
+ `shutdownTimeout` (default 10 s).
100
+ - **Process handlers**: every `new Spark()` added `uncaughtException`,
101
+ `unhandledRejection`, `SIGTERM` and `SIGINT` listeners that were never removed, and an
102
+ uncaught exception exited with code 0. Handlers are now installed by `listen()`,
103
+ removed by `close()`, and an uncaught exception exits with code 1.
104
+ - **ESM**: `import { bodyParser, cors, ... } from '@oxog/spark'` failed for everything
105
+ except `Spark`, `App`, `Application`, `Router` and `Context`; all exports are now
106
+ available as named imports.
107
+ - **Types**: the declarations were not resolvable through `exports` (TypeScript
108
+ reported "implicitly has an 'any' type" under `moduleResolution: node16/nodenext`),
109
+ were an ambient `declare module` block, and described a different API in places
110
+ (`listen()` returning a Promise, `createError(status, message)`, missing `static`).
111
+ They are rewritten to match the runtime.
112
+ - **Logger**: hyphenated tokens (`:response-time`, `:content-length`, `:remote-addr`)
113
+ were never replaced, so the default format printed `--time ms`; `:content-length`
114
+ now reports the response length.
115
+ - **Cache middleware**: cached the request body instead of the response, so nothing was
116
+ ever cached; the default store was an unbounded Map. It now caches sent responses
117
+ (not ones that set cookies or are private) in a bounded store.
118
+ - **Health/metrics**: custom health check timeout timers were never cleared; metrics
119
+ tracked unlimited distinct paths (now capped at 1000 plus `(other)`).
120
+ - **errorHandling.errorHandler** sent 5xx messages and stack traces unless
121
+ `NODE_ENV=production`; it now follows the application rule (only in development).
122
+
123
+ ### Added
124
+
125
+ - `ctx.stream(readable)` pipes a stream as the response with backpressure.
126
+ - Application options `settings`, `shutdownTimeout` and `handleSignals`.
127
+ - Top-level exports `csrf`, `csrfToken`, `serveStatic`, `cache`, `asyncHandler`,
128
+ `createError`, `errors` and `version`.
129
+ - `compression({ encodings })`, `staticFiles({ dotfiles: 'allow' | 'deny' | 'ignore' })`,
130
+ `If-Modified-Since` support, RegExp entries in `cors({ origin: [...] })`.
131
+
132
+ ### Changed
133
+
134
+ - The constructor no longer pretends to configure security: the `security` option
135
+ (CORS, CSRF, rate limit, helmet "secure defaults") was never applied and has been
136
+ removed from the documented defaults. Register the middleware with `app.use()`.
137
+ - `app.use()` throws a `TypeError` for arguments that are neither middleware nor a
138
+ router (they were silently ignored).
139
+ - `ctx.redirect()` only redirects to other hosts over http/https (`mailto:` and other
140
+ schemes are refused).
141
+ - The CSRF `_csrf` cookie now holds the client secret, not a token.
142
+ - Static files are sent with `charset=utf-8` for text types, `Accept-Ranges: bytes`,
143
+ and directory redirects keep the mount path.
144
+ - Malformed cookies are no longer logged with `console.error` for every request.
145
+ - Removed modules that were never reachable through the package `exports`
146
+ (`core/request.js`, `core/response.js`, `utils/http.js`, `utils/cache.js`,
147
+ `utils/error-types.js`, `middleware/index.js`) and the stale `dist/` copy that 1.1.1
148
+ shipped.
149
+
150
+ ### Tooling
151
+
152
+ - Real test suite (Vitest, real HTTP requests on ephemeral ports) with enforced coverage
153
+ thresholds; ESLint over `src`, `tests` and `scripts`; TypeScript checks of the
154
+ declarations and README examples; `npm run test:package` packs the archive, installs
155
+ it and imports/type-checks it under ESM, CommonJS and NodeNext.
156
+ - CI on Node 18-24; npm publishing moved to a manual trusted-publishing workflow.
157
+
158
+ ## [1.1.2] - 2025-11-17
159
+
160
+ ### ๐Ÿ”’ Major Security Release - 16 Critical Bug Fixes
161
+
162
+ This release addresses **16 security vulnerabilities and critical bugs** identified through comprehensive repository analysis. All CRITICAL and HIGH priority issues have been resolved.
163
+
164
+ #### ๐Ÿ”ด CRITICAL Security Fixes (5)
165
+
166
+ - **[SECURITY]** Replaced MD5 with SHA-256 for ETag generation to prevent hash collision attacks
167
+ - Files: `src/middleware/static.js`, `src/core/middleware.js`
168
+ - Impact: Prevents cache poisoning via collision attacks
169
+
170
+ - **[SECURITY]** Added JSON parsing depth and size limits to prevent DoS attacks
171
+ - New utility: `src/utils/safe-json.js`
172
+ - Files: `src/core/request.js`, `src/middleware/body-parser.js`
173
+ - Limits: Maximum 20 nesting levels, 1MB-10MB configurable size
174
+ - Impact: Prevents memory exhaustion and CPU DoS via deeply nested JSON
175
+
176
+ - **[SECURITY]** Added query string size limits and prototype pollution protection
177
+ - File: `src/utils/http.js`
178
+ - Limit: 1MB maximum query string size
179
+ - Protection: Null-prototype objects, blocked `__proto__`, `constructor`, `prototype` keys
180
+ - Impact: Prevents memory exhaustion DoS and prototype pollution attacks
181
+
182
+ - **[BUG]** Fixed division by zero in metrics calculation
183
+ - File: `src/middleware/metrics.js`
184
+ - Impact: Prevents Infinity/NaN when metrics accessed immediately after startup
185
+
186
+ - **[BUG]** Fixed LRU eviction logic in rate limiter (was using FIFO instead of LRU)
187
+ - File: `src/middleware/rate-limit.js`
188
+ - Impact: Prevents memory leaks and improves cache efficiency
189
+
190
+ #### ๐ŸŸ  HIGH Priority Fixes (4)
191
+
192
+ - **[BUG]** Fixed cache middleware not sending responses (complete feature failure)
193
+ - File: `src/middleware/cache.js`
194
+ - Impact: Cache middleware now functional - previously cached responses were never sent to clients
195
+
196
+ - **[SECURITY]** Fixed timing attack in basic authentication
197
+ - File: `src/core/middleware.js`
198
+ - Uses `crypto.timingSafeEqual()` for constant-time password comparison
199
+ - Impact: Prevents character-by-character password enumeration via timing side-channel
200
+
201
+ - **[BUG]** Fixed session save race condition
202
+ - File: `src/middleware/session.js`
203
+ - Added mutex flag (`isSaving`) to prevent concurrent saves
204
+ - Impact: Prevents session data loss from rapid property modifications
205
+
206
+ - **[BUG]** Fixed event listener memory leaks on application shutdown
207
+ - File: `src/core/application.js`
208
+ - Properly removes SIGTERM/SIGINT/SIGBREAK handlers
209
+ - Impact: Prevents listener accumulation in test environments and long-running applications
210
+
211
+ #### ๐ŸŸก MEDIUM Priority Fixes (7)
212
+
213
+ - **[BUG]** Fixed timeout resource leak in static file serving
214
+ - File: `src/middleware/static.js`
215
+ - Clears timeout when promise resolves
216
+ - Impact: Prevents timeout handle accumulation
217
+
218
+ - **[BUG]** Fixed type coercion in status code validation
219
+ - File: `src/core/context.js`
220
+ - Strict integer validation, rejects inputs like "200abc"
221
+ - Impact: Catches programming errors, prevents invalid status codes
222
+
223
+ - **[SECURITY]** Fixed URL-encoded path traversal bypass
224
+ - File: `src/middleware/static.js`
225
+ - Double-decode to catch attacks like `%252e%252e`
226
+ - Checks for traversal patterns after decoding
227
+ - Impact: Prevents directory traversal via URL encoding
228
+
229
+ - **[SECURITY]** Fixed information disclosure in error messages
230
+ - File: `src/core/application.js`
231
+ - Generic error messages for 5xx in production
232
+ - Stack traces only in development with explicit flag
233
+ - Impact: Prevents exposure of file paths, internal structure, and sensitive data
234
+
235
+ - **[SECURITY]** Fixed unvalidated redirect destinations (open redirect)
236
+ - File: `src/core/context.js`
237
+ - Blocks dangerous protocols: `javascript:`, `data:`, `vbscript:`, `file:`, `about:`
238
+ - Requires `allowedRedirectDomains` whitelist or explicit `allowOpenRedirects: true`
239
+ - Impact: Prevents open redirect attacks and XSS via protocol injection
240
+
241
+ - **[SECURITY]** Added cookie length validation
242
+ - File: `src/core/context.js`
243
+ - Cookie name max: 256 bytes, Cookie value max: 4096 bytes
244
+ - Impact: Prevents header size limit attacks
245
+
246
+ - **[BUG]** Fixed SameSite empty string edge case
247
+ - File: `src/core/context.js`
248
+ - Validates length before charAt() transformation
249
+ - Impact: Prevents runtime errors from malformed cookie options
250
+
251
+ #### ๐Ÿ†• Added
252
+
253
+ - **Safe JSON Parser Utility** (`src/utils/safe-json.js`)
254
+ - Validates JSON depth (prevents stack overflow)
255
+ - Validates JSON size (prevents memory exhaustion)
256
+ - Detects circular references
257
+ - Reusable across the framework
258
+
259
+ #### ๐Ÿ“š Documentation
260
+
261
+ - Added `COMPREHENSIVE_BUG_ANALYSIS_AND_FIX_REPORT_2025_11_17.md` - Complete analysis of 99+ identified issues
262
+ - Added `FINAL_BUG_FIX_SUMMARY_2025_11_17.md` - Summary of first 12 fixes
263
+ - Added `COMPLETE_BUG_FIX_REPORT_2025_11_17.md` - Comprehensive report of all 16 fixes with deployment guide
264
+
265
+ #### โš™๏ธ Configuration
266
+
267
+ New security settings available:
268
+
269
+ ```javascript
270
+ const app = new Spark({
271
+ settings: {
272
+ // External redirect control (prevents open redirects)
273
+ allowedRedirectDomains: ['yourdomain.com'], // Whitelist (recommended)
274
+ // OR
275
+ allowOpenRedirects: true, // Explicit opt-in (not recommended)
276
+ }
277
+ });
278
+
279
+ // Control error message exposure
280
+ process.env.NODE_ENV = 'production'; // Hides sensitive errors
281
+ process.env.EXPOSE_STACK_TRACES = 'false'; // Disables stack traces even in dev
282
+ ```
283
+
284
+ #### ๐Ÿงช Testing
285
+
286
+ - All tests passing: 34/34 (100% success rate)
287
+ - Test coverage: 100% maintained
288
+ - No breaking changes introduced
289
+ - All examples functional
290
+
291
+ #### ๐Ÿ›ก๏ธ Security Impact
292
+
293
+ **Attack Vectors Eliminated:**
294
+ - โœ… Hash collision attacks (MD5 โ†’ SHA-256)
295
+ - โœ… JSON depth/size DoS (limits enforced)
296
+ - โœ… Query string DoS (1MB limit)
297
+ - โœ… Prototype pollution (dangerous keys blocked)
298
+ - โœ… Timing attacks (constant-time comparisons)
299
+ - โœ… Path traversal via encoding (double-decode protection)
300
+ - โœ… Cache poisoning (functional cache + SHA-256)
301
+ - โœ… Open redirects (protocol + whitelist validation)
302
+ - โœ… Information disclosure (sanitized error messages)
303
+
304
+ **Risk Reduction:**
305
+ - Before: 10 active security vulnerabilities
306
+ - After: 0 critical immediate threats
307
+ - Overall: 100% of critical/high security bugs eliminated
308
+
309
+ #### โš ๏ธ Breaking Changes
310
+
311
+ **None** - All changes are backwards compatible. However, some behaviors are now more strict:
312
+
313
+ - External redirects now require `allowedRedirectDomains` configuration or explicit `allowOpenRedirects: true`
314
+ - Production error messages are now generic for 5xx errors (use `NODE_ENV=development` for detailed errors)
315
+ - Cookie names/values have length limits (256/4096 bytes respectively)
316
+
317
+ #### ๐Ÿ“ฆ Upgrade Notes
318
+
319
+ This is a **recommended security upgrade** for all users. No code changes required, but review the new security configurations for optimal protection.
320
+
321
+ See `COMPLETE_BUG_FIX_REPORT_2025_11_17.md` for detailed production deployment guide.
322
+
323
+ ---
324
+
325
+ ## [1.1.1] - 2025-08-18
326
+
327
+ ### ๐Ÿ› Bug Fixes & Code Quality Improvements
328
+
329
+ #### Fixed
330
+ - **Code Quality**: Added 'use strict' directives to all source files for better error catching
331
+ - **Whitespace Issues**: Removed trailing whitespace in test files
332
+ - **Production Logging**: Removed console.log statements from production code
333
+ - **Regex Validator**: Fixed async performance check to work synchronously
334
+ - **Error Handling**: Improved async error handler to properly emit errors to application
335
+ - **Context Pooling**: Verified and maintained proper init() and reset() methods
336
+
337
+ #### Added
338
+ - **Bug Fix Tests**: Comprehensive test suite to verify all bug fixes
339
+ - **Maintenance Scripts**: Added utility scripts for code quality maintenance
340
+ - `fix-use-strict.js`: Adds 'use strict' to all source files
341
+ - `remove-console-logs.js`: Removes debug logging from production
342
+
343
+ #### Security
344
+ - No vulnerabilities found in dependencies
345
+ - All security tests pass
346
+
347
+ ## [1.1.0] - 2025-07-17
348
+
349
+ ### ๐Ÿ”ง Production Validation & Bug Fixes
350
+
351
+ #### Fixed
352
+ - **Router Middleware Bug**: Fixed critical bug where Route HTTP methods only accepted single handlers instead of multiple handlers for middleware composition
353
+ - Updated all HTTP methods (get, post, put, delete, etc.) to accept rest parameters (...handlers)
354
+ - Fixed middleware chain execution for route-specific middleware
355
+ - Ensured proper request flow through middleware stack
356
+ - **Session Auto-Save**: Fixed session authentication issues where sessions were being saved after response was sent
357
+ - Implemented auto-save functionality in session proxy
358
+ - Session data now saves immediately when modified
359
+ - Session cookies are set properly during the request lifecycle
360
+ - **Port Handling**: Fixed port 0 handling for dynamic port allocation
361
+ - Changed from falsy check to explicit undefined check
362
+ - Enables proper testing with dynamic port assignment
363
+ - **Memory Leak Prevention**: Fixed EventEmitter memory leak warnings in validation tests
364
+ - Increased max listeners limit for test environments
365
+ - Optimized test iteration counts to prevent memory buildup
366
+
367
+ #### Added
368
+ - **Complete Production Pipeline**: Comprehensive validation and release preparation system
369
+ - 20+ validation checks covering all aspects of production readiness
370
+ - Automated testing for all 4 example applications
371
+ - Performance benchmarking (4000+ req/sec validated)
372
+ - Security vulnerability scanning
373
+ - Package size optimization (reduced from 236KB to 65KB)
374
+ - Memory leak detection and prevention
375
+ - Cross-platform compatibility testing
376
+ - **Enhanced Test Coverage**: Achieved 100% test success rate across all components
377
+ - Complete test suite for all example applications
378
+ - Integration tests for ecommerce API with session authentication
379
+ - Unit tests for all middleware components
380
+ - Performance and stress testing
381
+ - **TypeScript Definitions**: Cleaned and optimized TypeScript definitions
382
+ - Self-contained definitions without Node.js dependencies
383
+ - Accurate interfaces matching actual implementation
384
+ - Fixed method signatures (setCookie vs cookie)
385
+ - Enhanced SessionOptions and RateLimitOptions interfaces
386
+
387
+ #### Changed
388
+ - **Documentation Overhaul**: Completely rewrote all documentation from scratch
389
+ - Clean, modern README.md with focused feature highlights
390
+ - Comprehensive API Reference with detailed examples
391
+ - Step-by-step Getting Started guide with complete tutorials
392
+ - Extensive Middleware Guide with advanced patterns and best practices
393
+ - Removed unnecessary debug and temporary documentation files
394
+ - **Package Optimization**: Streamlined package contents
395
+ - Removed debug files and temporary validation artifacts
396
+ - Cleaned up development-only files
397
+ - Optimized bundle size for production deployment
398
+
399
+ #### Improved
400
+ - **Error Handling**: Enhanced error messages and validation feedback
401
+ - **Performance**: Optimized request handling and middleware execution
402
+ - **Security**: Validated all security features are working correctly
403
+ - **Reliability**: Extensive testing ensures production-ready stability
404
+
405
+ ---
406
+
407
+ ## [1.1.0] - 2025-07-16
408
+
409
+ ### ๐Ÿ”’ Security Enhancements
410
+
411
+ #### Added
412
+ - **Path Traversal Protection**: Comprehensive protection against directory traversal attacks in static file middleware
413
+ - URL normalization and validation
414
+ - Path containment verification
415
+ - Malformed URL error handling
416
+ - **ReDoS Protection**: Regular Expression Denial of Service protection
417
+ - SafeRegexCache with performance testing
418
+ - RegexValidator for pattern complexity analysis
419
+ - Automatic pattern sanitization for unsafe expressions
420
+ - **Header/Cookie Injection Protection**: Prevention of CRLF injection attacks
421
+ - Header value validation against null bytes and CRLF characters
422
+ - Cookie value sanitization
423
+ - Header length limits (8192 characters max)
424
+ - **Enhanced Input Validation**: Improved parameter and URL validation throughout the framework
425
+
426
+ ### ๐Ÿ›ก๏ธ Memory Management & Performance
427
+
428
+ #### Added
429
+ - **Memory Leak Protection**: Comprehensive cleanup mechanisms
430
+ - Automatic interval cleanup during shutdown
431
+ - Cleanup handler registration system
432
+ - Graceful shutdown with timeout handling
433
+ - **Object Pooling**: Context object reuse for better memory efficiency
434
+ - Context.init() and Context.reset() methods
435
+ - Reduced garbage collection pressure
436
+ - **Buffer Optimizations**: Enhanced memory usage in request handling
437
+ - Stream processing improvements
438
+ - Optimized string operations
439
+
440
+ ### ๐Ÿšจ Error Handling Improvements
441
+
442
+ #### Added
443
+ - **Advanced Error Handler**: Comprehensive error handling system
444
+ - Custom error types with status codes
445
+ - AsyncHandler for automatic promise error catching
446
+ - Structured error responses with proper HTTP status codes
447
+ - Development vs production error detail handling
448
+ - **Common HTTP Errors**: Pre-defined error creators
449
+ - BadRequest, Unauthorized, Forbidden, NotFound
450
+ - MethodNotAllowed, Conflict, TooManyRequests
451
+ - InternalServerError, ServiceUnavailable, etc.
452
+
453
+ #### Fixed
454
+ - **Error Propagation**: Proper error handling through middleware chain
455
+ - **Response Formatting**: Consistent error response structure
456
+ - **Status Code Handling**: Correct HTTP status codes for different error types
457
+
458
+ ### ๐Ÿ”ง Framework Enhancements
459
+
460
+ #### Added
461
+ - **Enhanced Router**: Improved routing capabilities
462
+ - Better path parameter extraction
463
+ - Improved route matching performance
464
+ - Support for router mounting with path prefixes
465
+ - **Middleware Improvements**: Enhanced middleware system
466
+ - Better error handling in middleware chain
467
+ - Cleanup handler support for middleware
468
+ - Improved middleware execution flow
469
+
470
+ #### Fixed
471
+ - **Case Sensitivity**: Fixed HTTP method handling case sensitivity issues
472
+ - **Route Parameters**: Improved parameter extraction and URL decoding
473
+ - **Router Mounting**: Fixed app.use() with router and path prefix functionality
474
+
475
+ ### ๐Ÿ“ฆ TypeScript & API Improvements
476
+
477
+ #### Added
478
+ - **Enhanced Type Definitions**: Improved TypeScript support
479
+ - Better generic type constraints
480
+ - More precise interface definitions
481
+ - Enhanced IDE autocomplete support
482
+
483
+ ### ๐Ÿงช Testing & Quality
484
+
485
+ #### Added
486
+ - **Comprehensive Integration Tests**: Full framework testing suite
487
+ - Security feature testing
488
+ - Memory leak testing
489
+ - Error handling validation
490
+ - Performance testing
491
+ - CORS and middleware testing
492
+
493
+ #### Fixed
494
+ - **Test Suite**: Stable and reliable testing framework
495
+ - **Error Test Coverage**: Complete error handling test coverage
496
+
497
+ ### ๐Ÿ”„ Developer Experience
498
+
499
+ #### Changed
500
+ - **Package.json**: Updated scripts and metadata
501
+ - Version bump to 1.1.0
502
+ - Updated description highlighting security features
503
+ - Added security-related keywords
504
+ - Updated test scripts
505
+ - **Documentation**: Enhanced code documentation
506
+ - Comprehensive JSDoc comments
507
+ - Security feature documentation
508
+ - API usage examples
509
+
510
+ ### ๐Ÿ—๏ธ Internal Improvements
511
+
512
+ #### Added
513
+ - **Graceful Shutdown**: Proper application shutdown handling
514
+ - Signal handling (SIGTERM, SIGINT, SIGBREAK)
515
+ - Cleanup handler execution
516
+ - Connection draining
517
+ - **Error Logging**: Enhanced error logging with context
518
+ - **Development Mode**: Better development experience with detailed error reporting
519
+
520
+ #### Changed
521
+ - **Code Organization**: Improved file structure and module organization
522
+ - **Performance Optimizations**: Various micro-optimizations throughout the codebase
523
+
524
+ ---
525
+
526
+ ## [1.0.0] - 2025-07-15
527
+
528
+ ### ๐ŸŽ‰ Initial Release as @oxog/spark
529
+
530
+ #### Added
531
+ - โœจ Production-ready with comprehensive test suite (434+ tests)
532
+ - ๐Ÿ›ก๏ธ Security hardened with OWASP Top 10 compliance
533
+ - โšก Blazing fast performance (42,000+ req/sec)
534
+ - ๐Ÿ“ Complete TypeScript definitions
535
+ - ๐ŸŽฏ Zero dependencies - built on Node.js core
536
+ - ๐Ÿ”’ Secure defaults (CORS disabled, CSRF enabled)
537
+ - ๐Ÿ’พ Multiple session stores (Memory, File)
538
+ - ๐Ÿšฆ Advanced rate limiting strategies
539
+ - ๐Ÿ—œ๏ธ Built-in compression support
540
+ - ๐Ÿ“Š Comprehensive middleware suite
541
+ - ๐Ÿ”ง Developer-friendly with hot reload
542
+ - ๐Ÿ“ˆ Production monitoring ready
543
+
544
+ #### Security
545
+ - ๐Ÿ” Removed all hardcoded secrets
546
+ - ๐Ÿ›ก๏ธ Fixed path traversal vulnerabilities
547
+ - ๐Ÿ”’ Enhanced CSRF protection
548
+ - โœ… Input validation on all user inputs
549
+ - ๐Ÿšซ Secure session management
550
+
551
+ #### Performance
552
+ - ๐Ÿ’จ Sub-millisecond latency (p50: 0.8ms)
553
+ - ๐Ÿš€ High throughput (42K+ requests/second)
554
+ - ๐Ÿ’พ Low memory footprint (38MB baseline)
555
+ - ๐Ÿ“‰ Efficient per-connection memory (<0.1KB)
556
+
557
+ #### Developer Experience
558
+ - ๐Ÿ› ๏ธ Complete build tooling
559
+ - ๐Ÿ“‹ ESLint configuration
560
+ - ๐Ÿ“ Comprehensive documentation
561
+ - ๐Ÿ’ก Working examples (e-commerce API)
562
+ - ๐Ÿงช Extensive test coverage (98.7%)
563
+
564
+ ---
565
+
566
+ ## Security Advisories
567
+
568
+ ### [1.1.0] Security Improvements
569
+ - **CVE-2024-SPARK-001**: Fixed path traversal vulnerability in static middleware
570
+ - **CVE-2024-SPARK-002**: Added ReDoS protection for regex operations
571
+ - **CVE-2024-SPARK-003**: Prevented header/cookie injection attacks
572
+ - **CVE-2024-SPARK-004**: Enhanced input validation across all components
573
+
574
+ ### Recommendations
575
+ - **Upgrade immediately** from version 1.0.0 to 1.1.0 for security fixes
576
+ - **Review configurations** to ensure security features are properly enabled
577
+ - **Test applications** with the new security features enabled
578
+ - **Monitor logs** for any security-related events
579
+
580
+ ---
581
+
582
+ ## Migration Guide
583
+
584
+ ### From 1.0.0 to 1.1.0
585
+
586
+ #### Breaking Changes
587
+ - None. Version 1.1.0 is fully backward compatible with 1.0.0
588
+
589
+ #### New Features Available
590
+ 1. **Enhanced Error Handling**:
591
+ ```javascript
592
+ const { errorHandling } = require('@oxog/spark');
593
+
594
+ // Use async handler for automatic error catching
595
+ app.get('/users/:id', errorHandling.asyncHandler(async (ctx) => {
596
+ const user = await findUser(ctx.params.id);
597
+ if (!user) {
598
+ throw errorHandling.errors.notFound('User not found');
599
+ }
600
+ ctx.json(user);
601
+ }));
602
+ ```
603
+
604
+ 2. **Security Features** (automatically enabled):
605
+ - Path traversal protection in static middleware
606
+ - ReDoS protection in routing
607
+ - Header injection protection
608
+ - Memory leak protection
609
+
610
+ 3. **Graceful Shutdown**:
611
+ ```javascript
612
+ app.onShutdown(async () => {
613
+ await database.close();
614
+ console.log('Database connection closed');
615
+ });
616
+ ```
617
+
618
+ #### Recommended Actions
619
+ 1. Update package.json to version 1.1.0
620
+ 2. Review error handling and consider using new asyncHandler
621
+ 3. Test security features in your environment
622
+ 4. Add graceful shutdown handlers for your resources
623
+
624
+ ---
625
+
626
+ ### Links
627
+ - ๐Ÿ“ฆ NPM: https://www.npmjs.com/package/@oxog/spark
628
+ - ๐Ÿ™ GitHub: https://github.com/ersinkoc/spark
629
+ - ๐Ÿ“š Documentation: https://github.com/ersinkoc/spark/tree/main/docs
630
+
631
+ ---
632
+
294
633
  Made with โค๏ธ by Ersin Koรง