connect-memcached 1.0.0 → 2.0.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.
package/.tool-versions ADDED
@@ -0,0 +1 @@
1
+ nodejs 18.2.0
package/Readme.md CHANGED
@@ -4,10 +4,16 @@ Memcached session store, using [node-memcached](http://github.com/3rd-Eden/node-
4
4
 
5
5
  ## Installation
6
6
 
7
- via npm:
7
+ npm:
8
8
 
9
- ```bash
10
- $ npm install connect-memcached
9
+ ```shell
10
+ npm install connect-memcached express-session
11
+ ```
12
+
13
+ yarn:
14
+
15
+ ```shell
16
+ yarn add connect-memcached express-session
11
17
  ```
12
18
 
13
19
  ## Example
@@ -15,12 +21,9 @@ $ npm install connect-memcached
15
21
  ```javascript
16
22
  var express = require("express"),
17
23
  session = require("express-session"),
18
- cookieParser = require("cookie-parser"),
19
- http = require("http"),
20
24
  app = express(),
21
25
  MemcachedStore = require("connect-memcached")(session);
22
26
 
23
- app.use(cookieParser());
24
27
  app.use(
25
28
  session({
26
29
  secret: "CatOnKeyboard",
@@ -30,7 +33,7 @@ app.use(
30
33
  saveUninitialized: false,
31
34
  store: new MemcachedStore({
32
35
  hosts: ["127.0.0.1:11211"],
33
- secret: "123, easy as ABC. ABC, easy as 123" // Optionally use transparent encryption for memcache session data
36
+ secret: "123, easy as ABC. ABC, easy as 123" // Optionally use transparent encryption for memcached session data
34
37
  })
35
38
  })
36
39
  );
@@ -44,21 +47,26 @@ app.get("/", function(req, res) {
44
47
  res.send("Viewed <strong>" + req.session.views + "</strong> times.");
45
48
  });
46
49
 
47
- http.createServer(app).listen(9341, function() {
50
+ app.listen(9341, function() {
48
51
  console.log("Listening on %d", this.address().port);
49
52
  });
50
53
  ```
51
54
 
52
55
  ## Options
53
56
 
54
- - `hosts` Memcached servers locations, can be string, array, hash.
55
- - `prefix` An optional prefix for each memcache key, in case you are sharing your memcached servers with something generating its own keys.
56
- - `ttl` An optional parameter used for setting the default TTL (in seconds)
57
- - `secret` An optional secret can be used to encrypt/decrypt session contents.
58
- - `algorithm` An optional algorithm parameter may be used, but must be valid based on returned `crypto.getCiphers()`. The current default is `aes-256-ctr` and was chosen based on the following [information](http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html)
59
- - ... Rest of given option will be passed directly to the node-memcached constructor.
57
+ - `hosts` (Optional) Memcached servers locations, can be string, array or hash. Default is `127.0.0.1:11211`.
58
+ - `prefix` (Optional) Prefix for each memcached key, in case you are sharing your memcached servers with something generating its own keys.
59
+ - `ttl` (Optional) Default TTL parameter for the session data (in seconds).
60
+ - `secret` (Optional) Secret used to encrypt/decrypt session contents. Setting it enables data encryption, which is handled by [kruptein](https://github.com/jas-/kruptein) module.
61
+ - `algorithm` (Optional) Cipher algorithm from `crypto.getCiphers()`. Default is `aes-256-gcm`.
62
+ - `hashing` (Optional) Hash algorithm from `crypto.getHashes()`. Default is `sha512`.
63
+ - ... Rest of given options will be passed directly to the [node-memcached](http://github.com/3rd-Eden/node-memcached) and [kruptein](https://github.com/jas-/kruptein) constructors, see their appropriate docs for extra configurability.
64
+
65
+ ## Upgrading to v2.x.x
66
+
67
+ When upgrading from pre v2 and using data encryption please flush all the session entries from memcached before rolling the update.
60
68
 
61
- For details see [node-memcached](http://github.com/3rd-Eden/node-memcached).
69
+ Sessions without data encryption are not affected.
62
70
 
63
71
  ## Upgrading from v0.x.x -> v1.x.x
64
72
 
package/index.js CHANGED
@@ -1,2 +1 @@
1
-
2
- module.exports = require('./lib/connect-memcached');
1
+ module.exports = require('./lib/connect-memcached');
@@ -39,16 +39,17 @@ module.exports = function(session) {
39
39
  if (!options.hosts) {
40
40
  options.hosts = "127.0.0.1:11211";
41
41
  }
42
- if (options.secret) {
43
- (this.crypto = require("crypto")), (this.secret = options.secret);
44
- }
45
- if (options.algorithm) {
46
- this.algorithm = options.algorithm;
47
- }
48
42
 
49
43
  options.client = new Memcached(options.hosts, options);
50
44
  }
51
45
 
46
+ if (options.secret) {
47
+ options.algorithm = options.algorithm || 'aes-256-gcm';
48
+ options.hashing = options.hashing || 'sha512';
49
+ this.kruptein = require("kruptein")(options);
50
+ this.secret = options.secret;
51
+ }
52
+
52
53
  this.client = options.client;
53
54
  }
54
55
 
@@ -72,7 +73,8 @@ module.exports = function(session) {
72
73
  * @api public
73
74
  */
74
75
  MemcachedStore.prototype.get = function(sid, fn) {
75
- (secret = this.secret), (self = this), (sid = this.getKey(sid));
76
+ var self = this, sid = this.getKey(sid),
77
+ parseable_string;
76
78
 
77
79
  this.client.get(sid, function(err, data) {
78
80
  if (err) {
@@ -82,13 +84,19 @@ module.exports = function(session) {
82
84
  if (!data) {
83
85
  return fn();
84
86
  }
85
- if (secret) {
86
- parseable_string = decryptData.call(self, data.toString());
87
+
88
+ if (self.secret) {
89
+ self.kruptein.get(self.secret, data, function(err, ct) {
90
+ if (err)
91
+ return fn(err, {});
92
+
93
+ parseable_string = JSON.parse(ct);
94
+ });
87
95
  } else {
88
- parseable_string = data.toString();
96
+ parseable_string = data;
89
97
  }
90
98
 
91
- fn(null, JSON.parse(parseable_string));
99
+ fn(null, parseable_string);
92
100
  } catch (e) {
93
101
  fn(e);
94
102
  }
@@ -110,16 +118,15 @@ module.exports = function(session) {
110
118
  var maxAge = sess.cookie.maxAge;
111
119
  var ttl =
112
120
  this.ttl || ("number" == typeof maxAge ? (maxAge / 1000) | 0 : oneDay);
113
- var sess = JSON.stringify(
114
- this.secret
115
- ? encryptData.call(
116
- this,
117
- JSON.stringify(sess),
118
- this.secret,
119
- this.algorithm
120
- )
121
- : sess
122
- );
121
+
122
+ if (this.secret) {
123
+ this.kruptein.set(this.secret, sess, function(err, ct) {
124
+ if (err)
125
+ return fn(err);
126
+
127
+ sess = ct;
128
+ });
129
+ }
123
130
 
124
131
  this.client.set(sid, sess, ttl, ensureCallback(fn));
125
132
  } catch (err) {
@@ -172,70 +179,5 @@ module.exports = function(session) {
172
179
  this.set(sid, sess, fn);
173
180
  };
174
181
 
175
- function encryptData(plaintext) {
176
- var pt = encrypt.call(this, this.secret, plaintext, this.algo),
177
- hmac = digest.call(this, this.secret, pt);
178
-
179
- return {
180
- ct: pt,
181
- mac: hmac
182
- };
183
- }
184
-
185
- function decryptData(ciphertext) {
186
- ciphertext = JSON.parse(ciphertext);
187
-
188
- var hmac = digest.call(this, this.secret, ciphertext.ct);
189
-
190
- if (hmac != ciphertext.mac) {
191
- throw "Encrypted session was tampered with!";
192
- }
193
-
194
- return decrypt.call(this, this.secret, ciphertext.ct, this.algo);
195
- }
196
-
197
- function digest(key, obj) {
198
- var hmac = this.crypto.createHmac("sha512", key);
199
- hmac.setEncoding("hex");
200
- hmac.write(obj);
201
- hmac.end();
202
- return hmac.read();
203
- }
204
-
205
- function encrypt(key, pt, algo) {
206
- algo = algo || "aes-256-ctr";
207
- pt = Buffer.isBuffer(pt) ? pt : new bufferFrom(pt);
208
- var iv = this.crypto.randomBytes(16);
209
- var hashedKey = this.crypto
210
- .createHash("sha256")
211
- .update(key)
212
- .digest();
213
- var cipher = this.crypto.createCipheriv(algo, hashedKey, iv),
214
- ct = [];
215
- ct.push(iv.toString("hex"));
216
- ct.push(cipher.update(pt, "buffer", "hex"));
217
- ct.push(cipher.final("hex"));
218
-
219
- return ct.join("");
220
- }
221
-
222
- function decrypt(key, ct, algo) {
223
- algo = algo || "aes-256-ctr";
224
- var dataBuffer = bufferFrom(ct, "hex");
225
- var iv = dataBuffer.slice(0, 16);
226
- var hashedKey = this.crypto
227
- .createHash("sha256")
228
- .update(key)
229
- .digest();
230
-
231
- var cipher = this.crypto.createDecipheriv(algo, hashedKey, iv),
232
- pt = [];
233
-
234
- pt.push(cipher.update(dataBuffer.slice(16), "hex", "utf8"));
235
- pt.push(cipher.final("utf8"));
236
-
237
- return pt.join("");
238
- }
239
-
240
182
  return MemcachedStore;
241
183
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "connect-memcached",
3
- "version": "1.0.0",
3
+ "version": "2.0.0",
4
4
  "description": "Memcached session store for Connect",
5
5
  "keywords": [
6
6
  "memcached",
@@ -16,8 +16,24 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "buffer-from": "1.1.0",
19
+ "kruptein": "3.0.x",
19
20
  "memcached": "2.2.x"
20
21
  },
22
+ "devDependencies": {
23
+ "express": "^4.17.3",
24
+ "express-session": "^1.17.2",
25
+ "jest": "^27.5.1",
26
+ "supertest": "^6.2.2"
27
+ },
28
+ "scripts": {
29
+ "test": "NODE_ENV=test jest --testTimeout=10000"
30
+ },
31
+ "jest": {
32
+ "testEnvironment": "node",
33
+ "coveragePathIgnorePatterns": [
34
+ "/node_modules/"
35
+ ]
36
+ },
21
37
  "engines": {
22
38
  "node": ">= 0.10.0"
23
39
  },
@@ -0,0 +1 @@
1
+ nodejs 17.9.0
@@ -0,0 +1,40 @@
1
+ const express = require("express"),
2
+ session = require("express-session"),
3
+ app = express(),
4
+ MemcachedStore = require("../../lib/connect-memcached")(session);
5
+
6
+ const memcachedStore = new MemcachedStore({
7
+ hosts: ["127.0.0.1:11211"],
8
+ prefix: "testapp_",
9
+ });
10
+
11
+ app.use(
12
+ session({
13
+ secret: "TestSecret",
14
+ key: "test",
15
+ proxy: "true",
16
+ resave: false,
17
+ saveUninitialized: false,
18
+ store: memcachedStore,
19
+ })
20
+ );
21
+
22
+ app.get("/", function (req, res) {
23
+ if (req.session.views) {
24
+ ++req.session.views;
25
+ } else {
26
+ req.session.views = 1;
27
+ }
28
+ res.json({ pageviews: req.session.views });
29
+ });
30
+
31
+ if (process.env.NODE_ENV !== "test") {
32
+ app.listen(9341, function () {
33
+ console.log("Listening on %d", this.address().port);
34
+ });
35
+ }
36
+
37
+ module.exports = {
38
+ app: app,
39
+ memcachedStore: memcachedStore,
40
+ };
@@ -0,0 +1,41 @@
1
+ const express = require("express"),
2
+ session = require("express-session"),
3
+ app = express(),
4
+ MemcachedStore = require("../../lib/connect-memcached")(session);
5
+
6
+ const memcachedStore = new MemcachedStore({
7
+ hosts: ["127.0.0.1:11211"],
8
+ secret: "Hello there stranger!",
9
+ prefix: "testapp_encrypt_",
10
+ });
11
+
12
+ app.use(
13
+ session({
14
+ secret: "TestEncryptSecret",
15
+ key: "test_encrypt",
16
+ proxy: "true",
17
+ resave: false,
18
+ saveUninitialized: false,
19
+ store: memcachedStore,
20
+ })
21
+ );
22
+
23
+ app.get("/", function (req, res) {
24
+ if (req.session.views) {
25
+ ++req.session.views;
26
+ } else {
27
+ req.session.views = 1;
28
+ }
29
+ res.json({ pageviews: req.session.views });
30
+ });
31
+
32
+ if (process.env.NODE_ENV !== "test") {
33
+ app.listen(9341, function () {
34
+ console.log("Listening on %d", this.address().port);
35
+ });
36
+ }
37
+
38
+ module.exports = {
39
+ app: app,
40
+ memcachedStore: memcachedStore,
41
+ };
@@ -0,0 +1,44 @@
1
+ const express = require("express"),
2
+ session = require("express-session"),
3
+ app = express(),
4
+ Memcached = require("memcached"),
5
+ MemcachedStore = require("../../lib/connect-memcached")(session);
6
+
7
+ const memcachedClient = new Memcached("127.0.0.1:11211");
8
+
9
+ const memcachedStore = new MemcachedStore({
10
+ client: memcachedClient,
11
+ prefix: "testapp_encrypt_",
12
+ secret: "Hello there stranger!",
13
+ });
14
+
15
+ app.use(
16
+ session({
17
+ secret: "TestEncryptSecret",
18
+ key: "test_encrypt",
19
+ proxy: "true",
20
+ resave: false,
21
+ saveUninitialized: false,
22
+ store: memcachedStore,
23
+ })
24
+ );
25
+
26
+ app.get("/", function (req, res) {
27
+ if (req.session.views) {
28
+ ++req.session.views;
29
+ } else {
30
+ req.session.views = 1;
31
+ }
32
+ res.json({ pageviews: req.session.views });
33
+ });
34
+
35
+ if (process.env.NODE_ENV !== "test") {
36
+ app.listen(9341, function () {
37
+ console.log("Listening on %d", this.address().port);
38
+ });
39
+ }
40
+
41
+ module.exports = {
42
+ app: app,
43
+ memcachedStore: memcachedStore,
44
+ };
package/test/test.js ADDED
@@ -0,0 +1,63 @@
1
+ const supertest = require("supertest");
2
+
3
+
4
+ describe("Plain memcached session store", () => {
5
+ const { app, memcachedStore } = require("./services/memcached_basic.js");
6
+ const serverAgent = supertest.agent(app);
7
+
8
+ it("GET / should increment views value at each request", async () => {
9
+ let lastPageView = 0;
10
+ for (var i = 1; i < 50; i++) {
11
+ const res = await serverAgent.get("/");
12
+ expect(res.status).toEqual(200);
13
+ expect(res.type).toEqual(expect.stringContaining("json"));
14
+ expect(res.body.pageviews).toBeGreaterThan(lastPageView);
15
+ lastPageView = res.body.pageviews;
16
+ }
17
+ });
18
+
19
+ afterAll(() => {
20
+ memcachedStore.client.end();
21
+ });
22
+ });
23
+
24
+ describe("Encrypted memcached session store", () => {
25
+ const { app, memcachedStore } = require("./services/memcached_crypt.js");
26
+ const serverAgent = supertest.agent(app);
27
+
28
+ it("GET / should increment views value at each request", async () => {
29
+ let lastPageView = 0;
30
+ for (var i = 1; i < 50; i++) {
31
+ const res = await serverAgent.get("/");
32
+ expect(res.status).toEqual(200);
33
+ expect(res.type).toEqual(expect.stringContaining("json"));
34
+ expect(res.body.pageviews).toBeGreaterThan(lastPageView);
35
+ lastPageView = res.body.pageviews;
36
+ }
37
+ });
38
+
39
+ afterAll(() => {
40
+ memcachedStore.client.end();
41
+ });
42
+ });
43
+
44
+ describe("Encrypted session store using preexising memcached client", () => {
45
+ const { app, memcachedStore } = require("./services/memcached_preexisting_crypt_connection.js");
46
+ const serverAgent = supertest.agent(app);
47
+
48
+ it("GET / should increment views value at each request", async () => {
49
+ let lastPageView = 0;
50
+ for (var i = 1; i < 50; i++) {
51
+ const res = await serverAgent.get("/");
52
+ expect(res.status).toEqual(200);
53
+ expect(res.type).toEqual(expect.stringContaining("json"));
54
+ expect(res.body.pageviews).toBeGreaterThan(lastPageView);
55
+ expect(memcachedStore.kruptein.crypto).toBe(require("crypto"));
56
+ lastPageView = res.body.pageviews;
57
+ }
58
+ });
59
+
60
+ afterAll(() => {
61
+ memcachedStore.client.end();
62
+ });
63
+ });
package/.npmignore DELETED
@@ -1,2 +0,0 @@
1
- .idea
2
- node_modules
package/tests/test.js DELETED
@@ -1,34 +0,0 @@
1
- var express = require("express"),
2
- session = require("express-session"),
3
- cookieParser = require("cookie-parser"),
4
- http = require("http"),
5
- app = express(),
6
- MemcachedStore = require("../lib/connect-memcached")(session);
7
-
8
- app.use(cookieParser());
9
- app.use(
10
- session({
11
- secret: "TestSecret",
12
- key: "test",
13
- proxy: "true",
14
- resave: false,
15
- saveUninitialized: false,
16
- store: new MemcachedStore({
17
- hosts: ["127.0.0.1:11211"],
18
- prefix: "testapp_"
19
- })
20
- })
21
- );
22
-
23
- app.get("/", function(req, res) {
24
- if (req.session.views) {
25
- ++req.session.views;
26
- } else {
27
- req.session.views = 1;
28
- }
29
- res.send("Viewed <strong>" + req.session.views + "</strong> times.");
30
- });
31
-
32
- http.createServer(app).listen(9341, function() {
33
- console.log("Listening on %d", this.address().port);
34
- });
@@ -1,35 +0,0 @@
1
- var express = require("express"),
2
- session = require("express-session"),
3
- cookieParser = require("cookie-parser"),
4
- http = require("http"),
5
- app = express(),
6
- MemcachedStore = require("../lib/connect-memcached")(session);
7
-
8
- app.use(cookieParser());
9
- app.use(
10
- session({
11
- secret: "TestEncryptSecret",
12
- key: "test_encrypt",
13
- proxy: "true",
14
- resave: false,
15
- saveUninitialized: false,
16
- store: new MemcachedStore({
17
- hosts: ["127.0.0.1:11211"],
18
- secret: "Hello there stranger!",
19
- prefix: "testapp_encrypt_"
20
- })
21
- })
22
- );
23
-
24
- app.get("/", function(req, res) {
25
- if (req.session.views) {
26
- ++req.session.views;
27
- } else {
28
- req.session.views = 1;
29
- }
30
- res.send("Viewed <strong>" + req.session.views + "</strong> times.");
31
- });
32
-
33
- http.createServer(app).listen(9341, function() {
34
- console.log("Listening on %d", this.address().port);
35
- });