Low-density magnesium (Mg) alloys are excellent engineering materials, and can significantly reduce energy consumption by replacing existing steel and aluminum materials. However, Mg species are susceptible to corrosion, especially in harsh environments (high-temperature or acidic), severely limiting the range of practical applications. Here, 2D covalent organic framework (COF) is synthesized with pore diameters ranging from 1.5 to 2.9 nm to obtain ultrafast nanofluidic channels. Loaded with silver (Ag+) ions, 2-mercaptobenzimidazole (2-MB) inhibitors are immobilized in the COF channels through the silver bridges. Based on the strong metal-complexing capability, Ag+ ions precipitated with various corrosive media (Cl−, Br−, I−, SO32−, S2−, S2O32− SO42−, CO32−, PO43−); meanwhile, the 2-MB inhibitors are rapidly released through the nanofluidic channels, forming a passivation film as a corrosion barrier to protect the Mg substrate. After integration with commercial polyethersulfone (PES), the COF-based coating exhibits high repairing capability achieving 100% damage restoration within 7 h, outperforming all existing coatings of Mg alloys. Notably, the coating shows almost complete protection of Mg alloys after being treated in respective 473 K, acidic (pH ≈4.0), and alkaline (pH ≈10.0) environments.