PERM filing through Company B , While working with Company A

Advance thanks for your Time and Response

I am working for company A on H1B, 5+ years completed of my H1B, Company A has not yet filed my PERM.
I reached out to Company-B, Company-B is ready to file my PERM considering me as a future employment category( without Company B payroll), once my PERM is approved in the next 5/6 months then Company-B ll file my H1B transfer then I-140 file on ASAP

Q-1 Working with a company -A and filing a PERM by another company B, is legally OK?
Q-2 Is there any other legal challenge will come in future for my I140 Approval and/or my on Green card processing on EB2/EB3 category

Green card is a future job and any employer can sponsor green card job, so yes this is perfectly alright.

Not sure what you mean by legal challenge? If the green card sponsoring employer has a bonafide job for you and have the ability to pay, there should be no issue.