pax_global_header00006660000000000000000000000064123653476720014531gustar00rootroot0000000000000052 comment=2dcb71f130a7eaafd16e71b9af70debe11d4c93f cookies-0.5.0/000077500000000000000000000000001236534767200131675ustar00rootroot00000000000000cookies-0.5.0/.gitignore000066400000000000000000000000151236534767200151530ustar00rootroot00000000000000node_modules cookies-0.5.0/.npmignore000066400000000000000000000000221236534767200151600ustar00rootroot00000000000000test/ .travis.yml cookies-0.5.0/.travis.yml000066400000000000000000000001771236534767200153050ustar00rootroot00000000000000language: node_js node_js: - "0.8" - "0.10" - "0.11" matrix: allow_failures: - node_js: "0.11" fast_finish: true cookies-0.5.0/History.md000066400000000000000000000016361236534767200151600ustar00rootroot000000000000000.5.0 / 2014-07-27 ================== * Integrate with `req.protocol` for secure cookies * Support `maxAge` as well as `maxage` 0.4.1 / 2014-05-07 ================== * Update package for repo move 0.4.0 / 2014-01-31 ================== * Allow passing an array of strings as keys 0.3.8-0.2.0 =========== * TODO: write down history for these releases 0.1.6 / 2011-03-01 ================== * SSL cookies secure by default * Use httpOnly by default unless explicitly false 0.1.5 / 2011-02-26 ================== * Delete sig cookie if signed cookie is deleted 0.1.4 / 2011-02-26 ================== * Always set path 0.1.3 / 2011-02-26 ================== * Add sensible defaults for path 0.1.2 / 2011-02-26 ================== * Inherit cookie properties to signature cookie 0.1.1 / 2011-02-25 ================== * Readme updates 0.1.0 / 2011-02-25 ================== * Initial release cookies-0.5.0/LICENSE.txt000066400000000000000000000021051236534767200150100ustar00rootroot00000000000000(The MIT License) Copyright (c) 2014 Jed Schmidt, http://jed.is/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. cookies-0.5.0/README.md000066400000000000000000000154501236534767200144530ustar00rootroot00000000000000Cookies ======= [![NPM Version](https://badge.fury.io/js/cookies.svg)](https://badge.fury.io/js/cookies) [![Build Status](https://travis-ci.org/expressjs/cookies.svg?branch=master)](https://travis-ci.org/expressjs/cookies) Cookies is a [node.js](http://nodejs.org/) module for getting and setting HTTP(S) cookies. Cookies can be signed to prevent tampering, using [Keygrip](https://github.com/expressjs/keygrip). It can be used with the built-in node.js HTTP library, or as Connect/Express middleware. ## Requirements * [node.js](http://nodejs.org/), tested with 0.8 and 0.10 ## Install $ npm install cookies ## Features * **Lazy**: Since cookie verification against multiple keys could be expensive, cookies are only verified lazily when accessed, not eagerly on each request. * **Secure**: All cookies are `httponly` by default, and cookies sent over SSL are `secure` by default. An error will be thrown if you try to send secure cookies over an insecure socket. * **Unobtrusive**: Signed cookies are stored the same way as unsigned cookies, instead of in an obfuscated signing format. An additional signature cookie is stored for each signed cookie, using a standard naming convention (_cookie-name_`.sig`). This allows other libraries to access the original cookies without having to know the signing mechanism. * **Agnostic**: This library is optimized for use with [Keygrip](https://github.com/expressjs/keygrip), but does not require it; you can implement your own signing scheme instead if you like and use this library only to read/write cookies. Factoring the signing into a separate library encourages code reuse and allows you to use the same signing library for other areas where signing is needed, such as in URLs. ## API ### cookies = new Cookies( request, response, keys ) This creates a cookie jar corresponding to the current _request_ and _response_. A [Keygrip](https://github.com/expressjs/keygrip) object or an array of keys can optionally be passed as the third argument _keygrip_ to enable cryptographic signing based on SHA1 HMAC, using rotated credentials. Note that since this only saves parameters without any other processing, it is very lightweight. Cookies are only parsed on demand when they are accessed. ### express.createServer( Cookies.express( keys ) ) This adds cookie support as a Connect middleware layer for use in Express apps, allowing inbound cookies to be read using `req.cookies.get` and outbound cookies to be set using `res.cookies.set`. ### cookies.get( name, [ options ] ) This extracts the cookie with the given name from the `Cookie` header in the request. If such a cookie exists, its value is returned. Otherwise, nothing is returned. `{ signed: true }` can optionally be passed as the second parameter _options_. In this case, a signature cookie (a cookie of same name ending with the `.sig` suffix appended) is fetched. If no such cookie exists, nothing is returned. If the signature cookie _does_ exist, the provided [Keygrip](https://github.com/expressjs/keygrip) object is used to check whether the hash of _cookie-name_=_cookie-value_ matches that of any registered key: * If the signature cookie hash matches the first key, the original cookie value is returned. * If the signature cookie hash matches any other key, the original cookie value is returned AND an outbound header is set to update the signature cookie's value to the hash of the first key. This enables automatic freshening of signature cookies that have become stale due to key rotation. * If the signature cookie hash does not match any key, nothing is returned, and an outbound header with an expired date is used to delete the cookie. ### cookies.set( name, [ value ], [ options ] ) This sets the given cookie in the response and returns the current context to allow chaining. If the _value_ is omitted, an outbound header with an expired date is used to delete the cookie. If the _options_ object is provided, it will be used to generate the outbound cookie header as follows: * `maxAge`: a number representing the milliseconds from `Date.now()` for expiry * `expires`: a `Date` object indicating the cookie's expiration date (expires at the end of session by default). * `path`: a string indicating the path of the cookie (`/` by default). * `domain`: a string indicating the domain of the cookie (no default). * `secure`: a boolean indicating whether the cookie is only to be sent over HTTPS (`false` by default for HTTP, `true` by default for HTTPS). * `secureProxy`: a boolean indicating whether the cookie is only to be sent over HTTPS (use this if you handle SSL not in your node process). * `httpOnly`: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (`true` by default). * `signed`: a boolean indicating whether the cookie is to be signed (`false` by default). If this is true, another cookie of the same name with the `.sig` suffix appended will also be sent, with a 27-byte url-safe base64 SHA1 value representing the hash of _cookie-name_=_cookie-value_ against the first [Keygrip](https://github.com/expressjs/keygrip) key. This signature key is used to detect tampering the next time a cookie is received. * `overwrite`: a boolean indicating whether to overwrite previously set cookies of the same name (`false` by default). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie. ## Example ```javascript var http = require( "http" ) var Cookies = require( "cookies" ) server = http.createServer( function( req, res ) { var cookies = new Cookies( req, res, keys ) , unsigned, signed, tampered if ( req.url == "/set" ) { cookies // set a regular cookie .set( "unsigned", "foo", { httpOnly: false } ) // set a signed cookie .set( "signed", "bar", { signed: true } ) // mimic a signed cookie, but with a bogus signature .set( "tampered", "baz" ) .set( "tampered.sig", "bogus" ) res.writeHead( 302, { "Location": "/" } ) return res.end( "Now let's check." ) } unsigned = cookies.get( "unsigned" ) signed = cookies.get( "signed", { signed: true } ) tampered = cookies.get( "tampered", { signed: true } ) assert.equal( unsigned, "foo" ) assert.equal( signed, "bar" ) assert.notEqual( tampered, "baz" ) assert.equal( tampered, undefined ) res.writeHead( 200, { "Content-Type": "text/plain" } ) res.end( "unsigned expected: foo\n\n" + "unsigned actual: " + unsigned + "\n\n" + "signed expected: bar\n\n" + "signed actual: " + signed + "\n\n" + "tampered expected: undefined\n\n"+ "tampered: " + tampered + "\n\n" ) }) ``` Copyright --------- Copyright (c) 2014 Jed Schmidt. See LICENSE.txt for details. Send any questions or comments [here](http://twitter.com/jedschmidt). cookies-0.5.0/lib/000077500000000000000000000000001236534767200137355ustar00rootroot00000000000000cookies-0.5.0/lib/cookies.js000066400000000000000000000100461236534767200157300ustar00rootroot00000000000000var Keygrip = require('keygrip') var http = require('http') var cache = {} function Cookies(request, response, keys) { if (!(this instanceof Cookies)) return new Cookies(request, response, keys) this.request = request this.response = response if (keys) { // array of key strings if (Array.isArray(keys)) this.keys = new Keygrip(keys) // any keygrip constructor to allow different versions else if (keys.constructor && keys.constructor.name === 'Keygrip') this.keys = keys } } Cookies.prototype = { get: function(name, opts) { var sigName = name + ".sig" , header, match, value, remote, data, index , signed = opts && opts.signed !== undefined ? opts.signed : !!this.keys header = this.request.headers["cookie"] if (!header) return match = header.match(getPattern(name)) if (!match) return value = match[1] if (!opts || !signed) return value remote = this.get(sigName) if (!remote) return data = name + "=" + value if (!this.keys) throw new Error('.keys required for signed cookies'); index = this.keys.index(data, remote) if (index < 0) { this.set(sigName, null, {path: "/", signed: false }) } else { index && this.set(sigName, this.keys.sign(data), { signed: false }) return value } }, set: function(name, value, opts) { var res = this.response , req = this.request , headers = res.getHeader("Set-Cookie") || [] , secure = req.protocol === 'https' || req.connection.encrypted , cookie = new Cookie(name, value, opts) , signed = opts && opts.signed !== undefined ? opts.signed : !!this.keys if (typeof headers == "string") headers = [headers] if (!secure && opts && opts.secure) { throw new Error('Cannot send secure cookie over unencrypted connection') } cookie.secure = secure if (opts && "secure" in opts) cookie.secure = opts.secure if (opts && "secureProxy" in opts) cookie.secure = opts.secureProxy headers = pushCookie(headers, cookie) if (opts && signed) { if (!this.keys) throw new Error('.keys required for signed cookies'); cookie.value = this.keys.sign(cookie.toString()) cookie.name += ".sig" headers = pushCookie(headers, cookie) } var setHeader = res.set ? http.OutgoingMessage.prototype.setHeader : res.setHeader setHeader.call(res, 'Set-Cookie', headers) return this } } function Cookie(name, value, attrs) { value || (this.expires = new Date(0)) this.name = name this.value = value || "" for (var name in attrs) this[name] = attrs[name] } Cookie.prototype = { path: "/", expires: undefined, domain: undefined, httpOnly: true, secure: false, overwrite: false, toString: function() { return this.name + "=" + this.value }, toHeader: function() { var header = this.toString() if (this.maxAge) this.expires = new Date(Date.now() + this.maxAge); if (this.path ) header += "; path=" + this.path if (this.expires ) header += "; expires=" + this.expires.toUTCString() if (this.domain ) header += "; domain=" + this.domain if (this.secure ) header += "; secure" if (this.httpOnly ) header += "; httponly" return header } } // back-compat so maxage mirrors maxAge Object.defineProperty(Cookie.prototype, 'maxage', { configurable: true, enumerable: true, get: function () { return this.maxAge }, set: function (val) { return this.maxAge = val } }); function getPattern(name) { if (cache[name]) return cache[name] return cache[name] = new RegExp( "(?:^|;) *" + name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + "=([^;]*)" ) } function pushCookie(cookies, cookie) { if (cookie.overwrite) { cookies = cookies.filter(function(c) { return c.indexOf(cookie.name+'=') !== 0 }) } cookies.push(cookie.toHeader()) return cookies } Cookies.connect = Cookies.express = function(keys) { return function(req, res, next) { req.cookies = res.cookies = new Cookies(req, res, keys) next() } } Cookies.Cookie = Cookie module.exports = Cookies cookies-0.5.0/package.json000066400000000000000000000007721236534767200154630ustar00rootroot00000000000000{ "name": "cookies", "version": "0.5.0", "description": "Cookies, optionally signed using Keygrip.", "main": "./lib/cookies", "dependencies": { "keygrip": "~1.0.0" }, "devDependencies": { "express": "*", "restify": "*", "supertest": "0", "mocha": "1" }, "engines": { "node": ">= 0.8.0" }, "license": "MIT", "author": "Jed Schmidt (http://jed.is)", "repository": "expressjs/cookies", "scripts": { "test": "mocha --reporter spec" } } cookies-0.5.0/test/000077500000000000000000000000001236534767200141465ustar00rootroot00000000000000cookies-0.5.0/test/express.js000066400000000000000000000077011236534767200162020ustar00rootroot00000000000000 var assert = require( "assert" ) , express = require( "express" ) , http = require( "http" ) , keys = require( "keygrip" )(['a', 'b']) , cookies = require( "../" ).express , request = require('supertest') describe('Express', function () { var server var header before(function setup() { var app = express() app.use( cookies( keys ) ) app.get( "/set", function(req, res) { res.cookies // set a regular cookie .set( "unsigned", "foo", { signed:false, httpOnly: false } ) // set a signed cookie .set( "signed", "bar", { signed: true } ) // mimic a signed cookie, but with a bogus signature .set( "tampered", "baz" ) .set( "tampered.sig", "bogus" ) // set a cookie that will be overwritten .set( "overwrite", "old-value", { signed: true } ) .set( "overwrite", "new-value", { overwrite: true, signed: true } ) res.writeHead(302, {Location: "/"}) res.end() }) app.get("/", function(req, res) { var unsigned = req.cookies.get( "unsigned" ) , signed = req.cookies.get( "signed", { signed: true } ) , tampered = req.cookies.get( "tampered", { signed: true } ) , overwrite = req.cookies.get( "overwrite", { signed: true } ) assert.equal( unsigned, "foo" ) assert.equal( req.cookies.get( "unsigned.sig", { signed:false } ), undefined) assert.equal( signed, "bar" ) assert.equal( req.cookies.get( "signed.sig", { signed: false } ), keys.sign('signed=bar') ) assert.notEqual( tampered, "baz" ) assert.equal( tampered, undefined ) assert.equal( overwrite, "new-value" ) assert.equal( req.cookies.get( "overwrite.sig", { signed:false } ), keys.sign('overwrite=new-value') ) assert.equal(res.getHeader('Set-Cookie'), 'tampered.sig=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; httponly') res.send( "unsigned expected: foo\n" + "unsigned actual: " + unsigned + "\n\n" + "signed expected: bar\n" + "signed actual: " + signed + "\n\n" + "tampered expected: undefined\n"+ "tampered: " + tampered + "\n" ) }) server = require('http').createServer(app).listen() }) it('should set cookies', function (done) { request(server) .get('/set') .expect(302, function (err, res) { if (err) return done(err) header = res.headers['set-cookie'] assert.equal(header.length, 7) done() }) }) it('should get cookies', function (done) { request(server) .get('/') .set('Cookie', header.join(';')) .expect(200, done) }) describe('when "secure: true"', function () { it('should not set when not secure', function (done) { var app = express() app.set('env', 'test') app.use(cookies(keys)) app.use(function (req, res) { res.cookies.set('foo', 'bar', {secure: true}) res.end() }) request(app) .get('/') .expect(500, /Cannot send secure cookie over unencrypted connection/, done) }) it('should set for secure connection', function (done) { var app = express() app.set('env', 'test') app.use(cookies(keys)) app.use(function (req, res, next) { res.connection.encrypted = true next() }) app.use(function (req, res) { res.cookies.set('foo', 'bar', {secure: true}) res.end() }) request(app) .get('/') .expect('Set-Cookie', /foo=bar.*secure/i) .expect(200, done) }) it('should set for proxy settings', function (done) { var app = express() app.set('env', 'test') app.set('trust proxy', true) app.use(cookies(keys)) app.use(function (req, res) { res.cookies.set('foo', 'bar', {secure: true}) res.end() }) request(app) .get('/') .set('X-Forwarded-Proto', 'https') .expect('Set-Cookie', /foo=bar.*secure/i) .expect(200, done) }) }) }) cookies-0.5.0/test/http.js000066400000000000000000000051721236534767200154700ustar00rootroot00000000000000 var assert = require( "assert" ) , http = require( "http" ) , keys = require( "keygrip" )(['a', 'b']) , Cookies = require( "../" ) , request = require('supertest') describe('HTTP', function () { var server var header before(function setup() { server = http.createServer( function( req, res ) { var cookies = new Cookies( req, res, keys ) , unsigned, signed, tampered, overwrite if ( req.url == "/set" ) { cookies // set a regular cookie .set( "unsigned", "foo", { signed:false, httpOnly: false } ) // set a signed cookie .set( "signed", "bar", { signed: true } ) // mimic a signed cookie, but with a bogus signature .set( "tampered", "baz" ) .set( "tampered.sig", "bogus" ) // set a cookie that will be overwritten .set( "overwrite", "old-value", { signed: true } ) .set( "overwrite", "new-value", { overwrite: true, signed: true } ) res.writeHead( 302, { "Location": "/" } ) return res.end( "Now let's check." ) } unsigned = cookies.get( "unsigned" ) signed = cookies.get( "signed", { signed: true } ) tampered = cookies.get( "tampered", { signed: true } ) overwrite = cookies.get( "overwrite", { signed: true } ) assert.equal( unsigned, "foo" ) assert.equal( cookies.get( "unsigned.sig", { signed:false } ), undefined) assert.equal( signed, "bar" ) assert.equal( cookies.get( "signed.sig", { signed: false } ), keys.sign('signed=bar') ) assert.notEqual( tampered, "baz" ) assert.equal( tampered, undefined ) assert.equal( overwrite, "new-value" ) assert.equal( cookies.get( "overwrite.sig", { signed:false } ), keys.sign('overwrite=new-value') ) assert.equal(res.getHeader('Set-Cookie'), 'tampered.sig=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; httponly') res.writeHead( 200, { "Content-Type": "text/plain" } ) res.end( "unsigned expected: foo\n" + "unsigned actual: " + unsigned + "\n\n" + "signed expected: bar\n" + "signed actual: " + signed + "\n\n" + "tampered expected: undefined\n"+ "tampered: " + tampered + "\n" ) }).listen() }) it('should set cookies', function (done) { request(server) .get('/set') .expect(302, function (err, res) { if (err) return done(err) header = res.headers['set-cookie'] assert.equal(header.length, 7) done() }) }) it('should get cookies', function (done) { request(server) .get('/') .set('Cookie', header.join(';')) .expect(200, done) }) }) cookies-0.5.0/test/restify.js000066400000000000000000000052521236534767200161750ustar00rootroot00000000000000var assert = require('assert'), restify = require('restify'), keys = require('keygrip')(['a', 'b']), http = require('http'), Cookies = require('../'), request = require('supertest') describe('Restify', function () { var header var server before(function setup(done) { server = restify.createServer() server.get('/set', function (req, res) { setCookies(req, res) res.json({ status : 'ok'}) }) server.get('/get', function (req, res) { assertCookies(req, res) res.send(200) }) server.listen(done) }) it('should set cookies', function (done) { request(server) .get('/set') .expect(200, function (err, res) { if (err) return done(err) header = res.headers['set-cookie'] assertSetCookieHeader(header) done() }) }) it('should get cookies', function (done) { request(server) .get('/get') .set('Cookie', header.join(';')) .expect(200, done) }) }) function setCookies(req, res) { var cookies = new Cookies(req, res, keys) cookies .set('unsigned', 'foo', { signed:false, httpOnly: false }) .set('signed', 'bar', { signed: true }) .set('tampered', 'baz') .set('tampered.sig', 'bogus') .set('overwrite', 'old-value', { signed: true }) .set('overwrite', 'new-value', { overwrite: true, signed: true }) } function assertCookies(req, res) { var cookies = new Cookies(req, res, keys) var unsigned = cookies.get('unsigned'), signed = cookies.get('signed', { signed: true }), tampered = cookies.get('tampered', { signed: true }), overwrite = cookies.get('overwrite', { signed: true }) assert.equal(unsigned, 'foo') assert.equal(cookies.get('unsigned.sig', { signed:false }), undefined) assert.equal(signed, 'bar') assert.equal(cookies.get('signed.sig', { signed: false }), keys.sign('signed=bar')) assert.notEqual(tampered, 'baz') assert.equal(tampered, undefined) assert.equal(overwrite, 'new-value') assert.equal(cookies.get('overwrite.sig', { signed:false }), keys.sign('overwrite=new-value')) assert.equal(res.getHeader('Set-Cookie'), 'tampered.sig=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; httponly') } function assertSetCookieHeader(header) { assert.equal(header.length, 7) assert.equal(header[0], 'unsigned=foo; path=/') assert.equal(header[1], 'signed=bar; path=/; httponly') assert.ok(/^signed\.sig=.{27}; path=\/; httponly$/.test(header[2])) assert.equal(header[3], 'tampered=baz; path=/; httponly') assert.equal(header[4], 'tampered.sig=bogus; path=/; httponly') assert.equal(header[5], 'overwrite=new-value; path=/; httponly') assert.ok(/^overwrite\.sig=.{27}; path=\/; httponly$/.test(header[6])) }