@oxog/spark 1.1.1 → 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 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1068 -956
  6. package/src/core/context.js +1098 -830
  7. package/src/core/middleware.js +303 -217
  8. package/src/index.js +183 -280
  9. package/src/middleware/body-parser.js +482 -526
  10. package/src/middleware/cache.js +177 -170
  11. package/src/middleware/compression.js +177 -182
  12. package/src/middleware/cors.js +176 -95
  13. package/src/middleware/health.js +219 -218
  14. package/src/middleware/logger.js +195 -194
  15. package/src/middleware/metrics.js +339 -327
  16. package/src/middleware/rate-limit.js +367 -319
  17. package/src/middleware/security.js +442 -332
  18. package/src/middleware/session.js +647 -529
  19. package/src/middleware/static.js +404 -299
  20. package/src/router/layer.js +197 -117
  21. package/src/router/route.js +149 -123
  22. package/src/router/router.js +703 -755
  23. package/src/utils/async-handler.js +145 -147
  24. package/src/utils/context-pool.js +83 -82
  25. package/src/utils/regex-validator.js +187 -163
  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 -959
  31. package/dist/core/context.js +0 -833
  32. package/dist/core/middleware.js +0 -220
  33. package/dist/core/request.js +0 -335
  34. package/dist/core/response.js +0 -377
  35. package/dist/index.js +0 -280
  36. package/dist/middleware/body-parser.js +0 -528
  37. package/dist/middleware/cache.js +0 -173
  38. package/dist/middleware/compression.js +0 -185
  39. package/dist/middleware/cors.js +0 -97
  40. package/dist/middleware/health.js +0 -221
  41. package/dist/middleware/index.js +0 -23
  42. package/dist/middleware/logger.js +0 -197
  43. package/dist/middleware/metrics.js +0 -330
  44. package/dist/middleware/rate-limit.js +0 -322
  45. package/dist/middleware/security.js +0 -335
  46. package/dist/middleware/session.js +0 -532
  47. package/dist/middleware/static.js +0 -301
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -119
  50. package/dist/router/route.js +0 -125
  51. package/dist/router/router.js +0 -758
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -150
  54. package/dist/utils/cache.js +0 -443
  55. package/dist/utils/context-pool.js +0 -85
  56. package/dist/utils/error-types.js +0 -134
  57. package/dist/utils/http.js +0 -415
  58. package/dist/utils/regex-validator.js +0 -166
  59. package/src/core/request.js +0 -335
  60. package/src/core/response.js +0 -377
  61. package/src/middleware/index.js +0 -23
  62. package/src/utils/cache.js +0 -443
  63. package/src/utils/error-types.js +0 -134
  64. package/src/utils/http.js +0 -415
@@ -1,833 +1,1101 @@
1
1
  'use strict';
2
2
 
3
- /**
4
- * @fileoverview Context class for handling HTTP requests and responses in Spark Framework
5
- * @author Spark Framework Team
6
- * @since 1.0.0
7
- * @version 1.0.0
8
- */
9
-
10
- const { URL } = require('url');
11
- const querystring = require('querystring');
12
-
13
- /**
14
- * Context class that wraps HTTP request and response objects
15
- *
16
- * The Context class provides a unified interface for handling HTTP requests and responses.
17
- * It parses incoming request data, provides helper methods for setting headers and status codes,
18
- * and includes convenience methods for sending various types of responses.
19
- *
20
- * @class Context
21
- * @since 1.0.0
22
- *
23
- * @example
24
- * // In a middleware or route handler
25
- * app.get('/users/:id', (ctx) => {
26
- * const userId = ctx.params.id;
27
- * const userAgent = ctx.get('user-agent');
28
- *
29
- * ctx.set('X-Response-Time', '10ms');
30
- * ctx.json({ id: userId, userAgent });
31
- * });
32
- *
33
- * @example
34
- * // Working with cookies
35
- * app.post('/login', (ctx) => {
36
- * const { username, password } = ctx.body;
37
- *
38
- * if (authenticate(username, password)) {
39
- * ctx.setCookie('session', 'abc123', {
40
- * httpOnly: true,
41
- * secure: true,
42
- * maxAge: 3600000
43
- * });
44
- * ctx.json({ success: true });
45
- * } else {
46
- * ctx.status(401).json({ error: 'Invalid credentials' });
47
- * }
48
- * });
49
- */
50
- class Context {
51
- /**
52
- * Create a new Context instance
53
- *
54
- * @param {http.IncomingMessage} req - The HTTP request object
55
- * @param {http.ServerResponse} res - The HTTP response object
56
- * @param {Application} app - The Spark application instance
57
- *
58
- * @since 1.0.0
59
- *
60
- * @example
61
- * // Context is typically created automatically by the framework
62
- * const ctx = new Context(req, res, app);
63
- */
64
- constructor(req, res, app) {
65
- /**
66
- * The HTTP request object
67
- * @type {http.IncomingMessage}
68
- * @readonly
69
- */
70
- this.req = req;
71
-
72
- /**
73
- * The HTTP response object
74
- * @type {http.ServerResponse}
75
- * @readonly
76
- */
77
- this.res = res;
78
-
79
- /**
80
- * The Spark application instance
81
- * @type {Application}
82
- * @readonly
83
- */
84
- this.app = app;
85
-
86
- /**
87
- * Whether a response has been sent
88
- * @type {boolean}
89
- * @readonly
90
- */
91
- this.responded = false;
92
-
93
- /**
94
- * The HTTP status code for the response
95
- * @type {number}
96
- */
97
- this.statusCode = 200;
98
-
99
- this.initializeUrl();
100
- this.initializeHeaders();
101
- this.initializeQuery();
102
- this.initializeCookies();
103
-
104
- /**
105
- * Route parameters extracted from the URL
106
- * @type {Object}
107
- * @example
108
- * // For route '/users/:id' with URL '/users/123'
109
- * ctx.params.id // '123'
110
- */
111
- this.params = {};
112
-
113
- /**
114
- * Parsed request body
115
- * @type {*}
116
- */
117
- this.body = null;
118
-
119
- /**
120
- * Uploaded files (when using multipart/form-data)
121
- * @type {Object|null}
122
- */
123
- this.files = null;
124
-
125
- /**
126
- * Session data (when session middleware is used)
127
- * @type {Object|null}
128
- */
129
- this.session = null;
130
-
131
- /**
132
- * Application state for storing custom data
133
- * @type {Object}
134
- */
135
- this.state = {};
136
- }
137
-
138
- /**
139
- * Initialize URL-related properties from the request
140
- *
141
- * Parses the request URL and extracts path, method, and other URL components.
142
- * Handles malformed URLs by throwing an appropriate error.
143
- *
144
- * @private
145
- * @throws {Error} When the URL cannot be parsed
146
- * @since 1.0.0
147
- */
148
- initializeUrl() {
149
- const protocol = this.req.connection.encrypted ? 'https' : 'http';
150
- const host = this.req.headers.host || 'localhost';
151
-
152
- try {
153
- /**
154
- * Parsed URL object
155
- * @type {URL|null}
156
- * @readonly
157
- */
158
- this.url = new URL(this.req.url, `${protocol}://${host}`);
159
-
160
- /**
161
- * Request path (pathname without query string)
162
- * @type {string}
163
- * @readonly
164
- */
165
- this.path = this.url.pathname;
166
- } catch (error) {
167
- // Handle malformed URLs - throw proper error instead of just logging
168
- this.url = null;
169
- this.path = '/';
170
- this.statusCode = 400;
171
- this.body = { error: 'Invalid URL format' };
172
- throw new Error(`Failed to parse URL: ${error.message}`);
173
- }
174
-
175
- /**
176
- * HTTP method (GET, POST, PUT, etc.)
177
- * @type {string}
178
- * @readonly
179
- */
180
- this.method = this.req.method ? this.req.method.toUpperCase() : 'GET';
181
-
182
- /**
183
- * Original request URL including query string
184
- * @type {string}
185
- * @readonly
186
- */
187
- this.originalUrl = this.req.url;
188
- }
189
-
190
- /**
191
- * Initialize request and response headers
192
- *
193
- * Copies request headers and initializes response headers object.
194
- *
195
- * @private
196
- * @since 1.0.0
197
- */
198
- initializeHeaders() {
199
- /**
200
- * Request headers (lowercase keys)
201
- * @type {Object}
202
- * @readonly
203
- */
204
- this.headers = { ...this.req.headers };
205
-
206
- /**
207
- * Response headers to be sent
208
- * @type {Object}
209
- * @private
210
- */
211
- this.responseHeaders = {};
212
- }
213
-
214
- /**
215
- * Initialize query string parameters
216
- *
217
- * Parses the URL query string into an object.
218
- *
219
- * @private
220
- * @since 1.0.0
221
- */
222
- initializeQuery() {
223
- /**
224
- * Parsed query string parameters
225
- * @type {Object}
226
- * @readonly
227
- * @example
228
- * // For URL '/search?q=hello&limit=10'
229
- * ctx.query.q // 'hello'
230
- * ctx.query.limit // '10'
231
- */
232
- this.query = {};
233
- if (this.url.search) {
234
- this.query = querystring.parse(this.url.search.slice(1));
235
- }
236
- }
237
-
238
- /**
239
- * Initialize cookies from the request
240
- *
241
- * Parses the Cookie header and decodes cookie values.
242
- * Malformed cookies are skipped and logged.
243
- *
244
- * @private
245
- * @since 1.0.0
246
- */
247
- initializeCookies() {
248
- /**
249
- * Parsed cookies from the request
250
- * @type {Object}
251
- * @readonly
252
- * @example
253
- * // For Cookie header 'session=abc123; theme=dark'
254
- * ctx.cookies.session // 'abc123'
255
- * ctx.cookies.theme // 'dark'
256
- */
257
- this.cookies = {};
258
- const cookieHeader = this.req.headers.cookie;
259
- if (cookieHeader) {
260
- cookieHeader.split(';').forEach(cookie => {
261
- const [name, value] = cookie.trim().split('=');
262
- if (name && value) {
263
- try {
264
- this.cookies[name] = decodeURIComponent(value);
265
- } catch (error) {
266
- // Skip malformed cookie values
267
- console.error(`Failed to decode cookie ${name}: ${error.message}`);
268
- }
269
- }
270
- });
271
- }
272
- }
273
-
274
- /**
275
- * Get a request header value
276
- *
277
- * @param {string} headerName - The header name (case-insensitive)
278
- * @returns {string|undefined} The header value or undefined if not present
279
- *
280
- * @since 1.0.0
281
- *
282
- * @example
283
- * const userAgent = ctx.get('User-Agent');
284
- * const contentType = ctx.get('content-type');
285
- */
286
- get(headerName) {
287
- return this.headers[headerName.toLowerCase()];
288
- }
289
-
290
- /**
291
- * Set a response header
292
- *
293
- * Sets a response header with validation for security and RFC compliance.
294
- * Header names and values are validated to prevent injection attacks.
295
- *
296
- * @param {string} headerName - The header name
297
- * @param {string|number} value - The header value
298
- * @returns {Context} The context instance for method chaining
299
- *
300
- * @throws {Error} When header name or value is invalid
301
- *
302
- * @since 1.0.0
303
- *
304
- * @example
305
- * ctx.set('Content-Type', 'application/json');
306
- * ctx.set('X-Response-Time', '10ms');
307
- *
308
- * @example
309
- * // Method chaining
310
- * ctx.set('Content-Type', 'text/html')
311
- * .set('Cache-Control', 'no-cache');
312
- */
313
- set(headerName, value) {
314
- // Validate header name
315
- if (!headerName || typeof headerName !== 'string') {
316
- throw new Error('Header name must be a non-empty string');
317
- }
318
-
319
- // Validate header name format (RFC 7230)
320
- if (!/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(headerName)) {
321
- throw new Error(`Invalid header name: ${headerName}`);
322
- }
323
-
324
- // Validate header value
325
- if (value !== undefined && value !== null) {
326
- const stringValue = String(value);
327
- // Check for invalid characters in header value (CRLF and null byte)
328
- if (/[\r\n\x00]/.test(stringValue)) {
329
- throw new Error('Header value cannot contain CRLF or null characters');
330
- }
331
- // Check header value length
332
- if (stringValue.length > 8192) {
333
- throw new Error('Header value too long (max 8192 characters)');
334
- }
335
- this.responseHeaders[headerName.toLowerCase()] = stringValue;
336
- }
337
-
338
- return this;
339
- }
340
-
341
- /**
342
- * Alias for set() method
343
- *
344
- * @param {string} name - The header name
345
- * @param {string|number} value - The header value
346
- * @returns {Context} The context instance for method chaining
347
- *
348
- * @since 1.0.0
349
- * @see {@link Context#set}
350
- */
351
- setHeader(name, value) {
352
- return this.set(name, value);
353
- }
354
-
355
- /**
356
- * Get a response header value
357
- *
358
- * @param {string} name - The header name (case-insensitive)
359
- * @returns {string|undefined} The header value or undefined if not set
360
- *
361
- * @since 1.0.0
362
- *
363
- * @example
364
- * ctx.set('Content-Type', 'application/json');
365
- * const contentType = ctx.getHeader('content-type'); // 'application/json'
366
- */
367
- getHeader(name) {
368
- return this.responseHeaders[name.toLowerCase()];
369
- }
370
-
371
- /**
372
- * Remove a response header
373
- *
374
- * @param {string} name - The header name (case-insensitive)
375
- * @returns {Context} The context instance for method chaining
376
- *
377
- * @since 1.0.0
378
- *
379
- * @example
380
- * ctx.removeHeader('X-Powered-By');
381
- */
382
- removeHeader(name) {
383
- delete this.responseHeaders[name.toLowerCase()];
384
- return this;
385
- }
386
-
387
- /**
388
- * Set the HTTP status code
389
- *
390
- * @param {number|string} code - HTTP status code (100-599)
391
- * @returns {Context} The context instance for method chaining
392
- *
393
- * @throws {Error} When status code is invalid
394
- *
395
- * @since 1.0.0
396
- *
397
- * @example
398
- * ctx.status(200); // OK
399
- * ctx.status(404); // Not Found
400
- * ctx.status(500); // Internal Server Error
401
- *
402
- * @example
403
- * // Method chaining
404
- * ctx.status(201).json({ id: 123, name: 'User' });
405
- */
406
- status(code) {
407
- // Validate status code
408
- const statusCode = parseInt(code);
409
- if (isNaN(statusCode) || statusCode < 100 || statusCode > 599) {
410
- throw new Error(`Invalid status code: ${code}. Must be between 100 and 599`);
411
- }
412
- this.statusCode = statusCode;
413
- return this;
414
- }
415
-
416
- /**
417
- * Redirect to a URL
418
- *
419
- * Sets the Location header and status code, then ends the response.
420
- *
421
- * @param {string} url - The URL to redirect to
422
- * @param {number} [status=302] - HTTP status code for redirect
423
- * @returns {Context} The context instance for method chaining
424
- *
425
- * @since 1.0.0
426
- *
427
- * @example
428
- * // Temporary redirect (302)
429
- * ctx.redirect('/login');
430
- *
431
- * @example
432
- * // Permanent redirect (301)
433
- * ctx.redirect('/new-path', 301);
434
- */
435
- redirect(url, status = 302) {
436
- this.status(status);
437
- this.set('Location', url);
438
- this.end();
439
- return this;
440
- }
441
-
442
- /**
443
- * Send a JSON response
444
- *
445
- * Sets the Content-Type header to application/json and sends the data as JSON.
446
- *
447
- * @param {*} data - The data to send as JSON
448
- * @returns {Context} The context instance for method chaining
449
- *
450
- * @since 1.0.0
451
- *
452
- * @example
453
- * ctx.json({ message: 'Hello World' });
454
- *
455
- * @example
456
- * // With status code
457
- * ctx.status(201).json({ id: 123, name: 'User' });
458
- */
459
- json(data) {
460
- this.set('Content-Type', 'application/json');
461
- this.send(JSON.stringify(data));
462
- return this;
463
- }
464
-
465
- /**
466
- * Send a plain text response
467
- *
468
- * Sets the Content-Type header to text/plain and sends the data as text.
469
- *
470
- * @param {string} data - The text data to send
471
- * @returns {Context} The context instance for method chaining
472
- *
473
- * @since 1.0.0
474
- *
475
- * @example
476
- * ctx.text('Hello World');
477
- *
478
- * @example
479
- * // With status code
480
- * ctx.status(200).text('Success');
481
- */
482
- text(data) {
483
- this.set('Content-Type', 'text/plain');
484
- this.send(data);
485
- return this;
486
- }
487
-
488
- /**
489
- * Send an HTML response
490
- *
491
- * Sets the Content-Type header to text/html and sends the data as HTML.
492
- *
493
- * @param {string} data - The HTML data to send
494
- * @returns {Context} The context instance for method chaining
495
- *
496
- * @since 1.0.0
497
- *
498
- * @example
499
- * ctx.html('<h1>Hello World</h1>');
500
- *
501
- * @example
502
- * // With status code
503
- * ctx.status(200).html('<p>Welcome!</p>');
504
- */
505
- html(data) {
506
- this.set('Content-Type', 'text/html');
507
- this.send(data);
508
- return this;
509
- }
510
-
511
- /**
512
- * Send a response with data
513
- *
514
- * Sends the response with the specified data. This method is called by other
515
- * response methods like json(), text(), and html(). Once called, no further
516
- * response methods can be used.
517
- *
518
- * @param {*} data - The data to send
519
- * @returns {Context} The context instance for method chaining
520
- *
521
- * @since 1.0.0
522
- *
523
- * @example
524
- * ctx.send('Hello World');
525
- * ctx.send(Buffer.from('binary data'));
526
- */
527
- send(data) {
528
- if (this.responded) {
529
- return this;
530
- }
531
-
532
- this.responded = true;
533
- this.res.statusCode = this.statusCode;
534
-
535
- Object.keys(this.responseHeaders).forEach(name => {
536
- this.res.setHeader(name, this.responseHeaders[name]);
537
- });
538
-
539
- if (data === null || data === undefined) {
540
- this.res.end();
541
- } else if (typeof data === 'string' || Buffer.isBuffer(data)) {
542
- this.res.end(data);
543
- } else {
544
- this.res.end(String(data));
545
- }
546
-
547
- return this;
548
- }
549
-
550
- /**
551
- * End the response
552
- *
553
- * Ends the response optionally with data. This is an alias for send().
554
- *
555
- * @param {*} [data] - Optional data to send before ending
556
- * @returns {Context} The context instance for method chaining
557
- *
558
- * @since 1.0.0
559
- *
560
- * @example
561
- * ctx.status(204).end(); // No content
562
- * ctx.end('Final message');
563
- */
564
- end(data) {
565
- if (data) {
566
- this.send(data);
567
- } else {
568
- this.send();
569
- }
570
- return this;
571
- }
572
-
573
- setCookie(name, value, options = {}) {
574
- // Validate cookie name
575
- if (!name || typeof name !== 'string') {
576
- throw new Error('Cookie name must be a non-empty string');
577
- }
578
-
579
- // Validate cookie name format (RFC 6265)
580
- if (!/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(name)) {
581
- throw new Error(`Invalid cookie name: ${name}`);
582
- }
583
-
584
- // Check for control characters in cookie name
585
- if (/[\x00-\x1F\x7F]/.test(name)) {
586
- throw new Error('Cookie name cannot contain control characters');
587
- }
588
-
589
- // Validate cookie value
590
- if (value === null || value === undefined) {
591
- value = '';
592
- }
593
-
594
- // Convert value to string and check for invalid characters
595
- const stringValue = String(value);
596
- if (/[\x00-\x1F\x7F]/.test(stringValue)) {
597
- throw new Error('Cookie value cannot contain control characters');
598
- }
599
-
600
- let cookieString = `${name}=${encodeURIComponent(value)}`;
601
-
602
- if (options.domain) {
603
- cookieString += `; Domain=${options.domain}`;
604
- }
605
-
606
- if (options.path) {
607
- cookieString += `; Path=${options.path}`;
608
- }
609
-
610
- if (options.expires) {
611
- cookieString += `; Expires=${options.expires.toUTCString()}`;
612
- }
613
-
614
- if (options.maxAge) {
615
- cookieString += `; Max-Age=${options.maxAge}`;
616
- }
617
-
618
- if (options.httpOnly) {
619
- cookieString += '; HttpOnly';
620
- }
621
-
622
- if (options.secure) {
623
- cookieString += '; Secure';
624
- }
625
-
626
- if (options.sameSite) {
627
- const validSameSite = ['Strict', 'Lax', 'None'];
628
- const sameSiteValue = options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1).toLowerCase();
629
- if (!validSameSite.includes(sameSiteValue)) {
630
- throw new Error(`Invalid SameSite value: ${options.sameSite}. Must be 'Strict', 'Lax', or 'None'`);
631
- }
632
- cookieString += `; SameSite=${sameSiteValue}`;
633
- }
634
-
635
- const existingCookies = this.responseHeaders['set-cookie'] || [];
636
- if (Array.isArray(existingCookies)) {
637
- existingCookies.push(cookieString);
638
- this.responseHeaders['set-cookie'] = existingCookies;
639
- } else if (existingCookies) {
640
- this.responseHeaders['set-cookie'] = [existingCookies, cookieString];
641
- } else {
642
- this.responseHeaders['set-cookie'] = [cookieString];
643
- }
644
-
645
- return this;
646
- }
647
-
648
- clearCookie(name, options = {}) {
649
- const clearOptions = {
650
- ...options,
651
- expires: new Date(0),
652
- maxAge: 0
653
- };
654
- return this.setCookie(name, '', clearOptions);
655
- }
656
-
657
- is(type) {
658
- const contentType = this.get('content-type');
659
- if (!contentType) return false;
660
-
661
- const mimeTypes = {
662
- json: 'application/json',
663
- form: 'application/x-www-form-urlencoded',
664
- multipart: 'multipart/form-data',
665
- text: 'text/plain',
666
- html: 'text/html'
667
- };
668
-
669
- const targetType = mimeTypes[type] || type;
670
- return contentType.includes(targetType);
671
- }
672
-
673
- accepts(types) {
674
- const accept = this.get('accept') || '*/*';
675
-
676
- if (typeof types === 'string') {
677
- types = [types];
678
- }
679
-
680
- for (const type of types) {
681
- if (accept.includes(type) || accept.includes('*/*')) {
682
- return type;
683
- }
684
- }
685
-
686
- return false;
687
- }
688
-
689
- fresh() {
690
- const method = this.method;
691
- const status = this.statusCode;
692
-
693
- if (method !== 'GET' && method !== 'HEAD') return false;
694
- if ((status >= 200 && status < 300) || status === 304) return true;
695
-
696
- return false;
697
- }
698
-
699
- stale() {
700
- return !this.fresh();
701
- }
702
-
703
- secure() {
704
- return this.req.connection.encrypted;
705
- }
706
-
707
- xhr() {
708
- return this.get('x-requested-with') === 'XMLHttpRequest';
709
- }
710
-
711
- ip() {
712
- return this.get('x-forwarded-for') ||
713
- this.get('x-real-ip') ||
714
- this.req.connection.remoteAddress ||
715
- this.req.socket.remoteAddress;
716
- }
717
-
718
- ips() {
719
- const forwarded = this.get('x-forwarded-for');
720
- return forwarded ? forwarded.split(/\s*,\s*/) : [this.ip()];
721
- }
722
-
723
- protocol() {
724
- return this.req.connection.encrypted ? 'https' : 'http';
725
- }
726
-
727
- host() {
728
- return this.get('host') || 'localhost';
729
- }
730
-
731
- hostname() {
732
- return this.host().split(':')[0];
733
- }
734
-
735
- port() {
736
- const host = this.host();
737
- const portMatch = host.match(/:(\d+)$/);
738
- return portMatch ? parseInt(portMatch[1]) : (this.secure() ? 443 : 80);
739
- }
740
-
741
- subdomains() {
742
- const hostname = this.hostname();
743
- const parts = hostname.split('.');
744
- return parts.length > 2 ? parts.slice(0, -2).reverse() : [];
745
- }
746
-
747
- type() {
748
- const contentType = this.get('content-type');
749
- return contentType ? contentType.split(';')[0] : '';
750
- }
751
-
752
- charset() {
753
- const contentType = this.get('content-type');
754
- if (!contentType) return '';
755
-
756
- const match = contentType.match(/charset=([^;]+)/);
757
- return match ? match[1] : '';
758
- }
759
-
760
- length() {
761
- const contentLength = this.get('content-length');
762
- return contentLength ? parseInt(contentLength) : 0;
763
- }
764
-
765
- toString() {
766
- return `${this.method} ${this.originalUrl}`;
767
- }
768
-
769
- toJSON() {
770
- return {
771
- method: this.method,
772
- url: this.originalUrl,
773
- path: this.path,
774
- query: this.query,
775
- params: this.params,
776
- headers: this.headers,
777
- cookies: this.cookies,
778
- statusCode: this.statusCode,
779
- responded: this.responded
780
- };
781
- }
782
-
783
- /**
784
- * Initialize context with new request/response (for object pooling)
785
- * @param {IncomingMessage} req - HTTP request
786
- * @param {ServerResponse} res - HTTP response
787
- * @param {Application} app - Spark application
788
- */
789
- init(req, res, app) {
790
- this.req = req;
791
- this.res = res;
792
- this.app = app;
793
- this.responded = false;
794
- this.statusCode = 200;
795
-
796
- this.initializeUrl();
797
- this.initializeHeaders();
798
- this.initializeQuery();
799
- this.initializeCookies();
800
-
801
- this.params = {};
802
- this.body = null;
803
- this.files = null;
804
- this.session = null;
805
- this.state = {};
806
- }
807
-
808
- /**
809
- * Reset context for object pooling
810
- */
811
- reset() {
812
- this.req = null;
813
- this.res = null;
814
- this.app = null;
815
- this.responded = false;
816
- this.statusCode = 200;
817
- this.url = null;
818
- this.path = null;
819
- this.method = null;
820
- this.originalUrl = null;
821
- this.headers = {};
822
- this.responseHeaders = {};
823
- this.query = {};
824
- this.cookies = {};
825
- this.params = {};
826
- this.body = null;
827
- this.files = null;
828
- this.session = null;
829
- this.state = {};
830
- }
831
- }
832
-
3
+ /**
4
+ * @fileoverview Context class for handling HTTP requests and responses in Spark Framework
5
+ * @author Spark Framework Team
6
+ * @since 1.0.0
7
+ * @version 1.0.0
8
+ */
9
+
10
+ const { URL } = require('url');
11
+ const querystring = require('querystring');
12
+ const { pipeline } = require('stream');
13
+
14
+ /**
15
+ * Context class that wraps HTTP request and response objects
16
+ *
17
+ * The Context class provides a unified interface for handling HTTP requests and responses.
18
+ * It parses incoming request data, provides helper methods for setting headers and status codes,
19
+ * and includes convenience methods for sending various types of responses.
20
+ *
21
+ * @class Context
22
+ * @since 1.0.0
23
+ *
24
+ * @example
25
+ * // In a middleware or route handler
26
+ * app.get('/users/:id', (ctx) => {
27
+ * const userId = ctx.params.id;
28
+ * const userAgent = ctx.get('user-agent');
29
+ *
30
+ * ctx.set('X-Response-Time', '10ms');
31
+ * ctx.json({ id: userId, userAgent });
32
+ * });
33
+ *
34
+ * @example
35
+ * // Working with cookies
36
+ * app.post('/login', (ctx) => {
37
+ * const { username, password } = ctx.body;
38
+ *
39
+ * if (authenticate(username, password)) {
40
+ * ctx.setCookie('session', 'abc123', {
41
+ * httpOnly: true,
42
+ * secure: true,
43
+ * maxAge: 3600000
44
+ * });
45
+ * ctx.json({ success: true });
46
+ * } else {
47
+ * ctx.status(401).json({ error: 'Invalid credentials' });
48
+ * }
49
+ * });
50
+ */
51
+ class Context {
52
+ /**
53
+ * Create a new Context instance
54
+ *
55
+ * @param {http.IncomingMessage} req - The HTTP request object
56
+ * @param {http.ServerResponse} res - The HTTP response object
57
+ * @param {Application} app - The Spark application instance
58
+ *
59
+ * @since 1.0.0
60
+ *
61
+ * @example
62
+ * // Context is typically created automatically by the framework
63
+ * const ctx = new Context(req, res, app);
64
+ */
65
+ constructor(req, res, app) {
66
+ /**
67
+ * The HTTP request object
68
+ * @type {http.IncomingMessage}
69
+ * @readonly
70
+ */
71
+ this.req = req;
72
+
73
+ /**
74
+ * The HTTP response object
75
+ * @type {http.ServerResponse}
76
+ * @readonly
77
+ */
78
+ this.res = res;
79
+
80
+ /**
81
+ * The Spark application instance
82
+ * @type {Application}
83
+ * @readonly
84
+ */
85
+ this.app = app;
86
+
87
+ /**
88
+ * Whether a response has been sent
89
+ * @type {boolean}
90
+ * @readonly
91
+ */
92
+ this.responded = false;
93
+
94
+ /**
95
+ * The HTTP status code for the response
96
+ * @type {number}
97
+ */
98
+ this.statusCode = 200;
99
+
100
+ this.initializeUrl();
101
+ this.initializeHeaders();
102
+ this.initializeQuery();
103
+ this.initializeCookies();
104
+
105
+ /**
106
+ * Route parameters extracted from the URL
107
+ * @type {Object}
108
+ * @example
109
+ * // For route '/users/:id' with URL '/users/123'
110
+ * ctx.params.id // '123'
111
+ */
112
+ this.params = {};
113
+
114
+ /**
115
+ * Parsed request body
116
+ * @type {*}
117
+ */
118
+ this.body = null;
119
+
120
+ /**
121
+ * Uploaded files (when using multipart/form-data)
122
+ * @type {Object|null}
123
+ */
124
+ this.files = null;
125
+
126
+ /**
127
+ * Session data (when session middleware is used)
128
+ * @type {Object|null}
129
+ */
130
+ this.session = null;
131
+
132
+ /**
133
+ * Application state for storing custom data
134
+ * @type {Object}
135
+ */
136
+ this.state = {};
137
+ }
138
+
139
+ /**
140
+ * Initialize URL-related properties from the request
141
+ *
142
+ * Parses the request URL and extracts path, method, and other URL components.
143
+ * Handles malformed URLs by throwing an appropriate error.
144
+ *
145
+ * @private
146
+ * @throws {Error} When the URL cannot be parsed
147
+ * @since 1.0.0
148
+ */
149
+ initializeUrl() {
150
+ // Use optional chaining to safely access connection properties
151
+ const protocol = this.req.connection?.encrypted ? 'https' : 'http';
152
+ const host = this.req.headers?.host || 'localhost';
153
+
154
+ try {
155
+ /**
156
+ * Parsed URL object
157
+ * @type {URL|null}
158
+ * @readonly
159
+ */
160
+ this.url = new URL(this.req.url, `${protocol}://${host}`);
161
+
162
+ /**
163
+ * Request path (pathname without query string)
164
+ * @type {string}
165
+ * @readonly
166
+ */
167
+ this.path = this.url.pathname;
168
+ } catch (error) {
169
+ // Handle malformed URLs - throw proper error instead of just logging
170
+ this.url = null;
171
+ this.path = '/';
172
+ this.statusCode = 400;
173
+ this.body = { error: 'Invalid URL format' };
174
+ throw new Error(`Failed to parse URL: ${error.message}`);
175
+ }
176
+
177
+ /**
178
+ * HTTP method (GET, POST, PUT, etc.)
179
+ * @type {string}
180
+ * @readonly
181
+ */
182
+ this.method = this.req.method?.toUpperCase() || 'GET';
183
+
184
+ /**
185
+ * Original request URL including query string
186
+ * @type {string}
187
+ * @readonly
188
+ */
189
+ this.originalUrl = this.req.url;
190
+ }
191
+
192
+ /**
193
+ * Initialize request and response headers
194
+ *
195
+ * Copies request headers and initializes response headers object.
196
+ *
197
+ * @private
198
+ * @since 1.0.0
199
+ */
200
+ initializeHeaders() {
201
+ /**
202
+ * Request headers (lowercase keys)
203
+ * @type {Object}
204
+ * @readonly
205
+ */
206
+ this.headers = { ...this.req.headers };
207
+
208
+ /**
209
+ * Response headers to be sent
210
+ * @type {Object}
211
+ * @private
212
+ */
213
+ this.responseHeaders = {};
214
+ }
215
+
216
+ /**
217
+ * Initialize query string parameters
218
+ *
219
+ * Parses the URL query string into an object.
220
+ *
221
+ * @private
222
+ * @since 1.0.0
223
+ */
224
+ initializeQuery() {
225
+ /**
226
+ * Parsed query string parameters
227
+ * @type {Object}
228
+ * @readonly
229
+ * @example
230
+ * // For URL '/search?q=hello&limit=10'
231
+ * ctx.query.q // 'hello'
232
+ * ctx.query.limit // '10'
233
+ */
234
+ // Use null-prototype object to prevent prototype pollution
235
+ this.query = Object.create(null);
236
+
237
+ if (this.url && this.url.search) {
238
+ const parsed = querystring.parse(this.url.search.slice(1));
239
+
240
+ // Filter out dangerous prototype pollution keys
241
+ const dangerousKeys = ['__proto__', 'constructor', 'prototype'];
242
+
243
+ for (const [key, value] of Object.entries(parsed)) {
244
+ // Skip dangerous keys that could cause prototype pollution
245
+ if (!dangerousKeys.includes(key) && !key.includes('__proto__')) {
246
+ this.query[key] = value;
247
+ }
248
+ }
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Initialize cookies from the request
254
+ *
255
+ * Parses the Cookie header and decodes cookie values.
256
+ * Malformed cookies are skipped and logged.
257
+ *
258
+ * @private
259
+ * @since 1.0.0
260
+ */
261
+ initializeCookies() {
262
+ /**
263
+ * Parsed cookies from the request
264
+ * @type {Object}
265
+ * @readonly
266
+ * @example
267
+ * // For Cookie header 'session=abc123; theme=dark'
268
+ * ctx.cookies.session // 'abc123'
269
+ * ctx.cookies.theme // 'dark'
270
+ */
271
+ this.cookies = {};
272
+ const cookieHeader = this.req.headers.cookie;
273
+ if (cookieHeader) {
274
+ cookieHeader.split(';').forEach(cookie => {
275
+ const trimmed = cookie.trim();
276
+ // SECURITY: Split only on first '=' to preserve cookie values containing '='
277
+ const eqIndex = trimmed.indexOf('=');
278
+
279
+ if (eqIndex === -1) {
280
+ // Cookie without value (flag cookie)
281
+ if (trimmed) {
282
+ this.cookies[trimmed] = true;
283
+ }
284
+ return;
285
+ }
286
+
287
+ const name = trimmed.substring(0, eqIndex);
288
+ const value = trimmed.substring(eqIndex + 1);
289
+
290
+ if (name && value !== undefined) {
291
+ try {
292
+ this.cookies[name] = decodeURIComponent(value);
293
+ } catch (error) {
294
+ // If decoding fails, use raw value (might be unencoded)
295
+ this.cookies[name] = value;
296
+ }
297
+ }
298
+ });
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Get a request header value
304
+ *
305
+ * @param {string} headerName - The header name (case-insensitive)
306
+ * @returns {string|undefined} The header value or undefined if not present
307
+ *
308
+ * @since 1.0.0
309
+ *
310
+ * @example
311
+ * const userAgent = ctx.get('User-Agent');
312
+ * const contentType = ctx.get('content-type');
313
+ */
314
+ get(headerName) {
315
+ return this.headers[headerName.toLowerCase()];
316
+ }
317
+
318
+ /**
319
+ * Set a response header
320
+ *
321
+ * Sets a response header with validation for security and RFC compliance.
322
+ * Header names and values are validated to prevent injection attacks.
323
+ *
324
+ * @param {string} headerName - The header name
325
+ * @param {string|number} value - The header value
326
+ * @returns {Context} The context instance for method chaining
327
+ *
328
+ * @throws {Error} When header name or value is invalid
329
+ *
330
+ * @since 1.0.0
331
+ *
332
+ * @example
333
+ * ctx.set('Content-Type', 'application/json');
334
+ * ctx.set('X-Response-Time', '10ms');
335
+ *
336
+ * @example
337
+ * // Method chaining
338
+ * ctx.set('Content-Type', 'text/html')
339
+ * .set('Cache-Control', 'no-cache');
340
+ */
341
+ set(headerName, value) {
342
+ // Validate header name
343
+ if (!headerName || typeof headerName !== 'string') {
344
+ throw new Error('Header name must be a non-empty string');
345
+ }
346
+
347
+ // Validate header name format (RFC 7230)
348
+ if (!/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(headerName)) {
349
+ throw new Error(`Invalid header name: ${headerName}`);
350
+ }
351
+
352
+ // Validate header value
353
+ if (value !== undefined && value !== null) {
354
+ const stringValue = String(value);
355
+ // Check for invalid characters in header value (CRLF and null byte)
356
+ if (/[\r\n\x00]/.test(stringValue)) {
357
+ throw new Error('Header value cannot contain CRLF or null characters');
358
+ }
359
+ // Check header value length
360
+ if (stringValue.length > 8192) {
361
+ throw new Error('Header value too long (max 8192 characters)');
362
+ }
363
+ this.responseHeaders[headerName.toLowerCase()] = stringValue;
364
+ }
365
+
366
+ return this;
367
+ }
368
+
369
+ /**
370
+ * Alias for set() method
371
+ *
372
+ * @param {string} name - The header name
373
+ * @param {string|number} value - The header value
374
+ * @returns {Context} The context instance for method chaining
375
+ *
376
+ * @since 1.0.0
377
+ * @see {@link Context#set}
378
+ */
379
+ setHeader(name, value) {
380
+ return this.set(name, value);
381
+ }
382
+
383
+ /**
384
+ * Get a response header value
385
+ *
386
+ * @param {string} name - The header name (case-insensitive)
387
+ * @returns {string|undefined} The header value or undefined if not set
388
+ *
389
+ * @since 1.0.0
390
+ *
391
+ * @example
392
+ * ctx.set('Content-Type', 'application/json');
393
+ * const contentType = ctx.getHeader('content-type'); // 'application/json'
394
+ */
395
+ getHeader(name) {
396
+ return this.responseHeaders[name.toLowerCase()];
397
+ }
398
+
399
+ /**
400
+ * Remove a response header
401
+ *
402
+ * @param {string} name - The header name (case-insensitive)
403
+ * @returns {Context} The context instance for method chaining
404
+ *
405
+ * @since 1.0.0
406
+ *
407
+ * @example
408
+ * ctx.removeHeader('X-Powered-By');
409
+ */
410
+ removeHeader(name) {
411
+ delete this.responseHeaders[name.toLowerCase()];
412
+ return this;
413
+ }
414
+
415
+ /**
416
+ * Set the HTTP status code
417
+ *
418
+ * @param {number|string} code - HTTP status code (100-599)
419
+ * @returns {Context} The context instance for method chaining
420
+ *
421
+ * @throws {Error} When status code is invalid
422
+ *
423
+ * @since 1.0.0
424
+ *
425
+ * @example
426
+ * ctx.status(200); // OK
427
+ * ctx.status(404); // Not Found
428
+ * ctx.status(500); // Internal Server Error
429
+ *
430
+ * @example
431
+ * // Method chaining
432
+ * ctx.status(201).json({ id: 123, name: 'User' });
433
+ */
434
+ status(code) {
435
+ // BUG FIX: Strict type validation - reject non-integer inputs
436
+ // parseInt("200abc") would silently convert to 200, masking bugs
437
+ if (typeof code !== 'number' || !Number.isInteger(code)) {
438
+ // Try to parse if it's a string, but validate strictly
439
+ if (typeof code === 'string') {
440
+ // Check if the string is purely numeric
441
+ if (!/^\d+$/.test(code.trim())) {
442
+ throw new Error(`Invalid status code: ${code}. Must be an integer between 100 and 599`);
443
+ }
444
+ code = parseInt(code, 10);
445
+ } else {
446
+ throw new Error(`Invalid status code type: ${typeof code}. Must be a number`);
447
+ }
448
+ }
449
+
450
+ // Validate status code range
451
+ if (code < 100 || code > 599) {
452
+ throw new Error(`Invalid status code: ${code}. Must be between 100 and 599`);
453
+ }
454
+
455
+ this.statusCode = code;
456
+ return this;
457
+ }
458
+
459
+ /**
460
+ * Redirect to a URL
461
+ *
462
+ * Sets the Location header and status code, then ends the response.
463
+ *
464
+ * @param {string} url - The URL to redirect to
465
+ * @param {number} [status=302] - HTTP status code for redirect
466
+ * @returns {Context} The context instance for method chaining
467
+ *
468
+ * @since 1.0.0
469
+ *
470
+ * @example
471
+ * // Temporary redirect (302)
472
+ * ctx.redirect('/login');
473
+ *
474
+ * @example
475
+ * // Permanent redirect (301)
476
+ * ctx.redirect('/new-path', 301);
477
+ */
478
+ redirect(url, status = 302) {
479
+ // Validate redirect URL
480
+ if (!url || typeof url !== 'string') {
481
+ throw new Error('Invalid redirect URL');
482
+ }
483
+
484
+ // Check for CRLF injection
485
+ if (/[\r\n]/.test(url)) {
486
+ throw new Error('Invalid redirect URL contains CRLF characters');
487
+ }
488
+
489
+ // SECURITY: Validate protocol to prevent XSS via javascript:, data:, etc.
490
+ const dangerousProtocols = ['javascript:', 'data:', 'vbscript:', 'file:', 'about:'];
491
+ const lowerUrl = url.toLowerCase();
492
+ if (dangerousProtocols.some(proto => lowerUrl.startsWith(proto))) {
493
+ throw new Error(`Redirect to ${lowerUrl.split(':')[0]}: protocol is not allowed`);
494
+ }
495
+
496
+ // Resolve against a placeholder origin: relative paths stay on it, while
497
+ // absolute ('https://x'), protocol-relative ('//x') and backslash
498
+ // ('/\\x', which browsers treat as '//x') URLs leave it.
499
+ const placeholderHost = 'spark-redirect.invalid';
500
+ let target;
501
+ try {
502
+ target = new URL(url, `http://${placeholderHost}`);
503
+ } catch (error) {
504
+ throw new Error(`Invalid redirect URL: ${error.message}`);
505
+ }
506
+
507
+ if (target.hostname !== placeholderHost) {
508
+ if (target.protocol !== 'http:' && target.protocol !== 'https:') {
509
+ throw new Error(`Redirect to ${target.protocol.replace(':', '')}: protocol is not allowed`);
510
+ }
511
+ }
512
+
513
+ // Redirects to the request's own host (e.g. http -> https) are not external
514
+ const external = target.hostname !== placeholderHost &&
515
+ target.hostname.toLowerCase() !== String(this.hostname()).toLowerCase();
516
+
517
+ if (external) {
518
+ const allowedDomains = this.app?.settings?.allowedRedirectDomains || [];
519
+ const allowOpenRedirects = this.app?.settings?.allowOpenRedirects === true;
520
+
521
+ if (allowedDomains.length > 0) {
522
+ const isAllowed = allowedDomains.some(domain => {
523
+ if (typeof domain === 'string') {
524
+ return target.hostname === domain || target.hostname.endsWith(`.${domain}`);
525
+ }
526
+ if (domain instanceof RegExp) {
527
+ return domain.test(target.hostname);
528
+ }
529
+ return false;
530
+ });
531
+
532
+ if (!isAllowed) {
533
+ throw new Error('Redirect to external domain not allowed');
534
+ }
535
+ } else if (!allowOpenRedirects) {
536
+ throw new Error('External redirects require allowedRedirectDomains configuration or allowOpenRedirects: true');
537
+ }
538
+ }
539
+
540
+ this.status(status);
541
+ this.set('Location', url);
542
+ this.end();
543
+ return this;
544
+ }
545
+
546
+ /**
547
+ * Send a JSON response
548
+ *
549
+ * Sets the Content-Type header to application/json and sends the data as JSON.
550
+ *
551
+ * @param {*} data - The data to send as JSON
552
+ * @returns {Context} The context instance for method chaining
553
+ *
554
+ * @since 1.0.0
555
+ *
556
+ * @example
557
+ * ctx.json({ message: 'Hello World' });
558
+ *
559
+ * @example
560
+ * // With status code
561
+ * ctx.status(201).json({ id: 123, name: 'User' });
562
+ */
563
+ json(data) {
564
+ this.set('Content-Type', 'application/json');
565
+ this.send(JSON.stringify(data));
566
+ return this;
567
+ }
568
+
569
+ /**
570
+ * Send a plain text response
571
+ *
572
+ * Sets the Content-Type header to text/plain and sends the data as text.
573
+ *
574
+ * @param {string} data - The text data to send
575
+ * @returns {Context} The context instance for method chaining
576
+ *
577
+ * @since 1.0.0
578
+ *
579
+ * @example
580
+ * ctx.text('Hello World');
581
+ *
582
+ * @example
583
+ * // With status code
584
+ * ctx.status(200).text('Success');
585
+ */
586
+ text(data) {
587
+ this.set('Content-Type', 'text/plain');
588
+ this.send(data);
589
+ return this;
590
+ }
591
+
592
+ /**
593
+ * Send an HTML response
594
+ *
595
+ * Sets the Content-Type header to text/html and sends the data as HTML.
596
+ *
597
+ * @param {string} data - The HTML data to send
598
+ * @returns {Context} The context instance for method chaining
599
+ *
600
+ * @since 1.0.0
601
+ *
602
+ * @example
603
+ * ctx.html('<h1>Hello World</h1>');
604
+ *
605
+ * @example
606
+ * // With status code
607
+ * ctx.status(200).html('<p>Welcome!</p>');
608
+ */
609
+ html(data) {
610
+ this.set('Content-Type', 'text/html');
611
+ this.send(data);
612
+ return this;
613
+ }
614
+
615
+ /**
616
+ * Send a response with data
617
+ *
618
+ * Sends the response with the specified data. This method is called by other
619
+ * response methods like json(), text(), and html(). Once called, no further
620
+ * response methods can be used.
621
+ *
622
+ * @param {*} data - The data to send
623
+ * @returns {Context} The context instance for method chaining
624
+ *
625
+ * @since 1.0.0
626
+ *
627
+ * @example
628
+ * ctx.send('Hello World');
629
+ * ctx.send(Buffer.from('binary data'));
630
+ */
631
+ send(data) {
632
+ if (this.responded) {
633
+ return this;
634
+ }
635
+
636
+ this.responded = true;
637
+ this.writeHeaders();
638
+
639
+ if (data === null || data === undefined) {
640
+ this.res.end();
641
+ } else if (typeof data === 'string' || Buffer.isBuffer(data)) {
642
+ this.res.end(data);
643
+ } else {
644
+ this.res.end(String(data));
645
+ }
646
+
647
+ return this;
648
+ }
649
+
650
+ /**
651
+ * End the response
652
+ *
653
+ * Ends the response optionally with data. This is an alias for send().
654
+ *
655
+ * @param {*} [data] - Optional data to send before ending
656
+ * @returns {Context} The context instance for method chaining
657
+ *
658
+ * @since 1.0.0
659
+ *
660
+ * @example
661
+ * ctx.status(204).end(); // No content
662
+ * ctx.end('Final message');
663
+ */
664
+ end(data) {
665
+ if (data) {
666
+ this.send(data);
667
+ } else {
668
+ this.send();
669
+ }
670
+ return this;
671
+ }
672
+
673
+ /**
674
+ * Copy the status code and headers set on the context to the response.
675
+ *
676
+ * @private
677
+ */
678
+ writeHeaders() {
679
+ if (this.res.headersSent) {
680
+ return;
681
+ }
682
+ this.res.statusCode = this.statusCode;
683
+ Object.keys(this.responseHeaders).forEach(name => {
684
+ this.res.setHeader(name, this.responseHeaders[name]);
685
+ });
686
+ }
687
+
688
+ /**
689
+ * Send a readable stream as the response body.
690
+ *
691
+ * The status code and headers set on the context are sent first. The stream
692
+ * is piped with backpressure; if the client disconnects, the source stream is
693
+ * destroyed. The returned promise settles when the response has finished or
694
+ * the connection closed.
695
+ *
696
+ * @param {import('stream').Readable} readable - Body stream
697
+ * @returns {Promise<void>} Resolves when done; rejects if the source stream fails
698
+ *
699
+ * @since 1.2.0
700
+ *
701
+ * @example
702
+ * app.get('/download', (ctx) => {
703
+ * ctx.set('Content-Type', 'application/octet-stream');
704
+ * return ctx.stream(fs.createReadStream('big.bin'));
705
+ * });
706
+ */
707
+ stream(readable) {
708
+ if (this.responded) {
709
+ readable.destroy();
710
+ return Promise.resolve();
711
+ }
712
+ this.responded = true;
713
+ this.writeHeaders();
714
+
715
+ if (this.method === 'HEAD') {
716
+ readable.destroy();
717
+ this.res.end();
718
+ return Promise.resolve();
719
+ }
720
+
721
+ return new Promise((resolve, reject) => {
722
+ pipeline(readable, this.res, (error) => {
723
+ if (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE' || this.res.destroyed) {
724
+ // Finished, or the client went away (nothing left to send).
725
+ resolve();
726
+ } else {
727
+ reject(error);
728
+ }
729
+ });
730
+ });
731
+ }
732
+
733
+ setCookie(name, value, options = {}) {
734
+ // Validate cookie name
735
+ if (!name || typeof name !== 'string') {
736
+ throw new Error('Cookie name must be a non-empty string');
737
+ }
738
+
739
+ // SECURITY: Validate cookie name length (RFC 6265 recommends max 4096 bytes total)
740
+ if (name.length > 256) {
741
+ throw new Error(`Cookie name too long: ${name.length} bytes (max 256)`);
742
+ }
743
+
744
+ // Validate cookie name format (RFC 6265)
745
+ if (!/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(name)) {
746
+ throw new Error(`Invalid cookie name: ${name}`);
747
+ }
748
+
749
+ // Check for control characters in cookie name
750
+ if (/[\x00-\x1F\x7F]/.test(name)) {
751
+ throw new Error('Cookie name cannot contain control characters');
752
+ }
753
+
754
+ // Validate cookie value
755
+ if (value === null || value === undefined) {
756
+ value = '';
757
+ }
758
+
759
+ // Convert value to string and check for invalid characters
760
+ const stringValue = String(value);
761
+
762
+ // SECURITY: Validate cookie value length
763
+ if (stringValue.length > 4096) {
764
+ throw new Error(`Cookie value too long: ${stringValue.length} bytes (max 4096)`);
765
+ }
766
+
767
+ if (/[\x00-\x1F\x7F]/.test(stringValue)) {
768
+ throw new Error('Cookie value cannot contain control characters');
769
+ }
770
+
771
+ let cookieString = `${name}=${encodeURIComponent(value)}`;
772
+
773
+ if (options.domain) {
774
+ // SECURITY: Validate domain to prevent CRLF injection
775
+ const domain = String(options.domain);
776
+ if (/[\r\n]/.test(domain)) {
777
+ throw new Error('Cookie domain cannot contain CRLF characters');
778
+ }
779
+ cookieString += `; Domain=${domain}`;
780
+ }
781
+
782
+ if (options.path) {
783
+ // SECURITY: Validate path to prevent CRLF injection
784
+ const path = String(options.path);
785
+ if (/[\r\n]/.test(path)) {
786
+ throw new Error('Cookie path cannot contain CRLF characters');
787
+ }
788
+ cookieString += `; Path=${path}`;
789
+ }
790
+
791
+ if (options.expires) {
792
+ cookieString += `; Expires=${options.expires.toUTCString()}`;
793
+ }
794
+
795
+ if (options.maxAge !== undefined && options.maxAge !== null) {
796
+ // maxAge is in milliseconds (like Express); Max-Age is in seconds
797
+ const maxAge = Number(options.maxAge);
798
+ if (!Number.isFinite(maxAge)) {
799
+ throw new Error(`Invalid cookie maxAge: ${options.maxAge}`);
800
+ }
801
+ cookieString += `; Max-Age=${Math.max(0, Math.floor(maxAge / 1000))}`;
802
+ }
803
+
804
+ if (options.httpOnly) {
805
+ cookieString += '; HttpOnly';
806
+ }
807
+
808
+ if (options.secure) {
809
+ cookieString += '; Secure';
810
+ }
811
+
812
+ if (options.sameSite !== undefined) {
813
+ // BUG FIX: Handle empty string and validate length before charAt
814
+ const sameSiteStr = String(options.sameSite);
815
+ if (!sameSiteStr || sameSiteStr.length === 0) {
816
+ throw new Error('SameSite value cannot be empty');
817
+ }
818
+
819
+ const validSameSite = ['Strict', 'Lax', 'None'];
820
+ const sameSiteValue = sameSiteStr.charAt(0).toUpperCase() + sameSiteStr.slice(1).toLowerCase();
821
+
822
+ if (!validSameSite.includes(sameSiteValue)) {
823
+ throw new Error(`Invalid SameSite value: ${options.sameSite}. Must be 'Strict', 'Lax', or 'None'`);
824
+ }
825
+ cookieString += `; SameSite=${sameSiteValue}`;
826
+ }
827
+
828
+ const existingCookies = this.responseHeaders['set-cookie'] || [];
829
+ if (Array.isArray(existingCookies)) {
830
+ existingCookies.push(cookieString);
831
+ this.responseHeaders['set-cookie'] = existingCookies;
832
+ } else if (existingCookies) {
833
+ this.responseHeaders['set-cookie'] = [existingCookies, cookieString];
834
+ } else {
835
+ this.responseHeaders['set-cookie'] = [cookieString];
836
+ }
837
+
838
+ return this;
839
+ }
840
+
841
+ clearCookie(name, options = {}) {
842
+ const clearOptions = {
843
+ ...options,
844
+ expires: new Date(0),
845
+ maxAge: 0
846
+ };
847
+ return this.setCookie(name, '', clearOptions);
848
+ }
849
+
850
+ is(type) {
851
+ const contentType = this.get('content-type');
852
+ if (!contentType) return false;
853
+
854
+ const mimeTypes = {
855
+ json: 'application/json',
856
+ form: 'application/x-www-form-urlencoded',
857
+ multipart: 'multipart/form-data',
858
+ text: 'text/plain',
859
+ html: 'text/html'
860
+ };
861
+
862
+ const targetType = mimeTypes[type] || type;
863
+ return contentType.includes(targetType);
864
+ }
865
+
866
+ accepts(types) {
867
+ const accept = this.get('accept') || '*/*';
868
+
869
+ if (typeof types === 'string') {
870
+ types = [types];
871
+ }
872
+
873
+ for (const type of types) {
874
+ if (accept.includes(type) || accept.includes('*/*')) {
875
+ return type;
876
+ }
877
+ }
878
+
879
+ return false;
880
+ }
881
+
882
+ fresh() {
883
+ const method = this.method;
884
+ const status = this.statusCode;
885
+
886
+ if (method !== 'GET' && method !== 'HEAD') return false;
887
+ if ((status >= 200 && status < 300) || status === 304) return true;
888
+
889
+ return false;
890
+ }
891
+
892
+ stale() {
893
+ return !this.fresh();
894
+ }
895
+
896
+ secure() {
897
+ return this.req.connection.encrypted;
898
+ }
899
+
900
+ xhr() {
901
+ return this.get('x-requested-with') === 'XMLHttpRequest';
902
+ }
903
+
904
+ /**
905
+ * Validate if a string is a valid IP address (IPv4 or IPv6)
906
+ * @param {string} ip - IP address to validate
907
+ * @returns {boolean} True if valid IP address
908
+ * @private
909
+ */
910
+ _isValidIP(ip) {
911
+ if (!ip || typeof ip !== 'string') return false;
912
+
913
+ // Basic IPv4 validation
914
+ const ipv4 = /^(\d{1,3}\.){3}\d{1,3}$/;
915
+ if (ipv4.test(ip)) {
916
+ const octets = ip.split('.');
917
+ return octets.every(o => {
918
+ const num = parseInt(o, 10);
919
+ return num >= 0 && num <= 255;
920
+ });
921
+ }
922
+
923
+ // Basic IPv6 validation (simplified)
924
+ const ipv6 = /^([\da-fA-F]{0,4}:){2,7}[\da-fA-F]{0,4}$/;
925
+ return ipv6.test(ip);
926
+ }
927
+
928
+ /**
929
+ * Get the client IP address
930
+ * WARNING: Only trust X-Forwarded-For if app.settings.trustProxy is enabled
931
+ * @returns {string} Client IP address
932
+ */
933
+ ip() {
934
+ const trustProxy = this.app?.settings?.trustProxy || false;
935
+
936
+ // Only use forwarded headers if proxy trust is enabled
937
+ if (trustProxy) {
938
+ const forwarded = this.get('x-forwarded-for');
939
+ if (forwarded) {
940
+ // X-Forwarded-For contains client IP as first entry
941
+ const ips = forwarded.split(/\s*,\s*/);
942
+ const clientIP = ips[0]?.trim();
943
+ if (clientIP && this._isValidIP(clientIP)) {
944
+ return clientIP;
945
+ }
946
+ }
947
+
948
+ const realIP = this.get('x-real-ip');
949
+ if (realIP && this._isValidIP(realIP)) {
950
+ return realIP;
951
+ }
952
+ }
953
+
954
+ // Fall back to connection IP
955
+ return this.req.connection?.remoteAddress ||
956
+ this.req.socket?.remoteAddress ||
957
+ '0.0.0.0';
958
+ }
959
+
960
+ /**
961
+ * Get all IPs in the X-Forwarded-For chain
962
+ * WARNING: Only trust X-Forwarded-For if app.settings.trustProxy is enabled
963
+ * @returns {string[]} Array of IP addresses
964
+ */
965
+ ips() {
966
+ const trustProxy = this.app?.settings?.trustProxy || false;
967
+
968
+ if (!trustProxy) {
969
+ const singleIP = this.ip();
970
+ return singleIP !== '0.0.0.0' ? [singleIP] : [];
971
+ }
972
+
973
+ const forwarded = this.get('x-forwarded-for');
974
+ if (!forwarded) {
975
+ const singleIP = this.ip();
976
+ return singleIP !== '0.0.0.0' ? [singleIP] : [];
977
+ }
978
+
979
+ return forwarded
980
+ .split(/\s*,\s*/)
981
+ .map(ip => ip.trim())
982
+ .filter(ip => ip && this._isValidIP(ip));
983
+ }
984
+
985
+ protocol() {
986
+ return this.req.connection.encrypted ? 'https' : 'http';
987
+ }
988
+
989
+ host() {
990
+ return this.get('host') || 'localhost';
991
+ }
992
+
993
+ hostname() {
994
+ const host = this.host();
995
+ if (host.startsWith('[')) {
996
+ // IPv6 literal: [::1]:8080
997
+ const end = host.indexOf(']');
998
+ return end === -1 ? host : host.slice(0, end + 1);
999
+ }
1000
+ return host.split(':')[0];
1001
+ }
1002
+
1003
+ port() {
1004
+ const host = this.host();
1005
+ const portMatch = host.match(/:(\d+)$/);
1006
+ return portMatch ? parseInt(portMatch[1], 10) : (this.secure() ? 443 : 80);
1007
+ }
1008
+
1009
+ subdomains() {
1010
+ const hostname = this.hostname();
1011
+ const parts = hostname.split('.');
1012
+ return parts.length > 2 ? parts.slice(0, -2).reverse() : [];
1013
+ }
1014
+
1015
+ type() {
1016
+ const contentType = this.get('content-type');
1017
+ return contentType ? contentType.split(';')[0] : '';
1018
+ }
1019
+
1020
+ charset() {
1021
+ const contentType = this.get('content-type');
1022
+ if (!contentType) return '';
1023
+
1024
+ const match = contentType.match(/charset=([^;]+)/);
1025
+ return match ? match[1] : '';
1026
+ }
1027
+
1028
+ length() {
1029
+ const contentLength = this.get('content-length');
1030
+ return contentLength ? parseInt(contentLength, 10) : 0;
1031
+ }
1032
+
1033
+ toString() {
1034
+ return `${this.method} ${this.originalUrl}`;
1035
+ }
1036
+
1037
+ toJSON() {
1038
+ return {
1039
+ method: this.method,
1040
+ url: this.originalUrl,
1041
+ path: this.path,
1042
+ query: this.query,
1043
+ params: this.params,
1044
+ headers: this.headers,
1045
+ cookies: this.cookies,
1046
+ statusCode: this.statusCode,
1047
+ responded: this.responded
1048
+ };
1049
+ }
1050
+
1051
+ /**
1052
+ * Initialize context with new request/response (for object pooling)
1053
+ * @param {IncomingMessage} req - HTTP request
1054
+ * @param {ServerResponse} res - HTTP response
1055
+ * @param {Application} app - Spark application
1056
+ */
1057
+ init(req, res, app) {
1058
+ this.req = req;
1059
+ this.res = res;
1060
+ this.app = app;
1061
+ this.responded = false;
1062
+ this.statusCode = 200;
1063
+
1064
+ this.initializeUrl();
1065
+ this.initializeHeaders();
1066
+ this.initializeQuery();
1067
+ this.initializeCookies();
1068
+
1069
+ this.params = {};
1070
+ this.body = null;
1071
+ this.files = null;
1072
+ this.session = null;
1073
+ this.state = {};
1074
+ }
1075
+
1076
+ /**
1077
+ * Reset context for object pooling
1078
+ */
1079
+ reset() {
1080
+ this.req = null;
1081
+ this.res = null;
1082
+ this.app = null;
1083
+ this.responded = false;
1084
+ this.statusCode = 200;
1085
+ this.url = null;
1086
+ this.path = null;
1087
+ this.method = null;
1088
+ this.originalUrl = null;
1089
+ this.headers = {};
1090
+ this.responseHeaders = {};
1091
+ this.query = {};
1092
+ this.cookies = {};
1093
+ this.params = {};
1094
+ this.body = null;
1095
+ this.files = null;
1096
+ this.session = null;
1097
+ this.state = {};
1098
+ }
1099
+ }
1100
+
833
1101
  module.exports = Context;