How does a propeller remain attached to the engine? I know there is a gearbox and/or some other mechanism that transmit the movement but is there any security mechanism that avoids it from completely detaching from the main engine? There is a huge amount of forces acting on that tiny spot where the propeller is attached to the engine, especially on turboprops, and this is where my question comes from.
Nuts. Technically nuts and bolts.
If you look at pictures of propeller hubs (google "propeller hub") you'll see that the individual prop blades are held onto the prop hub by nuts and bolts holding the hub halves together. Or for wooden props they're bolted directly onto the hub.
If you then take the hub apart, you'll see that the hub is attached to the shaft using nuts and bolts.
I sometimes see people asking why aircraft engineers specify very expensive nuts and bolts for certain parts of the aircraft when a cheaper part can handle an equivalent load. Your question is exactly the reason - it's better to over-engineer certain parts like the prop assembly than have the prop accidentally fly off during flight.