Listening objects in Javascript

In the last 2 years, my development activity completely shifted towards javascript, i write javascript everywhere: when querying MongoDB, writing APIs with NodeJS and writing some MVC classes i needed for my projects. So i decided to log in this blog every relevant thing i learn about javascript and its beautiful object paradigm.
Let's start with something common to almost every Model-View interaction: observing objects.

First of all let's make some clarification about naming:
Listener and Observer are two slightly different implementation of the same pattern: The Observer pattern .
In this article i write about the first one, the Listener, but objects are called Observable and Observer because attaining to the "listen" semantic would bring ugly names , such as Audible... which is not fancy.

Fancy names are important, thats why java has POJO

Applications work around objects that represent data, your business data; in the MVC world they are called models. Most of the times you want to represent such data into the interface, for example when you create a model named User and load its properties from the server/database in order to display a profile page. But what if that data can change and you want to reflect those changes into the interface?
The object responsible for the rendering of the object has to catch those changes, so the model has to be Observable.
Let's look at some code: (You can run it here http://jsfiddle.net/fatmatto/wF5Th/)

var Observable = function() {
    this.eventHandlers = [];
    this.emit = function(eventName,eventObject) {

            if (this.eventHandlers.hasOwnProperty(eventName)) {
                    this.eventHandlers[eventName].call(this,eventObject);
            }
                
        }

        this.on = function(eventName,callback) { 
            if ('function' !== typeof callback)
                throw new Error('callback must be a function');
            this.eventHandlers[eventName] = callback;
        }

        this.set = function(prop,value) {
            var oldval = this[prop];
            this[prop] = value;
            if(oldval !== this[prop])
                this.emit('change '+prop,{oldValue : oldval,
                                          newValue : value});
            
        }
}
var Observer = function() {
    
    this.observe = function(eventType,observableObject,callback) {
        observableObject.on(eventType,callback);
    }

}

var hero = new Observable();
hero.name = 'Deadpool';
hero.power = 'Katanas';
var o = new Observer();
o.observe('change name',hero,function(eventOptions){
    console.log('The name of the hero changed to '+eventOptions.newValue);
});
o.observe('change power',hero,function(eventOptions){
    console.log('The power of the hero changed to '+eventOptions.newValue);
});
hero.set('name','Wade Wilson');
hero.set('power','Regeneration');

As you can see the Observer will be notified by the observable simply declaring a proper observer callback.

The Observable object has a method emit() that notifies the observer and a method on() that allows you to define a callback to some kind of event.



Pretending multiple runtime inheritance in php 5.X

Sometimes you REALLY need something that your programming language doesn't offers. Maybe because your programming language is obsolete, or because it offers you a different solution to the same problem, but you don't like this alternative solution.

Here i will discuss about how to implement multiple inheritance in php, not why, just how. Most of the times, if you need multiple inheritance in your classes, you could be able to solve the problem without it but HEY where's the fun?

Here's my implementation of an abstract class that you can extend in order to define your class that will need runtime inheritance-like funcitonalities.

<?php
class Pirate
{
public function doPirateStuff()
{
echo "YARRRRRRRR I SINK SHIPS!";
}
}

class Cyborg
{
public function doCyborgStuff()
{
echo "I DESTROY HUMANS";
}
}

class Ninja
{

public function doNinjaStuff()
{
echo "I SLICE AND DICE";
}
}

class SUPERHERO extends MultipleInheritant
{
public function __construct($name)
{
echo "I AM $name THE NEW SUPERHERO IN TOWN";
}
}

$s = new SUPERHERO('FATMAN');
$s->inherit('Ninja');
$s->inherit('Pirate');
$s->inherit('Cyborg');
$s->doCyborgStuff();
$s->doPirateStuff();
$s->doNinjaStuff();

The output for this, is:

I AM FATMAN THE NEW SUPERHERO IN TOWN
I DESTROY HUMANS
YARRRRRRRR I SINK SHIPS!
I SLICE AND DICE






Threats behind Wordpress.com: Link Injection

I am an enthusiastic ownerof a Wordpress.com blog, and those of you who use thath blogging platform like me would admit the utility of the stat counter. Infact it provides you a pretty detailed record of in/out http traffic of your blog: search engine keywords, most viewed articles, (...) and referers. Most of you could have already guessed what i'm going to tell you, but let's explain a bit what referer is.

When you browse the web, even if this is completely transparent to (most of )users, there is a continuos exchange of meta data between your web browser and the server in which the website is hosted. Tecnically speaking, browser and server send and receive requests. These requests contain headers: fields defining characteristic of the sent data, in particular the referer contains the url of the previous web page from which a link led the user to the current page.


In this way the referer tell us which pages are currently linking to our weblog so we can check who's talking about us.

Beyond this advantage there is a big pitfall: Storing and showing the referer expose the application to potential threats such as Cross Site Scripting and more silently to an unusual threat that i decided to call Link Injection (I say that "I decided" because i have not found any literature about this kind of issue yet).

Wordpress.com seems to filter user input properly to protect users against XSS and code injection, but it does not provide any protection against link injection!

HTTP Referer can be easily modifyed : I used to do with the firefox extension Modify Headers or with the fantastic Webscarab a powerful framework from OWASP; the easiness of this attack makes its power, here's a possible scenario:

The attacker knows the url of victim's blog, so he write a script to send http requests on it. Let's say that the victim's blog is not very popular so a dozen visits to his blog from the same source could make him curious; the attacker knows that, or maybe he decide the number of requests to send by probabilistic considerations. In this way the victim will follow the injected link . That link could represent an infected page or something else.

Unfortunately there isn't an easy way to avoid this kind of threat without compromise the efficiency of the service, personally i would remove the anchor tag from referers and i'd put a little "Warning" near them.


Insecurity Of Referer checking services

I recently wrote on my italian speaking blog about insecurity of referer viewing services. In particular i wrote about link injection on wordpress.com administration page (maybe i will translate it in this blog). From that article i started thinking about : How bad guys could use this vulnerabilty to threat good guys? I had a first answer googling!

The second link i get from google searching "show your referer" is wwwDOTshowskyDOTcom (i dont want to link it because it may fuck up you browser). That site shows your referer, WOW what a miracle of scripting, but it also Store latests referer, without filtering input, this means Persistent XSS.

While i am writing this lines, surfing that site means be greeted by a few alert('xss'), but i don't know what could become in the future :)

This is a perfect example of "too much trust on user" and lack of input filtering.