Authentication with localStorage

Written by Pete Corey on Jun 8, 2015.

Unlike most modern web frameworks, Meteor doesn’t make use of cookies. Instead, it uses the relatively new localStorage functionality found in modern browsers. This design decision essentially makes Meteor immune to Cross Site Request Forgery (CSRF) attacks, and opens the door to exciting new authentication features not previously possible with cookies.

CSRF Proof

If Meteor were to use cookies for authentication, it would have to be done during the WebSocket handshake. The handshake is the first and only HTTP request Meteor applications make to the server and is therefore the only place to pass session cookies to the server. However, without some kind of added protection, authentication at this point would expose our Meteor applications to a particularly nasty variant of CSRF dubbed Cross Site WebSocket Hijacking, or CSWSH.

In this scenario, CSWSH could occur if a user authenticated with our application visited a malicious website that attempted to establish a DDP connection to our Meteor application:

var ddp = DDP.connect(‘’);

DDP.connect makes a GET request to our application’s WebSocket endpoint, passing along our session cookie. The GET request returns with a 101 Switching Protocols response and the WebSocket is established. WebSocket connections aren’t protected by modern browsers’ same-origin policy, so the browser happily establishes the DDP connection. The malicious site is now free to view, modify, and delete all of your user’s data without their knowledge or consent. Uh oh!

localStorage To The Rescue

Rather than using cookies and implementing complicated countermeasures against CSRF attacks, Meteor opts for a more elegant solution and stores session tokens in localStorage. localStorage, unlike cookie data, is accessed via JavaScript and is only accessible by the domain it belongs to. Unlike cookies, they are not sent along with HTTP requests. This means there is no chance of a third party website directly or indirectly accessing and using our users’ session tokens.

Reactive Authentication

Using localStorage as our authentication mechanism also lets us do cool things like reactive authentication. Imagine a user with your web application loaded on two different tabs. If that user were to log in to your application on one tab, they would instantly be logged in on the other tab. Similarly, logging out of the application in one tab also logs the user out in the second tab. Meteor accomplishes this by listening for storage events and reactively updating the client’s authentication state. These storage events also open the door for more exciting authentication functionality, like sharing authentication state across multiple applications.

Keep It Secret, Keep It Safe

Written by Pete Corey on May 25, 2015.

It’s fairly well established that you shouldn’t be storing your application’s deployment-specific configuration options directly in your source code. Keeping secrets in your code unnecessarily expands your application’s circle of trust. But did you know that by keeping secrets in your code you may inadvertently be leaking them to your clients?

The Setup

Let’s pretend that we have a Meteor method that’s called whenever a user purchases something in our application. Knowing that we want to leverage latency compensation, we define this method in a shared location so both the client and server have access to it. In a server block, the method adds a transaction to our payment processing system. In order to add this payment, we need to pass along a secret key associated with our application to verify that we authorize the transaction.

Take a look at the method:

    purchase: function(item) {
        // checks and validation
        if (Meteor.isServer) {
            Payments.add(..., 'XYZ-SSECRET-KEY');

It’s very important that we keep our secret key a secret! If anyone other than our server has access to our key, they would be able to add payments on our behalf.

The Problem

Unfortunately, in this scenario, our secret key is not being kept a secret. To grab our key, a malicious user would simply need to open their browser console anywhere in our application and grab the purchase method’s source:


"... 'XYZ-SSECRET-KEY' ..."

Our fundamental error here is assuming that our Meteor.isServer guard prevents code from being shipped to the client. This isn’t always true! When a method is defined in a location that is visible to both the client and the server, it’s entire handler function is passed to the client, server-only code and all.

Check out my post on black box auditing Meteor methods to get a better understanding of what code is made visible to the client.

The Solution

The quickest solution to this problem is to move our secret key out of our code and into our settings file:

    "payment_secret": "XYZ-SSECRET-KEY"

Our updated purchase method would look like this:

    purchase: function(item) {
        // checks and validation
        if (Meteor.isServer) {

From a client/server perspective, nothing has changed. Our Meteor.isServer block is still being sent to the client. The fundamental difference with this approach is that Meteor.settings.payment_settings is not available on the client. Even if a malicious user digs into the method’s source on the client, they won’t get to our secret key.

Mongo's Multi Parameter Saves the Day

Written by Pete Corey on May 18, 2015.

In the past, I’ve seen the multi parameter on MongoDB updates as an annoying inconvenience. Without fail, I’ll forget to add the flag when it’s needed, and waste a frustrating amount of time trying to deduce why my update isn’t behaving as expected. But, a recent trek through Telescope’s codebase revealed to me just how valuable it can be to default to updating a single item at a time. Come with me on a journey…

On a side note, Telescope is one of the highest quality open source Meteor projects I've seen to date. I highly recommend it as a platform!

Digging Into Telescope

The code that opened my proverbial eyes is the changeEmail method found in /server/users.js in Telescope. Take a look:

changeEmail: function (userId, newEmail) {
  var user = Meteor.users.findOne(userId);
  if (can.edit(Meteor.user(), user) !== true) {
    throw new Meteor.Error("Permission denied");
    {$set: {
        emails: [{address: newEmail, verified: false}],
        email_hash: Gravatar.hash(newEmail),
        "": newEmail

If you’ve read my previous posts, I hope you’ll immediately notice that userId and newEmail are not being checked. Can that be exploited? What happens if a malicious user, Mallory, decides to pass in a carefully crafted object as the userId?‘changeEmail', {_id: {$gte: Meteor.userId()}}, ‘mallory@is.evil');

This userId object, when used in a Mongo query, will return all users with IDs ordinally greater than or equal to the current user’s ID. We can roughly assume that this is about half of the users in the system. The list of returned users will always return the current user first, due to the index on the _id field.

In our changeEmail method, Meteor.users.findOne will happily accept our userId object and treat it as a query object. It will grab the first result of this query, which happens to be the current user (Mallory).

Next, the method checks if the current user has permission to edit the user found. Because the first user found is the current user, permission is granted. Proceed with the update!

You Get a New Email Address! And You Get a New Email Address!

If Mongo didn’t require explicitly setting the multi parameter, calling Meteor.users.update with our malicious userId object would result in a huge chunk of users having their emails changed to Mallory’s email address. This would be a Very Bad Thing™. He could easily reset their passwords through normal channels and take over their accounts!

But Not Really…

Thankfully, Mongo defaults to updating only a single object unless the multi flag is explicitly set to true. In this example, only the first result of the query, the current user, will be updated with the new email address. This means that the method functions as intended, and there is no vulnerability! Three cheers for the multi flag!

Final Thoughts

While I’m sure I’ll still continue to forget to add the multi flag when writing updates, I now have a newfound respect for this aspect of Mongo. This conservative default, which was initially built in with performance in mind, also acts as a protective mechanism to prevent us from inadvertently modifying more data than we intended.

Lastly, remember to always check your method and publication arguments! While it ended up not being a problem in this example, we nearly had a serious vulnerability on our hands. It’s always better to be safe than sorry.