How import map can be safe?

You suggest using import maps here: three.js docs

I have an interesting question from QTX on Discord:

I wonder how import map can be safe? After all if we have js file in node.modules we still have copy of our desired library that can’t be changed or abused, unless we update it. But if we import directly package from HTTP into production and someone change it / hack it to do smth bad, how will websites protect from such risk?

How could you answer on this question?

I don’t understand how the raised issue is related to Import Maps. A man-in-the-middle attack could alter any URLs in websites like the one’s in script or style tags.

1 Like

ElementalCode answered to QTX here:

File hashes can be used for integrity. You link the external js and tell the browser “only run if it matches this hash”
Subresource Integrity - Security on the web | MDN

Interesting. It seems the following discussion would be the right place for this issue:

1 Like

ElementalCode answered here:

While mitm can alter the html you get, if only a CDN or a particular npm package is compromised the integrity check can work.
Integrity check also makes sure you have the right version and didn’t get a sneaky update, think of it as package.lock

QTX answered here:

I kinda don’t understand this answer. If there is a guy in the middle, he can change the imported scripts for his view and not for everyone else. This is why npm packages basically save the version on your front end and pack them into a javascript, this way, he can’t manipulate that javascript on your CDN or express server.

The issue is not to change urls in your tag but to change code on package you are importing that can affect production.

In case of importMap, if you import let’s say package of color.js via HTTP (relatable :-D) and then the guy who owns the package just update it’s cdn exports, he can break your frontend without rebuilding your code. Because it will always re-fetch from CDN it can be manipulated and abused.

Like @ElementalCode said, storing exact hash so it will check if the CDN file was updated can be a good way to protect yourself from unexpected manipulations of the packag