I always figured S31 was only legal if you interpreted that section of the Federation charter in a way that was technically accurate but so far afield of the intended and/or generally-accepted meaning that the vast majority of beings who read it would never think that it sanctioned S31's activities. Of course, since there's no accountability within the organization, there's nobody to judge them either.
I also never thought S31's activities were limited to outside the Federation; it just sounds better if Sloan tells Bashir about threats posed by the Dominion than if he talks about how Admiral Jones didn't actually slip on his tea after he began advocating for a cease-fire with the Dominion.
In the end though, I don't really think the writers of "Inquisition" ever anticipated that S31 would receive the amount of exposure that it has within the franchise. In a way, good on them for raising compelling questions. In another way, maybe it would have been better if they hadn't...
What the NuNiverse did with them is somewhat irrelevant since Narada's incursion obviously had security ramifications for Starfleet, and it's easy enough to believe S31 would be more of a proper division in that timeline.
What DISCO did with them is a bit harder to handwave especially in light of what ENT had already done, though if you think of them as something that Starfleet ostensibly only activates during a pending crisis (e.g. the Klingon War) then it almost makes sense. ENT operated during peacetime, so S31 was operating covertly, but during the Klingon War they're activated...but after the fiasco with Control they're decommissioned/go dark again.