@oxog/spark 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +632 -293
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1070 -956
  6. package/src/core/context.js +1100 -830
  7. package/src/core/middleware.js +305 -217
  8. package/src/index.js +183 -278
  9. package/src/middleware/body-parser.js +484 -526
  10. package/src/middleware/cache.js +179 -170
  11. package/src/middleware/compression.js +179 -182
  12. package/src/middleware/cors.js +178 -95
  13. package/src/middleware/health.js +221 -218
  14. package/src/middleware/logger.js +197 -194
  15. package/src/middleware/metrics.js +341 -327
  16. package/src/middleware/rate-limit.js +369 -319
  17. package/src/middleware/security.js +444 -332
  18. package/src/middleware/session.js +649 -529
  19. package/src/middleware/static.js +406 -299
  20. package/src/router/layer.js +199 -117
  21. package/src/router/route.js +151 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +147 -144
  24. package/src/utils/context-pool.js +85 -82
  25. package/src/utils/regex-validator.js +189 -176
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +536 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -957
  31. package/dist/core/context.js +0 -831
  32. package/dist/core/middleware.js +0 -218
  33. package/dist/core/request.js +0 -333
  34. package/dist/core/response.js +0 -375
  35. package/dist/index.js +0 -278
  36. package/dist/middleware/body-parser.js +0 -526
  37. package/dist/middleware/cache.js +0 -171
  38. package/dist/middleware/compression.js +0 -183
  39. package/dist/middleware/cors.js +0 -95
  40. package/dist/middleware/health.js +0 -219
  41. package/dist/middleware/index.js +0 -21
  42. package/dist/middleware/logger.js +0 -195
  43. package/dist/middleware/metrics.js +0 -328
  44. package/dist/middleware/rate-limit.js +0 -320
  45. package/dist/middleware/security.js +0 -333
  46. package/dist/middleware/session.js +0 -530
  47. package/dist/middleware/static.js +0 -299
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -117
  50. package/dist/router/route.js +0 -123
  51. package/dist/router/router.js +0 -756
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -145
  54. package/dist/utils/cache.js +0 -441
  55. package/dist/utils/context-pool.js +0 -83
  56. package/dist/utils/error-types.js +0 -132
  57. package/dist/utils/http.js +0 -413
  58. package/dist/utils/regex-validator.js +0 -177
  59. package/src/core/request.js +0 -333
  60. package/src/core/response.js +0 -375
  61. package/src/middleware/index.js +0 -21
  62. package/src/utils/cache.js +0 -441
  63. package/src/utils/error-types.js +0 -132
  64. package/src/utils/http.js +0 -413
@@ -1,831 +1,1101 @@
1
- /**
2
- * @fileoverview Context class for handling HTTP requests and responses in Spark Framework
3
- * @author Spark Framework Team
4
- * @since 1.0.0
5
- * @version 1.0.0
6
- */
7
-
8
- const { URL } = require('url');
9
- const querystring = require('querystring');
10
-
11
- /**
12
- * Context class that wraps HTTP request and response objects
13
- *
14
- * The Context class provides a unified interface for handling HTTP requests and responses.
15
- * It parses incoming request data, provides helper methods for setting headers and status codes,
16
- * and includes convenience methods for sending various types of responses.
17
- *
18
- * @class Context
19
- * @since 1.0.0
20
- *
21
- * @example
22
- * // In a middleware or route handler
23
- * app.get('/users/:id', (ctx) => {
24
- * const userId = ctx.params.id;
25
- * const userAgent = ctx.get('user-agent');
26
- *
27
- * ctx.set('X-Response-Time', '10ms');
28
- * ctx.json({ id: userId, userAgent });
29
- * });
30
- *
31
- * @example
32
- * // Working with cookies
33
- * app.post('/login', (ctx) => {
34
- * const { username, password } = ctx.body;
35
- *
36
- * if (authenticate(username, password)) {
37
- * ctx.setCookie('session', 'abc123', {
38
- * httpOnly: true,
39
- * secure: true,
40
- * maxAge: 3600000
41
- * });
42
- * ctx.json({ success: true });
43
- * } else {
44
- * ctx.status(401).json({ error: 'Invalid credentials' });
45
- * }
46
- * });
47
- */
48
- class Context {
49
- /**
50
- * Create a new Context instance
51
- *
52
- * @param {http.IncomingMessage} req - The HTTP request object
53
- * @param {http.ServerResponse} res - The HTTP response object
54
- * @param {Application} app - The Spark application instance
55
- *
56
- * @since 1.0.0
57
- *
58
- * @example
59
- * // Context is typically created automatically by the framework
60
- * const ctx = new Context(req, res, app);
61
- */
62
- constructor(req, res, app) {
63
- /**
64
- * The HTTP request object
65
- * @type {http.IncomingMessage}
66
- * @readonly
67
- */
68
- this.req = req;
69
-
70
- /**
71
- * The HTTP response object
72
- * @type {http.ServerResponse}
73
- * @readonly
74
- */
75
- this.res = res;
76
-
77
- /**
78
- * The Spark application instance
79
- * @type {Application}
80
- * @readonly
81
- */
82
- this.app = app;
83
-
84
- /**
85
- * Whether a response has been sent
86
- * @type {boolean}
87
- * @readonly
88
- */
89
- this.responded = false;
90
-
91
- /**
92
- * The HTTP status code for the response
93
- * @type {number}
94
- */
95
- this.statusCode = 200;
96
-
97
- this.initializeUrl();
98
- this.initializeHeaders();
99
- this.initializeQuery();
100
- this.initializeCookies();
101
-
102
- /**
103
- * Route parameters extracted from the URL
104
- * @type {Object}
105
- * @example
106
- * // For route '/users/:id' with URL '/users/123'
107
- * ctx.params.id // '123'
108
- */
109
- this.params = {};
110
-
111
- /**
112
- * Parsed request body
113
- * @type {*}
114
- */
115
- this.body = null;
116
-
117
- /**
118
- * Uploaded files (when using multipart/form-data)
119
- * @type {Object|null}
120
- */
121
- this.files = null;
122
-
123
- /**
124
- * Session data (when session middleware is used)
125
- * @type {Object|null}
126
- */
127
- this.session = null;
128
-
129
- /**
130
- * Application state for storing custom data
131
- * @type {Object}
132
- */
133
- this.state = {};
134
- }
135
-
136
- /**
137
- * Initialize URL-related properties from the request
138
- *
139
- * Parses the request URL and extracts path, method, and other URL components.
140
- * Handles malformed URLs by throwing an appropriate error.
141
- *
142
- * @private
143
- * @throws {Error} When the URL cannot be parsed
144
- * @since 1.0.0
145
- */
146
- initializeUrl() {
147
- const protocol = this.req.connection.encrypted ? 'https' : 'http';
148
- const host = this.req.headers.host || 'localhost';
149
-
150
- try {
151
- /**
152
- * Parsed URL object
153
- * @type {URL|null}
154
- * @readonly
155
- */
156
- this.url = new URL(this.req.url, `${protocol}://${host}`);
157
-
158
- /**
159
- * Request path (pathname without query string)
160
- * @type {string}
161
- * @readonly
162
- */
163
- this.path = this.url.pathname;
164
- } catch (error) {
165
- // Handle malformed URLs - throw proper error instead of just logging
166
- this.url = null;
167
- this.path = '/';
168
- this.statusCode = 400;
169
- this.body = { error: 'Invalid URL format' };
170
- throw new Error(`Failed to parse URL: ${error.message}`);
171
- }
172
-
173
- /**
174
- * HTTP method (GET, POST, PUT, etc.)
175
- * @type {string}
176
- * @readonly
177
- */
178
- this.method = this.req.method ? this.req.method.toUpperCase() : 'GET';
179
-
180
- /**
181
- * Original request URL including query string
182
- * @type {string}
183
- * @readonly
184
- */
185
- this.originalUrl = this.req.url;
186
- }
187
-
188
- /**
189
- * Initialize request and response headers
190
- *
191
- * Copies request headers and initializes response headers object.
192
- *
193
- * @private
194
- * @since 1.0.0
195
- */
196
- initializeHeaders() {
197
- /**
198
- * Request headers (lowercase keys)
199
- * @type {Object}
200
- * @readonly
201
- */
202
- this.headers = { ...this.req.headers };
203
-
204
- /**
205
- * Response headers to be sent
206
- * @type {Object}
207
- * @private
208
- */
209
- this.responseHeaders = {};
210
- }
211
-
212
- /**
213
- * Initialize query string parameters
214
- *
215
- * Parses the URL query string into an object.
216
- *
217
- * @private
218
- * @since 1.0.0
219
- */
220
- initializeQuery() {
221
- /**
222
- * Parsed query string parameters
223
- * @type {Object}
224
- * @readonly
225
- * @example
226
- * // For URL '/search?q=hello&limit=10'
227
- * ctx.query.q // 'hello'
228
- * ctx.query.limit // '10'
229
- */
230
- this.query = {};
231
- if (this.url.search) {
232
- this.query = querystring.parse(this.url.search.slice(1));
233
- }
234
- }
235
-
236
- /**
237
- * Initialize cookies from the request
238
- *
239
- * Parses the Cookie header and decodes cookie values.
240
- * Malformed cookies are skipped and logged.
241
- *
242
- * @private
243
- * @since 1.0.0
244
- */
245
- initializeCookies() {
246
- /**
247
- * Parsed cookies from the request
248
- * @type {Object}
249
- * @readonly
250
- * @example
251
- * // For Cookie header 'session=abc123; theme=dark'
252
- * ctx.cookies.session // 'abc123'
253
- * ctx.cookies.theme // 'dark'
254
- */
255
- this.cookies = {};
256
- const cookieHeader = this.req.headers.cookie;
257
- if (cookieHeader) {
258
- cookieHeader.split(';').forEach(cookie => {
259
- const [name, value] = cookie.trim().split('=');
260
- if (name && value) {
261
- try {
262
- this.cookies[name] = decodeURIComponent(value);
263
- } catch (error) {
264
- // Skip malformed cookie values
265
- console.error(`Failed to decode cookie ${name}: ${error.message}`);
266
- }
267
- }
268
- });
269
- }
270
- }
271
-
272
- /**
273
- * Get a request header value
274
- *
275
- * @param {string} headerName - The header name (case-insensitive)
276
- * @returns {string|undefined} The header value or undefined if not present
277
- *
278
- * @since 1.0.0
279
- *
280
- * @example
281
- * const userAgent = ctx.get('User-Agent');
282
- * const contentType = ctx.get('content-type');
283
- */
284
- get(headerName) {
285
- return this.headers[headerName.toLowerCase()];
286
- }
287
-
288
- /**
289
- * Set a response header
290
- *
291
- * Sets a response header with validation for security and RFC compliance.
292
- * Header names and values are validated to prevent injection attacks.
293
- *
294
- * @param {string} headerName - The header name
295
- * @param {string|number} value - The header value
296
- * @returns {Context} The context instance for method chaining
297
- *
298
- * @throws {Error} When header name or value is invalid
299
- *
300
- * @since 1.0.0
301
- *
302
- * @example
303
- * ctx.set('Content-Type', 'application/json');
304
- * ctx.set('X-Response-Time', '10ms');
305
- *
306
- * @example
307
- * // Method chaining
308
- * ctx.set('Content-Type', 'text/html')
309
- * .set('Cache-Control', 'no-cache');
310
- */
311
- set(headerName, value) {
312
- // Validate header name
313
- if (!headerName || typeof headerName !== 'string') {
314
- throw new Error('Header name must be a non-empty string');
315
- }
316
-
317
- // Validate header name format (RFC 7230)
318
- if (!/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(headerName)) {
319
- throw new Error(`Invalid header name: ${headerName}`);
320
- }
321
-
322
- // Validate header value
323
- if (value !== undefined && value !== null) {
324
- const stringValue = String(value);
325
- // Check for invalid characters in header value (CRLF and null byte)
326
- if (/[\r\n\x00]/.test(stringValue)) {
327
- throw new Error('Header value cannot contain CRLF or null characters');
328
- }
329
- // Check header value length
330
- if (stringValue.length > 8192) {
331
- throw new Error('Header value too long (max 8192 characters)');
332
- }
333
- this.responseHeaders[headerName.toLowerCase()] = stringValue;
334
- }
335
-
336
- return this;
337
- }
338
-
339
- /**
340
- * Alias for set() method
341
- *
342
- * @param {string} name - The header name
343
- * @param {string|number} value - The header value
344
- * @returns {Context} The context instance for method chaining
345
- *
346
- * @since 1.0.0
347
- * @see {@link Context#set}
348
- */
349
- setHeader(name, value) {
350
- return this.set(name, value);
351
- }
352
-
353
- /**
354
- * Get a response header value
355
- *
356
- * @param {string} name - The header name (case-insensitive)
357
- * @returns {string|undefined} The header value or undefined if not set
358
- *
359
- * @since 1.0.0
360
- *
361
- * @example
362
- * ctx.set('Content-Type', 'application/json');
363
- * const contentType = ctx.getHeader('content-type'); // 'application/json'
364
- */
365
- getHeader(name) {
366
- return this.responseHeaders[name.toLowerCase()];
367
- }
368
-
369
- /**
370
- * Remove a response header
371
- *
372
- * @param {string} name - The header name (case-insensitive)
373
- * @returns {Context} The context instance for method chaining
374
- *
375
- * @since 1.0.0
376
- *
377
- * @example
378
- * ctx.removeHeader('X-Powered-By');
379
- */
380
- removeHeader(name) {
381
- delete this.responseHeaders[name.toLowerCase()];
382
- return this;
383
- }
384
-
385
- /**
386
- * Set the HTTP status code
387
- *
388
- * @param {number|string} code - HTTP status code (100-599)
389
- * @returns {Context} The context instance for method chaining
390
- *
391
- * @throws {Error} When status code is invalid
392
- *
393
- * @since 1.0.0
394
- *
395
- * @example
396
- * ctx.status(200); // OK
397
- * ctx.status(404); // Not Found
398
- * ctx.status(500); // Internal Server Error
399
- *
400
- * @example
401
- * // Method chaining
402
- * ctx.status(201).json({ id: 123, name: 'User' });
403
- */
404
- status(code) {
405
- // Validate status code
406
- const statusCode = parseInt(code);
407
- if (isNaN(statusCode) || statusCode < 100 || statusCode > 599) {
408
- throw new Error(`Invalid status code: ${code}. Must be between 100 and 599`);
409
- }
410
- this.statusCode = statusCode;
411
- return this;
412
- }
413
-
414
- /**
415
- * Redirect to a URL
416
- *
417
- * Sets the Location header and status code, then ends the response.
418
- *
419
- * @param {string} url - The URL to redirect to
420
- * @param {number} [status=302] - HTTP status code for redirect
421
- * @returns {Context} The context instance for method chaining
422
- *
423
- * @since 1.0.0
424
- *
425
- * @example
426
- * // Temporary redirect (302)
427
- * ctx.redirect('/login');
428
- *
429
- * @example
430
- * // Permanent redirect (301)
431
- * ctx.redirect('/new-path', 301);
432
- */
433
- redirect(url, status = 302) {
434
- this.status(status);
435
- this.set('Location', url);
436
- this.end();
437
- return this;
438
- }
439
-
440
- /**
441
- * Send a JSON response
442
- *
443
- * Sets the Content-Type header to application/json and sends the data as JSON.
444
- *
445
- * @param {*} data - The data to send as JSON
446
- * @returns {Context} The context instance for method chaining
447
- *
448
- * @since 1.0.0
449
- *
450
- * @example
451
- * ctx.json({ message: 'Hello World' });
452
- *
453
- * @example
454
- * // With status code
455
- * ctx.status(201).json({ id: 123, name: 'User' });
456
- */
457
- json(data) {
458
- this.set('Content-Type', 'application/json');
459
- this.send(JSON.stringify(data));
460
- return this;
461
- }
462
-
463
- /**
464
- * Send a plain text response
465
- *
466
- * Sets the Content-Type header to text/plain and sends the data as text.
467
- *
468
- * @param {string} data - The text data to send
469
- * @returns {Context} The context instance for method chaining
470
- *
471
- * @since 1.0.0
472
- *
473
- * @example
474
- * ctx.text('Hello World');
475
- *
476
- * @example
477
- * // With status code
478
- * ctx.status(200).text('Success');
479
- */
480
- text(data) {
481
- this.set('Content-Type', 'text/plain');
482
- this.send(data);
483
- return this;
484
- }
485
-
486
- /**
487
- * Send an HTML response
488
- *
489
- * Sets the Content-Type header to text/html and sends the data as HTML.
490
- *
491
- * @param {string} data - The HTML data to send
492
- * @returns {Context} The context instance for method chaining
493
- *
494
- * @since 1.0.0
495
- *
496
- * @example
497
- * ctx.html('<h1>Hello World</h1>');
498
- *
499
- * @example
500
- * // With status code
501
- * ctx.status(200).html('<p>Welcome!</p>');
502
- */
503
- html(data) {
504
- this.set('Content-Type', 'text/html');
505
- this.send(data);
506
- return this;
507
- }
508
-
509
- /**
510
- * Send a response with data
511
- *
512
- * Sends the response with the specified data. This method is called by other
513
- * response methods like json(), text(), and html(). Once called, no further
514
- * response methods can be used.
515
- *
516
- * @param {*} data - The data to send
517
- * @returns {Context} The context instance for method chaining
518
- *
519
- * @since 1.0.0
520
- *
521
- * @example
522
- * ctx.send('Hello World');
523
- * ctx.send(Buffer.from('binary data'));
524
- */
525
- send(data) {
526
- if (this.responded) {
527
- return this;
528
- }
529
-
530
- this.responded = true;
531
- this.res.statusCode = this.statusCode;
532
-
533
- Object.keys(this.responseHeaders).forEach(name => {
534
- this.res.setHeader(name, this.responseHeaders[name]);
535
- });
536
-
537
- if (data === null || data === undefined) {
538
- this.res.end();
539
- } else if (typeof data === 'string' || Buffer.isBuffer(data)) {
540
- this.res.end(data);
541
- } else {
542
- this.res.end(String(data));
543
- }
544
-
545
- return this;
546
- }
547
-
548
- /**
549
- * End the response
550
- *
551
- * Ends the response optionally with data. This is an alias for send().
552
- *
553
- * @param {*} [data] - Optional data to send before ending
554
- * @returns {Context} The context instance for method chaining
555
- *
556
- * @since 1.0.0
557
- *
558
- * @example
559
- * ctx.status(204).end(); // No content
560
- * ctx.end('Final message');
561
- */
562
- end(data) {
563
- if (data) {
564
- this.send(data);
565
- } else {
566
- this.send();
567
- }
568
- return this;
569
- }
570
-
571
- setCookie(name, value, options = {}) {
572
- // Validate cookie name
573
- if (!name || typeof name !== 'string') {
574
- throw new Error('Cookie name must be a non-empty string');
575
- }
576
-
577
- // Validate cookie name format (RFC 6265)
578
- if (!/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(name)) {
579
- throw new Error(`Invalid cookie name: ${name}`);
580
- }
581
-
582
- // Check for control characters in cookie name
583
- if (/[\x00-\x1F\x7F]/.test(name)) {
584
- throw new Error('Cookie name cannot contain control characters');
585
- }
586
-
587
- // Validate cookie value
588
- if (value === null || value === undefined) {
589
- value = '';
590
- }
591
-
592
- // Convert value to string and check for invalid characters
593
- const stringValue = String(value);
594
- if (/[\x00-\x1F\x7F]/.test(stringValue)) {
595
- throw new Error('Cookie value cannot contain control characters');
596
- }
597
-
598
- let cookieString = `${name}=${encodeURIComponent(value)}`;
599
-
600
- if (options.domain) {
601
- cookieString += `; Domain=${options.domain}`;
602
- }
603
-
604
- if (options.path) {
605
- cookieString += `; Path=${options.path}`;
606
- }
607
-
608
- if (options.expires) {
609
- cookieString += `; Expires=${options.expires.toUTCString()}`;
610
- }
611
-
612
- if (options.maxAge) {
613
- cookieString += `; Max-Age=${options.maxAge}`;
614
- }
615
-
616
- if (options.httpOnly) {
617
- cookieString += '; HttpOnly';
618
- }
619
-
620
- if (options.secure) {
621
- cookieString += '; Secure';
622
- }
623
-
624
- if (options.sameSite) {
625
- const validSameSite = ['Strict', 'Lax', 'None'];
626
- const sameSiteValue = options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1).toLowerCase();
627
- if (!validSameSite.includes(sameSiteValue)) {
628
- throw new Error(`Invalid SameSite value: ${options.sameSite}. Must be 'Strict', 'Lax', or 'None'`);
629
- }
630
- cookieString += `; SameSite=${sameSiteValue}`;
631
- }
632
-
633
- const existingCookies = this.responseHeaders['set-cookie'] || [];
634
- if (Array.isArray(existingCookies)) {
635
- existingCookies.push(cookieString);
636
- this.responseHeaders['set-cookie'] = existingCookies;
637
- } else if (existingCookies) {
638
- this.responseHeaders['set-cookie'] = [existingCookies, cookieString];
639
- } else {
640
- this.responseHeaders['set-cookie'] = [cookieString];
641
- }
642
-
643
- return this;
644
- }
645
-
646
- clearCookie(name, options = {}) {
647
- const clearOptions = {
648
- ...options,
649
- expires: new Date(0),
650
- maxAge: 0
651
- };
652
- return this.setCookie(name, '', clearOptions);
653
- }
654
-
655
- is(type) {
656
- const contentType = this.get('content-type');
657
- if (!contentType) return false;
658
-
659
- const mimeTypes = {
660
- json: 'application/json',
661
- form: 'application/x-www-form-urlencoded',
662
- multipart: 'multipart/form-data',
663
- text: 'text/plain',
664
- html: 'text/html'
665
- };
666
-
667
- const targetType = mimeTypes[type] || type;
668
- return contentType.includes(targetType);
669
- }
670
-
671
- accepts(types) {
672
- const accept = this.get('accept') || '*/*';
673
-
674
- if (typeof types === 'string') {
675
- types = [types];
676
- }
677
-
678
- for (const type of types) {
679
- if (accept.includes(type) || accept.includes('*/*')) {
680
- return type;
681
- }
682
- }
683
-
684
- return false;
685
- }
686
-
687
- fresh() {
688
- const method = this.method;
689
- const status = this.statusCode;
690
-
691
- if (method !== 'GET' && method !== 'HEAD') return false;
692
- if ((status >= 200 && status < 300) || status === 304) return true;
693
-
694
- return false;
695
- }
696
-
697
- stale() {
698
- return !this.fresh();
699
- }
700
-
701
- secure() {
702
- return this.req.connection.encrypted;
703
- }
704
-
705
- xhr() {
706
- return this.get('x-requested-with') === 'XMLHttpRequest';
707
- }
708
-
709
- ip() {
710
- return this.get('x-forwarded-for') ||
711
- this.get('x-real-ip') ||
712
- this.req.connection.remoteAddress ||
713
- this.req.socket.remoteAddress;
714
- }
715
-
716
- ips() {
717
- const forwarded = this.get('x-forwarded-for');
718
- return forwarded ? forwarded.split(/\s*,\s*/) : [this.ip()];
719
- }
720
-
721
- protocol() {
722
- return this.req.connection.encrypted ? 'https' : 'http';
723
- }
724
-
725
- host() {
726
- return this.get('host') || 'localhost';
727
- }
728
-
729
- hostname() {
730
- return this.host().split(':')[0];
731
- }
732
-
733
- port() {
734
- const host = this.host();
735
- const portMatch = host.match(/:(\d+)$/);
736
- return portMatch ? parseInt(portMatch[1]) : (this.secure() ? 443 : 80);
737
- }
738
-
739
- subdomains() {
740
- const hostname = this.hostname();
741
- const parts = hostname.split('.');
742
- return parts.length > 2 ? parts.slice(0, -2).reverse() : [];
743
- }
744
-
745
- type() {
746
- const contentType = this.get('content-type');
747
- return contentType ? contentType.split(';')[0] : '';
748
- }
749
-
750
- charset() {
751
- const contentType = this.get('content-type');
752
- if (!contentType) return '';
753
-
754
- const match = contentType.match(/charset=([^;]+)/);
755
- return match ? match[1] : '';
756
- }
757
-
758
- length() {
759
- const contentLength = this.get('content-length');
760
- return contentLength ? parseInt(contentLength) : 0;
761
- }
762
-
763
- toString() {
764
- return `${this.method} ${this.originalUrl}`;
765
- }
766
-
767
- toJSON() {
768
- return {
769
- method: this.method,
770
- url: this.originalUrl,
771
- path: this.path,
772
- query: this.query,
773
- params: this.params,
774
- headers: this.headers,
775
- cookies: this.cookies,
776
- statusCode: this.statusCode,
777
- responded: this.responded
778
- };
779
- }
780
-
781
- /**
782
- * Initialize context with new request/response (for object pooling)
783
- * @param {IncomingMessage} req - HTTP request
784
- * @param {ServerResponse} res - HTTP response
785
- * @param {Application} app - Spark application
786
- */
787
- init(req, res, app) {
788
- this.req = req;
789
- this.res = res;
790
- this.app = app;
791
- this.responded = false;
792
- this.statusCode = 200;
793
-
794
- this.initializeUrl();
795
- this.initializeHeaders();
796
- this.initializeQuery();
797
- this.initializeCookies();
798
-
799
- this.params = {};
800
- this.body = null;
801
- this.files = null;
802
- this.session = null;
803
- this.state = {};
804
- }
805
-
806
- /**
807
- * Reset context for object pooling
808
- */
809
- reset() {
810
- this.req = null;
811
- this.res = null;
812
- this.app = null;
813
- this.responded = false;
814
- this.statusCode = 200;
815
- this.url = null;
816
- this.path = null;
817
- this.method = null;
818
- this.originalUrl = null;
819
- this.headers = {};
820
- this.responseHeaders = {};
821
- this.query = {};
822
- this.cookies = {};
823
- this.params = {};
824
- this.body = null;
825
- this.files = null;
826
- this.session = null;
827
- this.state = {};
828
- }
829
- }
830
-
1
+ 'use strict';
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
+ 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
+
831
1101
  module.exports = Context;