When I get a new peripheral, like a fancy mouse, or a new keyboard, normally I see that a driver is installing.

Once the driver for the device has completely installed - the hardware works.

I'm curious (from a technical standpoint) how does windows detect a new device?

How does it have permission to automatically install onto a machine?

What code is written that pushes the driver software automatically?

Is this a Risk? Can this automatic software info be exploited?