It uses a theory called Operational Transformation [1] which is roughly the base for most collaborative tools like google docs.
My first attempt was using a library called ot.js [2], I changed it to support an async db since it only supported a in-memory store and I adapted to use mongodb. The experiment is in [3] and it has some bugs still.
Then I found out the guys at firebase adapted ot.js client side to work with their own db, and created something called Firepad [4]. So, I used that instead which was more stable and I added auth and authn.