From b5c1a60ac3016eab89d7ae98dd33a21134ad4708 Mon Sep 17 00:00:00 2001 From: dead_horse Date: Wed, 2 Dec 2015 23:13:01 +0800 Subject: [PATCH] fix cookies' secure detect --- lib/application.js | 5 ++++- package.json | 2 +- test/context.js | 2 ++ test/context/cookies.js | 39 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 46 insertions(+), 2 deletions(-) diff --git a/lib/application.js b/lib/application.js index b544aee..5750d96 100644 --- a/lib/application.js +++ b/lib/application.js @@ -157,7 +157,10 @@ app.createContext = function(req, res){ response.request = request; context.onerror = context.onerror.bind(context); context.originalUrl = request.originalUrl = req.url; - context.cookies = new Cookies(req, res, this.keys); + context.cookies = new Cookies(req, res, { + keys: this.keys, + secure: request.secure + }); context.accept = request.accept = accepts(req); context.state = {}; return context; diff --git a/package.json b/package.json index 7db5032..438f22a 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "composition": "^2.1.1", "content-disposition": "~0.5.0", "content-type": "^1.0.0", - "cookies": "~0.5.0", + "cookies": "~0.6.1", "debug": "*", "delegates": "^1.0.0", "destroy": "^1.0.3", diff --git a/test/context.js b/test/context.js index 87b4bd8..f936762 100644 --- a/test/context.js +++ b/test/context.js @@ -8,6 +8,8 @@ exports = module.exports = function(req, res){ var socket = new Stream.Duplex(); req = req || { headers: {}, socket: socket, __proto__: Stream.Readable.prototype }; res = res || { _headers: {}, socket: socket, __proto__: Stream.Writable.prototype }; + req.socket = req.socket || socket; + res.socket = res.socket || socket; res.getHeader = function(k){ return res._headers[k.toLowerCase()] }; res.setHeader = function(k, v){ res._headers[k.toLowerCase()] = v }; res.removeHeader = function(k, v){ delete res._headers[k.toLowerCase()] }; diff --git a/test/context/cookies.js b/test/context/cookies.js index 9097bf1..ca9a9b5 100644 --- a/test/context/cookies.js +++ b/test/context/cookies.js @@ -80,4 +80,43 @@ describe('ctx.cookies.set()', function(){ }) }) }) + + describe('with secure', function(){ + it('should get secure from request', function(done){ + var app = koa(); + + app.proxy = true; + app.keys = ['a', 'b']; + + app.use(function *(next){ + this.cookies.set('name', 'jon', { signed: true }); + this.status = 204; + }) + + var server = app.listen(); + + request(server) + .get('/') + .set('x-forwarded-proto', 'https') // mock secure + .expect(204) + .end(function(err, res){ + if (err) return done(err); + + var cookies = res.headers['set-cookie']; + cookies.some(function(cookie){ + return /^name=/.test(cookie); + }).should.be.ok; + + cookies.some(function(cookie){ + return /^name\.sig=/.test(cookie); + }).should.be.ok; + + cookies.every(function(cookie){ + return /secure/.test(cookie); + }).should.be.ok; + + done(); + }) + }) + }) })