Theory of the nonreciprocal Josephson effect