@oxog/spark 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +632 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1068 -956
  6. package/src/core/context.js +1098 -830
  7. package/src/core/middleware.js +303 -217
  8. package/src/index.js +183 -280
  9. package/src/middleware/body-parser.js +482 -526
  10. package/src/middleware/cache.js +177 -170
  11. package/src/middleware/compression.js +177 -182
  12. package/src/middleware/cors.js +176 -95
  13. package/src/middleware/health.js +219 -218
  14. package/src/middleware/logger.js +195 -194
  15. package/src/middleware/metrics.js +339 -327
  16. package/src/middleware/rate-limit.js +367 -319
  17. package/src/middleware/security.js +442 -332
  18. package/src/middleware/session.js +647 -529
  19. package/src/middleware/static.js +404 -299
  20. package/src/router/layer.js +197 -117
  21. package/src/router/route.js +149 -123
  22. package/src/router/router.js +703 -755
  23. package/src/utils/async-handler.js +145 -147
  24. package/src/utils/context-pool.js +83 -82
  25. package/src/utils/regex-validator.js +187 -163
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +536 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -959
  31. package/dist/core/context.js +0 -833
  32. package/dist/core/middleware.js +0 -220
  33. package/dist/core/request.js +0 -335
  34. package/dist/core/response.js +0 -377
  35. package/dist/index.js +0 -280
  36. package/dist/middleware/body-parser.js +0 -528
  37. package/dist/middleware/cache.js +0 -173
  38. package/dist/middleware/compression.js +0 -185
  39. package/dist/middleware/cors.js +0 -97
  40. package/dist/middleware/health.js +0 -221
  41. package/dist/middleware/index.js +0 -23
  42. package/dist/middleware/logger.js +0 -197
  43. package/dist/middleware/metrics.js +0 -330
  44. package/dist/middleware/rate-limit.js +0 -322
  45. package/dist/middleware/security.js +0 -335
  46. package/dist/middleware/session.js +0 -532
  47. package/dist/middleware/static.js +0 -301
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -119
  50. package/dist/router/route.js +0 -125
  51. package/dist/router/router.js +0 -758
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -150
  54. package/dist/utils/cache.js +0 -443
  55. package/dist/utils/context-pool.js +0 -85
  56. package/dist/utils/error-types.js +0 -134
  57. package/dist/utils/http.js +0 -415
  58. package/dist/utils/regex-validator.js +0 -166
  59. package/src/core/request.js +0 -335
  60. package/src/core/response.js +0 -377
  61. package/src/middleware/index.js +0 -23
  62. package/src/utils/cache.js +0 -443
  63. package/src/utils/error-types.js +0 -134
  64. package/src/utils/http.js +0 -415
@@ -1,532 +1,650 @@
1
1
  'use strict';
2
2
 
3
- const crypto = require('crypto');
4
- const { EventEmitter } = require('events');
5
-
6
- const DEFAULT_MAX_AGE = 24 * 60 * 60 * 1000; // 24 hours
7
- // Default secret removed for security - must be provided by user
8
-
9
- class MemoryStore extends EventEmitter {
10
- constructor() {
11
- super();
12
- this.sessions = new Map();
13
- this.timers = new Map();
14
- }
15
-
16
- async get(sessionId) {
17
- const session = this.sessions.get(sessionId);
18
- return session ? JSON.parse(session) : null;
19
- }
20
-
21
- async set(sessionId, session, maxAge) {
22
- this.sessions.set(sessionId, JSON.stringify(session));
23
-
24
- if (this.timers.has(sessionId)) {
25
- clearTimeout(this.timers.get(sessionId));
26
- }
27
-
28
- const timer = setTimeout(() => {
29
- this.destroy(sessionId);
30
- }, maxAge);
31
-
32
- this.timers.set(sessionId, timer);
33
- }
34
-
35
- async destroy(sessionId) {
36
- this.sessions.delete(sessionId);
37
-
38
- if (this.timers.has(sessionId)) {
39
- clearTimeout(this.timers.get(sessionId));
40
- this.timers.delete(sessionId);
41
- }
42
-
43
- this.emit('destroy', sessionId);
44
- }
45
-
46
- async touch(sessionId, session, maxAge) {
47
- await this.set(sessionId, session, maxAge);
48
- }
49
-
50
- async all() {
51
- const sessions = {};
52
- for (const [sessionId, sessionData] of this.sessions) {
53
- sessions[sessionId] = JSON.parse(sessionData);
54
- }
55
- return sessions;
56
- }
57
-
58
- async length() {
59
- return this.sessions.size;
60
- }
61
-
62
- async clear() {
63
- for (const timer of this.timers.values()) {
64
- clearTimeout(timer);
65
- }
66
- this.sessions.clear();
67
- this.timers.clear();
68
- }
69
- }
70
-
71
- function session(options = {}) {
72
- const opts = {
73
- key: options.key || 'connect.sid',
74
- secret: options.secret || throwMissingSecretError(),
75
- store: options.store || new MemoryStore(),
76
- cookie: {
77
- path: '/',
78
- httpOnly: true,
79
- secure: false,
80
- maxAge: DEFAULT_MAX_AGE,
81
- sameSite: 'lax',
82
- ...options.cookie
83
- },
84
- genid: options.genid || generateSessionId,
85
- rolling: options.rolling || false,
86
- resave: options.resave || false,
87
- saveUninitialized: options.saveUninitialized || false,
88
- ...options
89
- };
90
-
91
- return async (ctx, next) => {
92
- const sessionId = getSessionId(ctx, opts);
93
- let session = null;
94
- let isNew = false;
95
-
96
- if (sessionId) {
97
- session = await opts.store.get(sessionId);
98
- }
99
-
100
- if (!session) {
101
- session = {};
102
- isNew = true;
103
- }
104
-
105
- ctx.session = createSessionProxy(session, {
106
- sessionId: sessionId || opts.genid(),
107
- isNew,
108
- store: opts.store,
109
- cookie: opts.cookie,
110
- key: opts.key,
111
- secret: opts.secret,
112
- rolling: opts.rolling,
113
- resave: opts.resave,
114
- saveUninitialized: opts.saveUninitialized,
115
- ctx: ctx
116
- });
117
-
118
- // Store original response methods
119
- const originalSend = ctx.send;
120
- const originalJson = ctx.json;
121
-
122
- // Track if session needs to be saved
123
- ctx._sessionSaveNeeded = false;
124
- ctx._sessionSaved = false;
125
-
126
- // Override send methods to save session before response
127
- ctx.send = function(data) {
128
- if (!ctx.responded && !ctx._sessionSaved) {
129
- saveSessionSync(ctx, opts);
130
- ctx._sessionSaved = true;
131
- }
132
- return originalSend.call(ctx, data);
133
- };
134
-
135
- ctx.json = function(data) {
136
- if (!ctx.responded && !ctx._sessionSaved) {
137
- saveSessionSync(ctx, opts);
138
- ctx._sessionSaved = true;
139
- }
140
- return originalJson.call(ctx, data);
141
- };
142
-
143
- await next();
144
- };
145
- }
146
-
147
- function getSessionId(ctx, opts) {
148
- const cookieValue = ctx.cookies[opts.key];
149
-
150
- if (!cookieValue) {
151
- return null;
152
- }
153
-
154
- try {
155
- return unsignCookie(cookieValue, opts.secret);
156
- } catch (error) {
157
- return null;
158
- }
159
- }
160
-
161
- function createSessionProxy(session, options) {
162
- const proxy = new Proxy(session, {
163
- set(target, property, value) {
164
- if (property === 'cookie') {
165
- return true;
166
- }
167
-
168
- target[property] = value;
169
- options.modified = true;
170
-
171
- // Auto-save session when modified
172
- if (options.ctx && !options.ctx.responded) {
173
- const sessionData = {};
174
- for (const key in session) {
175
- if (session.hasOwnProperty(key)) {
176
- sessionData[key] = session[key];
177
- }
178
- }
179
- options.store.set(options.sessionId, sessionData, options.cookie.maxAge);
180
- const signedId = signCookie(options.sessionId, options.secret);
181
- options.ctx.setCookie(options.key, signedId, options.cookie);
182
- }
183
-
184
- return true;
185
- },
186
-
187
- deleteProperty(target, property) {
188
- delete target[property];
189
- options.modified = true;
190
- return true;
191
- }
192
- });
193
-
194
- Object.defineProperty(proxy, 'id', {
195
- get() { return options.sessionId; },
196
- enumerable: false
197
- });
198
-
199
- Object.defineProperty(proxy, 'isNew', {
200
- get() { return options.isNew; },
201
- enumerable: false
202
- });
203
-
204
- Object.defineProperty(proxy, 'cookie', {
205
- get() { return options.cookie; },
206
- set(value) { options.cookie = { ...options.cookie, ...value }; },
207
- enumerable: false
208
- });
209
-
210
- Object.defineProperty(proxy, 'destroy', {
211
- value: async function() {
212
- await options.store.destroy(options.sessionId);
213
- options.destroyed = true;
214
- },
215
- enumerable: false
216
- });
217
-
218
- Object.defineProperty(proxy, 'regenerate', {
219
- value: async function() {
220
- await options.store.destroy(options.sessionId);
221
- options.sessionId = options.genid();
222
- options.isNew = true;
223
- options.modified = true;
224
-
225
- for (const key in session) {
226
- delete session[key];
227
- }
228
- },
229
- enumerable: false
230
- });
231
-
232
- Object.defineProperty(proxy, 'reload', {
233
- value: async function() {
234
- const data = await options.store.get(options.sessionId);
235
- if (data) {
236
- Object.assign(session, data);
237
- }
238
- },
239
- enumerable: false
240
- });
241
-
242
- Object.defineProperty(proxy, 'save', {
243
- value: async function() {
244
- await options.store.set(options.sessionId, session, options.cookie.maxAge);
245
- },
246
- enumerable: false
247
- });
248
-
249
- Object.defineProperty(proxy, 'touch', {
250
- value: async function() {
251
- await options.store.touch(options.sessionId, session, options.cookie.maxAge);
252
- },
253
- enumerable: false
254
- });
255
-
256
- return proxy;
257
- }
258
-
259
- async function saveSession(ctx, opts) {
260
- const session = ctx.session;
261
-
262
- if (!session) {
263
- return;
264
- }
265
-
266
- if (ctx.responded) {
267
- return;
268
- }
269
-
270
- if (session.destroyed) {
271
- ctx.clearCookie(opts.key);
272
- return;
273
- }
274
-
275
- const shouldSave = session.modified ||
276
- (opts.resave && !session.isNew) ||
277
- (opts.saveUninitialized && session.isNew);
278
-
279
- if (shouldSave) {
280
- const sessionData = {};
281
- for (const key in session) {
282
- if (session.hasOwnProperty(key)) {
283
- sessionData[key] = session[key];
284
- }
285
- }
286
-
287
- await opts.store.set(session.id, sessionData, opts.cookie.maxAge);
288
-
289
- const signedId = signCookie(session.id, opts.secret);
290
- ctx.setCookie(opts.key, signedId, opts.cookie);
291
- } else if (opts.rolling) {
292
- await opts.store.touch(session.id, session, opts.cookie.maxAge);
293
-
294
- const signedId = signCookie(session.id, opts.secret);
295
- ctx.setCookie(opts.key, signedId, opts.cookie);
296
- }
297
- }
298
-
299
- function saveSessionSync(ctx, opts) {
300
- const session = ctx.session;
301
-
302
- if (!session) {
303
- return;
304
- }
305
-
306
- if (ctx.responded) {
307
- return;
308
- }
309
-
310
- if (session.destroyed) {
311
- ctx.clearCookie(opts.key);
312
- return;
313
- }
314
-
315
- const shouldSave = session.modified ||
316
- (opts.resave && !session.isNew) ||
317
- (opts.saveUninitialized && session.isNew);
318
-
319
- if (shouldSave) {
320
- const sessionData = {};
321
- for (const key in session) {
322
- if (session.hasOwnProperty(key)) {
323
- sessionData[key] = session[key];
324
- }
325
- }
326
-
327
- // Save session asynchronously but don't wait
328
- opts.store.set(session.id, sessionData, opts.cookie.maxAge);
329
-
330
- const signedId = signCookie(session.id, opts.secret);
331
- ctx.setCookie(opts.key, signedId, opts.cookie);
332
- } else if (opts.rolling) {
333
- opts.store.touch(session.id, session, opts.cookie.maxAge);
334
-
335
- const signedId = signCookie(session.id, opts.secret);
336
- ctx.setCookie(opts.key, signedId, opts.cookie);
337
- }
338
- }
339
-
340
- function generateSessionId() {
341
- return crypto.randomBytes(32).toString('hex');
342
- }
343
-
344
- function signCookie(value, secret) {
345
- const signature = crypto
346
- .createHmac('sha256', secret)
347
- .update(value)
348
- .digest('base64')
349
- .replace(/\+/g, '-')
350
- .replace(/\//g, '_')
351
- .replace(/=/g, '');
352
-
353
- return `${value}.${signature}`;
354
- }
355
-
356
- function unsignCookie(signedValue, secret) {
357
- const parts = signedValue.split('.');
358
- if (parts.length !== 2) {
359
- throw new Error('Invalid signed cookie');
360
- }
361
-
362
- const [value, signature] = parts;
363
- const expected = crypto
364
- .createHmac('sha256', secret)
365
- .update(value)
366
- .digest('base64')
367
- .replace(/\+/g, '-')
368
- .replace(/\//g, '_')
369
- .replace(/=/g, '');
370
-
371
- if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
372
- throw new Error('Cookie signature verification failed');
373
- }
374
-
375
- return value;
376
- }
377
-
378
- class FileStore extends EventEmitter {
379
- constructor(options = {}) {
380
- super();
381
- this.sessionPath = options.path || './sessions';
382
- this.ttl = options.ttl || DEFAULT_MAX_AGE;
383
- this.fs = require('fs');
384
- this.pathModule = require('path');
385
-
386
- this.ensureDirectory();
387
- }
388
-
389
- ensureDirectory() {
390
- if (!this.fs.existsSync(this.sessionPath)) {
391
- this.fs.mkdirSync(this.sessionPath, { recursive: true });
392
- }
393
- }
394
-
395
- getFilePath(sessionId) {
396
- // Sanitize sessionId to prevent path traversal
397
- if (!sessionId || typeof sessionId !== 'string') {
398
- throw new Error('Invalid session ID');
399
- }
400
-
401
- // Remove any path separators and special characters
402
- const sanitizedId = sessionId.replace(/[\/\\:*?"<>|]/g, '');
403
-
404
- if (!sanitizedId || sanitizedId !== sessionId) {
405
- throw new Error('Invalid session ID format');
406
- }
407
-
408
- return this.pathModule.join(this.sessionPath, `${sanitizedId}.json`);
409
- }
410
-
411
- async get(sessionId) {
412
- const filePath = this.getFilePath(sessionId);
413
-
414
- try {
415
- const data = await new Promise((resolve, reject) => {
416
- this.fs.readFile(filePath, 'utf8', (err, data) => {
417
- if (err) reject(err);
418
- else resolve(data);
419
- });
420
- });
421
- const session = JSON.parse(data);
422
-
423
- if (session.expires && Date.now() > session.expires) {
424
- await this.destroy(sessionId);
425
- return null;
426
- }
427
-
428
- return session.data;
429
- } catch (error) {
430
- return null;
431
- }
432
- }
433
-
434
- async set(sessionId, session, maxAge) {
435
- const filePath = this.getFilePath(sessionId);
436
- const data = {
437
- data: session,
438
- expires: Date.now() + maxAge
439
- };
440
-
441
- await new Promise((resolve, reject) => {
442
- this.fs.writeFile(filePath, JSON.stringify(data), 'utf8', (err) => {
443
- if (err) reject(err);
444
- else resolve();
445
- });
446
- });
447
- }
448
-
449
- async destroy(sessionId) {
450
- const filePath = this.getFilePath(sessionId);
451
-
452
- try {
453
- await new Promise((resolve, reject) => {
454
- this.fs.unlink(filePath, (err) => {
455
- if (err && err.code !== 'ENOENT') reject(err);
456
- else resolve();
457
- });
458
- });
459
- this.emit('destroy', sessionId);
460
- } catch (error) {
461
- // File doesn't exist, ignore
462
- }
463
- }
464
-
465
- async touch(sessionId, session, maxAge) {
466
- await this.set(sessionId, session, maxAge);
467
- }
468
-
469
- async all() {
470
- const sessions = {};
471
- const files = await new Promise((resolve, reject) => {
472
- this.fs.readdir(this.sessionPath, (err, files) => {
473
- if (err) reject(err);
474
- else resolve(files);
475
- });
476
- });
477
-
478
- for (const file of files) {
479
- if (file.endsWith('.json')) {
480
- const sessionId = file.replace('.json', '');
481
- const session = await this.get(sessionId);
482
- if (session) {
483
- sessions[sessionId] = session;
484
- }
485
- }
486
- }
487
-
488
- return sessions;
489
- }
490
-
491
- async length() {
492
- const files = await new Promise((resolve, reject) => {
493
- this.fs.readdir(this.sessionPath, (err, files) => {
494
- if (err) reject(err);
495
- else resolve(files);
496
- });
497
- });
498
- return files.filter(file => file.endsWith('.json')).length;
499
- }
500
-
501
- async clear() {
502
- const files = await new Promise((resolve, reject) => {
503
- this.fs.readdir(this.sessionPath, (err, files) => {
504
- if (err) reject(err);
505
- else resolve(files);
506
- });
507
- });
508
-
509
- for (const file of files) {
510
- if (file.endsWith('.json')) {
511
- await new Promise((resolve, reject) => {
512
- this.fs.unlink(this.pathModule.join(this.sessionPath, file), (err) => {
513
- if (err && err.code !== 'ENOENT') reject(err);
514
- else resolve();
515
- });
516
- });
517
- }
518
- }
519
- }
520
- }
521
-
522
- function throwMissingSecretError() {
523
- throw new Error(
524
- 'Session secret is required for security. ' +
525
- 'Please provide a secret in the session options: ' +
526
- 'session({ secret: "your-secret-here" })'
527
- );
528
- }
529
-
530
- module.exports = session;
531
- module.exports.MemoryStore = MemoryStore;
3
+ const crypto = require('crypto');
4
+ const { EventEmitter } = require('events');
5
+
6
+ const DEFAULT_MAX_AGE = 24 * 60 * 60 * 1000; // 24 hours
7
+
8
+ /** @constant {number} Largest delay setTimeout accepts (~24.8 days) */
9
+ const MAX_TIMER_DELAY = 2147483647;
10
+ // Default secret removed for security - must be provided by user
11
+
12
+ class MemoryStore extends EventEmitter {
13
+ constructor() {
14
+ super();
15
+ this.sessions = new Map();
16
+ this.timers = new Map();
17
+ }
18
+
19
+ async get(sessionId) {
20
+ const entry = this.sessions.get(sessionId);
21
+ if (!entry) {
22
+ return null;
23
+ }
24
+ if (entry.expires <= Date.now()) {
25
+ await this.destroy(sessionId);
26
+ return null;
27
+ }
28
+ return JSON.parse(entry.data);
29
+ }
30
+
31
+ async set(sessionId, session, maxAge) {
32
+ const ttl = Number.isFinite(maxAge) && maxAge > 0 ? maxAge : DEFAULT_MAX_AGE;
33
+ this.sessions.set(sessionId, { data: JSON.stringify(session), expires: Date.now() + ttl });
34
+ this.scheduleExpiry(sessionId, ttl);
35
+ }
36
+
37
+ /**
38
+ * Schedule removal of an expired session. Timers are unref'd so they never
39
+ * keep the process alive, and are capped at the largest delay setTimeout
40
+ * supports (longer sessions are re-checked when the timer fires).
41
+ *
42
+ * @param {string} sessionId - Session ID
43
+ * @param {number} ttl - Time to live in milliseconds
44
+ * @private
45
+ */
46
+ scheduleExpiry(sessionId, ttl) {
47
+ if (this.timers.has(sessionId)) {
48
+ clearTimeout(this.timers.get(sessionId));
49
+ }
50
+ const timer = setTimeout(() => {
51
+ this.timers.delete(sessionId);
52
+ const entry = this.sessions.get(sessionId);
53
+ if (!entry) {
54
+ return;
55
+ }
56
+ const remaining = entry.expires - Date.now();
57
+ if (remaining > 0) {
58
+ this.scheduleExpiry(sessionId, remaining);
59
+ } else {
60
+ this.destroy(sessionId);
61
+ }
62
+ }, Math.min(ttl, MAX_TIMER_DELAY));
63
+ if (timer.unref) {
64
+ timer.unref();
65
+ }
66
+ this.timers.set(sessionId, timer);
67
+ }
68
+
69
+ async destroy(sessionId) {
70
+ this.sessions.delete(sessionId);
71
+
72
+ if (this.timers.has(sessionId)) {
73
+ clearTimeout(this.timers.get(sessionId));
74
+ this.timers.delete(sessionId);
75
+ }
76
+
77
+ this.emit('destroy', sessionId);
78
+ }
79
+
80
+ async touch(sessionId, session, maxAge) {
81
+ await this.set(sessionId, session, maxAge);
82
+ }
83
+
84
+ async all() {
85
+ const sessions = {};
86
+ const now = Date.now();
87
+ for (const [sessionId, entry] of this.sessions) {
88
+ if (entry.expires > now) {
89
+ sessions[sessionId] = JSON.parse(entry.data);
90
+ }
91
+ }
92
+ return sessions;
93
+ }
94
+
95
+ async length() {
96
+ return this.sessions.size;
97
+ }
98
+
99
+ async clear() {
100
+ for (const timer of this.timers.values()) {
101
+ clearTimeout(timer);
102
+ }
103
+ this.sessions.clear();
104
+ this.timers.clear();
105
+ }
106
+ }
107
+
108
+ function session(options = {}) {
109
+ const opts = {
110
+ ...options,
111
+ key: options.key || 'connect.sid',
112
+ secret: options.secret || throwMissingSecretError(),
113
+ store: options.store || new MemoryStore(),
114
+ cookie: {
115
+ path: '/',
116
+ httpOnly: true,
117
+ secure: false,
118
+ maxAge: DEFAULT_MAX_AGE,
119
+ sameSite: 'lax',
120
+ ...options.cookie
121
+ },
122
+ genid: options.genid || generateSessionId,
123
+ rolling: options.rolling || false,
124
+ resave: options.resave || false,
125
+ saveUninitialized: options.saveUninitialized || false
126
+ };
127
+
128
+ return async (ctx, next) => {
129
+ const sessionId = getSessionId(ctx, opts);
130
+ let session = null;
131
+ let isNew = false;
132
+ let finalSessionId = null;
133
+
134
+ if (sessionId) {
135
+ session = await opts.store.get(sessionId);
136
+ }
137
+
138
+ if (!session) {
139
+ session = {};
140
+ isNew = true;
141
+ // SECURITY: Always generate new session ID for new sessions (prevents session fixation)
142
+ finalSessionId = opts.genid();
143
+ } else {
144
+ // Session exists, use the sessionId from cookie
145
+ finalSessionId = sessionId;
146
+ }
147
+
148
+ ctx.session = createSessionProxy(session, {
149
+ sessionId: finalSessionId,
150
+ isNew,
151
+ store: opts.store,
152
+ cookie: opts.cookie,
153
+ key: opts.key,
154
+ secret: opts.secret,
155
+ rolling: opts.rolling,
156
+ resave: opts.resave,
157
+ saveUninitialized: opts.saveUninitialized,
158
+ genid: opts.genid, // SECURITY: Pass genid for session regeneration
159
+ ctx: ctx
160
+ });
161
+
162
+ // Store original response methods
163
+ const originalSend = ctx.send;
164
+ const originalJson = ctx.json;
165
+ ctx._sessionSaveNeeded = false;
166
+ ctx._sessionSaved = false;
167
+
168
+ // Persist the session before the response goes out. A store failure
169
+ // becomes a 500 response instead of an unhandled rejection.
170
+ const saveBeforeResponse = async () => {
171
+ if (ctx.responded || ctx._sessionSaved) {
172
+ return true;
173
+ }
174
+ ctx._sessionSaved = true;
175
+ try {
176
+ await saveSession(ctx, opts);
177
+ return true;
178
+ } catch (error) {
179
+ if (ctx.app && typeof ctx.app.handleError === 'function') {
180
+ await ctx.app.handleError(error, ctx);
181
+ } else {
182
+ originalJson.call(ctx.status(500), { status: 500, error: 'Internal Server Error' });
183
+ }
184
+ return false;
185
+ }
186
+ };
187
+
188
+ ctx.send = async function(data) {
189
+ if (await saveBeforeResponse()) {
190
+ return originalSend.call(ctx, data);
191
+ }
192
+ return ctx;
193
+ };
194
+
195
+ ctx.json = async function(data) {
196
+ if (await saveBeforeResponse()) {
197
+ return originalJson.call(ctx, data);
198
+ }
199
+ return ctx;
200
+ };
201
+
202
+ await next();
203
+ };
204
+ }
205
+
206
+ function getSessionId(ctx, opts) {
207
+ const cookieValue = ctx.cookies[opts.key];
208
+
209
+ if (!cookieValue) {
210
+ return null;
211
+ }
212
+
213
+ try {
214
+ return unsignCookie(cookieValue, opts.secret);
215
+ } catch (error) {
216
+ return null;
217
+ }
218
+ }
219
+
220
+ function createSessionProxy(session, options) {
221
+ let saveTimeout = null;
222
+ let savePromise = null;
223
+ let isSaving = false; // BUG FIX: Add mutex flag to prevent concurrent saves
224
+
225
+ const debouncedSave = () => {
226
+ // Clear any pending save timeout
227
+ if (saveTimeout) {
228
+ clearTimeout(saveTimeout);
229
+ }
230
+
231
+ // Debounce saves to prevent race conditions
232
+ saveTimeout = setTimeout(async () => {
233
+ // BUG FIX: Skip if already saving to prevent race conditions
234
+ if (isSaving) {
235
+ // Reschedule if another save is in progress
236
+ saveTimeout = setTimeout(() => debouncedSave(), 10);
237
+ return;
238
+ }
239
+
240
+ if (options.ctx && !options.ctx.responded) {
241
+ isSaving = true; // Set mutex
242
+
243
+ try {
244
+ // SECURITY: Wait for any in-progress save to complete before starting new one
245
+ if (savePromise) {
246
+ try {
247
+ await savePromise;
248
+ } catch (err) {
249
+ // Previous save failed, continue with new save
250
+ console.error('Previous session save failed:', err);
251
+ }
252
+ }
253
+
254
+ // BUG FIX: Take snapshot inside try block to ensure consistent state
255
+ const sessionData = {};
256
+ for (const key in session) {
257
+ if (Object.prototype.hasOwnProperty.call(session, key)) {
258
+ sessionData[key] = session[key];
259
+ }
260
+ }
261
+
262
+ // Store the save promise to prevent concurrent saves
263
+ savePromise = Promise.resolve(
264
+ options.store.set(options.sessionId, sessionData, options.cookie.maxAge)
265
+ ).then(() => {
266
+ const signedId = signCookie(options.sessionId, options.secret);
267
+ options.ctx.setCookie(options.key, signedId, options.cookie);
268
+ savePromise = null;
269
+ }).catch(err => {
270
+ console.error('Session save error:', err);
271
+ savePromise = null;
272
+ throw err; // Re-throw to allow outer handler to catch
273
+ });
274
+
275
+ // Await the save to ensure it completes
276
+ await savePromise;
277
+ } catch (err) {
278
+ // Error already logged
279
+ } finally {
280
+ isSaving = false; // Always release mutex
281
+ }
282
+ }
283
+ }, 10); // 10ms debounce
284
+ if (saveTimeout.unref) {
285
+ saveTimeout.unref();
286
+ }
287
+ };
288
+
289
+ const proxy = new Proxy(session, {
290
+ set(target, property, value) {
291
+ if (property === 'cookie') {
292
+ return true;
293
+ }
294
+
295
+ target[property] = value;
296
+ options.modified = true;
297
+
298
+ // Auto-save session when modified (debounced)
299
+ debouncedSave();
300
+
301
+ return true;
302
+ },
303
+
304
+ deleteProperty(target, property) {
305
+ delete target[property];
306
+ options.modified = true;
307
+ debouncedSave();
308
+ return true;
309
+ }
310
+ });
311
+
312
+ Object.defineProperty(proxy, 'id', {
313
+ get() { return options.sessionId; },
314
+ enumerable: false
315
+ });
316
+
317
+ Object.defineProperty(proxy, 'isNew', {
318
+ get() { return options.isNew; },
319
+ enumerable: false
320
+ });
321
+
322
+ Object.defineProperty(proxy, 'cookie', {
323
+ get() { return options.cookie; },
324
+ set(value) { options.cookie = { ...options.cookie, ...value }; },
325
+ enumerable: false
326
+ });
327
+
328
+ Object.defineProperty(proxy, 'destroy', {
329
+ value: async function() {
330
+ await options.store.destroy(options.sessionId);
331
+ options.destroyed = true;
332
+ },
333
+ enumerable: false
334
+ });
335
+
336
+ Object.defineProperty(proxy, 'regenerate', {
337
+ value: async function() {
338
+ await options.store.destroy(options.sessionId);
339
+ options.sessionId = options.genid();
340
+ options.isNew = true;
341
+ options.modified = true;
342
+
343
+ for (const key in session) {
344
+ delete session[key];
345
+ }
346
+ },
347
+ enumerable: false
348
+ });
349
+
350
+ Object.defineProperty(proxy, 'modified', {
351
+ get() { return options.modified; },
352
+ set(value) { options.modified = value; },
353
+ enumerable: false
354
+ });
355
+
356
+ Object.defineProperty(proxy, 'destroyed', {
357
+ get() { return options.destroyed; },
358
+ enumerable: false
359
+ });
360
+
361
+ Object.defineProperty(proxy, 'reload', {
362
+ value: async function() {
363
+ const data = await options.store.get(options.sessionId);
364
+ if (data) {
365
+ Object.assign(session, data);
366
+ }
367
+ },
368
+ enumerable: false
369
+ });
370
+
371
+ Object.defineProperty(proxy, 'save', {
372
+ value: async function() {
373
+ await options.store.set(options.sessionId, session, options.cookie.maxAge);
374
+ },
375
+ enumerable: false
376
+ });
377
+
378
+ Object.defineProperty(proxy, 'touch', {
379
+ value: async function() {
380
+ await options.store.touch(options.sessionId, session, options.cookie.maxAge);
381
+ },
382
+ enumerable: false
383
+ });
384
+
385
+ return proxy;
386
+ }
387
+
388
+ async function saveSession(ctx, opts) {
389
+ const session = ctx.session;
390
+
391
+ if (!session) {
392
+ return;
393
+ }
394
+
395
+ if (ctx.responded) {
396
+ return;
397
+ }
398
+
399
+ if (session.destroyed) {
400
+ ctx.clearCookie(opts.key, { path: opts.cookie.path, domain: opts.cookie.domain });
401
+ return;
402
+ }
403
+
404
+ const shouldSave = session.modified ||
405
+ (opts.resave && !session.isNew) ||
406
+ (opts.saveUninitialized && session.isNew);
407
+
408
+ if (shouldSave) {
409
+ const sessionData = {};
410
+ for (const key in session) {
411
+ if (Object.prototype.hasOwnProperty.call(session, key)) {
412
+ sessionData[key] = session[key];
413
+ }
414
+ }
415
+
416
+ await opts.store.set(session.id, sessionData, opts.cookie.maxAge);
417
+
418
+ const signedId = signCookie(session.id, opts.secret);
419
+ ctx.setCookie(opts.key, signedId, opts.cookie);
420
+ } else if (opts.rolling) {
421
+ await opts.store.touch(session.id, session, opts.cookie.maxAge);
422
+
423
+ const signedId = signCookie(session.id, opts.secret);
424
+ ctx.setCookie(opts.key, signedId, opts.cookie);
425
+ }
426
+ }
427
+
428
+ function generateSessionId() {
429
+ return crypto.randomBytes(32).toString('hex');
430
+ }
431
+
432
+ function signCookie(value, secret) {
433
+ const signature = crypto
434
+ .createHmac('sha256', secret)
435
+ .update(value)
436
+ .digest('base64')
437
+ .replace(/\+/g, '-')
438
+ .replace(/\//g, '_')
439
+ .replace(/=/g, '');
440
+
441
+ return `${value}.${signature}`;
442
+ }
443
+
444
+ function unsignCookie(signedValue, secret) {
445
+ // SECURITY: Use constant-time validation to prevent timing attacks
446
+ // Avoid early returns that could create timing oracles
447
+
448
+ let isValid = true;
449
+ let value = '';
450
+ let signature = '';
451
+
452
+ // Check structure without early return
453
+ const parts = signedValue.split('.');
454
+ if (parts.length !== 2) {
455
+ isValid = false;
456
+ } else {
457
+ value = parts[0];
458
+ signature = parts[1];
459
+ }
460
+
461
+ // Always compute expected signature (constant-time behavior)
462
+ let expected = '';
463
+ try {
464
+ expected = crypto
465
+ .createHmac('sha256', secret)
466
+ .update(value || '')
467
+ .digest('base64')
468
+ .replace(/\+/g, '-')
469
+ .replace(/\//g, '_')
470
+ .replace(/=/g, '');
471
+ } catch (error) {
472
+ isValid = false;
473
+ }
474
+
475
+ // Constant-time comparison (only if lengths match)
476
+ if (signature.length !== expected.length) {
477
+ isValid = false;
478
+ } else {
479
+ try {
480
+ if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
481
+ isValid = false;
482
+ }
483
+ } catch (error) {
484
+ isValid = false;
485
+ }
486
+ }
487
+
488
+ // Single exit point to maintain constant-time behavior
489
+ if (!isValid) {
490
+ throw new Error('Cookie signature verification failed');
491
+ }
492
+
493
+ return value;
494
+ }
495
+
496
+ class FileStore extends EventEmitter {
497
+ constructor(options = {}) {
498
+ super();
499
+ this.sessionPath = options.path || './sessions';
500
+ this.ttl = options.ttl || DEFAULT_MAX_AGE;
501
+ this.fs = require('fs');
502
+ this.pathModule = require('path');
503
+
504
+ this.ensureDirectory();
505
+ }
506
+
507
+ ensureDirectory() {
508
+ if (!this.fs.existsSync(this.sessionPath)) {
509
+ this.fs.mkdirSync(this.sessionPath, { recursive: true });
510
+ }
511
+ }
512
+
513
+ getFilePath(sessionId) {
514
+ // Sanitize sessionId to prevent path traversal
515
+ if (!sessionId || typeof sessionId !== 'string') {
516
+ throw new Error('Invalid session ID');
517
+ }
518
+
519
+ // Remove any path separators and special characters
520
+ const sanitizedId = sessionId.replace(/[/\\:*?"<>|]/g, '');
521
+
522
+ if (!sanitizedId || sanitizedId !== sessionId) {
523
+ throw new Error('Invalid session ID format');
524
+ }
525
+
526
+ return this.pathModule.join(this.sessionPath, `${sanitizedId}.json`);
527
+ }
528
+
529
+ async get(sessionId) {
530
+ const filePath = this.getFilePath(sessionId);
531
+
532
+ try {
533
+ const data = await new Promise((resolve, reject) => {
534
+ this.fs.readFile(filePath, 'utf8', (err, data) => {
535
+ if (err) reject(err);
536
+ else resolve(data);
537
+ });
538
+ });
539
+ const session = JSON.parse(data);
540
+
541
+ if (session.expires && Date.now() > session.expires) {
542
+ await this.destroy(sessionId);
543
+ return null;
544
+ }
545
+
546
+ return session.data;
547
+ } catch (error) {
548
+ return null;
549
+ }
550
+ }
551
+
552
+ async set(sessionId, session, maxAge) {
553
+ const filePath = this.getFilePath(sessionId);
554
+ const data = {
555
+ data: session,
556
+ expires: Date.now() + maxAge
557
+ };
558
+
559
+ await new Promise((resolve, reject) => {
560
+ this.fs.writeFile(filePath, JSON.stringify(data), 'utf8', (err) => {
561
+ if (err) reject(err);
562
+ else resolve();
563
+ });
564
+ });
565
+ }
566
+
567
+ async destroy(sessionId) {
568
+ const filePath = this.getFilePath(sessionId);
569
+
570
+ try {
571
+ await new Promise((resolve, reject) => {
572
+ this.fs.unlink(filePath, (err) => {
573
+ if (err && err.code !== 'ENOENT') reject(err);
574
+ else resolve();
575
+ });
576
+ });
577
+ this.emit('destroy', sessionId);
578
+ } catch (error) {
579
+ // File doesn't exist, ignore
580
+ }
581
+ }
582
+
583
+ async touch(sessionId, session, maxAge) {
584
+ await this.set(sessionId, session, maxAge);
585
+ }
586
+
587
+ async all() {
588
+ const sessions = {};
589
+ const files = await new Promise((resolve, reject) => {
590
+ this.fs.readdir(this.sessionPath, (err, files) => {
591
+ if (err) reject(err);
592
+ else resolve(files);
593
+ });
594
+ });
595
+
596
+ for (const file of files) {
597
+ if (file.endsWith('.json')) {
598
+ const sessionId = file.replace('.json', '');
599
+ const session = await this.get(sessionId);
600
+ if (session) {
601
+ sessions[sessionId] = session;
602
+ }
603
+ }
604
+ }
605
+
606
+ return sessions;
607
+ }
608
+
609
+ async length() {
610
+ const files = await new Promise((resolve, reject) => {
611
+ this.fs.readdir(this.sessionPath, (err, files) => {
612
+ if (err) reject(err);
613
+ else resolve(files);
614
+ });
615
+ });
616
+ return files.filter(file => file.endsWith('.json')).length;
617
+ }
618
+
619
+ async clear() {
620
+ const files = await new Promise((resolve, reject) => {
621
+ this.fs.readdir(this.sessionPath, (err, files) => {
622
+ if (err) reject(err);
623
+ else resolve(files);
624
+ });
625
+ });
626
+
627
+ for (const file of files) {
628
+ if (file.endsWith('.json')) {
629
+ await new Promise((resolve, reject) => {
630
+ this.fs.unlink(this.pathModule.join(this.sessionPath, file), (err) => {
631
+ if (err && err.code !== 'ENOENT') reject(err);
632
+ else resolve();
633
+ });
634
+ });
635
+ }
636
+ }
637
+ }
638
+ }
639
+
640
+ function throwMissingSecretError() {
641
+ throw new Error(
642
+ 'Session secret is required for security. ' +
643
+ 'Please provide a secret in the session options: ' +
644
+ 'session({ secret: "your-secret-here" })'
645
+ );
646
+ }
647
+
648
+ module.exports = session;
649
+ module.exports.MemoryStore = MemoryStore;
532
650
  module.exports.FileStore = FileStore;