aetherframework-middleware 1.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/.env.example ADDED
@@ -0,0 +1,88 @@
1
+ # ============================================
2
+ # AetherJS Framework Configuration
3
+ # ============================================
4
+
5
+ # Server Configuration
6
+ PORT=3001
7
+
8
+ # Security Configuration
9
+ JWT_SECRET=your-super-secret-jwt-key-change-in-production
10
+ SESSION_SECRET=your-super-secret-session-key-change-in-production
11
+
12
+ # CORS Configuration
13
+ CORS_ENABLED=true
14
+ CORS_ORIGIN=*
15
+ CORS_METHODS=GET,POST,PUT,DELETE,PATCH,OPTIONS
16
+ CORS_ALLOWED_HEADERS=Content-Type,Authorization
17
+ CORS_CREDENTIALS=true
18
+ CORS_MAX_AGE=86400
19
+ CORS_PREFLIGHT_CONTINUE=false
20
+ CORS_OPTIONS_STATUS=204
21
+
22
+ # Compression Configuration
23
+ COMPRESSION_ENABLED=true
24
+ COMPRESSION_THRESHOLD=1024
25
+ COMPRESSION_LEVEL=6
26
+ COMPRESSION_MEM_LEVEL=8
27
+ COMPRESSION_STRATEGY=0
28
+ COMPRESSION_CHUNK_SIZE=16384
29
+ COMPRESSION_WINDOW_BITS=15
30
+ COMPRESSION_GZIP=true
31
+ COMPRESSION_DEFLATE=false
32
+ COMPRESSION_BROTLI=false
33
+ COMPRESSION_TYPES=application/json,text/plain,text/html,text/css,application/javascript
34
+
35
+ # Session Configuration
36
+ SESSION_ENABLED=true
37
+ SESSION_MAX_AGE=86400000
38
+ SESSION_COOKIE_NAME=aether_sid
39
+
40
+ # Rate Limiting Configuration
41
+ RATE_LIMIT_ENABLED=true
42
+ RATE_LIMIT_WINDOW_MS=900000 # 15 minutes
43
+ RATE_LIMIT_MAX_REQUESTS=100
44
+ RATE_LIMIT_MESSAGE="Too many requests, please try again later."
45
+ RATE_LIMIT_STATUS_CODE=429
46
+ RATE_LIMIT_SKIP_SUCCESSFUL=false
47
+ RATE_LIMIT_SKIP_FAILED=false
48
+
49
+ # Security Headers Configuration
50
+ SECURITY_HSTS_ENABLED=true
51
+ SECURITY_HSTS_MAX_AGE=31536000
52
+ SECURITY_NO_SNIFF=true
53
+ SECURITY_XSS_FILTER=true
54
+ SECURITY_FRAMEGUARD_ACTION=DENY
55
+ SECURITY_HIDE_POWERED_BY=true
56
+ SECURITY_REFERRER_POLICY=strict-origin-when-cross-origin
57
+
58
+ # JWT Configuration
59
+ JWT_ENABLED=true
60
+ JWT_ALGORITHMS=HS256
61
+ JWT_AUDIENCE=
62
+ JWT_ISSUER=
63
+ JWT_EXPIRES_IN=7d
64
+ JWT_IGNORE_EXPIRATION=false
65
+ JWT_CREDENTIALS_REQUIRED=true
66
+ JWT_TOKEN_HEADER=authorization
67
+ JWT_TOKEN_QUERY=token
68
+ JWT_TOKEN_COOKIE=token
69
+
70
+ # Body Parser Configuration
71
+ BODY_ENABLE_JSON=true
72
+ BODY_LIMIT_JSON=1mb
73
+ JSON_STRICT=true
74
+ JSON_REVIVER=
75
+
76
+ BODY_ENABLE_URLENCODED=true
77
+ BODY_LIMIT_URLENCODED=1mb
78
+
79
+ BODY_ENABLE_TEXT=true
80
+ BODY_LIMIT_TEXT=1mb
81
+
82
+ BODY_ENABLE_RAW=true
83
+ BODY_LIMIT_RAW=10mb
84
+
85
+ # Development/Production Mode
86
+ NODE_ENV=development
87
+ DEBUG=false
88
+ LOG_LEVEL=info
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aetherjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,578 @@
1
+
2
+ AetherFramework Middleware
3
+
4
+
5
+ 📦 Installation
6
+
7
+ Install AetherFramework Middleware via npm:
8
+
9
+ ```bash
10
+ npm install aetherframework-middleware
11
+ ```
12
+
13
+ 🚀 Quick Start
14
+
15
+ Basic Server Example
16
+
17
+ ```javascript
18
+ import http from "http";
19
+ import { AetherPipeline } from "aetherframework-middleware";
20
+
21
+ // Create pipeline
22
+ const pipeline = new AetherPipeline();
23
+
24
+ // Add middleware
25
+ pipeline.use((ctx) => {
26
+ ctx.setHeader("Content-Type", "application/json");
27
+ });
28
+
29
+ // Add routes
30
+ pipeline.use((ctx) => {
31
+ if (ctx.url === "/health") {
32
+ ctx.setStatus(200);
33
+ ctx.body = JSON.stringify({ status: "ok" });
34
+ ctx._isHandled = true;
35
+ return true;
36
+ }
37
+ });
38
+
39
+ // 404 handler
40
+ pipeline.use((ctx) => {
41
+ if (!ctx._isHandled) {
42
+ ctx.setStatus(404);
43
+ ctx.body = JSON.stringify({ error: "Not Found" });
44
+ }
45
+ });
46
+
47
+ // Precompile for performance
48
+ pipeline.precompile();
49
+
50
+ // Create server
51
+ const server = http.createServer(async (req, res) => {
52
+ await pipeline.handle(req, res);
53
+ });
54
+
55
+ server.listen(3001, () => {
56
+ console.log("🚀 Server running on http://localhost:3001");
57
+ });
58
+ ```
59
+
60
+ 📖 Documentation
61
+
62
+ Core Concepts
63
+
64
+ AetherPipeline
65
+ The central routing and middleware system that handles request processing with intelligent caching and optimization.
66
+
67
+ ```javascript
68
+ import { AetherPipeline } from "aetherframework-middleware";
69
+
70
+ const pipeline = new AetherPipeline();
71
+
72
+ // Add middleware
73
+ pipeline.use(securityMiddleware);
74
+ pipeline.use(corsMiddleware);
75
+ pipeline.use(compressionMiddleware);
76
+
77
+ // Add routes
78
+ pipeline.use((ctx) => {
79
+ if (ctx.url === "/api/users") {
80
+ ctx.json({ users: [] });
81
+ return true;
82
+ }
83
+ });
84
+
85
+ // Compile for performance
86
+ pipeline.precompile();
87
+ ```
88
+
89
+ AetherContext
90
+ The request context object with optimized header management and zero-allocation patterns.
91
+
92
+ ```javascript
93
+ // Setting headers
94
+ ctx.setHeader("Content-Type", "application/json");
95
+
96
+ // Setting status
97
+ ctx.setStatus(200);
98
+
99
+ // JSON response
100
+ ctx.json({ message: "Success" });
101
+
102
+ // Raw response
103
+ ctx.raw("Hello World");
104
+
105
+ // Get request data
106
+ const ip = ctx.ip;
107
+ const query = ctx.query;
108
+ const body = ctx.body;
109
+ ```
110
+
111
+ Middleware System
112
+
113
+ AetherJS includes a comprehensive set of built-in middleware:
114
+
115
+ Security Middleware
116
+ ```javascript
117
+ import { middleware } from "aetherframework-middleware";
118
+
119
+ const securityMiddleware = middleware.security({
120
+ hsts: { enabled: true, maxAge: 31536000 },
121
+ noSniff: { enabled: true },
122
+ frameguard: { enabled: true, action: "DENY" },
123
+ hidePoweredBy: true,
124
+ referrerPolicy: {
125
+ enabled: true,
126
+ value: "strict-origin-when-cross-origin"
127
+ },
128
+ permissionsPolicy: {
129
+ enabled: true,
130
+ directives: { camera: "()", microphone: "()", geolocation: "()" }
131
+ }
132
+ });
133
+ ```
134
+
135
+ CORS Middleware
136
+ ```javascript
137
+ import { middleware } from "aetherframework-middleware";
138
+
139
+ const corsMiddleware = middleware.cors({
140
+ origin: "*",
141
+ credentials: true,
142
+ methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
143
+ allowedHeaders: ["Content-Type", "Authorization"],
144
+ maxAge: 86400
145
+ });
146
+ ```
147
+
148
+ Compression Middleware
149
+ ```javascript
150
+ import { middleware } from "aetherframework-middleware";
151
+
152
+ const compressionMiddleware = middleware.compression({
153
+ enabled: true,
154
+ threshold: 1024,
155
+ gzip: true,
156
+ deflate: false,
157
+ brotli: false,
158
+ types: "application/json,text/plain,text/html"
159
+ });
160
+ ```
161
+
162
+ Rate Limiting Middleware
163
+ ```javascript
164
+ import { middleware } from "aetherframework-middleware";
165
+
166
+ const rateLimitMiddleware = middleware.rateLimit({
167
+ windowMs: 15 * 60 * 1000, // 15 minutes
168
+ max: 100, // Limit each IP to 100 requests per window
169
+ message: "Too many requests, please try again later.",
170
+ statusCode: 429
171
+ });
172
+ ```
173
+
174
+ JWT Middleware
175
+ ```javascript
176
+ import { middleware } from "aetherframework-middleware";
177
+
178
+ const jwtMiddleware = middleware.jwt({
179
+ secret: process.env.JWT_SECRET,
180
+ algorithms: ["HS256"],
181
+ credentialsRequired: true,
182
+ tokenHeader: "authorization"
183
+ });
184
+ ```
185
+
186
+ Session Middleware
187
+ ```javascript
188
+ import { middleware } from "aetherframework-middleware";
189
+
190
+ const sessionManager = new middleware.session({
191
+ enabled: true,
192
+ secret: process.env.SESSION_SECRET,
193
+ maxAge: 86400000, // 24 hours
194
+ cookieName: "aether_session",
195
+ store: "memory" // or custom store
196
+ });
197
+ const sessionMiddleware = sessionManager.middleware();
198
+ ```
199
+
200
+ Body Parser Middleware
201
+ ```javascript
202
+ import { middleware } from "aetherframework-middleware";
203
+
204
+ const bodyParserMiddleware = middleware.bodyParser({
205
+ json: { enabled: true, limit: "1mb" },
206
+ urlencoded: { enabled: true, limit: "1mb" },
207
+ text: { enabled: true, limit: "1mb" },
208
+ raw: { enabled: true, limit: "10mb" }
209
+ });
210
+ ```
211
+
212
+ 🔧 Advanced Server Example
213
+
214
+ ```javascript
215
+ import http from "http";
216
+ import { AetherPipeline, middleware } from "aetherframework-middleware";
217
+
218
+ // Initialize pipeline
219
+ const pipeline = new AetherPipeline();
220
+
221
+ // Middleware configuration
222
+ const securityMiddleware = middleware.security({
223
+ hsts: { enabled: true, maxAge: 31536000 },
224
+ noSniff: { enabled: true },
225
+ frameguard: { enabled: true, action: "DENY" }
226
+ });
227
+
228
+ const corsMiddleware = middleware.cors({
229
+ origin: "*",
230
+ credentials: true
231
+ });
232
+
233
+ const compressionMiddleware = middleware.compression({
234
+ enabled: process.env.COMPRESSION_ENABLED === "true",
235
+ threshold: parseInt(process.env.COMPRESSION_THRESHOLD) || 1024
236
+ });
237
+
238
+ const sessionManager = new middleware.session({
239
+ enabled: true,
240
+ secret: process.env.SESSION_SECRET,
241
+ maxAge: parseInt(process.env.SESSION_MAX_AGE) || 86400000
242
+ });
243
+
244
+ const rateLimitMiddleware = middleware.rateLimit({
245
+ windowMs: 15 * 60 * 1000,
246
+ max: 100,
247
+ enabled: true
248
+ });
249
+
250
+ const bodyParserMiddleware = middleware.bodyParser({
251
+ json: { enabled: true, limit: "1mb" }
252
+ });
253
+
254
+ const jwtMiddleware = middleware.jwt({
255
+ secret: process.env.JWT_SECRET,
256
+ algorithms: ["HS256"]
257
+ });
258
+
259
+ // Mount middleware
260
+ pipeline.use(securityMiddleware);
261
+ pipeline.use(corsMiddleware);
262
+ pipeline.use(compressionMiddleware);
263
+ pipeline.use(sessionManager.middleware());
264
+ pipeline.use(rateLimitMiddleware);
265
+ pipeline.use(bodyParserMiddleware);
266
+
267
+ // Public routes
268
+ pipeline.use((ctx, next) => {
269
+ if (ctx.url === "/public/info") {
270
+ ctx.setStatus(200);
271
+ ctx.json({ message: "Public information" });
272
+ return;
273
+ }
274
+ return next();
275
+ });
276
+
277
+ // Protected routes
278
+ pipeline.use(async (ctx, next) => {
279
+ if (ctx.url.startsWith("/api/")) {
280
+ await jwtMiddleware(ctx, next);
281
+ } else {
282
+ return next();
283
+ }
284
+ });
285
+
286
+ pipeline.use((ctx) => {
287
+ if (ctx.url === "/api/profile" && ctx.method === "GET") {
288
+ ctx.setStatus(200);
289
+ ctx.json({ user: { id: 1, name: "John Doe" } });
290
+ }
291
+ });
292
+
293
+ // 404 handler
294
+ pipeline.use((ctx) => {
295
+ ctx.setStatus(404);
296
+ ctx.json({ error: "Route not found" });
297
+ });
298
+
299
+ // Precompile for performance
300
+ pipeline.precompile();
301
+
302
+ // Create server
303
+ const server = http.createServer(async (req, res) => {
304
+ try {
305
+ await pipeline.handle(req, res);
306
+ } catch (err) {
307
+ console.error("Pipeline Error:", err);
308
+ if (!res.headersSent) {
309
+ res.statusCode = 500;
310
+ res.setHeader("Content-Type", "application/json");
311
+ res.end(JSON.stringify({ error: "Internal Server Error" }));
312
+ }
313
+ }
314
+ });
315
+
316
+ // Start server
317
+ const PORT = process.env.PORT || 3001;
318
+ server.listen(PORT, () => {
319
+ console.log(`🚀 AetherJS Server running on http://localhost:${PORT}`);
320
+ });
321
+ ```
322
+
323
+ ⚡ Performance Optimization
324
+
325
+ Object Pooling
326
+ AetherJS uses object pooling to reuse context objects, reducing garbage collection pressure:
327
+
328
+ ```javascript
329
+ // Object pool with 4096 pre-allocated contexts
330
+ const CONTEXT_POOL = [];
331
+ const CONTEXT_POOL_SIZE = 4096;
332
+
333
+ // Context reuse
334
+ _getContext(request, response) {
335
+ if (CONTEXT_POOL.length > 0) {
336
+ const context = CONTEXT_POOL.pop();
337
+ context._reset(request, response);
338
+ return context;
339
+ }
340
+ return new AetherContext(request, response);
341
+ }
342
+ ```
343
+
344
+ Header Buffer Optimization
345
+ Pre-allocated global buffer for header operations:
346
+
347
+ ```javascript
348
+ // Pre-allocated header buffer
349
+ const GLOBAL_HEADER_BUFFER = new Array(64);
350
+
351
+ // Fast header setting
352
+ _finalize() {
353
+ let cursor = 2;
354
+ for (let i = 0; i < this._headersCount; i++) {
355
+ const key = this._headersKeys[i];
356
+ const val = this._headersObj[key];
357
+ if (val !== undefined) {
358
+ GLOBAL_HEADER_BUFFER[cursor++] = key;
359
+ GLOBAL_HEADER_BUFFER[cursor++] = val;
360
+ }
361
+ }
362
+ }
363
+ ```
364
+
365
+ Middleware Compilation
366
+ AetherCompiler optimizes middleware chains at runtime:
367
+
368
+ ```javascript
369
+ // Compile middleware chain for optimal execution
370
+ compile() {
371
+ // Check if all middleware are synchronous
372
+ const isAllSync = middlewares.every((mw) => {
373
+ const str = mw.toString();
374
+ return !str.includes("async ") &&
375
+ !str.includes(".then") &&
376
+ !str.includes("await ");
377
+ });
378
+
379
+ // Fast path for synchronous chains
380
+ if (isAllSync) {
381
+ return function executePureSyncChain(context) {
382
+ for (let i = 0; i < len; i++) {
383
+ middlewares[i](context, null);
384
+ if (context.isTerminated()) return;
385
+ }
386
+ context._finalize();
387
+ };
388
+ }
389
+
390
+ // Async chain with optimized state machine
391
+ return function executeAsyncChain(context) {
392
+ // Async execution with minimal overhead
393
+ };
394
+ }
395
+ ```
396
+
397
+ 🔧 Configuration
398
+
399
+ Environment Variables
400
+ Copy .env.example to .env and customize:
401
+
402
+ ```bash
403
+ Server
404
+ PORT=3001
405
+
406
+ Security
407
+ JWT_SECRET=your-secure-jwt-secret
408
+ SESSION_SECRET=your-secure-session-secret
409
+
410
+ CORS
411
+ CORS_ENABLED=true
412
+ CORS_ORIGIN=*
413
+ CORS_CREDENTIALS=true
414
+
415
+ Compression
416
+ COMPRESSION_ENABLED=true
417
+ COMPRESSION_THRESHOLD=1024
418
+ COMPRESSION_GZIP=true
419
+
420
+ Rate Limiting
421
+ RATE_LIMIT_ENABLED=true
422
+ RATE_LIMIT_MAX_REQUESTS=100
423
+ RATE_LIMIT_WINDOW_MS=900000
424
+ ```
425
+
426
+ Custom Configuration
427
+ All middleware supports both environment variables and programmatic configuration:
428
+
429
+ ```javascript
430
+ // Programmatic configuration
431
+ const securityMiddleware = middleware.security({
432
+ hsts: {
433
+ enabled: true,
434
+ maxAge: 31536000,
435
+ includeSubDomains: true,
436
+ preload: false
437
+ },
438
+ noSniff: { enabled: true },
439
+ frameguard: { enabled: true, action: "DENY" },
440
+ hidePoweredBy: true,
441
+ referrerPolicy: {
442
+ enabled: true,
443
+ value: "strict-origin-when-cross-origin"
444
+ }
445
+ });
446
+ ```
447
+
448
+ 📊 Benchmarking
449
+
450
+ Running Benchmarks
451
+ ```bash
452
+ Install autocannon
453
+ npm install -g autocannon
454
+
455
+ Run benchmark
456
+ autocannon -c 100 -d 30 -p 10 http://localhost:3001/public/info
457
+ ```
458
+
459
+ Expected Results
460
+ - Throughput: 25,000+ requests per second
461
+ - Latency: 3-7ms average, <50ms P99
462
+ - Memory: <50MB under load
463
+ - CPU: Efficient single-core utilization
464
+
465
+ 🛡️ Security Features
466
+
467
+ Built-in Security Headers
468
+ - Strict-Transport-Security: Enforces HTTPS
469
+ - X-Content-Type-Options: Prevents MIME type sniffing
470
+ - X-Frame-Options: Clickjacking protection
471
+ - X-XSS-Protection: Cross-site scripting protection
472
+ - Referrer-Policy: Controls referrer information
473
+ - Permissions-Policy: Feature permission controls
474
+
475
+ JWT Security
476
+ - Synchronous verification for maximum performance
477
+ - Multiple token extraction methods (header, query, cookie)
478
+ - Configurable algorithms and validation options
479
+ - Token refresh capabilities
480
+
481
+ Rate Limiting
482
+ - Memory-efficient LRU storage
483
+ - Incremental cleanup to avoid blocking
484
+ - Configurable windows and limits
485
+ - Skip options for successful/failed requests
486
+
487
+ 🔌 Extending AetherJS
488
+
489
+ Custom Middleware
490
+ ```javascript
491
+ function customMiddleware(options = {}) {
492
+ return async function middleware(context, next) {
493
+ // Pre-processing
494
+ const startTime = Date.now();
495
+
496
+ // Call next middleware
497
+ if (typeof next === "function") {
498
+ await next();
499
+ }
500
+
501
+ // Post-processing
502
+ const duration = Date.now() - startTime;
503
+ context.setHeader("X-Response-Time", `${duration}ms`);
504
+ };
505
+ }
506
+
507
+ // Usage
508
+ pipeline.use(customMiddleware());
509
+ ```
510
+
511
+ Custom Stores
512
+ ```javascript
513
+ class RedisStore {
514
+ constructor(redisClient) {
515
+ this.client = redisClient;
516
+ }
517
+
518
+ async get(key) {
519
+ return await this.client.get(key);
520
+ }
521
+
522
+ async set(key, value, ttl) {
523
+ await this.client.setex(key, Math.floor(ttl / 1000), value);
524
+ }
525
+
526
+ async delete(key) {
527
+ await this.client.del(key);
528
+ }
529
+ }
530
+
531
+ // Usage with session manager
532
+ const sessionManager = new middleware.session({
533
+ store: new RedisStore(redisClient),
534
+ // ... other options
535
+ });
536
+ ```
537
+
538
+ 🏆 Our Advantages
539
+
540
+ 1. Unmatched Performance
541
+ - 25,000+ QPS on a single core
542
+ - Zero-allocation design minimizes GC pressure
543
+ - Object pooling for context reuse
544
+ - Pre-compiled middleware chains
545
+
546
+ 2. Memory Efficiency
547
+ - Fixed-size object pools prevent memory fragmentation
548
+ - LRU caching for intelligent resource management
549
+ - Incremental cleanup avoids blocking operations
550
+
551
+ 3. Developer Experience
552
+ - Familiar middleware pattern (Express/Koa-like)
553
+ - Comprehensive built-in middleware
554
+ - Environment-based configuration
555
+ - Type-safe (with TypeScript definitions)
556
+
557
+ 4. Production Ready
558
+ - Comprehensive security headers and protections
559
+ - Built-in rate limiting with efficient storage
560
+ - JWT authentication with synchronous verification
561
+ - Session management with multiple store options
562
+
563
+ 5. Extensible Architecture
564
+ - Easy custom middleware creation
565
+ - Pluggable storage backends
566
+ - Comprehensive error handling
567
+ - Detailed metrics and monitoring
568
+
569
+ 6. Modern Features
570
+ - Async/await support throughout
571
+ - HTTP/2 ready architecture
572
+ - Compression with multiple algorithms
573
+ - CORS with fine-grained control
574
+
575
+ 📄 License
576
+
577
+ MIT License - see LICENSE file for details.
578
+