For the "how" see https://news.ycombinator.com/item?id=46330258 - the game has been reverse engineered. There are reverse engineering and reimplementation projects like this for a lot of older games, i.e. Mario 64, Diablo and at least one of the Sonic games
Is it legal? Well, the reverse engineering typically is as long as you follow the rules, but hosting all the game assets on a public web server so you can play it probably isn't.