@oxog/spark 1.1.1 → 1.3.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 +656 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +90 -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 +705 -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 +538 -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,301 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
- const { promisify } = require('util');
6
- const crypto = require('crypto');
7
-
8
- const stat = promisify(fs.stat);
9
- const readFile = promisify(fs.readFile);
10
- const readdir = promisify(fs.readdir);
11
-
12
- const DEFAULT_MAX_AGE = 0;
13
- const DEFAULT_INDEX = ['index.html'];
14
-
15
- function staticFiles(root, options = {}) {
16
- const opts = {
17
- root: path.resolve(root),
18
- maxAge: options.maxAge || DEFAULT_MAX_AGE,
19
- index: options.index || DEFAULT_INDEX,
20
- hidden: options.hidden || false,
21
- dotfiles: options.dotfiles || 'ignore',
22
- etag: options.etag !== false,
23
- lastModified: options.lastModified !== false,
24
- extensions: options.extensions || [],
25
- fallthrough: options.fallthrough !== false,
26
- redirect: options.redirect !== false,
27
- setHeaders: options.setHeaders,
28
- ...options
29
- };
30
-
31
- const cache = new Map();
32
-
33
- return async (ctx, next) => {
34
- if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
35
- return next();
36
- }
37
-
38
- let pathname;
39
- try {
40
- pathname = decodeURIComponent(ctx.path);
41
- } catch (e) {
42
- return ctx.status(400).json({ error: 'Invalid URL encoding' });
43
- }
44
-
45
- // Normalize the path to prevent directory traversal
46
- const normalizedPath = path.normalize(pathname).replace(/^(\.\.(\/|\\|$))+/, '');
47
-
48
- // Ensure the path doesn't contain any traversal patterns
49
- if (pathname.includes('..') || pathname.includes('\0')) {
50
- if (opts.fallthrough) {
51
- return next();
52
- }
53
- return ctx.status(403).json({ error: 'Forbidden' });
54
- }
55
-
56
- const filePath = path.join(opts.root, normalizedPath);
57
-
58
- // Ensure the resolved path is within the root directory
59
- if (!filePath.startsWith(opts.root)) {
60
- if (opts.fallthrough) {
61
- return next();
62
- }
63
- return ctx.status(403).json({ error: 'Forbidden' });
64
- }
65
-
66
- try {
67
- const stats = await stat(filePath);
68
-
69
- if (stats.isDirectory()) {
70
- return await handleDirectory(ctx, filePath, opts, next);
71
- }
72
-
73
- if (stats.isFile()) {
74
- return await sendFile(ctx, filePath, stats, opts);
75
- }
76
-
77
- } catch (error) {
78
- if (error.code === 'ENOENT') {
79
- return await tryExtensions(ctx, filePath, opts, next);
80
- }
81
-
82
- if (opts.fallthrough) {
83
- return next();
84
- }
85
-
86
- return ctx.status(500).json({ error: 'Internal Server Error' });
87
- }
88
-
89
- if (opts.fallthrough) {
90
- return next();
91
- }
92
-
93
- ctx.status(404).json({ error: 'Not Found' });
94
- };
95
- }
96
-
97
- async function handleDirectory(ctx, dirPath, opts, next) {
98
- if (opts.redirect && !ctx.path.endsWith('/')) {
99
- // Using string concatenation for URL paths (not filesystem paths)
100
- const redirectPath = `${ctx.path}/`;
101
- return ctx.redirect(redirectPath);
102
- }
103
-
104
- for (const indexFile of opts.index) {
105
- const indexPath = path.join(dirPath, indexFile);
106
-
107
- try {
108
- const stats = await stat(indexPath);
109
- if (stats.isFile()) {
110
- return await sendFile(ctx, indexPath, stats, opts);
111
- }
112
- } catch (error) {
113
- continue;
114
- }
115
- }
116
-
117
- if (opts.fallthrough) {
118
- return next();
119
- }
120
-
121
- ctx.status(404).json({ error: 'Not Found' });
122
- }
123
-
124
- async function tryExtensions(ctx, filePath, opts, next) {
125
- for (const ext of opts.extensions) {
126
- const extPath = filePath + ext;
127
-
128
- try {
129
- const stats = await stat(extPath);
130
- if (stats.isFile()) {
131
- return await sendFile(ctx, extPath, stats, opts);
132
- }
133
- } catch (error) {
134
- continue;
135
- }
136
- }
137
-
138
- if (opts.fallthrough) {
139
- return next();
140
- }
141
-
142
- ctx.status(404).json({ error: 'Not Found' });
143
- }
144
-
145
- async function sendFile(ctx, filePath, stats, opts) {
146
- const basename = path.basename(filePath);
147
-
148
- if (!opts.hidden && basename.startsWith('.')) {
149
- if (opts.dotfiles === 'deny') {
150
- return ctx.status(403).json({ error: 'Forbidden' });
151
- } else if (opts.dotfiles === 'ignore') {
152
- return ctx.status(404).json({ error: 'Not Found' });
153
- }
154
- }
155
-
156
- const contentType = getContentType(filePath);
157
- ctx.set('Content-Type', contentType);
158
- ctx.set('Content-Length', stats.size);
159
-
160
- if (opts.lastModified) {
161
- ctx.set('Last-Modified', stats.mtime.toUTCString());
162
- }
163
-
164
- if (opts.etag) {
165
- const etag = generateETag(stats);
166
- ctx.set('ETag', etag);
167
-
168
- if (ctx.get('if-none-match') === etag) {
169
- return ctx.status(304).end();
170
- }
171
- }
172
-
173
- if (opts.maxAge) {
174
- const cacheControl = `public, max-age=${opts.maxAge}`;
175
- ctx.set('Cache-Control', cacheControl);
176
- }
177
-
178
- const range = ctx.get('range');
179
- if (range) {
180
- return await sendRangeFile(ctx, filePath, stats, range);
181
- }
182
-
183
- if (opts.setHeaders) {
184
- opts.setHeaders(ctx, filePath, stats);
185
- }
186
-
187
- if (ctx.method === 'HEAD') {
188
- return ctx.status(200).end();
189
- }
190
-
191
- try {
192
- const content = await readFile(filePath);
193
- ctx.status(200).send(content);
194
- } catch (error) {
195
- ctx.status(500).json({ error: 'Internal Server Error' });
196
- }
197
- }
198
-
199
- async function sendRangeFile(ctx, filePath, stats, rangeHeader) {
200
- const ranges = parseRange(stats.size, rangeHeader);
201
-
202
- if (!ranges || ranges.length === 0) {
203
- ctx.set('Content-Range', `bytes */${stats.size}`);
204
- return ctx.status(416).json({ error: 'Range Not Satisfiable' });
205
- }
206
-
207
- if (ranges.length === 1) {
208
- const range = ranges[0];
209
- const start = range.start;
210
- const end = range.end;
211
- const chunkSize = end - start + 1;
212
-
213
- ctx.set('Content-Range', `bytes ${start}-${end}/${stats.size}`);
214
- ctx.set('Content-Length', chunkSize);
215
- ctx.set('Accept-Ranges', 'bytes');
216
- ctx.status(206);
217
-
218
- const stream = fs.createReadStream(filePath, { start, end });
219
- stream.pipe(ctx.res);
220
- } else {
221
- ctx.status(416).json({ error: 'Multiple ranges not supported' });
222
- }
223
- }
224
-
225
- function parseRange(size, rangeHeader) {
226
- if (!rangeHeader || !rangeHeader.startsWith('bytes=')) {
227
- return null;
228
- }
229
-
230
- const ranges = [];
231
- const parts = rangeHeader.slice(6).split(',');
232
-
233
- for (const part of parts) {
234
- const [start, end] = part.trim().split('-');
235
- const startNum = parseInt(start);
236
- const endNum = parseInt(end);
237
-
238
- if (isNaN(startNum) && isNaN(endNum)) {
239
- continue;
240
- }
241
-
242
- if (isNaN(startNum)) {
243
- ranges.push({ start: Math.max(0, size - endNum), end: size - 1 });
244
- } else if (isNaN(endNum)) {
245
- ranges.push({ start: startNum, end: size - 1 });
246
- } else {
247
- ranges.push({ start: startNum, end: Math.min(endNum, size - 1) });
248
- }
249
- }
250
-
251
- return ranges;
252
- }
253
-
254
- function getContentType(filePath) {
255
- const ext = path.extname(filePath).toLowerCase();
256
-
257
- const mimeTypes = {
258
- '.html': 'text/html',
259
- '.htm': 'text/html',
260
- '.js': 'application/javascript',
261
- '.css': 'text/css',
262
- '.json': 'application/json',
263
- '.png': 'image/png',
264
- '.jpg': 'image/jpeg',
265
- '.jpeg': 'image/jpeg',
266
- '.gif': 'image/gif',
267
- '.svg': 'image/svg+xml',
268
- '.ico': 'image/x-icon',
269
- '.pdf': 'application/pdf',
270
- '.txt': 'text/plain',
271
- '.md': 'text/markdown',
272
- '.xml': 'application/xml',
273
- '.zip': 'application/zip',
274
- '.tar': 'application/x-tar',
275
- '.gz': 'application/gzip',
276
- '.mp4': 'video/mp4',
277
- '.webm': 'video/webm',
278
- '.mp3': 'audio/mpeg',
279
- '.wav': 'audio/wav',
280
- '.woff': 'font/woff',
281
- '.woff2': 'font/woff2',
282
- '.ttf': 'font/ttf',
283
- '.otf': 'font/otf'
284
- };
285
-
286
- return mimeTypes[ext] || 'application/octet-stream';
287
- }
288
-
289
- function generateETag(stats) {
290
- const hash = crypto.createHash('md5');
291
- hash.update(stats.size.toString());
292
- hash.update(stats.mtime.getTime().toString());
293
- return `"${hash.digest('hex')}"`;
294
- }
295
-
296
- function serveStatic(root, options) {
297
- return staticFiles(root, options);
298
- }
299
-
300
- module.exports = staticFiles;
301
- module.exports.serveStatic = serveStatic;
package/dist/package.json DELETED
@@ -1,62 +0,0 @@
1
- {
2
- "name": "@oxog/spark",
3
- "version": "1.1.1",
4
- "description": "Ultra-fast, zero-dependency Node.js web framework with security hardening, memory leak protection, and enhanced error handling",
5
- "main": "index.js",
6
- "types": "types/index.d.ts",
7
- "engines": {
8
- "node": ">=14.0.0"
9
- },
10
- "scripts": {
11
- "test": "node tests/run-all-tests.js"
12
- },
13
- "keywords": [
14
- "spark",
15
- "api",
16
- "framework",
17
- "rest",
18
- "http",
19
- "server",
20
- "web",
21
- "app",
22
- "middleware",
23
- "router",
24
- "zero-dependency",
25
- "fast",
26
- "secure",
27
- "lightweight",
28
- "performance",
29
- "typescript",
30
- "security",
31
- "memory-safe",
32
- "error-handling",
33
- "redos-protection",
34
- "path-traversal-protection",
35
- "header-injection-protection"
36
- ],
37
- "author": "Ersin Koç",
38
- "license": "MIT",
39
- "repository": {
40
- "type": "git",
41
- "url": "https://github.com/ersinkoc/spark.git"
42
- },
43
- "bugs": {
44
- "url": "https://github.com/ersinkoc/spark/issues"
45
- },
46
- "homepage": "https://github.com/ersinkoc/spark#readme",
47
- "files": [
48
- "src/",
49
- "types/",
50
- "dist/",
51
- "README.md",
52
- "LICENSE",
53
- "CHANGELOG.md"
54
- ],
55
- "exports": {
56
- ".": {
57
- "import": "./src/index.js",
58
- "require": "./src/index.js"
59
- },
60
- "./package.json": "./package.json"
61
- }
62
- }
@@ -1,119 +0,0 @@
1
- 'use strict';
2
-
3
- class Layer {
4
- constructor(path, options, handler, router = null) {
5
- this.path = path;
6
- this.handler = handler;
7
- this.name = handler.name || '<anonymous>';
8
- this.options = options;
9
- this.route = null;
10
- this.method = null;
11
- this.router = router;
12
-
13
- // Use router's pathToRegExp if available, otherwise create a default regex
14
- if (router && router.pathToRegExp) {
15
- this.regexp = router.pathToRegExp(path, options);
16
- } else {
17
- // Fallback to default regex creation without circular dependency
18
- this.regexp = this.createDefaultRegex(path, options);
19
- }
20
- this.keys = this.regexp.keys;
21
- }
22
-
23
- createDefaultRegex(path, options = {}) {
24
- const { sensitive = false, strict = false, end = true } = options;
25
-
26
- if (path instanceof RegExp) {
27
- return { regexp: path, keys: [] };
28
- }
29
-
30
- const keys = [];
31
- let regexp = path;
32
-
33
- // Escape forward slashes
34
- regexp = regexp.replace(/\\\//g, '/');
35
-
36
- // Replace parameters
37
- regexp = regexp.replace(/:([^(/\\]+)/g, (match, key) => {
38
- keys.push({ name: key, optional: false });
39
- return '([^/]+)';
40
- });
41
-
42
- // Replace wildcards
43
- regexp = regexp.replace(/\*([^(/\\]*)/g, (match, key) => {
44
- keys.push({ name: key || 'wild', optional: false });
45
- return '(.*)';
46
- });
47
-
48
- // Add end pattern
49
- if (end) {
50
- regexp += strict ? '' : '/?';
51
- }
52
-
53
- regexp += end ? '$' : '';
54
-
55
- const flags = sensitive ? '' : 'i';
56
- return {
57
- regexp: new RegExp(`^${regexp}`, flags),
58
- keys
59
- };
60
- }
61
-
62
- match(path) {
63
- const match = this.regexp.regexp.exec(path);
64
-
65
- if (!match) {
66
- return false;
67
- }
68
-
69
- const params = {};
70
-
71
- for (let i = 1; i < match.length; i++) {
72
- const key = this.keys[i - 1];
73
- const value = match[i];
74
-
75
- if (value !== undefined) {
76
- params[key.name] = decodeParam(value);
77
- }
78
- }
79
-
80
- return {
81
- path: match[0],
82
- params
83
- };
84
- }
85
-
86
- async handle(ctx, next) {
87
- if (this.handler.length > 2) {
88
- return this.handler(ctx, next);
89
- } else {
90
- await this.handler(ctx, next);
91
- }
92
- }
93
-
94
- handles_method(method) {
95
- if (this.method) {
96
- return this.method === method;
97
- }
98
-
99
- if (this.route) {
100
- return this.route.handles_method(method);
101
- }
102
-
103
- return true;
104
- }
105
- }
106
-
107
- function decodeParam(value) {
108
- if (typeof value !== 'string' || value.length === 0) {
109
- return value;
110
- }
111
-
112
- try {
113
- return decodeURIComponent(value);
114
- } catch (error) {
115
- throw new Error(`Failed to decode param '${value}'`);
116
- }
117
- }
118
-
119
- module.exports = Layer;
@@ -1,125 +0,0 @@
1
- 'use strict';
2
-
3
- class Route {
4
- constructor(path) {
5
- this.path = path;
6
- this.stack = [];
7
- this.methods = {};
8
- }
9
-
10
- get(...handlers) {
11
- handlers.forEach(handler => this.add('GET', handler));
12
- return this;
13
- }
14
-
15
- post(...handlers) {
16
- handlers.forEach(handler => this.add('POST', handler));
17
- return this;
18
- }
19
-
20
- put(...handlers) {
21
- handlers.forEach(handler => this.add('PUT', handler));
22
- return this;
23
- }
24
-
25
- delete(...handlers) {
26
- handlers.forEach(handler => this.add('DELETE', handler));
27
- return this;
28
- }
29
-
30
- patch(...handlers) {
31
- handlers.forEach(handler => this.add('PATCH', handler));
32
- return this;
33
- }
34
-
35
- head(...handlers) {
36
- handlers.forEach(handler => this.add('HEAD', handler));
37
- return this;
38
- }
39
-
40
- options(...handlers) {
41
- handlers.forEach(handler => this.add('OPTIONS', handler));
42
- return this;
43
- }
44
-
45
- all(...handlers) {
46
- const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
47
- handlers.forEach(handler => {
48
- methods.forEach(method => {
49
- this.add(method, handler);
50
- });
51
- });
52
- return this;
53
- }
54
-
55
- add(method, handler) {
56
- if (typeof handler !== 'function') {
57
- throw new Error('Handler must be a function');
58
- }
59
-
60
- if (!this.methods[method]) {
61
- this.methods[method] = true;
62
- }
63
-
64
- const layer = {
65
- method,
66
- handler,
67
- name: handler.name || '<anonymous>'
68
- };
69
-
70
- this.stack.push(layer);
71
- return this;
72
- }
73
-
74
- handles_method(method) {
75
- if (this.methods._all) {
76
- return true;
77
- }
78
-
79
- // Method'lar büyük harfle kaydediliyor, bu yüzden büyük harfe çevir
80
- const name = method.toUpperCase();
81
-
82
- if (name === 'HEAD' && !this.methods.HEAD) {
83
- return this.methods.GET;
84
- }
85
-
86
- return Boolean(this.methods[name]);
87
- }
88
-
89
- async dispatch(ctx, done) {
90
- let layerIndex = 0;
91
-
92
- const next = async (error) => {
93
- if (error) {
94
- return done(error);
95
- }
96
-
97
- if (layerIndex >= this.stack.length) {
98
- return done();
99
- }
100
-
101
- const layer = this.stack[layerIndex++];
102
-
103
- if (layer.method && layer.method !== ctx.method) {
104
- return next();
105
- }
106
-
107
- try {
108
- const result = layer.handler(ctx, next);
109
- if (result && typeof result.then === 'function') {
110
- await result;
111
- }
112
- } catch (err) {
113
- return next(err);
114
- }
115
- };
116
-
117
- await next();
118
- }
119
-
120
- toString() {
121
- return this.path;
122
- }
123
- }
124
-
125
- module.exports = Route;