Command Palette

Search for a command to run...

Security

Treege 3.0+ includes built-in security features to protect your applications from common web vulnerabilities.

XSS Protection with DOMPurify

What is XSS?

Cross-Site Scripting (XSS) is a security vulnerability where attackers inject malicious scripts into web applications. These scripts can steal user data, hijack sessions, or perform unauthorized actions.

Built-in Protection

TreegeRenderer automatically sanitizes all user input using DOMPurify, a trusted and well-maintained HTML sanitizer library. This protection works out of the box with no configuration required.

How it works:

  1. User submits form data (including potentially malicious HTML/JavaScript)
  2. TreegeRenderer automatically sanitizes the input using DOMPurify
  3. Only safe, sanitized content is rendered
  4. Malicious scripts are removed before they can execute

Example

import { TreegeRenderer } from "treege/renderer";
 
function App() {
  const flow = {
    id: "comment-form",
    nodes: [
      {
        id: "comment",
        type: "input",
        data: {
          type: "textarea",
          name: "userComment",
          label: "Your Comment",
          required: true
        }
      }
    ],
    edges: []
  };
 
  const handleSubmit = (values) => {
    // Even if values.userComment contains malicious HTML,
    // it has already been sanitized by TreegeRenderer
    console.log("Safe comment:", values.userComment);
  };
 
  return <TreegeRenderer flows={flow} onSubmit={handleSubmit} />;
}

What Gets Sanitized

DOMPurify removes potentially dangerous content including:

  • <script> tags and inline JavaScript
  • Event handlers (e.g., onclick, onerror)
  • JavaScript URLs (e.g., javascript:alert())
  • Data URIs with scripts
  • Other XSS vectors

Safe HTML Content

If you need to allow certain HTML formatting in user input (like bold, italic, links), DOMPurify intelligently preserves safe HTML while removing dangerous content:

// Input from user
const userInput = `
  <p>This is <strong>safe</strong> formatting</p>
  <script>alert('This will be removed')</script>
  <a href="javascript:alert('XSS')">This link will be sanitized</a>
  <a href="https://example.com">This link is safe</a>
`;
 
// After DOMPurify sanitization:
// <p>This is <strong>safe</strong> formatting</p>
// <a href="https://example.com">This link is safe</a>

React Native Security

The React Native renderer (treege/renderer-native) doesn't include DOMPurify because React Native doesn't use the DOM. However, React Native has its own security features:

  1. No DOM: React Native doesn't use HTML, so many XSS attacks don't apply
  2. Safe by default: Text components automatically escape special characters
  3. WebView isolation: If you use WebViews, they run in isolated contexts

Best Practices

1. Always Validate Server-Side

While TreegeRenderer provides client-side sanitization, always validate and sanitize data on your server as well. Client-side security can be bypassed by malicious actors.

// Client-side (TreegeRenderer handles this)
<TreegeRenderer flows={flow} onSubmit={handleSubmit} />
 
// Server-side (you should implement this)
app.post("/api/submit", (req, res) => {
  const sanitizedData = sanitizeInput(req.body); // Your server-side validation
  // Process sanitized data
});

2. Use HTTPS

Always serve your application over HTTPS to prevent man-in-the-middle attacks and ensure data is encrypted in transit.

3. Implement CSRF Protection

If you're building a web application with authentication, implement CSRF (Cross-Site Request Forgery) protection:

// Example with CSRF token
const handleSubmit = async (values) => {
  await fetch("/api/submit", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-CSRF-Token": getCsrfToken() // Your CSRF token
    },
    body: JSON.stringify(values)
  });
};
 
<TreegeRenderer flows={flow} onSubmit={handleSubmit} />

4. Validate File Uploads

When using the file input type, always validate file types and sizes on both client and server:

{
  id: "avatar",
  type: "input",
  data: {
    type: "file",
    name: "profilePicture",
    label: "Profile Picture",
    // Client-side validation
    accept: "image/png,image/jpeg",
    maxSize: 5 * 1024 * 1024 // 5MB
  }
}
 
// Server-side validation (implement this)
app.post("/api/upload", upload.single("file"), (req, res) => {
  const file = req.file;
 
  // Validate file type
  const allowedTypes = ["image/png", "image/jpeg"];
  if (!allowedTypes.includes(file.mimetype)) {
    return res.status(400).json({ error: "Invalid file type" });
  }
 
  // Validate file size
  if (file.size > 5 * 1024 * 1024) {
    return res.status(400).json({ error: "File too large" });
  }
 
  // Process file
});

5. Sanitize HTTP Input Responses

When using the http input type to fetch data from external APIs, be cautious with the response data:

{
  id: "country",
  type: "input",
  data: {
    type: "http",
    name: "country",
    label: "Select Country",
    httpConfig: {
      url: "https://trusted-api.example.com/countries",
      method: "GET",
      responsePath: "$.data",
      mapping: {
        label: "name",
        value: "code"
      }
    }
  }
}

Best practices for HTTP inputs:

  • Only fetch from trusted APIs
  • Validate the response structure
  • Sanitize any user-generated content in the response
  • Use HTTPS endpoints
  • Implement rate limiting to prevent abuse

6. Content Security Policy (CSP)

Implement a Content Security Policy to add an extra layer of protection against XSS:

<!-- In your HTML head -->
<meta http-equiv="Content-Security-Policy"
      content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';">

Or via HTTP headers:

// Express.js example
app.use((req, res, next) => {
  res.setHeader(
    "Content-Security-Policy",
    "default-src 'self'; script-src 'self'"
  );
  next();
});

7. Keep Dependencies Updated

Regularly update Treege and its dependencies to get the latest security patches:

npm update treege
# or
bun update treege

8. Implement Rate Limiting

Protect your forms from spam and abuse by implementing rate limiting:

import rateLimit from "express-rate-limit";
 
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 10, // Limit each IP to 10 requests per windowMs
  message: "Too many form submissions, please try again later"
});
 
app.post("/api/submit", limiter, (req, res) => {
  // Handle form submission
});

Security Checklist

Use this checklist to ensure your Treege implementation is secure:

  • [ ] Server-side validation implemented for all inputs
  • [ ] Application served over HTTPS
  • [ ] CSRF protection enabled for authenticated forms
  • [ ] File uploads validated (type, size, content)
  • [ ] HTTP inputs only fetch from trusted APIs
  • [ ] Content Security Policy configured
  • [ ] Dependencies kept up to date
  • [ ] Rate limiting implemented for public forms
  • [ ] Sensitive data encrypted at rest and in transit
  • [ ] Security headers configured (X-Frame-Options, X-Content-Type-Options, etc.)

Reporting Security Issues

If you discover a security vulnerability in Treege, please report it to the maintainers via:

Please do not publicly disclose security vulnerabilities until they have been addressed.

Additional Resources

Next Steps