mcpbeat Sign in

Xss Prevention Skill for Claude

XSS attack prevention with input sanitization, output encoding, Content Security Policy. Use for user-generated content, rich text editors, web application security, or encountering stored XSS, reflected XSS, DOM manipulation, script injection errors.

5k tokens
context cost
the whole folder, loaded on every use
3
files
instructions only
0
copies elsewhere
how many repositories repackaged it
202
stars on the repo
on the repository, not the skill itself

Install

one command, takes just this skill from the repository
npx skills add https://github.com/secondsky/claude-skills --skill xss-prevention

The instruction itself

14 sections, as written by the author

XSS Prevention

Overview

Implement comprehensive Cross-Site Scripting attack prevention through input sanitization, output encoding, Content Security Policy headers, and secure coding practices.

When to Use

  • User-generated content display
  • Rich text editors
  • Comment systems
  • Search functionality
  • Dynamic HTML generation
  • Template rendering scenarios

XSS Attack Types

| Type | Vector | Defense |

|------|--------|---------|

| Reflected | URL parameters | Output encoding |

| Stored | Database content | Input sanitization |

| DOM-based | Client-side JS | Safe DOM APIs |

| Mutation | HTML parser quirks | Strict sanitization |

Output Encoding (Node.js)

function encodeHTML(str) {
  return str
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;');
}

function encodeForAttribute(str) {
  return str.replace(/[^\w.-]/g, char =>
    `&#x${char.charCodeAt(0).toString(16)};`
  );
}

// Usage in templates
app.get('/profile', (req, res) => {
  const username = encodeHTML(req.query.name);
  res.send(`<h1>Welcome, ${username}</h1>`);
});

DOMPurify Sanitization

import DOMPurify from 'dompurify';

const config = {
  ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br'],
  ALLOWED_ATTR: ['href', 'title'],
  ALLOW_DATA_ATTR: false
};

function sanitizeHTML(dirty) {
  return DOMPurify.sanitize(dirty, config);
}

// React component
function RichContent({ html }) {
  return (
    <div dangerouslySetInnerHTML={{ __html: sanitizeHTML(html) }} />
  );
}

Content Security Policy

// Express middleware
app.use((req, res, next) => {
  const nonce = crypto.randomBytes(16).toString('base64');
  res.locals.nonce = nonce;

  res.setHeader('Content-Security-Policy', [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}'`,
    "style-src 'self' 'unsafe-inline'",
    "img-src 'self' data: https:",
    "connect-src 'self' https://api.example.com",
    "frame-ancestors 'none'",
    "base-uri 'self'",
    "form-action 'self'"
  ].join('; '));

  next();
});

Safe DOM APIs

❌ NEVER do any of the following with user-controlled input — these are XSS

sinks and there is no safe way to call them with untrusted data:

  • Assign it to element.innerHTML / element.outerHTML
  • Pass it to eval()
  • Pass it to document.write()
  • Pass it to setTimeout / setInterval as a string
  • Insert it into an inline event handler (e.g. onclick="...")
// SAFE — use these instead
element.textContent = userInput;      // Escaped automatically
element.setAttribute('data-id', id);  // Safe for attributes
document.createTextNode(userInput);   // Creates safe text node

The safe patterns above (textContent, attribute escaping via setAttribute,

DOMPurify.sanitize) are the only correct ways to handle user input in the DOM.

URL Validation

function isSafeURL(url) {
  try {
    const parsed = new URL(url);
    return ['http:', 'https:'].includes(parsed.protocol);
  } catch {
    return false;
  }
}

// Usage
const href = isSafeURL(userURL) ? userURL : '#';

Context-Specific Encoding

Different contexts require different encoding approaches:

  • HTML Entity Encoding: Safest option for text content
  • Attribute Encoding: For HTML attributes
  • JavaScript Escaping: For script contexts
  • URL Encoding: For URL parameters
  • CSS Escaping: For stylesheet contexts

Always encode output by the specific context where data will be rendered.

Additional Implementations

See references/python-sanitization.md for:

  • Python bleach library usage
  • Flask/Django template escaping
  • Server-side validation patterns

See references/nodejs-advanced.md for:

  • Complete XSSPrevention class with all methods
  • Express middleware (xssProtection)
  • React components (SafeText, SafeHTML, SafeLink, useSanitizedInput)
  • Helmet CSP configuration

Best Practices

✅ DO:

  • Encode output by default
  • Use templating engines with auto-escaping
  • Implement CSP headers
  • Sanitize rich content with allowlists
  • Validate URLs with protocol whitelisting
  • Use HTTPOnly cookies
  • Conduct regular security testing
  • Leverage secure frameworks

❌ DON'T:

  • Trust user input
  • Use unsafe functions (eval, innerHTML)
  • Disable security features for convenience
  • Rely solely on client-side validation
  • Use blocklists instead of allowlists
  • Skip context-specific encoding
  • Allow arbitrary script execution

Security Checklist

  • [ ] Encode all output by context (HTML, attribute, JS)
  • [ ] Sanitize HTML with allowlist (not blocklist)
  • [ ] Implement strict CSP headers
  • [ ] Use HTTPOnly cookies for sessions
  • [ ] Validate and sanitize URLs
  • [ ] Avoid innerHTML with user content
  • [ ] Regular security testing

Resources

Other skills for the same job

different authors, same section of the catalogue
Protocolsio Integration
by christophacham
×4

Integration with protocols.io API for managing scientific protocols. This skill should be used when working with protocols.io to search, create, update, or publish protocols; manage protocol steps and materials; handle discussions and comments; organize workspaces; upload and manage files; or integrate protocols.io functionality into workflows. Applicable for protocol discovery, collaborative protocol development, experiment tracking, lab protocol management, and scientific documentation.

16k tokens
Tailored Resume Generator
by frostant
×4

Analyzes job descriptions and generates tailored resumes that highlight relevant experience, skills, and achievements to maximize interview chances

3k tokens
Excalidraw Diagram Generator
by github
vendor ×3

Generate Excalidraw diagrams from natural language descriptions. Use when asked to "create a diagram", "make a flowchart", "visualize a process", "draw a system architecture", "create a mind map", or "generate an Excalidraw file". Supports flowcharts, relationship diagrams, mind maps, and system architecture diagrams. Outputs .excalidraw JSON files that can be opened directly in Excalidraw.

36k tokens scripts
Expo Dev Client
by openai
vendor ×3

Build and distribute Expo development clients locally or via TestFlight

961 tokens
Executing Plans
by ZhanlinCui
×3

Use when you have a written implementation plan to execute in a separate session with review checkpoints

542 tokens
Anndata
by christophacham
×3

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

16k tokens
Benchling Integration
by christophacham
×3

Benchling R&D platform integration. Access registry (DNA, proteins), inventory, ELN entries, workflows via API, build Benchling Apps, query Data Warehouse, for lab data management automation.

14k tokens
Biopython
by christophacham
×3

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

24k tokens

How to use it

Copy the folder

Take secondsky/xss-prevention from the repository into ~/.claude/skills for personal use, or into .claude/skills inside a project.

Check the name does not clash

The agent identifies a skill by the name field in its header. Two skills with the same name cannot sit side by side — one of them will be ignored.