Cross-Site Script Inclusion (XSSI) Attack in TypeScript-Based ERP

Modern ERP applications written in TypeScript are known for their type safety and scalable architecture. However, even with strong typing and modern syntax, they are not immune to web vulnerabilities. One such overlooked vulnerability is the Cross-Site Script Inclusion–XSSI attack. In this post, we’ll explore the impact of the XSSI attack in TypeScript-based ERP, show you how to replicate it with real-world coding examples, and offer effective prevention techniques.

Prevent XSSI Attack in TypeScript ERP: Best 7 Ways

🔍 What is a Cross-Site Script Inclusion–XSSI Attack?

XSSI is a technique where an attacker attempts to steal sensitive JSON data from an API by including it via a <script> tag. Since browsers do not enforce the same-origin policy for script resources, a vulnerable endpoint that returns JSON might be included in another site, leaking user information.

Here’s how it typically works:

  1. A web application returns a JSON response containing sensitive data.
  2. An attacker tricks a user into loading that JSON endpoint via a <script> tag.
  3. If the response is improperly formatted (e.g., wrapped in a variable assignment), the attacker can read or manipulate the data.

🚨 Example of a Vulnerable API in TypeScript ERP

// Vulnerable Express endpoint in a TypeScript-based ERP
app.get('/user-profile', (req, res) => {
  res.setHeader('Content-Type', 'application/javascript');
  res.send(`var userProfile = ${JSON.stringify({ username: 'admin', role: 'admin' })};`);
});

This code sends JSON data wrapped in a variable. If this endpoint is embedded in another domain:

<script src="https://erp.example.com/user-profile"></script>

The data will be accessible as a global variable (userProfile), even from an attacker-controlled website.


📸 Screenshot: Webpage of Our Free Website Security Scanning Tool

Screenshot of the free tools webpage where you can access security assessment tools for different vulnerability detection
Screenshot of the free tools webpage where you can access security assessment tools for different vulnerability detection.

Scan your ERP system with our Website Vulnerability Scanner tool to instantly detect vulnerabilities including XSSI, XSS, CSRF, and more.


🛡️ Secure Coding Practices to Prevent XSSI Attack in TypeScript ERP

Let’s walk through the 7 best ways to prevent XSSI attacks in your TypeScript ERP:


1. ✅ Return Only Raw JSON

Avoid wrapping responses in variable assignments.

app.get('/user-profile', (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.json({ username: 'admin', role: 'admin' });
});

2. 🚫 Avoid JSONP or JavaScript Responses

Old patterns like JSONP open the door for XSSI-style attacks:

// ❌ Don't use this
res.send(`callback(${JSON.stringify(data)});`);

Unless absolutely necessary, avoid using this approach.


3. 🔐 Use Strong CORS Policies

Always define a strict Access-Control-Allow-Origin header:

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'https://yourdomain.com');
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  next();
});

4. 💡 Use Anti-CSRF Tokens in API Calls

For sensitive operations, require CSRF tokens even for same-origin requests:

// Add CSRF protection middleware
import csrf from 'csurf';
app.use(csrf({ cookie: true }));

5. 🚧 Validate Accept Headers

Ensure only requests with valid Accept headers are processed:

app.use((req, res, next) => {
  const acceptHeader = req.headers.accept || '';
  if (!acceptHeader.includes('application/json')) {
    res.status(406).send('Not Acceptable');
  } else {
    next();
  }
});

6. ⚠️ Don’t Log Sensitive Data in Client-Side Console

Avoid logging entire API responses on the frontend which may aid in debugging, but exposes risk:

// ❌
console.log(await fetch('/api/user-profile'));

// ✅
console.log('User data loaded');

7. 🧪 Regular Security Scans

Use automated scanners to detect XSSI and other issues during development.

Try our free scanner at https://free.pentesttesting.com to get instant results and a downloadable vulnerability assessment report.


📸 Screenshot: Website Vulnerability Assessment Report

An example of a vulnerability assessment report generated with our free tool provides insights into possible vulnerabilities.
An example of a vulnerability assessment report generated with our free tool provides insights into possible vulnerabilities.

Our scanner detected XSSI in a TypeScript ERP system to check Website Vulnerability and offered suggestions like header corrections and data formatting fixes.


📘 Additional Coding Examples

Example: Secure Fetch in TypeScript

// Safe fetch using token
fetch('/api/data', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': getCsrfToken()
  },
  credentials: 'include'
});

Middleware to Enforce JSON-Only Response

function enforceJsonOnly(req: Request, res: Response, next: NextFunction) {
  res.setHeader('Content-Type', 'application/json');
  next();
}

Apply it to all sensitive routes:

app.use('/api', enforceJsonOnly);

🔗 Related Resources from Our Blog

Also, check out this related blog post from our other website:
👉 Prevent CRLF Injection in OpenCart


📋 Quick Checklist for XSSI Prevention

✔️ Step📌 Description
Use application/jsonDon’t return JSON as JS
Implement CSRF tokensEven for GET requests with sensitive data
Validate Accept headersEnforce correct headers on incoming requests
CORS PolicyOnly allow trusted origins
Avoid JSONPUse modern fetch APIs
Scan frequentlyUse tools like free.pentesttesting.com

🧠 Final Thoughts

Even in strongly typed TypeScript ERP platforms, security vulnerabilities like Cross-Site Script Inclusion (XSSI) can go unnoticed. It’s essential to understand that JSON is not safe by default when returned from an endpoint—how it is returned matters more than what is returned.

By applying the techniques discussed in this post, including strict content types, validated headers, and regular scanning, developers can significantly reduce the risk of XSSI attacks.

🎯 Don’t leave your security to chance—scan your ERP with our free tool now!


Free Consultation

If you have any questions or need expert assistance, feel free to schedule a Free consultation with one of our security engineers>>

Get a Quote

1 thought on “Prevent XSSI Attack in TypeScript ERP: Best 7 Ways”

  1. Pingback: Best 7 Ways to Prevent CRLF Injection in TypeScript ERP

Leave a Comment

Your email address will not be published. Required fields are marked *