First, there are a bunch of up-front costs to the lender that are spread out over what's expected to be the average length of the mortgage--somewhere between 5 and 7 years. If a homeowner wants to pay off the mortgage in a year or two, those longer-term costs haven't been recovered through the normal monthly payments. Thus, the penalty helps offset that.
Second--though less common now--teaser rates typically are below market. Again, the lender has done the calculations and figured that it can lose a bit of money (or not make as much) on the teaser rate, so long as the rate goes up and the homeowner keeps paying. But with a refinance, that doesn't happen.
Here's a simple illustration: You go into your favorite fast food restaurant. There's a promotion: A free soda with the purchase of a meal. The restaurant will still make money on the deal, and in fact hopes the additional volume from additional customers will more than make up for the lost revenue from the free soda. You can't just walk in and say, "Well, you're offering a free soda. I want that free soda. But I don't want the full-priced food." Point is: There are costs or expenses in many mortgages that are spread out over an anticipated life of 5-7 years. If the mortgage is refinanced or paid off after 6 months, those costs haven't been recovered.
Thus, the penalty.