I think a partial solution to this is when a USB device connects it should need permission to perform certain categories of actions. Like Safari asks the user “this website would like to know your location”, MacOS could tell users when they plug in their phone to charge off their laptop: “The device you just connected wants to be a keyboard. Allow?”
Yes, it would still spoof the apple Magic Keyboard or whatever, but you’d need to allow the keyboard to be a keyboard every time you connect it. If you plug in something that should definitely not be a keyboard, you can investigate the cable by swapping out with a known good cable.