Learn to Detect & Prevent JSD Attacks With This Guide

Nowadays, JS (Javascript) is the main and important part of our modern web applications which provides the interactive UI with full-fledged server-side logic. And now the attackers come into the picture and whatever weakness is there in JS, attackers will use the benefits of it and disturb the flow of the beautiful empire of JS. So now in this article, I’m gonna tell you about some cyberattacks and how the developer will put the safeguards in their applications so now, let’s get started.
Magecart Attacks
What is this magecart attack?
Attackers are very damn smart – they will inject the malicious js code into the e-commerce websites and steal the payment-related details, credit card numbers, and CVVs from the checkout pages. They disturb the third-party packages with the use of malicious js code and get the user’s sensitive data. The real examples of this attack are.
“The British Airways breach in 2018 resulted in 380,000 payment records being stolen due to a Magecart attack.”
“Newegg Breach (2018) – 50M+ Visitors at Risk” and so on…
Oh, it’s very critical then how to prevent it?
How to Detect a Magecart Attack
?
SRI (Subresource Integrity)
SRI is a security feature that helps protect your website from malicious or compromised external resources (like third-party JavaScript or CSS files). It ensures that the content you load hasn’t been tampered with by verifying the integrity of the file using a cryptographic hash
.
How do we do SRI in our code?
This is one code we need to add to our code base
src
– our URL of the external script.
integrity
– Cryptographic hash of the file content.
crossorigin="anonymous"
– Allows loading from a different origin without sending user credentials.
We added this but now what happened?
Whenever you will see this line in our code then this attribute contains some hashed value (for example – SHA-256, SHA-384, or SHA-512 any of the one) of file content now whenever our browser loads the resource it will calculate its own hash and compares it with the provided value). If you want to learn more about the SRI, below is an official SRI links.
https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
SRI Hash Generator – https://www.srihash.org/
CSP (Content Security Policy)
CSP is also one security feature that helps prevent cross-site scripting (XSS), code injection, and other malicious content attacks by restricting which resources (like JavaScript, CSS, images, etc.) can be loaded and executed on a web page.
How to do it code level?
Let me give the example of NodeJS
app.get('/', (req, res) => {
res.setHeader(
"Content-Security-Policy", // This is our main CSP Header Setting
"default-src 'self'; script-src 'self' https://apis.example.com;"
);
res.send('Hello, CSP is active!');
});
default-src 'self'
– It allows all the resources like scripts, styles, images, and so on. To load it from the same origin. And it’ll block any other external domains.script-src 'self' https://apis.example.com
How can we check it like CSP Header is there or not?
→ Open Developer Tool
→ Network Tab
→ Refresh The Page & Check The Response Headers
You will find this “Content-Security-Policy” like the below screenshot.
Malicious npm Packages
Malicious NPM Packages mean it’s harmful software packages only that are uploaded In the NPM (Node Package Manager) portal which is the the world’s largest repository for our javascript libraries. Now what packages will do? Pretends like a legitimate tool but it contains very harmful malicious code that affects our system.
Now, as a developer what we will do? We will install it and once it’s installed then attackers come into the picture and they will steal our sensitive data like API Keys, Passwords, bank-related info, and so on.
That’s fine but one question: how do attackers spread these malicious packages?
Good Question for this they are using some techniques to spread it, here is the most famous technique.
Typosquatting
In this technique what attackers will do? they will target the famous packages of npm and create the same package with misspelled or alternative names and our innocent developers accidentally install that package then boom. Attackers’ pockets are filled with our precious data.
Let me give some examples of it.
Main Package |
Malicious Package |
---|---|
http-server |
httpserver |
lodash |
lodsh |
Oh, that’s very dangerous but as a developer what do we need to take care of it?
Yeah, some points we need to keep in our mind.
- before installing any package we need to check if it has the correct spelling and if it’s official or what. With the use of the below example
npm view express
It’ll give the whole details of that package
2. As a developer, we need to always use the below command to check any vulnerability and typeosquatting.
npm audit
It’ll scan our project’s security vulnerability.
Cross-Site Scripting (XSS)
This is the most famous and most common vulnerability of the web. Here attackers will inject the malicious JS code into the website and then the script will run in the browser and attackers will steal our data.
How is that working?
-
The basic thing is attacker will inject code into our website but how?
Attackers will use different ways to do it like Comment Box, URL Parameters, form fields, and so on.
-
That script will perform some harmful actions like stealing cookies, displaying fake forms, website redirection, record keystrokes, and so on.
Cool, but how many attacks are there?
There are total 3 types of attacks of XSS
Reflected XSS
Let’s take a good example in NodeJS
Whenever user will use the search so at that time user will use below URL
URL –
Now the user will see this output
“Search Results for: helloWorld”
This is the basic flow and we don’t have any type of validation in Search Text
but now If the attacker knows about this then what they will do, they will hit the script via params like this,
Attackers will hit this URL =http://localhost:3000/search?searchText=
Now, the page will render it because of that malicious script and the output would be this
Oh, then How to protect it?
We will take the NodeJS example to solve this
There is one package namedescape-html
we will use and here is our updated code
But what is the difference here in the output?
Good question let me provide the output of it
Now, the Attacker will use this URL as per the above flow
http://localhost:3000/search?searchText=
Because of our npm
, it’ll remove the special characters and the output would be below and the page will not render it’ll show only text to the page but nothing will do.
Search Results for:
Stored XSS
In this attack, attackers add malicious JS code in the comment section or in the form field and that code will store the user’s data on the attacker’s server.
Let’s take the example of it in NodeJS
In our code, there is no validation and directly we are storing our data in our db without validation so it’ll show like this,
Now, if the normal user adds comments – “Good blog Post!”
then it’ll store to db and it’ll show like this on the page
Good blog Post!
But if attacker will add the comment – “”
then in page it’ll show this
And every time whenever user views that comment page their cookie (sessions, auth tokens
) will be stored in the attacker’s server,
Yeah, that is very dangerous but how to protect it?
There is a good way to handle it before storing comments in db. We need to sanitize it and then we can do it.
How to sanitize?
In the same example, we will add it, so what we have done is, we added one npm name “dompurify”
so it’ll sanitize the body content and then it’ll add the content in the db safely.
DOM-Based XSS
It occurs when the attacker’s malicious script disturbs the DOM (Document Object Model) on the client side without interacting with the server.
Let’s take an example of a search page term, This is the code of JS
// Get the search term from the URL
const searchQuery = location.hash.substring(1);
// Display the search term on the page
document.getElementById('result').innerHTML = `You searched for: ${searchQuery}`;
It means if the user searches with this “https://example.com/#Hello”
then it’ll return
“You searched for: Hello”
Now how attackers will hit it
They will use this “https://example.com/#”
and then the output would be
“You searched for: ”
and the script will execute it.
How to protect it?
In the same example, we need to use “textContent”
instead of “innerHTML”
const searchQuery = location.hash.substring(1);
document.getElementById('result').textContent = `You searched for: ${searchQuery}`;
Now, it attacker will use that code,
https://example.com/#
Then it’ll not execute and it’ll return this,
You searched for:
Conclusion
Modern web applications face increasing JavaScript-driven cybersecurity attacks because attackers successfully identify their weaknesses. The protection against these threats requires proactive security measures which include Subresource Integrity (SRI) implementation and Content Security Policies (CSP) configuration and proper npm package installation practices and XSS vulnerability management. Developers who follow best practices can protect their applications from malicious attacks while maintaining user data security. Always stay informed and maintain vigilance because security needs to be your top priority during development.