Hello, doctors and epidemiologists around the world overwhelmingly agree that HIV is only transmitted by unprotected vaginal or anal penetrative sex, sharing needles or mother to child.
Masturbation is not considered a risky activity, because there are no reports of people getting HIV by doing it.
No one of the "what ifs" you can imagine will change that.
Hope this helps.