@oxog/spark 1.1.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 (63) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/LICENSE +21 -0
  3. package/README.md +242 -0
  4. package/dist/LICENSE +21 -0
  5. package/dist/README.md +242 -0
  6. package/dist/core/application.js +957 -0
  7. package/dist/core/context.js +831 -0
  8. package/dist/core/middleware.js +218 -0
  9. package/dist/core/request.js +333 -0
  10. package/dist/core/response.js +375 -0
  11. package/dist/index.js +278 -0
  12. package/dist/middleware/body-parser.js +526 -0
  13. package/dist/middleware/cache.js +171 -0
  14. package/dist/middleware/compression.js +183 -0
  15. package/dist/middleware/cors.js +95 -0
  16. package/dist/middleware/health.js +219 -0
  17. package/dist/middleware/index.js +21 -0
  18. package/dist/middleware/logger.js +195 -0
  19. package/dist/middleware/metrics.js +328 -0
  20. package/dist/middleware/rate-limit.js +320 -0
  21. package/dist/middleware/security.js +333 -0
  22. package/dist/middleware/session.js +530 -0
  23. package/dist/middleware/static.js +299 -0
  24. package/dist/package.json +62 -0
  25. package/dist/router/layer.js +117 -0
  26. package/dist/router/route.js +123 -0
  27. package/dist/router/router.js +756 -0
  28. package/dist/types/index.d.ts +291 -0
  29. package/dist/utils/async-handler.js +145 -0
  30. package/dist/utils/cache.js +441 -0
  31. package/dist/utils/context-pool.js +83 -0
  32. package/dist/utils/error-types.js +132 -0
  33. package/dist/utils/http.js +413 -0
  34. package/dist/utils/regex-validator.js +177 -0
  35. package/package.json +89 -0
  36. package/src/core/application.js +957 -0
  37. package/src/core/context.js +831 -0
  38. package/src/core/middleware.js +218 -0
  39. package/src/core/request.js +333 -0
  40. package/src/core/response.js +375 -0
  41. package/src/index.js +278 -0
  42. package/src/middleware/body-parser.js +526 -0
  43. package/src/middleware/cache.js +171 -0
  44. package/src/middleware/compression.js +183 -0
  45. package/src/middleware/cors.js +95 -0
  46. package/src/middleware/health.js +219 -0
  47. package/src/middleware/index.js +21 -0
  48. package/src/middleware/logger.js +195 -0
  49. package/src/middleware/metrics.js +328 -0
  50. package/src/middleware/rate-limit.js +320 -0
  51. package/src/middleware/security.js +333 -0
  52. package/src/middleware/session.js +530 -0
  53. package/src/middleware/static.js +299 -0
  54. package/src/router/layer.js +117 -0
  55. package/src/router/route.js +123 -0
  56. package/src/router/router.js +756 -0
  57. package/src/utils/async-handler.js +145 -0
  58. package/src/utils/cache.js +441 -0
  59. package/src/utils/context-pool.js +83 -0
  60. package/src/utils/error-types.js +132 -0
  61. package/src/utils/http.js +413 -0
  62. package/src/utils/regex-validator.js +177 -0
  63. package/types/index.d.ts +291 -0
@@ -0,0 +1,530 @@
1
+ const crypto = require('crypto');
2
+ const { EventEmitter } = require('events');
3
+
4
+ const DEFAULT_MAX_AGE = 24 * 60 * 60 * 1000; // 24 hours
5
+ // Default secret removed for security - must be provided by user
6
+
7
+ class MemoryStore extends EventEmitter {
8
+ constructor() {
9
+ super();
10
+ this.sessions = new Map();
11
+ this.timers = new Map();
12
+ }
13
+
14
+ async get(sessionId) {
15
+ const session = this.sessions.get(sessionId);
16
+ return session ? JSON.parse(session) : null;
17
+ }
18
+
19
+ async set(sessionId, session, maxAge) {
20
+ this.sessions.set(sessionId, JSON.stringify(session));
21
+
22
+ if (this.timers.has(sessionId)) {
23
+ clearTimeout(this.timers.get(sessionId));
24
+ }
25
+
26
+ const timer = setTimeout(() => {
27
+ this.destroy(sessionId);
28
+ }, maxAge);
29
+
30
+ this.timers.set(sessionId, timer);
31
+ }
32
+
33
+ async destroy(sessionId) {
34
+ this.sessions.delete(sessionId);
35
+
36
+ if (this.timers.has(sessionId)) {
37
+ clearTimeout(this.timers.get(sessionId));
38
+ this.timers.delete(sessionId);
39
+ }
40
+
41
+ this.emit('destroy', sessionId);
42
+ }
43
+
44
+ async touch(sessionId, session, maxAge) {
45
+ await this.set(sessionId, session, maxAge);
46
+ }
47
+
48
+ async all() {
49
+ const sessions = {};
50
+ for (const [sessionId, sessionData] of this.sessions) {
51
+ sessions[sessionId] = JSON.parse(sessionData);
52
+ }
53
+ return sessions;
54
+ }
55
+
56
+ async length() {
57
+ return this.sessions.size;
58
+ }
59
+
60
+ async clear() {
61
+ for (const timer of this.timers.values()) {
62
+ clearTimeout(timer);
63
+ }
64
+ this.sessions.clear();
65
+ this.timers.clear();
66
+ }
67
+ }
68
+
69
+ function session(options = {}) {
70
+ const opts = {
71
+ key: options.key || 'connect.sid',
72
+ secret: options.secret || throwMissingSecretError(),
73
+ store: options.store || new MemoryStore(),
74
+ cookie: {
75
+ path: '/',
76
+ httpOnly: true,
77
+ secure: false,
78
+ maxAge: DEFAULT_MAX_AGE,
79
+ sameSite: 'lax',
80
+ ...options.cookie
81
+ },
82
+ genid: options.genid || generateSessionId,
83
+ rolling: options.rolling || false,
84
+ resave: options.resave || false,
85
+ saveUninitialized: options.saveUninitialized || false,
86
+ ...options
87
+ };
88
+
89
+ return async (ctx, next) => {
90
+ const sessionId = getSessionId(ctx, opts);
91
+ let session = null;
92
+ let isNew = false;
93
+
94
+ if (sessionId) {
95
+ session = await opts.store.get(sessionId);
96
+ }
97
+
98
+ if (!session) {
99
+ session = {};
100
+ isNew = true;
101
+ }
102
+
103
+ ctx.session = createSessionProxy(session, {
104
+ sessionId: sessionId || opts.genid(),
105
+ isNew,
106
+ store: opts.store,
107
+ cookie: opts.cookie,
108
+ key: opts.key,
109
+ secret: opts.secret,
110
+ rolling: opts.rolling,
111
+ resave: opts.resave,
112
+ saveUninitialized: opts.saveUninitialized,
113
+ ctx: ctx
114
+ });
115
+
116
+ // Store original response methods
117
+ const originalSend = ctx.send;
118
+ const originalJson = ctx.json;
119
+
120
+ // Track if session needs to be saved
121
+ ctx._sessionSaveNeeded = false;
122
+ ctx._sessionSaved = false;
123
+
124
+ // Override send methods to save session before response
125
+ ctx.send = function(data) {
126
+ if (!ctx.responded && !ctx._sessionSaved) {
127
+ saveSessionSync(ctx, opts);
128
+ ctx._sessionSaved = true;
129
+ }
130
+ return originalSend.call(ctx, data);
131
+ };
132
+
133
+ ctx.json = function(data) {
134
+ if (!ctx.responded && !ctx._sessionSaved) {
135
+ saveSessionSync(ctx, opts);
136
+ ctx._sessionSaved = true;
137
+ }
138
+ return originalJson.call(ctx, data);
139
+ };
140
+
141
+ await next();
142
+ };
143
+ }
144
+
145
+ function getSessionId(ctx, opts) {
146
+ const cookieValue = ctx.cookies[opts.key];
147
+
148
+ if (!cookieValue) {
149
+ return null;
150
+ }
151
+
152
+ try {
153
+ return unsignCookie(cookieValue, opts.secret);
154
+ } catch (error) {
155
+ return null;
156
+ }
157
+ }
158
+
159
+ function createSessionProxy(session, options) {
160
+ const proxy = new Proxy(session, {
161
+ set(target, property, value) {
162
+ if (property === 'cookie') {
163
+ return true;
164
+ }
165
+
166
+ target[property] = value;
167
+ options.modified = true;
168
+
169
+ // Auto-save session when modified
170
+ if (options.ctx && !options.ctx.responded) {
171
+ const sessionData = {};
172
+ for (const key in session) {
173
+ if (session.hasOwnProperty(key)) {
174
+ sessionData[key] = session[key];
175
+ }
176
+ }
177
+ options.store.set(options.sessionId, sessionData, options.cookie.maxAge);
178
+ const signedId = signCookie(options.sessionId, options.secret);
179
+ options.ctx.setCookie(options.key, signedId, options.cookie);
180
+ }
181
+
182
+ return true;
183
+ },
184
+
185
+ deleteProperty(target, property) {
186
+ delete target[property];
187
+ options.modified = true;
188
+ return true;
189
+ }
190
+ });
191
+
192
+ Object.defineProperty(proxy, 'id', {
193
+ get() { return options.sessionId; },
194
+ enumerable: false
195
+ });
196
+
197
+ Object.defineProperty(proxy, 'isNew', {
198
+ get() { return options.isNew; },
199
+ enumerable: false
200
+ });
201
+
202
+ Object.defineProperty(proxy, 'cookie', {
203
+ get() { return options.cookie; },
204
+ set(value) { options.cookie = { ...options.cookie, ...value }; },
205
+ enumerable: false
206
+ });
207
+
208
+ Object.defineProperty(proxy, 'destroy', {
209
+ value: async function() {
210
+ await options.store.destroy(options.sessionId);
211
+ options.destroyed = true;
212
+ },
213
+ enumerable: false
214
+ });
215
+
216
+ Object.defineProperty(proxy, 'regenerate', {
217
+ value: async function() {
218
+ await options.store.destroy(options.sessionId);
219
+ options.sessionId = options.genid();
220
+ options.isNew = true;
221
+ options.modified = true;
222
+
223
+ for (const key in session) {
224
+ delete session[key];
225
+ }
226
+ },
227
+ enumerable: false
228
+ });
229
+
230
+ Object.defineProperty(proxy, 'reload', {
231
+ value: async function() {
232
+ const data = await options.store.get(options.sessionId);
233
+ if (data) {
234
+ Object.assign(session, data);
235
+ }
236
+ },
237
+ enumerable: false
238
+ });
239
+
240
+ Object.defineProperty(proxy, 'save', {
241
+ value: async function() {
242
+ await options.store.set(options.sessionId, session, options.cookie.maxAge);
243
+ },
244
+ enumerable: false
245
+ });
246
+
247
+ Object.defineProperty(proxy, 'touch', {
248
+ value: async function() {
249
+ await options.store.touch(options.sessionId, session, options.cookie.maxAge);
250
+ },
251
+ enumerable: false
252
+ });
253
+
254
+ return proxy;
255
+ }
256
+
257
+ async function saveSession(ctx, opts) {
258
+ const session = ctx.session;
259
+
260
+ if (!session) {
261
+ return;
262
+ }
263
+
264
+ if (ctx.responded) {
265
+ return;
266
+ }
267
+
268
+ if (session.destroyed) {
269
+ ctx.clearCookie(opts.key);
270
+ return;
271
+ }
272
+
273
+ const shouldSave = session.modified ||
274
+ (opts.resave && !session.isNew) ||
275
+ (opts.saveUninitialized && session.isNew);
276
+
277
+ if (shouldSave) {
278
+ const sessionData = {};
279
+ for (const key in session) {
280
+ if (session.hasOwnProperty(key)) {
281
+ sessionData[key] = session[key];
282
+ }
283
+ }
284
+
285
+ await opts.store.set(session.id, sessionData, opts.cookie.maxAge);
286
+
287
+ const signedId = signCookie(session.id, opts.secret);
288
+ ctx.setCookie(opts.key, signedId, opts.cookie);
289
+ } else if (opts.rolling) {
290
+ await opts.store.touch(session.id, session, opts.cookie.maxAge);
291
+
292
+ const signedId = signCookie(session.id, opts.secret);
293
+ ctx.setCookie(opts.key, signedId, opts.cookie);
294
+ }
295
+ }
296
+
297
+ function saveSessionSync(ctx, opts) {
298
+ const session = ctx.session;
299
+
300
+ if (!session) {
301
+ return;
302
+ }
303
+
304
+ if (ctx.responded) {
305
+ return;
306
+ }
307
+
308
+ if (session.destroyed) {
309
+ ctx.clearCookie(opts.key);
310
+ return;
311
+ }
312
+
313
+ const shouldSave = session.modified ||
314
+ (opts.resave && !session.isNew) ||
315
+ (opts.saveUninitialized && session.isNew);
316
+
317
+ if (shouldSave) {
318
+ const sessionData = {};
319
+ for (const key in session) {
320
+ if (session.hasOwnProperty(key)) {
321
+ sessionData[key] = session[key];
322
+ }
323
+ }
324
+
325
+ // Save session asynchronously but don't wait
326
+ opts.store.set(session.id, sessionData, opts.cookie.maxAge);
327
+
328
+ const signedId = signCookie(session.id, opts.secret);
329
+ ctx.setCookie(opts.key, signedId, opts.cookie);
330
+ } else if (opts.rolling) {
331
+ opts.store.touch(session.id, session, opts.cookie.maxAge);
332
+
333
+ const signedId = signCookie(session.id, opts.secret);
334
+ ctx.setCookie(opts.key, signedId, opts.cookie);
335
+ }
336
+ }
337
+
338
+ function generateSessionId() {
339
+ return crypto.randomBytes(32).toString('hex');
340
+ }
341
+
342
+ function signCookie(value, secret) {
343
+ const signature = crypto
344
+ .createHmac('sha256', secret)
345
+ .update(value)
346
+ .digest('base64')
347
+ .replace(/\+/g, '-')
348
+ .replace(/\//g, '_')
349
+ .replace(/=/g, '');
350
+
351
+ return `${value}.${signature}`;
352
+ }
353
+
354
+ function unsignCookie(signedValue, secret) {
355
+ const parts = signedValue.split('.');
356
+ if (parts.length !== 2) {
357
+ throw new Error('Invalid signed cookie');
358
+ }
359
+
360
+ const [value, signature] = parts;
361
+ const expected = crypto
362
+ .createHmac('sha256', secret)
363
+ .update(value)
364
+ .digest('base64')
365
+ .replace(/\+/g, '-')
366
+ .replace(/\//g, '_')
367
+ .replace(/=/g, '');
368
+
369
+ if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
370
+ throw new Error('Cookie signature verification failed');
371
+ }
372
+
373
+ return value;
374
+ }
375
+
376
+ class FileStore extends EventEmitter {
377
+ constructor(options = {}) {
378
+ super();
379
+ this.sessionPath = options.path || './sessions';
380
+ this.ttl = options.ttl || DEFAULT_MAX_AGE;
381
+ this.fs = require('fs');
382
+ this.pathModule = require('path');
383
+
384
+ this.ensureDirectory();
385
+ }
386
+
387
+ ensureDirectory() {
388
+ if (!this.fs.existsSync(this.sessionPath)) {
389
+ this.fs.mkdirSync(this.sessionPath, { recursive: true });
390
+ }
391
+ }
392
+
393
+ getFilePath(sessionId) {
394
+ // Sanitize sessionId to prevent path traversal
395
+ if (!sessionId || typeof sessionId !== 'string') {
396
+ throw new Error('Invalid session ID');
397
+ }
398
+
399
+ // Remove any path separators and special characters
400
+ const sanitizedId = sessionId.replace(/[\/\\:*?"<>|]/g, '');
401
+
402
+ if (!sanitizedId || sanitizedId !== sessionId) {
403
+ throw new Error('Invalid session ID format');
404
+ }
405
+
406
+ return this.pathModule.join(this.sessionPath, `${sanitizedId}.json`);
407
+ }
408
+
409
+ async get(sessionId) {
410
+ const filePath = this.getFilePath(sessionId);
411
+
412
+ try {
413
+ const data = await new Promise((resolve, reject) => {
414
+ this.fs.readFile(filePath, 'utf8', (err, data) => {
415
+ if (err) reject(err);
416
+ else resolve(data);
417
+ });
418
+ });
419
+ const session = JSON.parse(data);
420
+
421
+ if (session.expires && Date.now() > session.expires) {
422
+ await this.destroy(sessionId);
423
+ return null;
424
+ }
425
+
426
+ return session.data;
427
+ } catch (error) {
428
+ return null;
429
+ }
430
+ }
431
+
432
+ async set(sessionId, session, maxAge) {
433
+ const filePath = this.getFilePath(sessionId);
434
+ const data = {
435
+ data: session,
436
+ expires: Date.now() + maxAge
437
+ };
438
+
439
+ await new Promise((resolve, reject) => {
440
+ this.fs.writeFile(filePath, JSON.stringify(data), 'utf8', (err) => {
441
+ if (err) reject(err);
442
+ else resolve();
443
+ });
444
+ });
445
+ }
446
+
447
+ async destroy(sessionId) {
448
+ const filePath = this.getFilePath(sessionId);
449
+
450
+ try {
451
+ await new Promise((resolve, reject) => {
452
+ this.fs.unlink(filePath, (err) => {
453
+ if (err && err.code !== 'ENOENT') reject(err);
454
+ else resolve();
455
+ });
456
+ });
457
+ this.emit('destroy', sessionId);
458
+ } catch (error) {
459
+ // File doesn't exist, ignore
460
+ }
461
+ }
462
+
463
+ async touch(sessionId, session, maxAge) {
464
+ await this.set(sessionId, session, maxAge);
465
+ }
466
+
467
+ async all() {
468
+ const sessions = {};
469
+ const files = await new Promise((resolve, reject) => {
470
+ this.fs.readdir(this.sessionPath, (err, files) => {
471
+ if (err) reject(err);
472
+ else resolve(files);
473
+ });
474
+ });
475
+
476
+ for (const file of files) {
477
+ if (file.endsWith('.json')) {
478
+ const sessionId = file.replace('.json', '');
479
+ const session = await this.get(sessionId);
480
+ if (session) {
481
+ sessions[sessionId] = session;
482
+ }
483
+ }
484
+ }
485
+
486
+ return sessions;
487
+ }
488
+
489
+ async length() {
490
+ const files = await new Promise((resolve, reject) => {
491
+ this.fs.readdir(this.sessionPath, (err, files) => {
492
+ if (err) reject(err);
493
+ else resolve(files);
494
+ });
495
+ });
496
+ return files.filter(file => file.endsWith('.json')).length;
497
+ }
498
+
499
+ async clear() {
500
+ const files = await new Promise((resolve, reject) => {
501
+ this.fs.readdir(this.sessionPath, (err, files) => {
502
+ if (err) reject(err);
503
+ else resolve(files);
504
+ });
505
+ });
506
+
507
+ for (const file of files) {
508
+ if (file.endsWith('.json')) {
509
+ await new Promise((resolve, reject) => {
510
+ this.fs.unlink(this.pathModule.join(this.sessionPath, file), (err) => {
511
+ if (err && err.code !== 'ENOENT') reject(err);
512
+ else resolve();
513
+ });
514
+ });
515
+ }
516
+ }
517
+ }
518
+ }
519
+
520
+ function throwMissingSecretError() {
521
+ throw new Error(
522
+ 'Session secret is required for security. ' +
523
+ 'Please provide a secret in the session options: ' +
524
+ 'session({ secret: "your-secret-here" })'
525
+ );
526
+ }
527
+
528
+ module.exports = session;
529
+ module.exports.MemoryStore = MemoryStore;
530
+ module.exports.FileStore = FileStore;