@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,530 +1,650 @@
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;
1
+ 'use strict';
2
+
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;
530
650
  module.exports.FileStore = FileStore;