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