Water trapped inside lunar soils probably comes from the solar wind—the steady stream of charged particles from the sun.
As faraway stars die, they generate massive solar winds that eject up to half the star’s mass into space, where it becomes accessible for building Earth-like planets.