koa-classic-server 1.1.0 → 2.0.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.
package/BENCHMARKS.md ADDED
@@ -0,0 +1,317 @@
1
+ # Performance Benchmarks
2
+
3
+ This directory contains comprehensive performance benchmarks for `koa-classic-server`.
4
+
5
+ ## Purpose
6
+
7
+ These benchmarks measure:
8
+ - **Response times** for different file sizes
9
+ - **Directory listing performance** for various sizes
10
+ - **Concurrent request handling**
11
+ - **Memory usage**
12
+ - **Throughput** (requests/second, MB/second)
13
+
14
+ ## Quick Start
15
+
16
+ ### 1. Setup Benchmark Data
17
+
18
+ First, create the test files and directories:
19
+
20
+ ```bash
21
+ npm run benchmark:setup
22
+ ```
23
+
24
+ This creates:
25
+ - `benchmark-data/small-files/` - 100 files × 1KB
26
+ - `benchmark-data/medium-files/` - 50 files × 100KB
27
+ - `benchmark-data/large-files/` - 10 files × 1MB
28
+ - `benchmark-data/large-directory/` - 1,000 files for listing test
29
+ - `benchmark-data/very-large-directory/` - 10,000 files for stress test
30
+ - `benchmark-data/nested/` - 5 levels deep directory structure
31
+
32
+ Total: ~15 MB of test data
33
+
34
+ ### 2. Run Jest Performance Tests
35
+
36
+ ```bash
37
+ npm run test:performance
38
+ ```
39
+
40
+ This runs comprehensive tests measuring:
41
+ - Individual file serving times
42
+ - Directory listing times
43
+ - Concurrent request handling
44
+ - 404 error handling
45
+ - Memory usage
46
+
47
+ **Save results:**
48
+ ```bash
49
+ npm run test:performance > results-baseline-v1.2.0.txt
50
+ ```
51
+
52
+ ### 3. Run HTTP Load Tests (autocannon)
53
+
54
+ ```bash
55
+ npm run benchmark
56
+ ```
57
+
58
+ This performs realistic load testing with:
59
+ - 10 seconds per scenario
60
+ - 5-10 concurrent connections
61
+ - Measures requests/sec, latency, throughput
62
+
63
+ **Save results for comparison:**
64
+ ```bash
65
+ npm run benchmark:save baseline-v1.2.0.json
66
+ ```
67
+
68
+ ## Workflow: Before/After Optimization
69
+
70
+ ### Step 1: Baseline (BEFORE optimization)
71
+
72
+ ```bash
73
+ # Setup test data
74
+ npm run benchmark:setup
75
+
76
+ # Run tests and save results
77
+ npm run test:performance > results-before.txt
78
+ npm run benchmark:save baseline-before.json
79
+ ```
80
+
81
+ ### Step 2: Apply Optimizations
82
+
83
+ Make code changes to improve performance...
84
+
85
+ ### Step 3: Compare (AFTER optimization)
86
+
87
+ ```bash
88
+ # Run tests again
89
+ npm run test:performance > results-after.txt
90
+ npm run benchmark:save baseline-after.json --compare baseline-before.json
91
+ ```
92
+
93
+ ### Step 4: Analyze Differences
94
+
95
+ ```bash
96
+ # Compare test results
97
+ diff results-before.txt results-after.txt
98
+
99
+ # Benchmark comparison is shown automatically
100
+ ```
101
+
102
+ ## Expected Improvements
103
+
104
+ After implementing the optimizations from `PERFORMANCE_ANALYSIS.md`:
105
+
106
+ | Metric | Before | After | Improvement |
107
+ |--------|--------|-------|-------------|
108
+ | Small file (1KB) | ~2.5ms | ~0.5ms | **80% faster** |
109
+ | Directory (1,000 files) | ~120ms | ~40ms | **67% faster** |
110
+ | Directory (10,000 files) | ~1,800ms | ~450ms | **75% faster** |
111
+ | Concurrent requests | Sequential | Parallel | **5-10x faster** |
112
+ | Memory (10k directory) | ~25MB | ~15MB | **40% less** |
113
+
114
+ With HTTP caching enabled:
115
+ | Metric | Before | After | Improvement |
116
+ |--------|--------|-------|-------------|
117
+ | Cached file | 2.5ms | 0.1ms | **96% faster** |
118
+ | Bandwidth | 100% | 5% | **95% reduction** |
119
+
120
+ ## Understanding the Results
121
+
122
+ ### Jest Performance Tests
123
+
124
+ Output includes:
125
+ - **Average time**: Mean across all iterations
126
+ - **Median time**: 50th percentile (less affected by outliers)
127
+ - **Min/Max time**: Range of values
128
+ - **Warnings**: Areas where optimizations will have big impact
129
+
130
+ Example output:
131
+ ```
132
+ 📊 Large Directory (1,000 files) Benchmark:
133
+ Average: 123.45ms
134
+ Median: 120.30ms
135
+ Min: 110.20ms
136
+ Max: 145.80ms
137
+ ⚠️ WARNING: This will be MUCH faster after async optimization
138
+ ```
139
+
140
+ ### Autocannon Load Tests
141
+
142
+ Output includes:
143
+ - **Requests/sec**: How many requests the server can handle per second
144
+ - **Latency**: Response time (avg, p50, p99)
145
+ - **Throughput**: Data transferred per second (MB/sec)
146
+
147
+ Example output:
148
+ ```
149
+ Scenario | Req/sec | Latency (avg) | Throughput
150
+ ----------------------------------|---------|---------------|-------------
151
+ Small file (1KB) | 2500 | 4.00ms | 2.44 MB/s
152
+ Directory listing (1,000 files) | 80 | 125.00ms | 15.60 MB/s
153
+ ```
154
+
155
+ Higher **Requests/sec** = Better ✅
156
+ Lower **Latency** = Better ✅
157
+ Higher **Throughput** = Better ✅
158
+
159
+ ## Interpreting Latency Percentiles
160
+
161
+ - **p50 (median)**: 50% of requests complete in this time
162
+ - **p75**: 75% of requests complete in this time
163
+ - **p90**: 90% of requests complete in this time
164
+ - **p99**: 99% of requests complete in this time
165
+ - **p999**: 99.9% of requests complete in this time
166
+
167
+ **Why p99 matters:**
168
+ - p50 might be 10ms, but p99 could be 100ms
169
+ - This means 1% of users experience 10× slower responses
170
+ - Optimizations should improve both average AND p99
171
+
172
+ ## Memory Usage Tests
173
+
174
+ Memory tests show:
175
+ - **Heap used**: JavaScript objects, strings, arrays
176
+ - **External**: Buffers, native objects
177
+ - **Response size**: Size of HTML/data generated
178
+
179
+ **What to look for:**
180
+ - Large heap increase = memory leaks or inefficient allocation
181
+ - After optimization: should see 30-40% reduction
182
+
183
+ ## Directory Structure
184
+
185
+ ```
186
+ koa-classic-server/
187
+ ├── benchmark-data/ # Test data (git-ignored, ~15MB)
188
+ │ ├── small-files/
189
+ │ ├── medium-files/
190
+ │ ├── large-files/
191
+ │ ├── large-directory/
192
+ │ └── very-large-directory/
193
+ ├── scripts/
194
+ │ └── setup-benchmark.js # Creates test data
195
+ ├── __tests__/
196
+ │ └── performance.test.js # Jest performance tests
197
+ ├── benchmark.js # Autocannon load tests
198
+ └── BENCHMARKS.md # This file
199
+ ```
200
+
201
+ ## Troubleshooting
202
+
203
+ ### "Benchmark data not found"
204
+
205
+ Run: `npm run benchmark:setup`
206
+
207
+ ### Tests timeout
208
+
209
+ Increase Jest timeout in `performance.test.js`:
210
+ ```javascript
211
+ test('...', async () => { ... }, 60000); // 60 seconds
212
+ ```
213
+
214
+ ### Out of memory
215
+
216
+ Reduce iterations or skip very-large-directory tests:
217
+ ```javascript
218
+ test.skip('Very large directory...', async () => { ... });
219
+ ```
220
+
221
+ ### Inconsistent results
222
+
223
+ - Close other applications
224
+ - Run multiple times and average results
225
+ - Check system load: `top` or `htop`
226
+ - Disable CPU throttling
227
+
228
+ ## Best Practices
229
+
230
+ 1. **Run on idle system**: Close browsers, apps
231
+ 2. **Run multiple times**: Results vary, average 3+ runs
232
+ 3. **Same environment**: Use same machine for before/after
233
+ 4. **Document environment**: Note CPU, RAM, Node version
234
+ 5. **Save results**: Use `> file.txt` to save for comparison
235
+
236
+ ## Example: Complete Before/After Test
237
+
238
+ ```bash
239
+ # === BEFORE OPTIMIZATION ===
240
+
241
+ # Setup
242
+ npm run benchmark:setup
243
+
244
+ # Jest tests
245
+ npm run test:performance > results-v1.2.0-before.txt
246
+
247
+ # Load tests
248
+ npm run benchmark:save baseline-v1.2.0.json
249
+
250
+ # === APPLY OPTIMIZATIONS ===
251
+ # Edit index.cjs...
252
+
253
+ # === AFTER OPTIMIZATION ===
254
+
255
+ # Jest tests
256
+ npm run test:performance > results-v1.3.0-after.txt
257
+
258
+ # Load tests with comparison
259
+ node benchmark.js --save baseline-v1.3.0.json --compare baseline-v1.2.0.json
260
+
261
+ # Review differences
262
+ diff results-v1.2.0-before.txt results-v1.3.0-after.txt
263
+ ```
264
+
265
+ ## Environment Information
266
+
267
+ When reporting results, include:
268
+
269
+ ```bash
270
+ node --version
271
+ npm --version
272
+ cat /proc/cpuinfo | grep "model name" | head -n 1
273
+ free -h
274
+ ```
275
+
276
+ Example:
277
+ ```
278
+ Node.js: v20.10.0
279
+ npm: 10.2.3
280
+ CPU: Intel(R) Core(TM) i7-9750H @ 2.60GHz
281
+ RAM: 16GB
282
+ OS: Ubuntu 22.04 LTS
283
+ ```
284
+
285
+ ## Next Steps
286
+
287
+ After running baseline benchmarks:
288
+
289
+ 1. Review `PERFORMANCE_ANALYSIS.md` for optimization recommendations
290
+ 2. Review `OPTIMIZATION_HTTP_CACHING.md` for HTTP caching details
291
+ 3. Implement Priority 1 optimizations:
292
+ - Convert sync operations to async
293
+ - Fix string concatenation in `show_dir()`
294
+ - Add HTTP caching headers
295
+ 4. Re-run benchmarks to measure improvements
296
+ 5. Update to v1.3.0 "Performance Edition"
297
+
298
+ ## Contributing
299
+
300
+ When submitting performance improvements:
301
+
302
+ 1. Run baseline benchmarks BEFORE changes
303
+ 2. Apply your optimization
304
+ 3. Run benchmarks AFTER changes
305
+ 4. Include both results in PR
306
+ 5. Document the optimization approach
307
+
308
+ ## Resources
309
+
310
+ - [autocannon documentation](https://github.com/mcollina/autocannon)
311
+ - [Jest performance testing](https://jestjs.io/docs/timer-mocks)
312
+ - [Node.js performance best practices](https://nodejs.org/en/docs/guides/simple-profiling/)
313
+
314
+ ---
315
+
316
+ **Last updated**: 2025-11-18
317
+ **Version**: 1.2.0 (baseline)
package/CHANGELOG.md ADDED
@@ -0,0 +1,181 @@
1
+ # Changelog
2
+
3
+ All notable changes to koa-classic-server 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] - 2025-11-17
9
+
10
+ ### 🎉 SECURITY & BUG FIX RELEASE
11
+
12
+ This release contains **critical security fixes** and important bug fixes. All users should upgrade immediately.
13
+
14
+ ### 🔒 Security Fixes (CRITICAL)
15
+
16
+ #### Fixed Path Traversal Vulnerability
17
+ - **Issue**: Attackers could access files outside the served directory using `../` sequences
18
+ - **Impact**: CRITICAL - Unauthorized file access
19
+ - **Fix**: Added path normalization and validation to ensure all file access stays within `rootDir`
20
+ - **Code**: `index.cjs:106-124`
21
+
22
+ #### Fixed Template Rendering Crash
23
+ - **Issue**: Unhandled errors in template rendering could crash the entire server
24
+ - **Impact**: CRITICAL - Denial of Service
25
+ - **Fix**: Added try-catch around template render calls with proper error handling
26
+ - **Code**: `index.cjs:195-205`
27
+
28
+ ### ✅ Bug Fixes
29
+
30
+ #### Fixed HTTP Status Code 404
31
+ - **Issue**: Missing files returned HTML "Not Found" with HTTP 200 status instead of 404
32
+ - **Impact**: HIGH - Violates HTTP standards, affects SEO, breaks caching
33
+ - **Fix**: Properly set `ctx.status = 404` when resources are not found
34
+ - **Locations**:
35
+ - `index.cjs:130` - File/directory not found
36
+ - `index.cjs:158` - Directory listing disabled
37
+
38
+ #### Fixed Race Condition in File Access
39
+ - **Issue**: Files could be deleted between existence check and reading, causing uncaught errors
40
+ - **Impact**: HIGH - Server crashes on file access errors
41
+ - **Fix**: Added `fs.promises.access()` check before streaming files with error handling
42
+ - **Code**: `index.cjs:208-216`
43
+
44
+ #### Fixed File Extension Extraction
45
+ - **Issue**: Using `split(".")` failed for:
46
+ - Files without extension (`README`)
47
+ - Hidden files (`.gitignore`)
48
+ - Paths with dots (`/folder.backup/file`)
49
+ - **Impact**: HIGH - Template rendering activated incorrectly
50
+ - **Fix**: Use `path.extname()` for robust extension extraction
51
+ - **Code**: `index.cjs:192`
52
+
53
+ #### Fixed Directory Read Errors
54
+ - **Issue**: `fs.readdirSync()` could throw unhandled errors (permissions, deleted directories)
55
+ - **Impact**: MEDIUM - Server crashes on directory access errors
56
+ - **Fix**: Added try-catch with user-friendly error message
57
+ - **Code**: `index.cjs:245-264`
58
+
59
+ #### Fixed Content-Disposition Header
60
+ - **Issue**: Filename in Content-Disposition header was not quoted and included full path
61
+ - **Impact**: MEDIUM - Download issues with special characters in filenames
62
+ - **Fix**:
63
+ - Use only basename (not full path)
64
+ - Quote filename and escape quotes
65
+ - **Code**: `index.cjs:234-239`
66
+
67
+ ### 🎨 Improvements
68
+
69
+ #### Added Input Validation
70
+ - Validate `rootDir` is a non-empty string
71
+ - Validate `rootDir` is an absolute path
72
+ - Throw meaningful errors for invalid input
73
+
74
+ #### Added XSS Protection
75
+ - HTML-escape all user-controlled content in directory listings
76
+ - Escapes filenames, paths, and MIME types
77
+ - Prevents XSS attacks through malicious filenames
78
+
79
+ #### Improved Error Messages
80
+ - More descriptive error messages
81
+ - Console logging for debugging
82
+ - Stream error handling
83
+
84
+ #### Code Quality
85
+ - Fixed usage of `Array()` constructor to literal syntax `[]`
86
+ - Better code organization and comments
87
+ - Improved HTML output formatting
88
+
89
+ ### 📝 Added Files
90
+
91
+ - **`__tests__/security.test.js`**: Comprehensive security and bug tests
92
+ - **`DEBUG_REPORT.md`**: Detailed analysis of all bugs and fixes
93
+ - **`DOCUMENTATION.md`**: Complete documentation (1500+ lines)
94
+ - **`CHANGELOG.md`**: This file
95
+
96
+ ### 🧪 Testing
97
+
98
+ - All 71 tests passing
99
+ - Added security test suite
100
+ - Path traversal tests
101
+ - Template error handling tests
102
+ - Status code validation tests
103
+ - Race condition tests
104
+ - Content-Disposition tests
105
+
106
+ ### 📦 Package Changes
107
+
108
+ - **Version**: `1.1.0` → `1.2.0`
109
+ - **Description**: Enhanced with security fixes
110
+ - **Keywords**: Added `secure`, `middleware`, `file-server`, `directory-listing`
111
+ - **Scripts**: Added `test:security` command
112
+
113
+ ### ⚠️ Breaking Changes
114
+
115
+ **None** - This is a backwards-compatible release. However, behavior changes for security:
116
+
117
+ 1. **404 Status Codes**: Now properly returns 404 instead of 200 for missing resources
118
+ 2. **Path Traversal**: Requests with `../` now return 403 Forbidden instead of allowing access
119
+ 3. **Error Handling**: Template errors return 500 instead of crashing the server
120
+
121
+ These changes fix bugs and security issues. The new behavior is correct and standards-compliant.
122
+
123
+ ### 🔄 Migration Guide
124
+
125
+ No code changes required! Simply update:
126
+
127
+ ```bash
128
+ npm update koa-classic-server
129
+ ```
130
+
131
+ **Recommended**: Verify that:
132
+ 1. `rootDir` is an absolute path (e.g., `__dirname + '/public'`)
133
+ 2. Your error handling expects proper 404/403/500 status codes
134
+ 3. Your tests pass with the new behavior
135
+
136
+ ### 📊 Statistics
137
+
138
+ - **Lines of code fixed**: ~200
139
+ - **Security vulnerabilities fixed**: 2 critical
140
+ - **Bugs fixed**: 6
141
+ - **Tests added**: 12 security tests
142
+ - **Documentation added**: 2000+ lines
143
+ - **Test coverage**: 71 tests passing
144
+
145
+ ### 🙏 Credits
146
+
147
+ - **Author**: Italo Paesano
148
+ - **Security Audit**: Comprehensive code analysis
149
+ - **Testing**: Jest & Supertest
150
+
151
+ ---
152
+
153
+ ## [1.1.0] - Previous Release
154
+
155
+ ### Features
156
+ - Basic static file serving
157
+ - Directory listing
158
+ - Template engine support
159
+ - URL prefixes
160
+ - Reserved URLs
161
+
162
+ ### Known Issues (Fixed in 1.2.0)
163
+ - Path traversal vulnerability ⚠️ CRITICAL
164
+ - Missing 404 status codes
165
+ - Unhandled template errors ⚠️ CRITICAL
166
+ - Race condition in file access
167
+ - Fragile file extension extraction
168
+ - Missing error handling
169
+
170
+ ---
171
+
172
+ ## Links
173
+
174
+ - [Full Documentation](./DOCUMENTATION.md)
175
+ - [Debug Report](./DEBUG_REPORT.md)
176
+ - [Repository](https://github.com/italopaesano/koa-classic-server)
177
+ - [npm Package](https://www.npmjs.com/package/koa-classic-server)
178
+
179
+ ---
180
+
181
+ **⚠️ Security Notice**: Version 1.2.0 fixes critical vulnerabilities. Update immediately if using 1.1.0 or earlier.
@@ -0,0 +1,53 @@
1
+ #!/bin/bash
2
+ # Script per creare la release v1.2.0
3
+
4
+ echo "🏷️ Creazione Release v1.2.0..."
5
+
6
+ # Assicurati di essere sul branch principale
7
+ echo "📥 Fetch delle ultime modifiche..."
8
+ git fetch origin
9
+
10
+ # Checkout al branch principale (prova main, poi master)
11
+ if git show-ref --verify --quiet refs/remotes/origin/main; then
12
+ echo "✅ Checkout a main..."
13
+ git checkout main
14
+ git pull origin main
15
+ elif git show-ref --verify --quiet refs/remotes/origin/master; then
16
+ echo "✅ Checkout a master..."
17
+ git checkout master
18
+ git pull origin master
19
+ else
20
+ echo "❌ Branch principale non trovato. Usa l'interfaccia GitHub."
21
+ exit 1
22
+ fi
23
+
24
+ # Crea il tag
25
+ echo "🏷️ Creazione tag v1.2.0..."
26
+ git tag -a v1.2.0 -m "Release v1.2.0 - Critical Security Update
27
+
28
+ ⚠️ CRITICAL SECURITY FIXES
29
+
30
+ Security Fixes:
31
+ - Fixed Path Traversal Vulnerability (CRITICAL)
32
+ - Fixed Template Rendering Crash (CRITICAL)
33
+
34
+ Bug Fixes:
35
+ - HTTP Status Code 404 (HIGH)
36
+ - Race Condition File Access (HIGH)
37
+ - File Extension Extraction (HIGH)
38
+ - Directory Read Errors (MEDIUM)
39
+ - Content-Disposition Header (MEDIUM)
40
+ - Code Quality & XSS Protection
41
+
42
+ Statistics:
43
+ - Security vulnerabilities: 2 critical fixed
44
+ - Bugs fixed: 6
45
+ - Tests: 71 passing
46
+ - Documentation: 2000+ lines added"
47
+
48
+ # Push del tag
49
+ echo "📤 Push del tag a GitHub..."
50
+ git push origin v1.2.0
51
+
52
+ echo "✅ Tag creato! Ora vai su GitHub per creare la release:"
53
+ echo " https://github.com/italopaesano/koa-classic-server/releases/new?tag=v1.2.0"