The idea behind this is that the code generated by Device A must be transmitted separately to Device B. Any method of communication will do: email, text message, phone call, etc.
To answer your questions:
How is the code calculated in the first place? From a keypair?
This depends on the software of the device. Some vendors will generate a random 4 digit pin. Some will generate a passcode. It's up to the vendor how they wish to generate it, and how much entropy they want to have. TeamViewer uses this same type of method for its remote desktop software. They allow the user to choose the length, and type of passcode. Using a key-pair to generate passcodes seems like overkill, and they're most likely using some type of pseudo-random number generator.
Isn't sending the code from device B to device A subject to a passive
MITM attack? How is this communication authenticated?
This depends on how/if the communication is secured. It's possible that a secure protocol is used to encrypt the communication between the devices. This could be a standardized protocol like SSL/TLS, or it could be proprietary. As long as the communication is secured in some way the passcode would be sent encrypted to the device, and would be less likely to be subject to a MitM attack.
If the passcode is sent in the clear for everyone to see, then yes I would say a MitM attack is very possible.