pax_global_header00006660000000000000000000000064130764747710014532gustar00rootroot0000000000000052 comment=b621a4ad49cf517ae43d6060f4ceb8306ac22506 node-client-sessions-0.8.0/000077500000000000000000000000001307647477100156045ustar00rootroot00000000000000node-client-sessions-0.8.0/.gitignore000066400000000000000000000000171307647477100175720ustar00rootroot00000000000000node_modules *~node-client-sessions-0.8.0/.jshintrc000066400000000000000000000007411307647477100174330ustar00rootroot00000000000000{ "bitwise": false, "boss": true, "browser": true, "camelcase": true, "curly": true, "esnext": true, "eqeqeq": true, "eqnull": true, "expr": true, "forin": false, "indent": 2, "latedef": true, "laxbreak": true, "laxcomma": true, "maxcomplexity": 10, "maxlen": 80, "maxerr": 100, "node": true, "noarg": true, "passfail": false, "shadow": true, "strict": false, "supernew": false, "trailing": true, "undef": true, "unused": true } node-client-sessions-0.8.0/.travis.yml000066400000000000000000000000661307647477100177170ustar00rootroot00000000000000language: node_js node_js: - "4" - "6" - stable node-client-sessions-0.8.0/ChangeLog000066400000000000000000000027121307647477100173600ustar00rootroot000000000000000.7.0 - * add `session.destroy()` alias for `session.reset()` * invalid base64 will return undefined instead of throw 0.6.0 - * add secret can also be a Buffer * add `encryptonKey` and `signatureKey` options, to be used instead of `secret` * add `encryptionAlgorithm` and `signatureAlgorithm` options * fix zero out buffers during encryption * docs for new crypto options * docs describing how crypto is used 0.5.0 - * fix dirty checking for nested objects. req.session.foo.bar = 'baz' now works. * fix setting req.session = someObj will update from someObj * removed usage of Proxy, now uses getters/setters 0.4.1 - * change to writeHead, no longer depending on connect's res.on('header') event * fix checking existence of res.socket before checking res.socket.encrypted * documentation added js syntax highlighting 0.4.0 - * add activeDuration with default to 5 minutes * add checking for native Proxy before using node-proxy * add cookie.ephemeral option, default false * add constant-time check * adds self-aware check. wont override req.session if already exists * fix wrong handled of utf8 replacement character * fix http expiry of cookie to match duration * fix updating cookie expiry whenever duration/createdAt changes 0.3.1 - * documentation update * support opt.requestKey to allow usage of a key other than cookie name 0.1.0 - * node 0.10.x support * fix bug in .reset() - session would load from an existing cookie - thanks @khmelichek node-client-sessions-0.8.0/LICENSE000066400000000000000000000405261307647477100166200ustar00rootroot00000000000000Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. node-client-sessions-0.8.0/README.md000066400000000000000000000211731307647477100170670ustar00rootroot00000000000000[![build status](https://secure.travis-ci.org/mozilla/node-client-sessions.png)](http://travis-ci.org/mozilla/node-client-sessions) client-sessions is connect middleware that implements sessions in encrypted tamper-free cookies. For a complete introduction to encrypted client side sessions, refer to [Francois Marier's blog post on the subject][]; [Francois Marier's blog post on the subject]: https://hacks.mozilla.org/2012/12/using-secure-client-side-sessions-to-build-simple-and-scalable-node-js-applications-a-node-js-holiday-season-part-3/ **NOTE:** It is not recommended using both this middleware and connect's built-in session middleware. ## Installation `npm install client-sessions` ## Usage Basic usage: ```js var sessions = require("client-sessions"); app.use(sessions({ cookieName: 'mySession', // cookie name dictates the key name added to the request object secret: 'blargadeeblargblarg', // should be a large unguessable string duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms activeDuration: 1000 * 60 * 5 // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds })); app.use(function(req, res, next) { if (req.mySession.seenyou) { res.setHeader('X-Seen-You', 'true'); } else { // setting a property will automatically cause a Set-Cookie response // to be sent req.mySession.seenyou = true; res.setHeader('X-Seen-You', 'false'); } }); ``` You can control more specific cookie behavior during setup: ```js app.use(sessions({ cookieName: 'mySession', // cookie name dictates the key name added to the request object secret: 'blargadeeblargblarg', // should be a large unguessable string duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms cookie: { path: '/api', // cookie will only be sent to requests under '/api' maxAge: 60000, // duration of the cookie in milliseconds, defaults to duration above ephemeral: false, // when true, cookie expires when the browser closes httpOnly: true, // when true, cookie is not accessible from javascript secure: false // when true, cookie will only be sent over SSL. use key 'secureProxy' instead if you handle SSL not in your node process } })); ``` You can have multiple cookies: ```js // a 1 week session app.use(sessions({ cookieName: 'shopping_cart', secret: 'first secret', duration: 7 * 24 * 60 * 60 * 1000 })); // a 2 hour encrypted session app.use(sessions({ cookieName: 'authenticated', secret: 'first secret', duration: 2 * 60 * 60 * 1000 })); ``` In this example, there's a 2 hour authentication session, but shopping carts persist for a week. Finally, you can use requestKey to force the name where information can be accessed on the request object. ```js var sessions = require("client-sessions"); app.use(sessions({ cookieName: 'mySession', requestKey: 'forcedSessionKey', // requestKey overrides cookieName for the key name added to the request object. secret: 'blargadeeblargblarg', // should be a large unguessable string or Buffer duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms })); app.use(function(req, res, next) { // requestKey forces the session information to be // accessed via forcedSessionKey if (req.forcedSessionKey.seenyou) { res.setHeader('X-Seen-You', 'true'); } next(); }); ``` ## Cryptography A pair of encryption and signature keys are derived from the `secret` option via HMAC-SHA-256; the `secret` isn't used directly to encrypt or compute the MAC. The key-derivation function, in pseudocode: ```text encKey := HMAC-SHA-256(secret, 'cookiesession-encryption'); sigKey := HMAC-SHA-256(secret, 'cookiesession-signature'); ``` The **AES-256-CBC** cipher is used to encrypt the session contents, with an **HMAC-SHA-256** authentication tag (via **Encrypt-then-Mac** composition). A random 128-bit Initialization Vector (IV) is generated for each encryption operation (this is the AES block size regardless of the key size). The CBC-mode input is padded with the usual PKCS#5 scheme. In pseudocode, the encryption looks like the following, with `||` denoting concatenation. The `createdAt` and `duration` parameters are decimal strings. ```text sessionText := cookieName || '=' || sessionJson iv := secureRandom(16 bytes) ciphertext := AES-256-CBC(encKey, iv, sessionText) payload := iv || '.' || ciphertext || '.' || createdAt || '.' || duration hmac := HMAC-SHA-256(sigKey, payload) cookie := base64url(iv) || '.' || base64url(ciphertext) || '.' || createdAt || '.' || duration || '.' || base64url(hmac) ``` For decryption, a constant-time equality operation is used to verify the HMAC output to avoid the plausible timing attack. ### Advanced Cryptographic Options The defaults are secure, but may not suit your requirements. Some example scenarios: - You want to use randomly-generated keys instead of using the key-derivation function used in this module. - AES-256 is overkill for the type of data you store in the session (e.g. not personally-identifiable or sensitive) and you'd like to trade-off decreasing the security level for CPU economy. - SHA-256 is maybe too weak for your application and you want to have more MAC security by using SHA-512, which grows the size of your cookies slightly. If the defaults don't suit your needs, you can customize client-sessions. **Beware: Changing keys and/or algorithms will make previously-generated Cookies invalid!** #### Configuring Keys To configure independent encryption and signature (HMAC) keys: ```js app.use(sessions({ encryptionKey: loadFromKeyStore('session-encryption-key'), signatureKey: loadFromKeyStore('session-signature-key'), // ... other options discussed above ... })); ``` #### Configuring Algorithms To specify custom algorithms and keys: ```js app.use(sessions({ // use WEAKER-than-default encryption: encryptionAlgorithm: 'aes128', encryptionKey: loadFromKeyStore('session-encryption-key'), // use a SHORTER-than-default MAC: signatureAlgorithm: 'sha256-drop128', signatureKey: loadFromKeyStore('session-signature-key'), // ... other options discussed above ... })); ``` #### Encryption Algorithms Supported CBC-mode `encryptionAlgorithm`s (and key length requirements): | Cipher | Key length | | ------ | ---------- | | aes128 | 16 bytes | | aes192 | 24 bytes | | aes256 | 32 bytes | These key lengths are exactly as required by the [Advanced Encryption Standard](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard). #### Signature (HMAC) Algorithms Supported HMAC `signatureAlgorithm`s (and key length requirements): | HMAC | Minimum Key Length | Maximum Key Length | | -------------- | ------------------ | ------------------ | | sha256 | 32 bytes | 64 bytes | | sha256-drop128 | 32 bytes | 64 bytes | | sha384 | 48 bytes | 128 bytes | | sha384-drop192 | 48 bytes | 128 bytes | | sha512 | 64 bytes | 128 bytes | | sha512-drop256 | 64 bytes | 128 bytes | The HMAC key length requirements are derived from [RFC 2104 section 3](https://tools.ietf.org/html/rfc2104#section-3). The maximum key length can be exceeded, but it doesn't increase the security of the signature. The `-dropN` algorithms discard the latter half of the HMAC output, which provides some additional protection against SHA2 length-extension attacks on top of HMAC. The same technique is used in the upcoming [JSON Web Algorithms `AES_CBC_HMAC_SHA2` authenticated cipher](http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-19#section-5.2). #### Generating Keys One can easily generate both AES and HMAC-SHA2 keys via command line: `openssl rand -base64 32` for a 32-byte (256-bit) key. It's easy to then parse that output into a `Buffer`: ```js function loadKeyFromStore(name) { var text = myConfig.keys[name]; return new Buffer(text, 'base64'); } ``` #### Key Constraints If you specify `encryptionKey` or `signatureKey`, you must supply the other as well. The following constraints must be met or an `Error` will be thrown: 1. both keys must be `Buffer`s. 2. the keys must be _different_. 3. the encryption key are _exactly_ the length required (see above). 4. the signature key has _at least_ the length required (see above). Based on the above, please note that if you specify a `secret` _and_ a `signatureAlgorithm`, you need to use `sha256` or `sha256-drop128`. ## License > This Source Code Form is subject to the terms of the Mozilla Public > License, v. 2.0. If a copy of the MPL was not distributed with this > file, You can obtain one at http://mozilla.org/MPL/2.0/. node-client-sessions-0.8.0/lib/000077500000000000000000000000001307647477100163525ustar00rootroot00000000000000node-client-sessions-0.8.0/lib/client-sessions.js000066400000000000000000000402171307647477100220360ustar00rootroot00000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const Cookies = require("cookies"); const crypto = require("crypto"); const util = require("util"); const COOKIE_NAME_SEP = '='; const ACTIVE_DURATION = 1000 * 60 * 5; const KDF_ENC = 'cookiesession-encryption'; const KDF_MAC = 'cookiesession-signature'; /* map from cipher algorithm to exact key byte length */ const ENCRYPTION_ALGORITHMS = { aes128: 16, // implicit CBC mode aes192: 24, aes256: 32 }; const DEFAULT_ENCRYPTION_ALGO = 'aes256'; /* map from hmac algorithm to _minimum_ key byte length */ const SIGNATURE_ALGORITHMS = { 'sha256': 32, 'sha256-drop128': 32, 'sha384': 48, 'sha384-drop192': 48, 'sha512': 64, 'sha512-drop256': 64 }; const DEFAULT_SIGNATURE_ALGO = 'sha256'; function isObject(val) { return Object.prototype.toString.call(val) === '[object Object]'; } function base64urlencode(arg) { var s = arg.toString('base64'); s = s.split('=')[0]; // Remove any trailing '='s s = s.replace(/\+/g, '-'); // 62nd char of encoding s = s.replace(/\//g, '_'); // 63rd char of encoding // TODO optimize this; we can do much better return s; } function base64urldecode(arg) { var s = arg; s = s.replace(/-/g, '+'); // 62nd char of encoding s = s.replace(/_/g, '/'); // 63rd char of encoding switch (s.length % 4) { // Pad with trailing '='s case 0: break; // No pad chars in this case case 2: s += "=="; break; // Two pad chars case 3: s += "="; break; // One pad char default: throw new Error("Illegal base64url string!"); } return new Buffer(s, 'base64'); // Standard base64 decoder } function forceBuffer(binaryOrBuffer) { if (Buffer.isBuffer(binaryOrBuffer)) { return binaryOrBuffer; } else { return new Buffer(binaryOrBuffer, 'binary'); } } function deriveKey(master, type) { // eventually we want to use HKDF. For now we'll do something simpler. var hmac = crypto.createHmac('sha256', master); hmac.update(type); return forceBuffer(hmac.digest()); } function setupKeys(opts) { // derive two keys, one for signing one for encrypting, from the secret. if (!opts.encryptionKey) { opts.encryptionKey = deriveKey(opts.secret, KDF_ENC); } if (!opts.signatureKey) { opts.signatureKey = deriveKey(opts.secret, KDF_MAC); } if (!opts.signatureAlgorithm) { opts.signatureAlgorithm = DEFAULT_SIGNATURE_ALGO; } if (!opts.encryptionAlgorithm) { opts.encryptionAlgorithm = DEFAULT_ENCRYPTION_ALGO; } } function keyConstraints(opts) { if (!Buffer.isBuffer(opts.encryptionKey)) { throw new Error('encryptionKey must be a Buffer'); } if (!Buffer.isBuffer(opts.signatureKey)) { throw new Error('signatureKey must be a Buffer'); } if (constantTimeEquals(opts.encryptionKey, opts.signatureKey)) { throw new Error('Encryption and Signature keys must be different'); } var encAlgo = opts.encryptionAlgorithm; var required = ENCRYPTION_ALGORITHMS[encAlgo]; if (opts.encryptionKey.length !== required) { throw new Error( 'Encryption Key for '+encAlgo+' must be exactly '+required+' bytes '+ '('+(required*8)+' bits)' ); } var sigAlgo = opts.signatureAlgorithm; var minimum = SIGNATURE_ALGORITHMS[sigAlgo]; if (opts.signatureKey.length < minimum) { throw new Error( 'Encryption Key for '+sigAlgo+' must be at least '+minimum+' bytes '+ '('+(minimum*8)+' bits)' ); } } function constantTimeEquals(a, b) { // Ideally this would be a native function, so it's less sensitive to how the // JS engine might optimize. if (a.length !== b.length) { return false; } var ret = 0; for (var i = 0; i < a.length; i++) { ret |= a.readUInt8(i) ^ b.readUInt8(i); } return ret === 0; } // it's good cryptographic pracitice to not leave buffers with sensitive // contents hanging around. function zeroBuffer(buf) { for (var i = 0; i < buf.length; i++) { buf[i] = 0; } return buf; } function hmacInit(algo, key) { var match = algo.match(/^([^-]+)(?:-drop(\d+))?$/); var baseAlg = match[1]; var drop = match[2] ? parseInt(match[2], 10) : 0; var hmacAlg = crypto.createHmac(baseAlg, key); var origDigest = hmacAlg.digest; if (drop === 0) { // Before 0.10, crypto returns binary-encoded strings. Remove when dropping // 0.8 support. hmacAlg.digest = function() { return forceBuffer(origDigest.call(this)); }; } else { var N = drop / 8; // bits to bytes hmacAlg.digest = function dropN() { var result = forceBuffer(origDigest.call(this)); // Throw away the second half of the 512-bit result, leaving the first // 256-bits. var truncated = new Buffer(N); result.copy(truncated, 0, 0, N); zeroBuffer(result); return truncated; }; } return hmacAlg; } function computeHmac(opts, iv, ciphertext, duration, createdAt) { var hmacAlg = hmacInit(opts.signatureAlgorithm, opts.signatureKey); hmacAlg.update(iv); hmacAlg.update("."); hmacAlg.update(ciphertext); hmacAlg.update("."); hmacAlg.update(createdAt.toString()); hmacAlg.update("."); hmacAlg.update(duration.toString()); return hmacAlg.digest(); } function encode(opts, content, duration, createdAt){ // format will be: // iv.ciphertext.createdAt.duration.hmac if (!opts.cookieName) { throw new Error('cookieName option required'); } else if (String(opts.cookieName).indexOf(COOKIE_NAME_SEP) !== -1) { throw new Error('cookieName cannot include "="'); } setupKeys(opts); duration = duration || 24*60*60*1000; createdAt = createdAt || new Date().getTime(); // generate iv var iv = crypto.randomBytes(16); // encrypt with encryption key var plaintext = new Buffer( opts.cookieName + COOKIE_NAME_SEP + JSON.stringify(content), 'utf8' ); var cipher = crypto.createCipheriv( opts.encryptionAlgorithm, opts.encryptionKey, iv ); var ciphertextStart = forceBuffer(cipher.update(plaintext)); zeroBuffer(plaintext); var ciphertextEnd = forceBuffer(cipher.final()); var ciphertext = Buffer.concat([ciphertextStart, ciphertextEnd]); zeroBuffer(ciphertextStart); zeroBuffer(ciphertextEnd); // hmac it var hmac = computeHmac(opts, iv, ciphertext, duration, createdAt); var result = [ base64urlencode(iv), base64urlencode(ciphertext), createdAt, duration, base64urlencode(hmac) ].join('.'); zeroBuffer(iv); zeroBuffer(ciphertext); zeroBuffer(hmac); return result; } function decode(opts, content) { if (!opts.cookieName) { throw new Error("cookieName option required"); } // stop at any time if there's an issue var components = content.split("."); if (components.length !== 5) { return; } setupKeys(opts); var iv; var ciphertext; var hmac; try { iv = base64urldecode(components[0]); ciphertext = base64urldecode(components[1]); hmac = base64urldecode(components[4]); } catch (ignored) { cleanup(); return; } var createdAt = parseInt(components[2], 10); var duration = parseInt(components[3], 10); function cleanup() { if (iv) { zeroBuffer(iv); } if (ciphertext) { zeroBuffer(ciphertext); } if (hmac) { zeroBuffer(hmac); } if (expectedHmac) { // declared below zeroBuffer(expectedHmac); } } // make sure IV is right length if (iv.length !== 16) { cleanup(); return; } // check hmac var expectedHmac = computeHmac(opts, iv, ciphertext, duration, createdAt); if (!constantTimeEquals(hmac, expectedHmac)) { cleanup(); return; } // decrypt var cipher = crypto.createDecipheriv( opts.encryptionAlgorithm, opts.encryptionKey, iv ); var plaintext = cipher.update(ciphertext, 'binary', 'utf8'); plaintext += cipher.final('utf8'); var cookieName = plaintext.substring(0, plaintext.indexOf(COOKIE_NAME_SEP)); if (cookieName !== opts.cookieName) { cleanup(); return; } var result; try { result = { content: JSON.parse( plaintext.substring(plaintext.indexOf(COOKIE_NAME_SEP) + 1) ), createdAt: createdAt, duration: duration }; } catch (ignored) { } cleanup(); return result; } /* * Session object * * this should be implemented with proxies at some point */ function Session(req, res, cookies, opts) { this.req = req; this.res = res; this.cookies = cookies; this.opts = opts; if (opts.cookie.ephemeral && opts.cookie.maxAge) { throw new Error("you cannot have an ephemeral cookie with a maxAge."); } this.content = {}; this.json = JSON.stringify(this._content); this.loaded = false; this.dirty = false; // no need to initialize it, loadFromCookie will do // via reset() or unbox() this.createdAt = null; this.duration = opts.duration; this.activeDuration = opts.activeDuration; // support for maxAge if (opts.cookie.maxAge) { this.expires = new Date(new Date().getTime() + opts.cookie.maxAge); } else { this.updateDefaultExpires(); } // here, we check that the security bits are set correctly var secure = (res.socket && res.socket.encrypted) || (req.connection && req.connection.proxySecure); if (opts.cookie.secure && !secure) { throw new Error("you cannot have a secure cookie unless the socket is " + " secure or you declare req.connection.proxySecure to be true."); } } Session.prototype = { updateDefaultExpires: function() { if (this.opts.cookie.maxAge) { return; } if (this.opts.cookie.ephemeral) { this.expires = null; } else { var time = this.createdAt || new Date().getTime(); // the cookie should expire when it becomes invalid // we add an extra second because the conversion to a date // truncates the milliseconds this.expires = new Date(time + this.duration + 1000); } }, clearContent: function(keysToPreserve) { var self = this; Object.keys(this._content).forEach(function(k) { // exclude this key if it's meant to be preserved if (keysToPreserve && (keysToPreserve.indexOf(k) > -1)) { return; } delete self._content[k]; }); }, reset: function(keysToPreserve) { this.clearContent(keysToPreserve); this.createdAt = new Date().getTime(); this.duration = this.opts.duration; this.updateDefaultExpires(); this.dirty = true; this.loaded = true; }, // alias for `reset` function for compatibility destroy: function(){ this.reset(); }, setDuration: function(newDuration, ephemeral) { if (ephemeral && this.opts.cookie.maxAge) { throw new Error("you cannot have an ephemeral cookie with a maxAge."); } if (!this.loaded) { this.loadFromCookie(true); } this.dirty = true; this.duration = newDuration; this.createdAt = new Date().getTime(); this.opts.cookie.ephemeral = ephemeral; this.updateDefaultExpires(); }, // take the content and do the encrypt-and-sign // boxing builds in the concept of createdAt box: function() { return encode(this.opts, this._content, this.duration, this.createdAt); }, unbox: function(content) { this.clearContent(); var unboxed = decode(this.opts, content); if (!unboxed) { return; } var self = this; Object.keys(unboxed.content).forEach(function(k) { self._content[k] = unboxed.content[k]; }); this.createdAt = unboxed.createdAt; this.duration = unboxed.duration; this.updateDefaultExpires(); }, updateCookie: function() { if (this.isDirty()) { // support for adding/removing cookie expires this.opts.cookie.expires = this.expires; try { this.cookies.set(this.opts.cookieName, this.box(), this.opts.cookie); } catch (x) { // this really shouldn't happen. Right now it happens if secure is set // but cookies can't determine that the connection is secure. } } }, loadFromCookie: function(forceReset) { var cookie = this.cookies.get(this.opts.cookieName); if (cookie) { this.unbox(cookie); var expiresAt = this.createdAt + this.duration; var now = Date.now(); // should we reset this session? if (expiresAt < now) { this.reset(); // if expiration is soon, push back a few minutes to not interrupt user } else if (expiresAt - now < this.activeDuration) { this.createdAt += this.activeDuration; this.dirty = true; this.updateDefaultExpires(); } } else { if (forceReset) { this.reset(); } else { return false; // didn't actually load the cookie } } this.loaded = true; this.json = JSON.stringify(this._content); return true; }, isDirty: function() { return this.dirty || (this.json !== JSON.stringify(this._content)); } }; Object.defineProperty(Session.prototype, 'content', { get: function getContent() { if (!this.loaded) { this.loadFromCookie(); } return this._content; }, set: function setContent(value) { Object.defineProperty(value, 'reset', { enumerable: false, value: this.reset.bind(this) }); Object.defineProperty(value, 'destroy', { enumerable: false, value: this.destroy.bind(this) }); Object.defineProperty(value, 'setDuration', { enumerable: false, value: this.setDuration.bind(this) }); this._content = value; } }); function clientSessionFactory(opts) { if (!opts) { throw new Error("no options provided, some are required"); } if (!(opts.secret || (opts.encryptionKey && opts.signatureKey))) { throw new Error("cannot set up sessions without a secret "+ "or encryptionKey/signatureKey pair"); } // defaults opts.cookieName = opts.cookieName || "session_state"; opts.duration = opts.duration || 24*60*60*1000; opts.activeDuration = 'activeDuration' in opts ? opts.activeDuration : ACTIVE_DURATION; var encAlg = opts.encryptionAlgorithm || DEFAULT_ENCRYPTION_ALGO; encAlg = encAlg.toLowerCase(); if (!ENCRYPTION_ALGORITHMS[encAlg]) { throw new Error('invalid encryptionAlgorithm, supported are: '+ Object.keys(ENCRYPTION_ALGORITHMS).join(', ')); } opts.encryptionAlgorithm = encAlg; var sigAlg = opts.signatureAlgorithm || DEFAULT_SIGNATURE_ALGO; sigAlg = sigAlg.toLowerCase(); if (!SIGNATURE_ALGORITHMS[sigAlg]) { throw new Error('invalid signatureAlgorithm, supported are: '+ Object.keys(SIGNATURE_ALGORITHMS).join(', ')); } opts.signatureAlgorithm = sigAlg; // set up cookie defaults opts.cookie = opts.cookie || {}; if (typeof opts.cookie.httpOnly === 'undefined') { opts.cookie.httpOnly = true; } // let's not default to secure just yet, // as this depends on the socket being secure, // which is tricky to determine if proxied. /* if (typeof(opts.cookie.secure) == 'undefined') opts.cookie.secure = true; */ setupKeys(opts); keyConstraints(opts); const propertyName = opts.requestKey || opts.cookieName; return function clientSession(req, res, next) { if (propertyName in req) { return next(); //self aware } var cookies = new Cookies(req, res); var rawSession; try { rawSession = new Session(req, res, cookies, opts); } catch (x) { // this happens only if there's a big problem process.nextTick(function() { next(new Error("client-sessions error: " + x.toString())); }); return; } Object.defineProperty(req, propertyName, { get: function getSession() { return rawSession.content; }, set: function setSession(value) { if (isObject(value)) { rawSession.content = value; } else { throw new TypeError("cannot set client-session to non-object"); } } }); var writeHead = res.writeHead; res.writeHead = function () { rawSession.updateCookie(); return writeHead.apply(res, arguments); }; next(); }; } module.exports = clientSessionFactory; // Expose encode and decode method module.exports.util = { encode: encode, decode: decode, computeHmac: computeHmac }; node-client-sessions-0.8.0/package.json000066400000000000000000000012521307647477100200720ustar00rootroot00000000000000{ "name" : "client-sessions", "version" : "0.8.0", "description" : "secure sessions stored in cookies", "main" : "lib/client-sessions", "repository" : { "type" : "git", "url" : "https://github.com/mozilla/node-client-sessions" }, "dependencies" : { "cookies" : "^0.7.0" }, "devDependencies": { "vows": "0.8.1", "express": "4.15.2", "request": "2.81.0" }, "author" : { "name" : "Ben Adida", "email" : "ben@adida.net" }, "scripts" : { "test": "vows --spec" }, "engines": { "node": ">= 0.8.0" }, "license": "MPL-2.0", "bugs": "https://github.com/mozilla/node-client-sessions/issues" } node-client-sessions-0.8.0/test/000077500000000000000000000000001307647477100165635ustar00rootroot00000000000000node-client-sessions-0.8.0/test/all-test.js000066400000000000000000001111521307647477100206470ustar00rootroot00000000000000// a NODE_ENV of test will supress console output to stderr which // connect likes to do when next() is called with a non-falsey error // message. We test such codepaths here. process.env.NODE_ENV = 'test'; var vows = require("vows"), assert = require("assert"), cookieSessions = require("../lib/client-sessions"), express = require("express"), request = require("request"); // screw you Vows process.on('uncaughtException', function(err) { console.error('Uncaught:', err.stack); process.exit(1); }); function create_app() { // set up the session middleware // XXX: same secret is important for a test var middleware = cookieSessions({ cookieName: 'session', secret: 'yo', activeDuration: 0, cookie: { maxAge: 5000 } }); var app = express(); app.use(middleware); // set up a second cookie storage middleware var secureStoreMiddleware = cookieSessions({ cookieName: 'securestore', secret: 'yo', activeDuration: 0, cookie: { maxAge: 5000 } }); app.use(secureStoreMiddleware); return app; } var startingPort = 9000; function createBrowser(server) { var jar = request.jar(); var browser = { get: function(url, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } if (typeof callback !== 'function') { throw new TypeError('callback must be a function'); } // Ensure that server is ready to take connections if (server && !server.__listening) { (server.__deferred = server.__deferred || []).push([url, options, callback]); if (!server.__started) { server.__listener = server.listen(server.__port = ++startingPort, '127.0.0.1', function(){ process.nextTick(function(){ server.__deferred.forEach(function(args){ browser.get.apply(browser, args); }); }); server.__listening = true; }); server.__started = true; } return; } url = 'http://127.0.0.1:' + server.__port + url; options.uri = url; options.jar = jar; request.get(options, function(err, res, body) { if (err) console.error('ERR', err.stack); browser.cookies = jar.getCookies(url); callback(res, body); }); }, done: function() { server.__listener.close(); server.__listener = null; server.__listening = false; server.__started = false; } }; return browser; } var suite = vows.describe('client-sessions'); suite.addBatch({ "middleware" : { topic: function() { var self = this; var middleware = cookieSessions({ cookieName: 'session', secret: 'yo', activeDuration: 0, cookie: { maxAge: 5000 } }); var req = { headers: {} }; var res = {}; middleware(req, res, function(err) { self.callback(err, req, res); }); }, "includes a session object": function(err, req) { assert.isObject(req.session); }, "session object stores and retrieves values properly": function(err, req) { req.session.foo = 'bar'; assert.equal(req.session.foo, 'bar'); }, "session object has reset function": function(err, req) { assert.isFunction(req.session.reset); }, "session object has setDuration function": function(err, req) { assert.isFunction(req.session.setDuration); }, "set variables and clear them yields no variables": function(err, req) { req.session.bar = 'baz'; req.session.reset(); assert.isUndefined(req.session.bar); }, "set variables does the right thing for Object.keys": function(err, req) { req.session.reset(); req.session.foo = 'foobar'; assert.equal(Object.keys(req.session).length, 1); assert.equal(Object.keys(req.session)[0], 'foo'); }, "reset preserves variables when asked": function(err, req) { req.session.reset(); req.session.foo = 'foobar'; req.session.bar = 'foobar2'; req.session.reset(['foo']); assert.isUndefined(req.session.bar); assert.equal(req.session.foo, 'foobar'); }, "set session property absorbs set object": function(err, req) { req.session.reset(); req.session.foo = 'quux'; req.session = { bar: 'baz' }; assert.isUndefined(req.session.foo); assert.isFunction(req.session.reset); assert.isFunction(req.session.setDuration); assert.equal(req.session.bar, 'baz'); assert.throws(function() { req.session = 'blah'; }, TypeError); } } }); suite.addBatch({ "a single request object" : { topic: function() { var self = this; // simple app var app = create_app(); app.get("/foo", function(req, res) { req.session.foo = 'foobar'; res.send("hello"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.done(); self.callback(null, res); }); }, "includes a set-cookie header": function(err, res) { assert.isArray(res.headers['set-cookie']); }, "only one set-cookie header": function(err, res) { assert.equal(res.headers['set-cookie'].length, 1); }, "with an expires attribute": function(err, res) { assert.match(res.headers['set-cookie'][0], /expires/); }, "with a path attribute": function(err, res) { assert.match(res.headers['set-cookie'][0], /path/); }, "with an httpOnly attribute": function(err, res) { assert.match(res.headers['set-cookie'][0], /httponly/); } } }); suite.addBatch({ "across two requests" : { topic: function() { var self = this; // simple app var app = create_app(); app.get("/foo", function(req, res) { req.session.reset(); req.session.foo = 'foobar'; req.session.bar = [1, 2, 3]; res.send("foo"); }); app.get("/bar", function(req, res) { self.callback(null, req); res.send("bar"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.get("/bar", function(res, $) { browser.done(); }); }); }, "session maintains state": function(err, req) { assert.equal(req.session.foo, 'foobar'); assert.equal(req.session.bar.length, 3); assert.equal(req.session.bar[0], 1); assert.equal(req.session.bar[1], 2); assert.equal(req.session.bar[2], 3); } } }); suite.addBatch({ "across two requests" : { topic: function() { var self = this; // simple app var app = create_app(); app.get("/foo", function(req, res) { req.session.reset(); req.session.foo = 'foobar'; res.send("foo"); }); app.get("/bar", function(req, res) { self.callback(null, req); res.send("bar"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.get("/bar", function(res, $) { browser.done(); }); }); }, "resetting a session with an existing cookie value yields no variables": function(err, req) { req.session.reset(); assert.isUndefined(req.session.foo); } } }); suite.addBatch({ "across three requests" : { topic: function() { var self = this; // simple app var app = create_app(); app.get("/foo", function(req, res) { req.session.reset(); req.session.foo = 'foobar'; req.session.bar = 'foobar2'; res.send("foo"); }); app.get("/bar", function(req, res) { delete req.session.bar; res.send("bar"); }); app.get("/baz", function(req, res) { self.callback(null, req); res.send("baz"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.get("/bar", function(res, $) { browser.get("/baz", function(res, $) { browser.done(); }); }); }); }, "session maintains state": function(err, req) { assert.equal(req.session.foo, 'foobar'); assert.isUndefined(req.session.bar); } }, "across three requests with deep objects" : { topic: function() { var self = this; // simple app var app = create_app(); app.get("/foo", function(req, res) { req.session.reset(); req.session.foo = 'foobar'; req.session.bar = { a: 'b' }; res.send("foo"); }); app.get("/bar", function(req, res) { req.session.bar.c = 'd'; res.send("bar"); }); app.get("/baz", function(req, res) { self.callback(null, req); res.send("baz"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.get("/bar", function(res, $) { browser.get("/baz", function(res, $) { browser.done(); }); }); }); }, "session maintains state": function(err, req) { assert.equal(req.session.foo, 'foobar'); assert.equal(req.session.bar.c, 'd'); } } }); suite.addBatch({ "reading from an existing session" : { topic: function() { var self = this; // simple app var app = create_app(); app.get("/foo", function(req, res) { req.session.foo = 'foobar'; res.send("foo"); }); app.get("/bar", function(req, res) { res.send(req.session.foo); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.get("/bar", function(res, $) { browser.done(); // observe the response to the second request self.callback(null, res); }); }); }, "does not set a cookie": function(err, res) { assert.isUndefined(res.headers['set-cookie']); } }, "reading from a non-existing session" : { topic: function() { var self = this; // simple app var app = create_app(); app.get("/foo", function(req, res) { // this should send undefined, not null res.send(req.session.foo); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.done(); self.callback(null, res, $); }); }, "does not set a cookie": function(err, res, body) { assert.isUndefined(res.headers['set-cookie']); assert.equal(body, ''); // undefined becomes an empty string } } }); suite.addBatch({ "writing to a session" : { topic: function() { var self = this; // simple app var app = create_app(); app.get("/foo", function(req, res) { req.session.foo = 'foobar'; res.send("foo"); }); app.get("/bar", function(req, res) { req.session.reset(); req.session.reset(); req.session.bar = 'bar'; req.session.baz = 'baz'; res.send("bar"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.get("/bar", function(res, $) { browser.done(); // observe the response to the second request self.callback(null, res); }); }); }, "sets a cookie": function(err, res) { assert.isArray(res.headers['set-cookie']); }, "and only one cookie": function(err, res) { assert.equal(res.headers['set-cookie'].length, 1); } } }); function create_app_with_duration() { // simple app var app = express(); app.use(cookieSessions({ cookieName: 'session', secret: 'yo', activeDuration: 0, duration: 500 // 0.5 seconds })); app.get("/foo", function(req, res) { req.session.reset(); req.session.foo = 'foobar'; res.send("foo"); }); return app; } suite.addBatch({ "querying within duration" : { topic: function() { var self = this; var app = create_app_with_duration(); app.get("/bar", function(req, res) { self.callback(null, req); res.send("bar"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { setTimeout(function () { browser.get("/bar", function(res, $) { browser.done(); }); }, 200); }); }, "session still has state": function(err, req) { assert.equal(req.session.foo, 'foobar'); } } }); suite.addBatch({ "modifying the session": { topic: function() { var self = this; var app = create_app_with_duration(); app.get("/bar", function(req, res) { self.callback(null, req); res.send("bar"); }); var browser = createBrowser(app); var firstCreatedAt, secondCreatedAt; browser.get("/foo", function(res, $) { browser.get("/bar", function(res, $) { browser.done(); }); }); }, "doesn't change createdAt": function(err, req) { assert.equal(req.session.foo, 'foobar'); } } }); suite.addBatch({ "querying outside the duration time": { topic: function() { var self = this; var app = create_app_with_duration(); app.get("/bar", function(req, res) { self.callback(null, req); res.send("bar"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { setTimeout(function () { browser.get("/bar", function(res, $) { browser.done(); }); }, 800); }); }, "session no longer has state": function(err, req) { assert.isUndefined(req.session.foo); } } }); suite.addBatch({ "querying twice, each at 2/5 duration time": { topic: function() { var self = this; var app = create_app_with_duration(); app.get("/bar", function(req, res) { req.session.baz = Math.random(); res.send("bar"); }); app.get("/bar2", function(req, res) { self.callback(null, req); res.send("bar2"); }); var browser = createBrowser(app); // first query resets the session to full duration browser.get("/foo", function(res, $) { setTimeout(function () { // this query should NOT reset the session browser.get("/bar", function(res, $) { setTimeout(function () { // so the session should still be valid browser.get("/bar2", function(res, $) { browser.done(); }); }, 200); }); }, 200); }); }, "session still has state": function(err, req) { assert.isDefined(req.session.baz); } } }); suite.addBatch({ "querying twice, each at 3/5 duration time": { topic: function() { var self = this; var app = create_app_with_duration(); app.get("/bar", function(req, res) { req.session.baz = Math.random(); res.send("bar"); }); app.get("/bar2", function(req, res) { self.callback(null, req); res.send("bar2"); }); var browser = createBrowser(app); // first query resets the session to full duration browser.get("/foo", function(res, $) { setTimeout(function () { // this query should NOT reset the session browser.get("/bar", function(res, $) { setTimeout(function () { // so the session should be dead by now browser.get("/bar2", function(res, $) { browser.done(); }); }, 300); }); }, 300); }); }, "session no longer has state": function(err, req) { assert.isUndefined(req.session.baz); } } }); function create_app_with_duration_modification() { // simple app var app = express(); app.use(cookieSessions({ cookieName: 'session', secret: 'yobaby', activeDuration: 0, duration: 5000 // 5.0 seconds })); app.get("/create", function(req, res) { req.session.foo = "foo"; res.send("created"); }); app.get("/augment", function(req, res) { req.session.bar = "bar"; res.send("augmented"); }); // invoking this will change the session duration to 500ms app.get("/change", function(req, res) { req.session.setDuration(500); res.send("duration changed"); }); return app; } suite.addBatch({ "after changing cookie duration and querying outside the modified duration": { topic: function() { var self = this; var app = create_app_with_duration_modification(); app.get("/complete", function(req, res) { self.callback(null, req); res.send("bar"); }); var browser = createBrowser(app); browser.get("/create", function(res, $) { browser.get("/change", function(res, $) { setTimeout(function () { browser.get("/complete", function(res, $) { browser.done(); }); }, 700); }); }); }, "session no longer has state": function(err, req) { assert.isUndefined(req.session.foo); } } }); var initialCookie; var updatedCookie; suite.addBatch({ "changing duration": { topic: function() { var self = this; var app = create_app_with_duration_modification(); app.get("/complete", function(req, res) { self.callback(null, req); res.send("bar"); }); var browser = createBrowser(app); browser.get("/create", function(res, $) { initialCookie = browser.cookies[0].value; browser.get("/change", function(res, $) { updatedCookie = browser.cookies[0].value; browser.get("/complete", function(res, $) { browser.done(); }); }); }); }, "doesn't affect session variables": function(err, req) { assert.equal(req.session.foo, "foo"); }, "does update creation time": function(err, req) { assert.notEqual(initialCookie.split('.')[2], updatedCookie.split('.')[2], "after duration update, creation should be updated"); }, "does update duration": function(err, req) { assert.strictEqual(parseInt(initialCookie.split('.')[3], 10), 5000); assert.strictEqual(parseInt(updatedCookie.split('.')[3], 10), 500); } } }); suite.addBatch({ "after changing duration then setting a new session variable": { topic: function() { var self = this; var app = create_app_with_duration_modification(); app.get("/set_then_duration", function(req, res) { req.session.baz = "baz"; req.session.setDuration(500); res.send("did it"); }); app.get("/complete", function(req, res) { self.callback(null, req); res.send("bar"); }); var browser = createBrowser(app); browser.get("/create", function(res, $) { browser.get("/set_then_duration", function(res, $) { browser.get("/complete", function(res, $) { browser.done(); }); }); }); }, "variable is visible": function(err, req) { assert.equal(req.session.foo, "foo"); assert.equal(req.session.baz, "baz"); } } }); suite.addBatch({ "after setting a new session variable then changing duration": { topic: function() { var self = this; var app = create_app_with_duration_modification(); app.get("/set_then_duration", function(req, res) { req.session.setDuration(500); req.session.baz = "baz"; res.send("did it"); }); app.get("/complete", function(req, res) { self.callback(null, req); res.send("bar"); }); var browser = createBrowser(app); browser.get("/create", function(res, $) { browser.get("/set_then_duration", function(res, $) { browser.get("/complete", function(res, $) { browser.done(); }); }); }); }, "variable is visible": function(err, req) { assert.equal(req.session.foo, "foo"); assert.equal(req.session.baz, "baz"); } } }); suite.addBatch({ "setting new variables then invoking setDuration": { topic: function() { var self = this; var app = create_app_with_duration_modification(); app.get("/complete", function(req, res) { self.callback(null, req); res.send("bar"); }); var browser = createBrowser(app); browser.get("/create", function(res, $) { browser.get("/change", function(res, $) { browser.get("/augment", function(res, $) { browser.get("/complete", function(res, $) { browser.done(); }); }); }); }); }, "both variables are visible": function(err, req) { assert.equal(req.session.foo, "foo"); assert.equal(req.session.bar, "bar"); } } }); function create_app_with_secure(firstMiddleware) { // set up the session middleware var middleware = cookieSessions({ cookieName: 'session', secret: 'yo', activeDuration: 0, cookie: { maxAge: 5000, secure: true } }); var app = express(); if (firstMiddleware) app.use(firstMiddleware); app.use(middleware); return app; } suite.addBatch({ "across two requests, without proxySecure, secure cookies" : { topic: function() { var self = this; var app = create_app_with_secure(); app.get("/foo", function(req, res) { res.send("foo"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.done(); self.callback(null, res); }); }, "cannot be set": function(err, res) { assert.equal(res.statusCode, 500); } } }); suite.addBatch({ "across two requests, with proxySecure, secure cookies" : { topic: function() { var self = this; var app = create_app_with_secure(function(req, res, next) { // say it is proxySecure req.connection.proxySecure = true; next(); }); app.get("/foo", function(req, res) { res.send("foo"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.done(); self.callback(null, res); }); }, "can be set": function(err, res) { assert.equal(res.statusCode, 200); } } }); suite.addBatch({ "public encode and decode util methods" : { topic: function() { var self = this; var app = create_app(); app.get("/foo", function(req, res) { self.callback(null, req); res.send("hello"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.done(); }); }, "encode " : function(err, req){ var result = cookieSessions.util.encode({cookieName: 'session', secret: 'yo'}, {foo:'bar'}); var result_arr = result.split("."); assert.equal(result_arr.length, 5); }, "encode and decode - is object" : function(err, req){ var encoded = cookieSessions.util.encode({cookieName: 'session', secret: 'yo'}, {foo:'bar'}); var decoded = cookieSessions.util.decode({cookieName: 'session', secret: 'yo'}, encoded); assert.isObject(decoded); }, "encode and decode - has all values" : function(err, req){ var encoded = cookieSessions.util.encode({cookieName: 'session', secret: 'yo'}, {foo:'bar', bar:'foo'}); var decoded = cookieSessions.util.decode({cookieName: 'session', secret: 'yo'}, encoded); assert.equal(decoded.content.foo, 'bar'); assert.equal(decoded.content.bar, 'foo'); assert.isNumber(decoded.duration); assert.isNumber(decoded.createdAt); }, "encode and decode - override duration and createdAt" : function(err, req){ var encoded = cookieSessions.util.encode({cookieName: 'session', secret: 'yo'}, {foo:'bar', bar:'foo'}, 5000, 1355408039221); var decoded = cookieSessions.util.decode({cookieName: 'session', secret: 'yo'}, encoded); assert.equal(decoded.duration, 5000); assert.equal(decoded.createdAt, 1355408039221); }, "encode and decode - default duration" : function(err, req){ var encoded = cookieSessions.util.encode({cookieName: 'session', secret: 'yo'}, {foo:'bar'}); var decoded = cookieSessions.util.decode({cookieName: 'session', secret: 'yo'}, encoded); assert.equal(decoded.duration, 86400000); }, "encode and decode - tampered HMAC" : function(err, req){ var encodedReal = 'LVB3G2lnPF75RzsT9mz7jQ.RT1Lcq0dOJ_DMRHyWJ4NZPjBXr2WzkFcUC4NO78gbCQ.1371704898483.5000.ILEusgnajT1sqCWLuzaUt-HFn2KPjYNd38DhI7aRCb9'; var encodedFake = encodedReal.substring(0, encodedReal.length - 1) + 'A'; var decodedReal = cookieSessions.util.decode({cookieName: 'session', secret: 'yo'}, encodedReal); assert.isObject(decodedReal); var decodedFake = cookieSessions.util.decode({cookieName: 'session', secret: 'yo'}, encodedFake); assert.isUndefined(decodedFake); }, "decode - invalid input" : function(err, req){ var notEnoughComponents = 'LVB3G2lnPF75RzsT9mz7jQ.RT1Lcq0dOJ_DMRHyWJ4NZPjBXr2WzkFcUC4NO78gbCQ.1371704898483.5000'; assert.isUndefined(cookieSessions.util.decode({cookieName: 'session', secret: 'yo'}, notEnoughComponents)); var invalidBase64 = 'LVB3G2lnPF75RzsT9mz7jQ.RT1Lcq0dOJ_DMRHyWJ4NZPjBXr2WzkFcUC4NO78gb.1371704898483.5000.ILEusgnajT1sqCWLuzaUt-HFn2KPjYNd38DhI7aRCb9'; assert.isUndefined(cookieSessions.util.decode({cookieName: 'session', secret: 'yo'}, invalidBase64)); } } }); suite.addBatch({ "two middlewares": { topic: function() { var self = this; var app = create_app(); app.get("/foo", function(req, res) { self.callback(null, req); res.send("hello"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $){ browser.done(); }); }, "We can write to both stores": function(err, req) { req.session.foo = 'bar'; req.securestore.foo = 'buzz'; req.securestore.widget = 4; assert.equal(req.session.foo, 'bar'); assert.equal(req.securestore.foo, 'buzz'); assert.equal(req.securestore.widget, 4); } } }); suite.addBatch({ "specifying requestKey different than cookieName": { topic: function() { var self = this; var app = express(); app.use(cookieSessions({ cookieName: 'ooga_booga_momma', activeDuration: 0, requestKey: 'ses', secret: 'yo' })); app.get('/foo', function(req, res) { self.callback(null, req); res.send('hello'); }); var browser = createBrowser(app); browser.get("/foo", function(res, $){ browser.done(); }); }, "session is defined as req[requestKey]": function(err, req) { assert.isObject(req.ses); assert.strictEqual(Object.keys(req.ses).length, 0); assert.isUndefined(req.session); assert.isUndefined(req.ooga_booga_momma); } } }); suite.addBatch({ "swapping two cookies": { topic: function() { var self = this; var app = create_app(); //important that they use the same secret app.get('/foo', function(req, res) { req.session.foo = 'bar'; req.securestore.foo = 'buzz'; req.securestore.widget = 4; res.send('hello'); }); app.get('/bar', function(req, res) { self.callback(null, req); res.send('bye'); }); createBrowser(app).get('/foo', function(res, $){ var cookies = res.headers['set-cookie']; var firstCookie = cookies[0]; var secondCookie = cookies[1]; function getCookieName(cookieHeader) { return cookieHeader.substring(0, cookieHeader.indexOf('=')); } function getCookieValue(cookieHeader) { return cookieHeader.substring(cookieHeader.indexOf('='), cookieHeader.indexOf(';')); } var firstHijack = getCookieName(firstCookie) + getCookieValue(secondCookie); var secondHijack = getCookieName(secondCookie) + getCookieValue(firstCookie); var browser = createBrowser(app); browser.get('/bar', { headers: { 'Cookie': firstHijack + '; ' + secondHijack } }, function(res, $){ browser.done(); }); }); }, "doesn't keep using cookie": function(err, req) { // session.foo should not be what securestore.foo was, or else // we swapped cookies! assert.notEqual(req.session.foo, 'buzz'); assert.notEqual(req.session.widget, 4); assert.notEqual(req.securestore.foo, 'bar'); } } }); suite.addBatch({ "missing cookie maxAge": { topic: function() { var self = this; var app = express(); app.use(cookieSessions({ cookieName: 'session', duration: 50000, activeDuration: 0, secret: 'yo' })); app.get("/foo", function(req, res) { req.session.foo = 'foobar'; res.send("hello"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.done(); self.callback(null, res); }); }, "still has an expires attribute": function(err, res) { assert.match(res.headers['set-cookie'][0], /expires/, "cookie is a session cookie"); }, "which roughly matches the session duration": function(err, res) { var expiryValue = res.headers['set-cookie'][0].replace(/^.*expires=([^;]+);.*$/, "$1"); var expiryDate = new Date(expiryValue); var cookieDuration = expiryDate.getTime() - Date.now(); assert(Math.abs(50000 - cookieDuration) < 1500, "expiry is pretty far from the specified duration"); } }, "changing the duration": { topic: function() { var self = this; var app = express(); app.use(cookieSessions({ cookieName: 'session', duration: 500, activeDuration: 0, secret: 'yo' })); app.get("/foo", function(req, res) { req.session.foo = 'foobar'; res.send("hello"); }); app.get("/bar", function(req, res) { req.session.setDuration(5000); res.send("bar"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { setTimeout(function () { browser.get("/bar", function(res, $) { browser.done(); self.callback(null, res); }); }, 200); }); }, "updates the cookie expiry": function(err, res) { var expiryValue = res.headers['set-cookie'][0].replace(/^.*expires=([^;]+);.*$/, "$1"); var expiryDate = new Date(expiryValue); var cookieDuration = expiryDate.getTime() - Date.now(); assert(Math.abs(cookieDuration - 5000) < 1000, "expiry is pretty far from the specified duration"); } }, "active user with session close to expiration": { topic: function() { var app = express(); var self = this; app.use(cookieSessions({ cookieName: 'session', duration: 300, activeDuration: 500, secret: 'yo' })); app.get("/foo", function(req, res) { req.session.foo = 'foobar'; res.send("hello"); }); app.get("/bar", function(req, res) { req.session.bar = 'baz'; res.send('hi'); }); app.get("/baz", function(req, res) { res.json({ "msg": req.session.foo + req.session.bar }); }); var browser = createBrowser(app); browser.get("/foo", function() { browser.get("/bar", function() { setTimeout(function () { browser.get("/baz", {json: true}, function(res, first) { setTimeout(function() { browser.get('/baz', {json: true}, function(res, second) { browser.done(); self.callback(null, first, second); }); }, 1000); }); }, 400); }); }); }, "extends session duration": function(err, extended, tooLate) { assert.equal(extended.msg, 'foobarbaz'); assert.equal(tooLate.msg, null); } } }); var shared_browser1; var shared_browser2; suite.addBatch({ "non-ephemeral cookie": { topic: function() { var self = this; var app = express(); app.use(cookieSessions({ cookieName: 'session', duration: 5000, secret: 'yo', cookie: { ephemeral: false } })); app.get("/foo", function(req, res) { req.session.foo = 'foobar'; res.send("hello"); }); app.get("/bar", function(req, res) { req.session.setDuration(6000, true); res.send("hello"); }); shared_browser1 = createBrowser(app); shared_browser1.get("/foo", function(res, $) { self.callback(null, res); }); }, "has an expires attribute": function(err, res) { assert.match(res.headers['set-cookie'][0], /expires/, "cookie is a session cookie"); }, "changing to an ephemeral one": { topic: function() { var self = this; shared_browser1.get("/bar", function(res, $) { shared_browser1.done(); self.callback(null, res); }); }, "removes its expires attribute": function(err, res) { assert.strictEqual(res.headers['set-cookie'][0].indexOf('expires='), -1, "cookie is not ephemeral"); } } }, "ephemeral cookie": { topic: function() { var self = this; var app = express(); app.use(cookieSessions({ cookieName: 'session', duration: 50000, activeDuration: 0, secret: 'yo', cookie: { ephemeral: true } })); app.get("/foo", function(req, res) { req.session.foo = 'foobar'; res.send("hello"); }); app.get("/bar", function(req, res) { req.session.setDuration(6000, false); res.send("hello"); }); shared_browser2 = createBrowser(app); shared_browser2.get("/foo", function(res, $) { self.callback(null, res); }); }, "doesn't have an expires attribute": function(err, res) { assert.strictEqual(res.headers['set-cookie'][0].indexOf('expires='), -1, "cookie is not ephemeral"); }, "changing to an non-ephemeral one": { topic: function() { var self = this; shared_browser2.get("/bar", function(res, $) { shared_browser2.done(); self.callback(null, res); }); }, "gains an expires attribute": function(err, res) { assert.match(res.headers['set-cookie'][0], /expires/, "cookie is a session cookie"); } } } }); suite.addBatch({ "sameSite cookie": { topic: function() { var self = this; var app = express(); app.use(cookieSessions({ cookieName: 'session', secret: 'yo', activeDuration: 0, cookie: { sameSite: 'lax' } })); app.get("/foo", function(req, res) { req.session.foo = 'foobar'; res.send("hello"); }); var browser = createBrowser(app); browser.get("/foo", function(res, $) { browser.done(); self.callback(null, res); }); }, "has samesite attribute": function(err, res) { assert.match(res.headers['set-cookie'][0], /samesite=lax/, "cookie uses samesite"); } } }); var sixtyFourByteKey = new Buffer( '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef', 'binary' ); var HMAC_EXPECT = { // aligned so you can see the dropN effect: 'sha256': 'PRYaxV/8RkMyIT/Ib+tIUOWiSn+0EvodJ5rtG1FQHz0=', 'sha256-drop128': 'PRYaxV/8RkMyIT/Ib+tIUA==', 'sha384': 'MND9nz6pxbQC5m41ZPRXhJIuqTj9/hu4gtWZ8t8LgdFLQFWQfC8jhijB0NHLpeA7', 'sha384-drop192': 'MND9nz6pxbQC5m41ZPRXhJIuqTj9/hu4', 'sha512': 'Hr4KLVLyglIwQ43C9U2bmieWBVLnD/F+lzCSF072Ds2b87MK+gbnR0p75A+I+5ez+aiemMGuMZyKVAUWfMMaUA==', 'sha512-drop256': 'Hr4KLVLyglIwQ43C9U2bmieWBVLnD/F+lzCSF072Ds0=' }; function testHmac(algo) { var block = {}; block.topic = function() { var opts = { signatureAlgorithm: algo, signatureKey: sixtyFourByteKey }; var iv = new Buffer('01234567890abcdef','binary'); // 128-bits var ciphertext = new Buffer('0123456789abcdef0123','binary'); var duration = 876543210; var createdAt = 1234567890; return cookieSessions.util.computeHmac( opts, iv, ciphertext, duration, createdAt ).toString('base64'); }; block['equals test vector'] = function(val) { assert.equal(val, HMAC_EXPECT[algo]); }; return block; } suite.addBatch({ "computeHmac": { "sha256": testHmac('sha256'), "sha256-drop128": testHmac('sha256-drop128'), "sha384": testHmac('sha384'), "sha384-drop192": testHmac('sha384-drop192'), "sha512": testHmac('sha512'), "sha512-drop256": testHmac('sha512-drop256'), } }); suite.export(module);