In the time before the internet I probaly would have spent 10 minutes or so pondering this and then just dismissed it as one of the unanswerable mysteries of life. In one of the myriad ways the information age has improved my life is the fact that I can now find out the answer to my curiosity without having to go bother a baker.
The following is from the straight dope. I have no clue if it's right but what's really important is it sounds good and I'm going to accept it as reality without further fact checking. The alternative would require actual effort and I'm not that curious about it. I am however thinking that a baker's dozen of cupcakes sounds pretty damn good right now.
The first theory goes back to ancient times. Bakers were widely viewed with suspicion, since it was common (and easy) for them to short-weight customers. Many societies had severe penalties for bakers who engaged in such underhanded practices. For instance, one source says that in ancient Egypt, the baker's ear was nailed to the doorpost of his bakery if he were found selling light loaves. (I'm not sure whether the ear was still attached to the baker. Either way it was a pretty stiff punishment.)
Under the code of Hammurabi, a loaf of bread and a man's hand were interchangeable. They took their bread seriously back then. (Can you imagine hacking off someone's hand and then showing up the next day with a loaf of bread and everyone calling it square? WTH?)
In the mid-13th century, British law imposed strict regulations on bakers regarding the weight of bread. Bakers wanted to make sure they complied, since the penalties were severe (a fine or the pillory, although nothing involving ears, so far as I know). It was difficult to make loaves of uniform weight in those days before automation, so bakers added a 13th loaf to every shipment of 12--better to be overweight than under. Thus "a baker's dozen" meant 13.
The second theory is more complicated. A baker selling to a third party (a street vendor, say) would add a 13th loaf as the profit for the middleman. That is, the baker sells the middleman 13 loaves for the price of 12, and the middle man sells the 13 individual loaves for a 7.7% profit.
Whichever theory you accept, the evolution of the expression today has come to mean that the baker adds an extra cookie, bun, pastry or whatever to the order of 12 as a bonus.