@africode/core 5.0.11 → 5.0.13
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/AGENTS.md +585 -585
- package/AGENT_INSTRUCTIONS.md +595 -595
- package/COMPONENT_SCHEMA.json +1826 -1800
- package/LICENSE +623 -623
- package/README.md +476 -476
- package/bin/africode.js +73 -73
- package/bin/cli.ts +82 -82
- package/bin/create-africode.js +220 -220
- package/bin/scaffold.ts +218 -218
- package/components/accordion.js +183 -183
- package/components/alert.js +131 -131
- package/components/auth-form.js +154 -154
- package/components/auth.js +172 -172
- package/components/avatar.js +117 -117
- package/components/badge.js +104 -104
- package/components/base.d.ts +139 -139
- package/components/base.js +234 -234
- package/components/breadcrumb.js +76 -72
- package/components/button.js +164 -164
- package/components/card.js +144 -137
- package/components/carousel.js +32 -32
- package/components/cart-drawer.js +28 -28
- package/components/code-block.js +20 -20
- package/components/contact-form.js +25 -25
- package/components/cookie-consent.js +23 -23
- package/components/cta-banner.js +38 -38
- package/components/cultural-card.js +243 -243
- package/components/dashboard-activity-list.js +103 -103
- package/components/dashboard-card.js +85 -85
- package/components/dashboard-metric.js +81 -81
- package/components/dashboard-shell.js +85 -85
- package/components/dashboard-topbar.js +84 -84
- package/components/divider.js +83 -83
- package/components/dropdown.js +171 -171
- package/components/error-boundary.js +155 -155
- package/components/faq-accordion.js +23 -23
- package/components/feature-grid.js +85 -85
- package/components/file-uploader.js +22 -22
- package/components/filter-bar.js +19 -19
- package/components/footer.js +113 -113
- package/components/form.js +131 -131
- package/components/gallery.js +22 -22
- package/components/hero.js +140 -138
- package/components/icon.js +36 -36
- package/components/index.js +128 -128
- package/components/input.js +252 -256
- package/components/kanga-card.js +185 -185
- package/components/kyc-upload.js +173 -173
- package/components/language-switcher.js +108 -108
- package/components/loader.js +80 -80
- package/components/modal.js +262 -262
- package/components/motion.js +84 -84
- package/components/nav-drawer.js +216 -216
- package/components/navbar.js +243 -236
- package/components/newsletter-signup.js +24 -24
- package/components/pagination.js +31 -31
- package/components/pattern-showcase.js +225 -225
- package/components/pricing-card.js +100 -100
- package/components/product-card.js +41 -41
- package/components/progress.js +132 -134
- package/components/react.js +111 -111
- package/components/search-box.js +24 -24
- package/components/section.js +54 -54
- package/components/select.js +321 -322
- package/components/sidebar.js +180 -180
- package/components/simple-chart.js +22 -22
- package/components/skeleton.js +85 -85
- package/components/stepper.js +28 -28
- package/components/table.js +181 -181
- package/components/tabs.js +202 -202
- package/components/team-grid.js +23 -23
- package/components/testimonial.js +94 -94
- package/components/theme-toggle.js +82 -82
- package/components/toast.js +139 -139
- package/components/tooltip.js +167 -167
- package/components/transaction-ledger.js +138 -138
- package/components/ui-avatar.js +79 -79
- package/components/ui-badge.js +61 -61
- package/components/ui-button.js +149 -149
- package/components/ui-card.js +74 -75
- package/components/ui-chip.js +87 -87
- package/components/ui-input.js +110 -110
- package/components/ui-popover.js +84 -84
- package/components/ui-progress-ring.js +60 -60
- package/components/ui-select.js +85 -85
- package/components/ui-stat.js +75 -75
- package/components/ui-switch.js +85 -85
- package/components/ui-table.js +69 -69
- package/components/ui-tabs.js +99 -99
- package/components/ui-tag.js +64 -64
- package/components/ui-textarea.js +84 -84
- package/components/ui-tooltip.js +66 -66
- package/components/video-player.js +22 -22
- package/components/wallet-balance.js +114 -114
- package/core/a2ui-schema-manager.js +351 -351
- package/core/a2ui.js +696 -696
- package/core/actions.js +27 -27
- package/core/bun-runtime.js +396 -396
- package/core/cli/commands/add.js +23 -23
- package/core/cli/commands/audit.js +58 -58
- package/core/cli/commands/build.js +193 -193
- package/core/cli/commands/create-plugin.js +241 -241
- package/core/cli/commands/dev.js +248 -283
- package/core/cli/commands/lint.js +23 -23
- package/core/cli/commands/test.js +33 -34
- package/core/cli/migrator.js +71 -71
- package/core/cli/ui.js +56 -56
- package/core/compliance.js +823 -823
- package/core/config.js +265 -265
- package/core/db-advanced.js +478 -481
- package/core/db.js +282 -284
- package/core/enhanced-hmr.js +406 -406
- package/core/errors.js +222 -222
- package/core/file-router.js +47 -47
- package/core/hmr-client.js +203 -204
- package/core/hmr.js +205 -197
- package/core/html.d.ts +30 -30
- package/core/html.js +84 -84
- package/core/hydration.js +52 -52
- package/core/lipa-namba-journey.js +548 -605
- package/core/logging.js +14 -14
- package/core/middleware.js +145 -145
- package/core/motion.js +106 -106
- package/core/nida-cig-middleware.js +417 -460
- package/core/patterns.d.ts +124 -124
- package/core/patterns.js +947 -1001
- package/core/plugins/index.js +345 -345
- package/core/request-analytics.js +253 -253
- package/core/request-identity.js +93 -93
- package/core/router.js +386 -386
- package/core/sdk-browser.js +140 -140
- package/core/sdk-client.js +61 -61
- package/core/sdk.d.ts +133 -133
- package/core/sdk.js +148 -148
- package/core/seo.js +76 -76
- package/core/server/auth-endpoints.js +339 -339
- package/core/server/auth.js +180 -180
- package/core/server/csrf.js +200 -206
- package/core/server/db.js +39 -39
- package/core/server/middleware.js +324 -324
- package/core/server/rate-limit.js +238 -238
- package/core/server/render.js +67 -69
- package/core/server/router.js +23 -11
- package/core/session-store.js +68 -68
- package/core/shim.js +28 -28
- package/core/state.d.ts +86 -86
- package/core/state.js +276 -276
- package/core/store.d.ts +122 -122
- package/core/store.js +61 -61
- package/core/validation.d.ts +232 -232
- package/core/validation.js +602 -602
- package/core/websocket.js +656 -641
- package/dist/africode.js +233 -230
- package/dist/africode.js.map +83 -83
- package/dist/build-info.json +3 -3
- package/dist/components.js +195 -192
- package/dist/components.js.map +73 -73
- package/dist/styles/africanity.css +321 -321
- package/dist/styles/typography.css +140 -140
- package/docs/IDE-Guide.md +50 -50
- package/package.json +113 -113
- package/scripts/generate-component-schema.js +82 -79
- package/styles/africanity.css +321 -321
- package/styles/typography.css +140 -140
- package/templates/starter/.env.example +15 -15
- package/templates/starter/africode.config.js +40 -40
- package/templates/starter/package.json +13 -13
- package/templates/starter/src/index.js +18 -18
- package/templates/starter/src/pages/index.html +55 -55
- package/templates/starter/src/pages/index.js +17 -17
- package/templates/starter/src/styles/main.css +3 -3
- package/templates/starter-3d/.env.example +7 -7
- package/templates/starter-3d/africode.config.js +29 -29
- package/templates/starter-3d/components/af-model-viewer.js +125 -125
- package/templates/starter-3d/package.json +14 -14
- package/templates/starter-3d/src/pages/index.html +55 -55
- package/templates/starter-3d/src/pages/index.js +50 -50
- package/templates/starter-3d/src/styles/main.css +3 -3
- package/templates/starter-dashboard/.env.example +21 -21
- package/templates/starter-dashboard/africode.config.js +20 -20
- package/templates/starter-dashboard/package.json +14 -14
- package/templates/starter-dashboard/src/index.js +17 -17
- package/templates/starter-dashboard/src/pages/api/analytics.js +24 -24
- package/templates/starter-dashboard/src/pages/index.html +118 -118
- package/templates/starter-dashboard/src/pages/index.js +110 -110
- package/templates/starter-dashboard/src/styles/main.css +172 -172
- package/templates/starter-fintech/.env.example +28 -28
- package/templates/starter-fintech/africode.config.js +20 -20
- package/templates/starter-fintech/package.json +15 -15
- package/templates/starter-fintech/src/index.js +17 -17
- package/templates/starter-fintech/src/pages/api/auth.js +45 -45
- package/templates/starter-fintech/src/pages/api/transfer.js +65 -65
- package/templates/starter-fintech/src/pages/api/wallet.js +39 -39
- package/templates/starter-fintech/src/pages/api/webhooks/payment.js +32 -32
- package/templates/starter-fintech/src/pages/index.html +169 -169
- package/templates/starter-fintech/src/pages/index.js +161 -161
- package/templates/starter-fintech/src/styles/main.css +246 -246
- package/templates/starter-react/.env.example +15 -15
- package/templates/starter-react/africode.config.js +40 -40
- package/templates/starter-react/package.json +15 -15
- package/templates/starter-react/src/pages/index.html +55 -55
- package/templates/starter-react/src/pages/index.js +68 -68
- package/templates/starter-react/src/styles/main.css +3 -3
- package/templates/starter-tailwind/.env.example +15 -15
- package/templates/starter-tailwind/africode.config.js +40 -40
- package/templates/starter-tailwind/package.json +19 -19
- package/templates/starter-tailwind/src/pages/index.html +55 -55
- package/templates/starter-tailwind/src/pages/index.js +67 -67
- package/templates/starter-tailwind/src/styles/main.css +3 -3
- package/templates/starter-tailwind/src/styles/tailwind.css +1 -1
- package/templates/starter-tailwind/src/tailwind-loader.js +30 -30
- package/templates/starter-tailwind/tailwind.config.cjs +18 -18
- package/templates/starter-website/.env.example +18 -18
- package/templates/starter-website/africode.config.js +20 -20
- package/templates/starter-website/package.json +14 -14
- package/templates/starter-website/src/index.js +17 -17
- package/templates/starter-website/src/pages/index.html +124 -124
- package/templates/starter-website/src/pages/index.js +116 -116
- package/templates/starter-website/src/styles/main.css +195 -195
- package/bin/africode.js.1758507140 +0 -343
- package/core/heartbeat.js +0 -64
|
@@ -1,324 +1,324 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* AfriCode Middleware Pipeline
|
|
3
|
-
*
|
|
4
|
-
* Chainable middleware system for cross-cutting concerns:
|
|
5
|
-
* - CORS handling
|
|
6
|
-
* - Request logging
|
|
7
|
-
* - Authentication checks
|
|
8
|
-
* - Rate limiting
|
|
9
|
-
* - Error handling
|
|
10
|
-
*
|
|
11
|
-
* Usage:
|
|
12
|
-
* ```javascript
|
|
13
|
-
* const app = new MiddlewareApp();
|
|
14
|
-
* app.use(cors({ origin: 'https://example.com' }));
|
|
15
|
-
* app.use(logging());
|
|
16
|
-
* app.use(authRequired());
|
|
17
|
-
* app.listen(3000);
|
|
18
|
-
* ```
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
export class MiddlewareApp {
|
|
22
|
-
constructor() {
|
|
23
|
-
this.middlewares = [];
|
|
24
|
-
this.errorHandlers = [];
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Register a middleware function
|
|
29
|
-
* Middleware receives (request, response, next) and can:
|
|
30
|
-
* - Modify request/response
|
|
31
|
-
* - Call next() to continue
|
|
32
|
-
* - Return a response to short-circuit
|
|
33
|
-
*/
|
|
34
|
-
use(middleware) {
|
|
35
|
-
if (typeof middleware !== 'function') {
|
|
36
|
-
throw new Error('Middleware must be a function');
|
|
37
|
-
}
|
|
38
|
-
this.middlewares.push(middleware);
|
|
39
|
-
return this; // Enable chaining
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Register error handling middleware
|
|
44
|
-
*/
|
|
45
|
-
onError(handler) {
|
|
46
|
-
if (typeof handler !== 'function') {
|
|
47
|
-
throw new Error('Error handler must be a function');
|
|
48
|
-
}
|
|
49
|
-
this.errorHandlers.push(handler);
|
|
50
|
-
return this;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Execute middleware chain
|
|
55
|
-
*/
|
|
56
|
-
async executeMiddlewares(request, response) {
|
|
57
|
-
let index = 0;
|
|
58
|
-
|
|
59
|
-
const next = async () => {
|
|
60
|
-
if (index >= this.middlewares.length) {
|
|
61
|
-
return; // End of chain
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
const middleware = this.middlewares[index++];
|
|
65
|
-
try {
|
|
66
|
-
await middleware(request, response, next);
|
|
67
|
-
} catch (error) {
|
|
68
|
-
// Call error handlers
|
|
69
|
-
for (const handler of this.errorHandlers) {
|
|
70
|
-
await handler(error, request, response);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
await next();
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* Start HTTP server
|
|
80
|
-
*/
|
|
81
|
-
listen(port = 3000, callback) {
|
|
82
|
-
const server = Bun.serve({
|
|
83
|
-
port,
|
|
84
|
-
fetch: async (request) => {
|
|
85
|
-
const response = new Response();
|
|
86
|
-
await this.executeMiddlewares(request, response);
|
|
87
|
-
return response;
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
console.log(`[Middleware] Server listening on port ${port}`);
|
|
92
|
-
if (callback) callback();
|
|
93
|
-
return server;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Built-in Middleware Functions
|
|
99
|
-
*/
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* CORS Middleware
|
|
103
|
-
* Handles Cross-Origin Resource Sharing
|
|
104
|
-
*/
|
|
105
|
-
export function cors(options = {}) {
|
|
106
|
-
const {
|
|
107
|
-
origin = '*',
|
|
108
|
-
methods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
|
109
|
-
allowedHeaders = ['Content-Type', 'Authorization'],
|
|
110
|
-
credentials = false,
|
|
111
|
-
maxAge = 3600
|
|
112
|
-
} = options;
|
|
113
|
-
|
|
114
|
-
return async (request, response, next) => {
|
|
115
|
-
const requestOrigin = request.headers.get('origin');
|
|
116
|
-
|
|
117
|
-
// Check if origin is allowed
|
|
118
|
-
let allowOrigin
|
|
119
|
-
if (origin === '*') {
|
|
120
|
-
allowOrigin = true;
|
|
121
|
-
} else if (Array.isArray(origin)) {
|
|
122
|
-
allowOrigin = origin.includes(requestOrigin);
|
|
123
|
-
} else if (typeof origin === 'function') {
|
|
124
|
-
allowOrigin = origin(requestOrigin);
|
|
125
|
-
} else {
|
|
126
|
-
allowOrigin = origin === requestOrigin;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
if (allowOrigin) {
|
|
130
|
-
response.headers.set('Access-Control-Allow-Origin', requestOrigin || '*');
|
|
131
|
-
response.headers.set('Access-Control-Allow-Methods', methods.join(', '));
|
|
132
|
-
response.headers.set('Access-Control-Allow-Headers', allowedHeaders.join(', '));
|
|
133
|
-
response.headers.set('Access-Control-Max-Age', maxAge.toString());
|
|
134
|
-
|
|
135
|
-
if (credentials) {
|
|
136
|
-
response.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// Handle preflight requests
|
|
141
|
-
if (request.method === 'OPTIONS') {
|
|
142
|
-
return new Response(null, { status: 204 });
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
await next();
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* Request Logging Middleware
|
|
151
|
-
*/
|
|
152
|
-
export function logging(options = {}) {
|
|
153
|
-
const {
|
|
154
|
-
format = 'combined',
|
|
155
|
-
logFn = console.log
|
|
156
|
-
} = options;
|
|
157
|
-
|
|
158
|
-
return async (request, response, next) => {
|
|
159
|
-
const startTime = Date.now();
|
|
160
|
-
const method = request.method;
|
|
161
|
-
const url = new URL(request.url);
|
|
162
|
-
const pathname = url.pathname;
|
|
163
|
-
|
|
164
|
-
await next();
|
|
165
|
-
|
|
166
|
-
const duration = Date.now() - startTime;
|
|
167
|
-
const ip = request.headers.get('x-forwarded-for') || '127.0.0.1';
|
|
168
|
-
|
|
169
|
-
if (format === 'json') {
|
|
170
|
-
logFn(JSON.stringify({
|
|
171
|
-
ip,
|
|
172
|
-
method,
|
|
173
|
-
pathname,
|
|
174
|
-
duration,
|
|
175
|
-
timestamp: new Date().toISOString()
|
|
176
|
-
}));
|
|
177
|
-
} else if (format === 'combined') {
|
|
178
|
-
logFn(`[${new Date().toISOString()}] ${ip} - ${method} ${pathname} - ${duration}ms`);
|
|
179
|
-
} else {
|
|
180
|
-
logFn(`[${new Date().toISOString()}] ${method} ${pathname} - ${duration}ms`);
|
|
181
|
-
}
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/**
|
|
186
|
-
* Authentication Required Middleware
|
|
187
|
-
*/
|
|
188
|
-
export function authRequired() {
|
|
189
|
-
return async (request, response, next) => {
|
|
190
|
-
// Extract session from cookies
|
|
191
|
-
const cookieHeader = request.headers.get('Cookie');
|
|
192
|
-
if (!cookieHeader) {
|
|
193
|
-
return new Response(
|
|
194
|
-
JSON.stringify({ error: 'Unauthorized' }),
|
|
195
|
-
{ status: 401, headers: { 'Content-Type': 'application/json' } }
|
|
196
|
-
);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
const sessionMatch = cookieHeader.match(/session_id=([^;]+)/);
|
|
200
|
-
if (!sessionMatch) {
|
|
201
|
-
return new Response(
|
|
202
|
-
JSON.stringify({ error: 'Unauthorized' }),
|
|
203
|
-
{ status: 401, headers: { 'Content-Type': 'application/json' } }
|
|
204
|
-
);
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// Attach session ID to request for later use
|
|
208
|
-
request.sessionId = sessionMatch[1];
|
|
209
|
-
|
|
210
|
-
await next();
|
|
211
|
-
};
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/**
|
|
215
|
-
* Rate Limiting Middleware
|
|
216
|
-
*/
|
|
217
|
-
export function rateLimit(options = {}) {
|
|
218
|
-
const {
|
|
219
|
-
maxRequests = 100,
|
|
220
|
-
windowMs = 60000, // 1 minute
|
|
221
|
-
keyGenerator = (request) => request.headers.get('x-forwarded-for') || '127.0.0.1'
|
|
222
|
-
} = options;
|
|
223
|
-
|
|
224
|
-
const store = new Map();
|
|
225
|
-
|
|
226
|
-
return async (request, response, next) => {
|
|
227
|
-
const key = keyGenerator(request);
|
|
228
|
-
const now = Date.now();
|
|
229
|
-
const record = store.get(key);
|
|
230
|
-
|
|
231
|
-
// Clean up old records
|
|
232
|
-
if (record && now - record.resetTime > windowMs) {
|
|
233
|
-
store.delete(key);
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// Check if limit exceeded
|
|
237
|
-
const current = store.get(key) || { count: 0, resetTime: now };
|
|
238
|
-
if (current.count >= maxRequests) {
|
|
239
|
-
return new Response(
|
|
240
|
-
JSON.stringify({ error: 'Rate limit exceeded' }),
|
|
241
|
-
{ status: 429, headers: { 'Content-Type': 'application/json' } }
|
|
242
|
-
);
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
current.count++;
|
|
246
|
-
store.set(key, current);
|
|
247
|
-
|
|
248
|
-
// Add rate limit headers
|
|
249
|
-
response.headers.set('X-RateLimit-Limit', maxRequests.toString());
|
|
250
|
-
response.headers.set('X-RateLimit-Remaining', (maxRequests - current.count).toString());
|
|
251
|
-
response.headers.set('X-RateLimit-Reset', (current.resetTime + windowMs).toString());
|
|
252
|
-
|
|
253
|
-
await next();
|
|
254
|
-
};
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Error Handling Middleware
|
|
259
|
-
*/
|
|
260
|
-
export function errorHandler() {
|
|
261
|
-
return async (error, request, response) => {
|
|
262
|
-
console.error('[Error]', error);
|
|
263
|
-
|
|
264
|
-
const statusCode = error.status || 500;
|
|
265
|
-
const message = error.message || 'Internal Server Error';
|
|
266
|
-
|
|
267
|
-
response.status = statusCode;
|
|
268
|
-
response.headers.set('Content-Type', 'application/json');
|
|
269
|
-
|
|
270
|
-
return new Response(
|
|
271
|
-
JSON.stringify({
|
|
272
|
-
error: message,
|
|
273
|
-
status: statusCode,
|
|
274
|
-
timestamp: new Date().toISOString()
|
|
275
|
-
}),
|
|
276
|
-
{ status: statusCode, headers: { 'Content-Type': 'application/json' } }
|
|
277
|
-
);
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
/**
|
|
282
|
-
* Content Type Validation Middleware
|
|
283
|
-
*/
|
|
284
|
-
export function validateContentType(acceptedTypes = ['application/json']) {
|
|
285
|
-
return async (request, response, next) => {
|
|
286
|
-
if (request.method === 'POST' || request.method === 'PUT') {
|
|
287
|
-
const contentType = request.headers.get('Content-Type')?.split(';')[0];
|
|
288
|
-
if (!acceptedTypes.includes(contentType)) {
|
|
289
|
-
return new Response(
|
|
290
|
-
JSON.stringify({ error: 'Unsupported Content-Type' }),
|
|
291
|
-
{ status: 415, headers: { 'Content-Type': 'application/json' } }
|
|
292
|
-
);
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
await next();
|
|
296
|
-
};
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
/**
|
|
300
|
-
* Security Headers Middleware
|
|
301
|
-
*/
|
|
302
|
-
export function securityHeaders() {
|
|
303
|
-
return async (request, response, next) => {
|
|
304
|
-
response.headers.set('X-Content-Type-Options', 'nosniff');
|
|
305
|
-
response.headers.set('X-Frame-Options', 'DENY');
|
|
306
|
-
response.headers.set('X-XSS-Protection', '1; mode=block');
|
|
307
|
-
response.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
|
|
308
|
-
response.headers.set('Content-Security-Policy', "default-src 'self'");
|
|
309
|
-
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
|
|
310
|
-
|
|
311
|
-
await next();
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
export default {
|
|
316
|
-
MiddlewareApp,
|
|
317
|
-
cors,
|
|
318
|
-
logging,
|
|
319
|
-
authRequired,
|
|
320
|
-
rateLimit,
|
|
321
|
-
errorHandler,
|
|
322
|
-
validateContentType,
|
|
323
|
-
securityHeaders
|
|
324
|
-
};
|
|
1
|
+
/**
|
|
2
|
+
* AfriCode Middleware Pipeline
|
|
3
|
+
*
|
|
4
|
+
* Chainable middleware system for cross-cutting concerns:
|
|
5
|
+
* - CORS handling
|
|
6
|
+
* - Request logging
|
|
7
|
+
* - Authentication checks
|
|
8
|
+
* - Rate limiting
|
|
9
|
+
* - Error handling
|
|
10
|
+
*
|
|
11
|
+
* Usage:
|
|
12
|
+
* ```javascript
|
|
13
|
+
* const app = new MiddlewareApp();
|
|
14
|
+
* app.use(cors({ origin: 'https://example.com' }));
|
|
15
|
+
* app.use(logging());
|
|
16
|
+
* app.use(authRequired());
|
|
17
|
+
* app.listen(3000);
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export class MiddlewareApp {
|
|
22
|
+
constructor() {
|
|
23
|
+
this.middlewares = [];
|
|
24
|
+
this.errorHandlers = [];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Register a middleware function
|
|
29
|
+
* Middleware receives (request, response, next) and can:
|
|
30
|
+
* - Modify request/response
|
|
31
|
+
* - Call next() to continue
|
|
32
|
+
* - Return a response to short-circuit
|
|
33
|
+
*/
|
|
34
|
+
use(middleware) {
|
|
35
|
+
if (typeof middleware !== 'function') {
|
|
36
|
+
throw new Error('Middleware must be a function');
|
|
37
|
+
}
|
|
38
|
+
this.middlewares.push(middleware);
|
|
39
|
+
return this; // Enable chaining
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Register error handling middleware
|
|
44
|
+
*/
|
|
45
|
+
onError(handler) {
|
|
46
|
+
if (typeof handler !== 'function') {
|
|
47
|
+
throw new Error('Error handler must be a function');
|
|
48
|
+
}
|
|
49
|
+
this.errorHandlers.push(handler);
|
|
50
|
+
return this;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Execute middleware chain
|
|
55
|
+
*/
|
|
56
|
+
async executeMiddlewares(request, response) {
|
|
57
|
+
let index = 0;
|
|
58
|
+
|
|
59
|
+
const next = async () => {
|
|
60
|
+
if (index >= this.middlewares.length) {
|
|
61
|
+
return; // End of chain
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const middleware = this.middlewares[index++];
|
|
65
|
+
try {
|
|
66
|
+
await middleware(request, response, next);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
// Call error handlers
|
|
69
|
+
for (const handler of this.errorHandlers) {
|
|
70
|
+
await handler(error, request, response);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
await next();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Start HTTP server
|
|
80
|
+
*/
|
|
81
|
+
listen(port = 3000, callback) {
|
|
82
|
+
const server = Bun.serve({
|
|
83
|
+
port,
|
|
84
|
+
fetch: async (request) => {
|
|
85
|
+
const response = new Response();
|
|
86
|
+
await this.executeMiddlewares(request, response);
|
|
87
|
+
return response;
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
console.log(`[Middleware] Server listening on port ${port}`);
|
|
92
|
+
if (callback) {callback();}
|
|
93
|
+
return server;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Built-in Middleware Functions
|
|
99
|
+
*/
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* CORS Middleware
|
|
103
|
+
* Handles Cross-Origin Resource Sharing
|
|
104
|
+
*/
|
|
105
|
+
export function cors(options = {}) {
|
|
106
|
+
const {
|
|
107
|
+
origin = '*',
|
|
108
|
+
methods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
|
109
|
+
allowedHeaders = ['Content-Type', 'Authorization'],
|
|
110
|
+
credentials = false,
|
|
111
|
+
maxAge = 3600
|
|
112
|
+
} = options;
|
|
113
|
+
|
|
114
|
+
return async (request, response, next) => {
|
|
115
|
+
const requestOrigin = request.headers.get('origin');
|
|
116
|
+
|
|
117
|
+
// Check if origin is allowed
|
|
118
|
+
let allowOrigin;
|
|
119
|
+
if (origin === '*') {
|
|
120
|
+
allowOrigin = true;
|
|
121
|
+
} else if (Array.isArray(origin)) {
|
|
122
|
+
allowOrigin = origin.includes(requestOrigin);
|
|
123
|
+
} else if (typeof origin === 'function') {
|
|
124
|
+
allowOrigin = origin(requestOrigin);
|
|
125
|
+
} else {
|
|
126
|
+
allowOrigin = origin === requestOrigin;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (allowOrigin) {
|
|
130
|
+
response.headers.set('Access-Control-Allow-Origin', requestOrigin || '*');
|
|
131
|
+
response.headers.set('Access-Control-Allow-Methods', methods.join(', '));
|
|
132
|
+
response.headers.set('Access-Control-Allow-Headers', allowedHeaders.join(', '));
|
|
133
|
+
response.headers.set('Access-Control-Max-Age', maxAge.toString());
|
|
134
|
+
|
|
135
|
+
if (credentials) {
|
|
136
|
+
response.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Handle preflight requests
|
|
141
|
+
if (request.method === 'OPTIONS') {
|
|
142
|
+
return new Response(null, { status: 204 });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
await next();
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Request Logging Middleware
|
|
151
|
+
*/
|
|
152
|
+
export function logging(options = {}) {
|
|
153
|
+
const {
|
|
154
|
+
format = 'combined',
|
|
155
|
+
logFn = console.log
|
|
156
|
+
} = options;
|
|
157
|
+
|
|
158
|
+
return async (request, response, next) => {
|
|
159
|
+
const startTime = Date.now();
|
|
160
|
+
const method = request.method;
|
|
161
|
+
const url = new URL(request.url);
|
|
162
|
+
const pathname = url.pathname;
|
|
163
|
+
|
|
164
|
+
await next();
|
|
165
|
+
|
|
166
|
+
const duration = Date.now() - startTime;
|
|
167
|
+
const ip = request.headers.get('x-forwarded-for') || '127.0.0.1';
|
|
168
|
+
|
|
169
|
+
if (format === 'json') {
|
|
170
|
+
logFn(JSON.stringify({
|
|
171
|
+
ip,
|
|
172
|
+
method,
|
|
173
|
+
pathname,
|
|
174
|
+
duration,
|
|
175
|
+
timestamp: new Date().toISOString()
|
|
176
|
+
}));
|
|
177
|
+
} else if (format === 'combined') {
|
|
178
|
+
logFn(`[${new Date().toISOString()}] ${ip} - ${method} ${pathname} - ${duration}ms`);
|
|
179
|
+
} else {
|
|
180
|
+
logFn(`[${new Date().toISOString()}] ${method} ${pathname} - ${duration}ms`);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Authentication Required Middleware
|
|
187
|
+
*/
|
|
188
|
+
export function authRequired() {
|
|
189
|
+
return async (request, response, next) => {
|
|
190
|
+
// Extract session from cookies
|
|
191
|
+
const cookieHeader = request.headers.get('Cookie');
|
|
192
|
+
if (!cookieHeader) {
|
|
193
|
+
return new Response(
|
|
194
|
+
JSON.stringify({ error: 'Unauthorized' }),
|
|
195
|
+
{ status: 401, headers: { 'Content-Type': 'application/json' } }
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const sessionMatch = cookieHeader.match(/session_id=([^;]+)/);
|
|
200
|
+
if (!sessionMatch) {
|
|
201
|
+
return new Response(
|
|
202
|
+
JSON.stringify({ error: 'Unauthorized' }),
|
|
203
|
+
{ status: 401, headers: { 'Content-Type': 'application/json' } }
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Attach session ID to request for later use
|
|
208
|
+
request.sessionId = sessionMatch[1];
|
|
209
|
+
|
|
210
|
+
await next();
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Rate Limiting Middleware
|
|
216
|
+
*/
|
|
217
|
+
export function rateLimit(options = {}) {
|
|
218
|
+
const {
|
|
219
|
+
maxRequests = 100,
|
|
220
|
+
windowMs = 60000, // 1 minute
|
|
221
|
+
keyGenerator = (request) => request.headers.get('x-forwarded-for') || '127.0.0.1'
|
|
222
|
+
} = options;
|
|
223
|
+
|
|
224
|
+
const store = new Map();
|
|
225
|
+
|
|
226
|
+
return async (request, response, next) => {
|
|
227
|
+
const key = keyGenerator(request);
|
|
228
|
+
const now = Date.now();
|
|
229
|
+
const record = store.get(key);
|
|
230
|
+
|
|
231
|
+
// Clean up old records
|
|
232
|
+
if (record && now - record.resetTime > windowMs) {
|
|
233
|
+
store.delete(key);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Check if limit exceeded
|
|
237
|
+
const current = store.get(key) || { count: 0, resetTime: now };
|
|
238
|
+
if (current.count >= maxRequests) {
|
|
239
|
+
return new Response(
|
|
240
|
+
JSON.stringify({ error: 'Rate limit exceeded' }),
|
|
241
|
+
{ status: 429, headers: { 'Content-Type': 'application/json' } }
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
current.count++;
|
|
246
|
+
store.set(key, current);
|
|
247
|
+
|
|
248
|
+
// Add rate limit headers
|
|
249
|
+
response.headers.set('X-RateLimit-Limit', maxRequests.toString());
|
|
250
|
+
response.headers.set('X-RateLimit-Remaining', (maxRequests - current.count).toString());
|
|
251
|
+
response.headers.set('X-RateLimit-Reset', (current.resetTime + windowMs).toString());
|
|
252
|
+
|
|
253
|
+
await next();
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Error Handling Middleware
|
|
259
|
+
*/
|
|
260
|
+
export function errorHandler() {
|
|
261
|
+
return async (error, request, response) => {
|
|
262
|
+
console.error('[Error]', error);
|
|
263
|
+
|
|
264
|
+
const statusCode = error.status || 500;
|
|
265
|
+
const message = error.message || 'Internal Server Error';
|
|
266
|
+
|
|
267
|
+
response.status = statusCode;
|
|
268
|
+
response.headers.set('Content-Type', 'application/json');
|
|
269
|
+
|
|
270
|
+
return new Response(
|
|
271
|
+
JSON.stringify({
|
|
272
|
+
error: message,
|
|
273
|
+
status: statusCode,
|
|
274
|
+
timestamp: new Date().toISOString()
|
|
275
|
+
}),
|
|
276
|
+
{ status: statusCode, headers: { 'Content-Type': 'application/json' } }
|
|
277
|
+
);
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Content Type Validation Middleware
|
|
283
|
+
*/
|
|
284
|
+
export function validateContentType(acceptedTypes = ['application/json']) {
|
|
285
|
+
return async (request, response, next) => {
|
|
286
|
+
if (request.method === 'POST' || request.method === 'PUT') {
|
|
287
|
+
const contentType = request.headers.get('Content-Type')?.split(';')[0];
|
|
288
|
+
if (!acceptedTypes.includes(contentType)) {
|
|
289
|
+
return new Response(
|
|
290
|
+
JSON.stringify({ error: 'Unsupported Content-Type' }),
|
|
291
|
+
{ status: 415, headers: { 'Content-Type': 'application/json' } }
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
await next();
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Security Headers Middleware
|
|
301
|
+
*/
|
|
302
|
+
export function securityHeaders() {
|
|
303
|
+
return async (request, response, next) => {
|
|
304
|
+
response.headers.set('X-Content-Type-Options', 'nosniff');
|
|
305
|
+
response.headers.set('X-Frame-Options', 'DENY');
|
|
306
|
+
response.headers.set('X-XSS-Protection', '1; mode=block');
|
|
307
|
+
response.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
|
|
308
|
+
response.headers.set('Content-Security-Policy', "default-src 'self'");
|
|
309
|
+
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
|
|
310
|
+
|
|
311
|
+
await next();
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export default {
|
|
316
|
+
MiddlewareApp,
|
|
317
|
+
cors,
|
|
318
|
+
logging,
|
|
319
|
+
authRequired,
|
|
320
|
+
rateLimit,
|
|
321
|
+
errorHandler,
|
|
322
|
+
validateContentType,
|
|
323
|
+
securityHeaders
|
|
324
|
+
};
|