@plotdb/express-session 1.17.3

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.
package/index.js ADDED
@@ -0,0 +1,693 @@
1
+ /*!
2
+ * express-session
3
+ * Copyright(c) 2010 Sencha Inc.
4
+ * Copyright(c) 2011 TJ Holowaychuk
5
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
6
+ * MIT Licensed
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ /**
12
+ * Module dependencies.
13
+ * @private
14
+ */
15
+
16
+ var Buffer = require('safe-buffer').Buffer
17
+ var cookie = require('cookie');
18
+ var crypto = require('crypto')
19
+ var debug = require('debug')('express-session');
20
+ var deprecate = require('depd')('express-session');
21
+ var onHeaders = require('on-headers')
22
+ var parseUrl = require('parseurl');
23
+ var signature = require('cookie-signature')
24
+ var uid = require('uid-safe').sync
25
+
26
+ var Cookie = require('./session/cookie')
27
+ var MemoryStore = require('./session/memory')
28
+ var Session = require('./session/session')
29
+ var Store = require('./session/store')
30
+
31
+ // environment
32
+
33
+ var env = process.env.NODE_ENV;
34
+
35
+ /**
36
+ * Expose the middleware.
37
+ */
38
+
39
+ exports = module.exports = session;
40
+
41
+ /**
42
+ * Expose constructors.
43
+ */
44
+
45
+ exports.Store = Store;
46
+ exports.Cookie = Cookie;
47
+ exports.Session = Session;
48
+ exports.MemoryStore = MemoryStore;
49
+
50
+ /**
51
+ * Warning message for `MemoryStore` usage in production.
52
+ * @private
53
+ */
54
+
55
+ var warning = 'Warning: connect.session() MemoryStore is not\n'
56
+ + 'designed for a production environment, as it will leak\n'
57
+ + 'memory, and will not scale past a single process.';
58
+
59
+ /**
60
+ * Node.js 0.8+ async implementation.
61
+ * @private
62
+ */
63
+
64
+ /* istanbul ignore next */
65
+ var defer = typeof setImmediate === 'function'
66
+ ? setImmediate
67
+ : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
68
+
69
+ /**
70
+ * Setup session store with the given `options`.
71
+ *
72
+ * @param {Object} [options]
73
+ * @param {Object} [options.cookie] Options for cookie
74
+ * @param {Function} [options.genid]
75
+ * @param {String} [options.name=connect.sid] Session ID cookie name
76
+ * @param {Boolean} [options.proxy]
77
+ * @param {Boolean} [options.resave] Resave unmodified sessions back to the store
78
+ * @param {Boolean} [options.rolling] Enable/disable rolling session expiration
79
+ * @param {Boolean} [options.saveUninitialized] Save uninitialized sessions to the store
80
+ * @param {String|Array} [options.secret] Secret for signing session ID
81
+ * @param {Object} [options.store=MemoryStore] Session store
82
+ * @param {String} [options.unset]
83
+ * @return {Function} middleware
84
+ * @public
85
+ */
86
+
87
+ function session(options) {
88
+ var opts = options || {}
89
+
90
+ // get the cookie options
91
+ var cookieOptions = opts.cookie || {}
92
+
93
+ // get the session id generate function
94
+ var generateId = opts.genid || generateSessionId
95
+
96
+ // get the session cookie name
97
+ var name = opts.name || opts.key || 'connect.sid'
98
+
99
+ // get the session store
100
+ var store = opts.store || new MemoryStore()
101
+
102
+ // get the trust proxy setting
103
+ var trustProxy = opts.proxy
104
+
105
+ // get the resave session option
106
+ var resaveSession = opts.resave;
107
+
108
+ // get the rolling session option
109
+ var rollingSessions = Boolean(opts.rolling)
110
+
111
+ // get the save uninitialized session option
112
+ var saveUninitializedSession = opts.saveUninitialized
113
+
114
+ // get the cookie signing secret
115
+ var secret = opts.secret
116
+
117
+ if (typeof generateId !== 'function') {
118
+ throw new TypeError('genid option must be a function');
119
+ }
120
+
121
+ if (resaveSession === undefined) {
122
+ deprecate('undefined resave option; provide resave option');
123
+ resaveSession = true;
124
+ }
125
+
126
+ if (saveUninitializedSession === undefined) {
127
+ deprecate('undefined saveUninitialized option; provide saveUninitialized option');
128
+ saveUninitializedSession = true;
129
+ }
130
+
131
+ if (opts.unset && opts.unset !== 'destroy' && opts.unset !== 'keep') {
132
+ throw new TypeError('unset option must be "destroy" or "keep"');
133
+ }
134
+
135
+ // TODO: switch to "destroy" on next major
136
+ var unsetDestroy = opts.unset === 'destroy'
137
+
138
+ if (Array.isArray(secret) && secret.length === 0) {
139
+ throw new TypeError('secret option array must contain one or more strings');
140
+ }
141
+
142
+ if (secret && !Array.isArray(secret)) {
143
+ secret = [secret];
144
+ }
145
+
146
+ if (!secret) {
147
+ deprecate('req.secret; provide secret option');
148
+ }
149
+
150
+ // notify user that this store is not
151
+ // meant for a production environment
152
+ /* istanbul ignore next: not tested */
153
+ if (env === 'production' && store instanceof MemoryStore) {
154
+ console.warn(warning);
155
+ }
156
+
157
+ // generates the new session
158
+ store.generate = function(req){
159
+ req.sessionID = generateId(req);
160
+ req.session = new Session(req);
161
+ req.session.cookie = new Cookie(cookieOptions);
162
+
163
+ if (cookieOptions.secure === 'auto') {
164
+ req.session.cookie.secure = issecure(req, trustProxy);
165
+ }
166
+ };
167
+
168
+ var storeImplementsTouch = typeof store.touch === 'function';
169
+
170
+ // register event listeners for the store to track readiness
171
+ var storeReady = true
172
+ store.on('disconnect', function ondisconnect() {
173
+ storeReady = false
174
+ })
175
+ store.on('connect', function onconnect() {
176
+ storeReady = true
177
+ })
178
+
179
+ return function session(req, res, next) {
180
+ // self-awareness
181
+ if (req.session) {
182
+ next()
183
+ return
184
+ }
185
+
186
+ // Handle connection as if there is no session if
187
+ // the store has temporarily disconnected etc
188
+ if (!storeReady) {
189
+ debug('store is disconnected')
190
+ next()
191
+ return
192
+ }
193
+
194
+ // pathname mismatch
195
+ var originalPath = parseUrl.original(req).pathname || '/'
196
+ if (originalPath.indexOf(cookieOptions.path || '/') !== 0) return next();
197
+
198
+ // ensure a secret is available or bail
199
+ if (!secret && !req.secret) {
200
+ next(new Error('secret option required for sessions'));
201
+ return;
202
+ }
203
+
204
+ // backwards compatibility for signed cookies
205
+ // req.secret is passed from the cookie parser middleware
206
+ var secrets = secret || [req.secret];
207
+
208
+ var originalHash;
209
+ var originalId;
210
+ var savedHash;
211
+ var touched = false
212
+
213
+ // expose store
214
+ req.sessionStore = store;
215
+
216
+ // get the session ID from the cookie
217
+ try {
218
+ var cookieId = req.sessionID = getcookie(req, name, secrets);
219
+ } catch(err) {
220
+ return next(err);
221
+ }
222
+
223
+ // set-cookie
224
+ onHeaders(res, function(){
225
+ if (!req.session) {
226
+ debug('no session');
227
+ return;
228
+ }
229
+
230
+ if (!shouldSetCookie(req)) {
231
+ return;
232
+ }
233
+
234
+ // only send secure cookies via https
235
+ if (req.session.cookie.secure && !issecure(req, trustProxy)) {
236
+ debug('not secured');
237
+ return;
238
+ }
239
+
240
+ if (!touched) {
241
+ // touch session
242
+ req.session.touch()
243
+ touched = true
244
+ }
245
+
246
+ // set cookie
247
+ setcookie(res, name, req.sessionID, secrets[0], req.session.cookie.data);
248
+ });
249
+
250
+ // proxy end() to commit the session
251
+ var _end = res.end;
252
+ var _write = res.write;
253
+ var ended = false;
254
+ res.end = function end(chunk, encoding) {
255
+ if (ended) {
256
+ return false;
257
+ }
258
+
259
+ ended = true;
260
+
261
+ var ret;
262
+ var sync = true;
263
+
264
+ function writeend() {
265
+ if (sync) {
266
+ ret = _end.call(res, chunk, encoding);
267
+ sync = false;
268
+ return;
269
+ }
270
+
271
+ _end.call(res);
272
+ }
273
+
274
+ function writetop() {
275
+ if (!sync) {
276
+ return ret;
277
+ }
278
+
279
+ if (!res._header) {
280
+ res._implicitHeader()
281
+ }
282
+
283
+ if (chunk == null) {
284
+ ret = true;
285
+ return ret;
286
+ }
287
+
288
+ var contentLength = Number(res.getHeader('Content-Length'));
289
+
290
+ if (!isNaN(contentLength) && contentLength > 0) {
291
+ // measure chunk
292
+ chunk = !Buffer.isBuffer(chunk)
293
+ ? Buffer.from(chunk, encoding)
294
+ : chunk;
295
+ encoding = undefined;
296
+
297
+ if (chunk.length !== 0) {
298
+ debug('split response');
299
+ ret = _write.call(res, chunk.slice(0, chunk.length - 1));
300
+ chunk = chunk.slice(chunk.length - 1, chunk.length);
301
+ return ret;
302
+ }
303
+ }
304
+
305
+ ret = _write.call(res, chunk, encoding);
306
+ sync = false;
307
+
308
+ return ret;
309
+ }
310
+
311
+ if (shouldDestroy(req)) {
312
+ // destroy session
313
+ debug('destroying');
314
+ store.destroy(req.sessionID, function ondestroy(err) {
315
+ if (err) {
316
+ defer(next, err);
317
+ }
318
+
319
+ debug('destroyed');
320
+ writeend();
321
+ });
322
+
323
+ return writetop();
324
+ }
325
+
326
+ // no session to save
327
+ if (!req.session) {
328
+ debug('no session');
329
+ return _end.call(res, chunk, encoding);
330
+ }
331
+
332
+ if (!touched) {
333
+ // touch session
334
+ req.session.touch()
335
+ touched = true
336
+ }
337
+
338
+ if (shouldSave(req)) {
339
+ req.session.save(function onsave(err) {
340
+ if (err) {
341
+ defer(next, err);
342
+ }
343
+
344
+ writeend();
345
+ });
346
+
347
+ return writetop();
348
+ } else if (storeImplementsTouch && shouldTouch(req)) {
349
+ // store implements touch method
350
+ debug('touching');
351
+ store.touch(req.sessionID, req.session, function ontouch(err) {
352
+ if (err) {
353
+ defer(next, err);
354
+ }
355
+
356
+ debug('touched');
357
+ writeend();
358
+ });
359
+
360
+ return writetop();
361
+ }
362
+
363
+ return _end.call(res, chunk, encoding);
364
+ };
365
+
366
+ // generate the session
367
+ function generate() {
368
+ store.generate(req);
369
+ originalId = req.sessionID;
370
+ originalHash = hash(req.session);
371
+ wrapmethods(req.session);
372
+ }
373
+
374
+ // inflate the session
375
+ function inflate (req, sess) {
376
+ store.createSession(req, sess)
377
+ originalId = req.sessionID
378
+ originalHash = hash(sess)
379
+
380
+ if (!resaveSession) {
381
+ savedHash = originalHash
382
+ }
383
+
384
+ wrapmethods(req.session)
385
+ }
386
+
387
+ function rewrapmethods (sess, callback) {
388
+ return function () {
389
+ if (req.session !== sess) {
390
+ wrapmethods(req.session)
391
+ }
392
+
393
+ callback.apply(this, arguments)
394
+ }
395
+ }
396
+
397
+ // wrap session methods
398
+ function wrapmethods(sess) {
399
+ var _reload = sess.reload
400
+ var _save = sess.save;
401
+
402
+ function reload(callback) {
403
+ debug('reloading %s', this.id)
404
+ _reload.call(this, rewrapmethods(this, callback))
405
+ }
406
+
407
+ function save() {
408
+ debug('saving %s', this.id);
409
+ savedHash = hash(this);
410
+ _save.apply(this, arguments);
411
+ }
412
+
413
+ Object.defineProperty(sess, 'reload', {
414
+ configurable: true,
415
+ enumerable: false,
416
+ value: reload,
417
+ writable: true
418
+ })
419
+
420
+ Object.defineProperty(sess, 'save', {
421
+ configurable: true,
422
+ enumerable: false,
423
+ value: save,
424
+ writable: true
425
+ });
426
+ }
427
+
428
+ // check if session has been modified
429
+ function isModified(sess) {
430
+ return originalId !== sess.id || originalHash !== hash(sess);
431
+ }
432
+
433
+ // check if session has been saved
434
+ function isSaved(sess) {
435
+ return originalId === sess.id && savedHash === hash(sess);
436
+ }
437
+
438
+ // determine if session should be destroyed
439
+ function shouldDestroy(req) {
440
+ return req.sessionID && unsetDestroy && req.session == null;
441
+ }
442
+
443
+ // determine if session should be saved to store
444
+ function shouldSave(req) {
445
+ // cannot set cookie without a session ID
446
+ if (typeof req.sessionID !== 'string') {
447
+ debug('session ignored because of bogus req.sessionID %o', req.sessionID);
448
+ return false;
449
+ }
450
+
451
+ return !saveUninitializedSession && !savedHash && cookieId !== req.sessionID
452
+ ? isModified(req.session)
453
+ : !isSaved(req.session)
454
+ }
455
+
456
+ // determine if session should be touched
457
+ function shouldTouch(req) {
458
+ // cannot set cookie without a session ID
459
+ if (typeof req.sessionID !== 'string') {
460
+ debug('session ignored because of bogus req.sessionID %o', req.sessionID);
461
+ return false;
462
+ }
463
+
464
+ return cookieId === req.sessionID && !shouldSave(req);
465
+ }
466
+
467
+ // determine if cookie should be set on response
468
+ function shouldSetCookie(req) {
469
+ // cannot set cookie without a session ID
470
+ if (typeof req.sessionID !== 'string') {
471
+ return false;
472
+ }
473
+
474
+ return cookieId !== req.sessionID
475
+ ? saveUninitializedSession || isModified(req.session)
476
+ : rollingSessions || req.session.cookie.expires != null && isModified(req.session);
477
+ }
478
+
479
+ // generate a session if the browser doesn't send a sessionID
480
+ if (!req.sessionID) {
481
+ debug('no SID sent, generating session');
482
+ generate();
483
+ next();
484
+ return;
485
+ }
486
+
487
+ // generate the session object
488
+ debug('fetching %s', req.sessionID);
489
+ store.get(req.sessionID, function(err, sess){
490
+ // error handling
491
+ if (err && err.code !== 'ENOENT') {
492
+ debug('error %j', err);
493
+ next(err)
494
+ return
495
+ }
496
+
497
+ try {
498
+ if (err || !sess) {
499
+ debug('no session found')
500
+ generate()
501
+ } else {
502
+ debug('session found')
503
+ inflate(req, sess)
504
+ }
505
+ } catch (e) {
506
+ next(e)
507
+ return
508
+ }
509
+
510
+ next()
511
+ });
512
+ };
513
+ };
514
+
515
+ /**
516
+ * Generate a session ID for a new session.
517
+ *
518
+ * @return {String}
519
+ * @private
520
+ */
521
+
522
+ function generateSessionId(sess) {
523
+ return uid(24);
524
+ }
525
+
526
+ /**
527
+ * Get the session ID cookie from request.
528
+ *
529
+ * @return {string}
530
+ * @private
531
+ */
532
+
533
+ function getcookie(req, name, secrets) {
534
+ var header = req.headers.cookie;
535
+ var raw;
536
+ var val;
537
+
538
+ // read from cookie header
539
+ if (header) {
540
+ var cookies = cookie.parse(header);
541
+
542
+ raw = cookies[name];
543
+
544
+ if (raw) {
545
+ if (raw.substr(0, 2) === 's:') {
546
+ val = unsigncookie(raw.slice(2), secrets);
547
+
548
+ if (val === false) {
549
+ debug('cookie signature invalid');
550
+ val = undefined;
551
+ var err = new Error();
552
+ err.name = 'lderror';
553
+ err.id = 1029;
554
+ throw err;
555
+ }
556
+ } else {
557
+ debug('cookie unsigned')
558
+ }
559
+ }
560
+ }
561
+
562
+ // back-compat read from cookieParser() signedCookies data
563
+ if (!val && req.signedCookies) {
564
+ val = req.signedCookies[name];
565
+
566
+ if (val) {
567
+ deprecate('cookie should be available in req.headers.cookie');
568
+ }
569
+ }
570
+
571
+ // back-compat read from cookieParser() cookies data
572
+ if (!val && req.cookies) {
573
+ raw = req.cookies[name];
574
+
575
+ if (raw) {
576
+ if (raw.substr(0, 2) === 's:') {
577
+ val = unsigncookie(raw.slice(2), secrets);
578
+
579
+ if (val) {
580
+ deprecate('cookie should be available in req.headers.cookie');
581
+ }
582
+
583
+ if (val === false) {
584
+ debug('cookie signature invalid');
585
+ val = undefined;
586
+ }
587
+ } else {
588
+ debug('cookie unsigned')
589
+ }
590
+ }
591
+ }
592
+
593
+ return val;
594
+ }
595
+
596
+ /**
597
+ * Hash the given `sess` object omitting changes to `.cookie`.
598
+ *
599
+ * @param {Object} sess
600
+ * @return {String}
601
+ * @private
602
+ */
603
+
604
+ function hash(sess) {
605
+ // serialize
606
+ var str = JSON.stringify(sess, function (key, val) {
607
+ // ignore sess.cookie property
608
+ if (this === sess && key === 'cookie') {
609
+ return
610
+ }
611
+
612
+ return val
613
+ })
614
+
615
+ // hash
616
+ return crypto
617
+ .createHash('sha1')
618
+ .update(str, 'utf8')
619
+ .digest('hex')
620
+ }
621
+
622
+ /**
623
+ * Determine if request is secure.
624
+ *
625
+ * @param {Object} req
626
+ * @param {Boolean} [trustProxy]
627
+ * @return {Boolean}
628
+ * @private
629
+ */
630
+
631
+ function issecure(req, trustProxy) {
632
+ // socket is https server
633
+ if (req.connection && req.connection.encrypted) {
634
+ return true;
635
+ }
636
+
637
+ // do not trust proxy
638
+ if (trustProxy === false) {
639
+ return false;
640
+ }
641
+
642
+ // no explicit trust; try req.secure from express
643
+ if (trustProxy !== true) {
644
+ return req.secure === true
645
+ }
646
+
647
+ // read the proto from x-forwarded-proto header
648
+ var header = req.headers['x-forwarded-proto'] || '';
649
+ var index = header.indexOf(',');
650
+ var proto = index !== -1
651
+ ? header.substr(0, index).toLowerCase().trim()
652
+ : header.toLowerCase().trim()
653
+
654
+ return proto === 'https';
655
+ }
656
+
657
+ /**
658
+ * Set cookie on response.
659
+ *
660
+ * @private
661
+ */
662
+
663
+ function setcookie(res, name, val, secret, options) {
664
+ var signed = 's:' + signature.sign(val, secret);
665
+ var data = cookie.serialize(name, signed, options);
666
+
667
+ debug('set-cookie %s', data);
668
+
669
+ var prev = res.getHeader('Set-Cookie') || []
670
+ var header = Array.isArray(prev) ? prev.concat(data) : [prev, data];
671
+
672
+ res.setHeader('Set-Cookie', header)
673
+ }
674
+
675
+ /**
676
+ * Verify and decode the given `val` with `secrets`.
677
+ *
678
+ * @param {String} val
679
+ * @param {Array} secrets
680
+ * @returns {String|Boolean}
681
+ * @private
682
+ */
683
+ function unsigncookie(val, secrets) {
684
+ for (var i = 0; i < secrets.length; i++) {
685
+ var result = signature.unsign(val, secrets[i]);
686
+
687
+ if (result !== false) {
688
+ return result;
689
+ }
690
+ }
691
+
692
+ return false;
693
+ }