andyMatthews.net

Secure storage in JavaScript, a proof of concept

A week or so ago, a fellow JavaScript developer threw down a challenge.

Suppose you wanted to extend the JavaScript Object such that getting and setting data in the object is only possible when providing a predetermined access key. The key is first used to instantiate the SecureObject and subsequently used when storing and retrieving data from the SecureObject. Provide the implementation for a JavaScript function that satisfies the use case.

While I've been using JavaScript for quite a long time, I'm still lacking in some of the more advanced functionality. Prototyping, classes, public and private members, etc. So I decided to take this challenge and see what I could come up with. After doing some research this is what I came up with. You can download the full source, along with the original challenge doc.


// index.html
// script block
var sk = 'abc123';
var myDV = new SecureObject(sk);
myDV.setValue(sk, 'foo', 'bar');
var myVal = myDV.getValue(sk, 'foo');
console.log(myVal);

// SecureObject.js
// full contents
/**
 * Instantiate a SecureObject object
 * SecureObject(accessKey)
 * @accessKey - a string representing the read/write access key
 * returns an instance of SecureObject
 * Andy Matthews - andy@commadelimited.com
 * http://twitter.com/commadelimited
 * http://andyMatthews.net
 * http://commadelimited.com
 * 3/11/2010
**/

function SecureObject(accessKey) {

	// set the secrey access code for this instance
	var key = accessKey;
	// storage object
	var storage = {};

	// make sure that the key is not null, and isn't empty
	if (accessKey ==  undefined || accessKey == ')
		throw 'Accesskey cannot be an empty string';

	// setter
	this.setValue = function(k, n, v) {
		if (k === key) storage[n] = v;
	}

	// getter
	this.getValue = function(k, n) {
		if (k === key && storage[n] != undefined) return storage[n];
	}

}

I'd love to get some feedback. I'd also love to discuss the merits of taking this approach...after all, the files are available as plain text via the browser. How secure is it really, and how far should you trust it? What sorts of applications could take advantage of this approach?