Security skill · Find and fix
XSS: find and fix.
Find cross-site scripting (reflected, stored, DOM-based) by tracing untrusted data to HTML, attribute, JavaScript, and URL sinks, confirm with harmless probes in a test environment, and fix with context-aware output encoding, framework defaults, sanitization, and Content-Security-Policy. Use when reviewing a web frontend or server-rendered pages for XSS (CWE-79).
Facts
- Category
- Find and fix
- License
- MIT
- Tags
- Code review
- Version
- 1.0.0
- Last updated
- 2026-12-02
- Folder
xss-find-and-fix/- MCP resource
skill://xss-find-and-fix/SKILL.md- Files
- SKILL.md
- LICENSE
- references/context-encoding.md
- Standards
- A05:2025
- CWE-79
Original Saasment content. Saasment is in early access; this skill does not require joining it.
Install via MCP or as files
Connect your client to https://www.saasment.com/api/mcp (see client setup) and call get_skill:
{
"name": "get_skill",
"arguments": {
"slug": "xss-find-and-fix"
}
}Or download the .zip and unpack it into your agent's skills directory:
Terminal, from your project root (user-level: ~/.cursor/skills)
mkdir -p .cursor/skills
curl -fsSL https://www.saasment.com/ai-security/skills/xss-find-and-fix/download.zip -o /tmp/xss-find-and-fix.zip
unzip -o /tmp/xss-find-and-fix.zip -d .cursor/skills
# result: .cursor/skills/xss-find-and-fix/SKILL.mdReview SKILL.md before enabling a skill. Skills are instructions your agent will follow.
SKILL.md
---
name: xss-find-and-fix
description: Find cross-site scripting (reflected, stored, DOM-based) by tracing untrusted data to HTML, attribute, JavaScript, and URL sinks, confirm with harmless probes in a test environment, and fix with context-aware output encoding, framework defaults, sanitization, and Content-Security-Policy. Use when reviewing a web frontend or server-rendered pages for XSS (CWE-79).
license: MIT
metadata:
author: Saasment
version: "1.0.0"
category: both
tags: "code-review"
---
# XSS: find and fix
License: MIT. Copyright (c) 2026 Saasment. Source: https://www.saasment.com/ai-security/skills/xss-find-and-fix
Cross-site scripting lets an attacker run script in another user's browser session, which can lead to account takeover, data theft, and actions taken as the victim. It happens when untrusted data reaches an HTML, attribute, script, or URL context without the right encoding for that context. The durable fixes are framework auto-escaping, context-aware encoding, sanitization when HTML is required, and a restrictive Content-Security-Policy as a second layer.
## When to use
- You review a frontend or server-rendered application for XSS.
- Users can submit content that other users see (comments, profiles, tickets, filenames, markdown).
- An application renders LLM output or third-party content in a browser.
## Safe by default
- Only test applications you own or are authorized to test, preferably in staging.
- Use harmless probes that prove execution without effects, such as an element with a visible marker or `console.log('CANARY-7f3a')` in a test browser. Do not use payloads that steal cookies, call external hosts, or alter other users' data.
- Do not leave probe payloads stored in shared or production data. Remove test records after verification.
- When testing stored XSS, use accounts you control so no real user sees your payload.
## Procedure
1. **Map sources.** List where untrusted data enters: query parameters, path segments, form fields, headers, JSON APIs, uploaded file names and contents, stored user profiles, third-party API data, URL fragments, `postMessage` events, and model output.
2. **Map sinks.** Search the code (patterns in `references/context-encoding.md`) for places that write data to the page:
- Server templates that disable escaping.
- Client DOM APIs: `innerHTML`, `outerHTML`, `insertAdjacentHTML`, `document.write`, `dangerouslySetInnerHTML`, `v-html`, `[innerHTML]`, `$.html()`.
- Script contexts: `eval`, `new Function`, `setTimeout` with a string, inline event handlers, inline `<script>` blocks that include data.
- URL contexts: `href`, `src`, `action`, `location` assigned from user data (look for `javascript:` and `data:` schemes).
3. **Match context to control.** For each flow, identify the output context and the control it needs:
- HTML body: HTML-encode, or rely on the framework's default escaping.
- HTML attribute: encode and always quote attributes.
- JavaScript data: pass data as JSON in a data attribute or a JSON script block with `<` encoded, not by string concatenation into script.
- URL: allow only expected schemes (`https:`, `http:`, `mailto:` as needed), and validate the URL with a parser.
- Rich HTML (user-authored markup): sanitize with a maintained allowlist sanitizer on output, such as DOMPurify in the browser, and never write your own regex filter.
4. **Confirm with harmless probes.** In the test environment, submit a distinctive string containing HTML metacharacters (`"><b id=canary>CANARY-7f3a</b>`) to each source and view the output in the browser. If it renders as a real element, or breaks out of an attribute, the sink is vulnerable. Check with the browser developer tools rather than relying on page text alone. Also test DOM-based flows by modifying the URL fragment or query parameters that client code reads.
5. **Fix:**
- Prefer the framework's default binding (React `{value}`, Vue `{{ value }}`, Angular interpolation, Jinja2 autoescape, ERB `<%= %>`, Razor `@`). Remove uses of "raw" or "safe" escape hatches unless the input is sanitized.
- Replace `innerHTML` with `textContent` where markup is not needed.
- When HTML is required, sanitize with an allowlist immediately before rendering, and keep the sanitizer up to date.
- Validate URLs with a scheme allowlist before placing them in `href` or `src`.
- Set cookies with `HttpOnly`, `Secure`, and an appropriate `SameSite` value to limit the impact of any remaining XSS.
- Add a Content-Security-Policy that avoids `unsafe-inline` for scripts where possible (use nonces or hashes), sets `object-src 'none'` and `base-uri 'self'`. Start in report-only mode to find breakage, then enforce. Consider Trusted Types for DOM sinks where browser support fits your users.
6. **Add tests.** Add component or integration tests that render metacharacter strings and assert they appear as text. Add a lint rule that flags `dangerouslySetInnerHTML`, `v-html`, and `innerHTML` assignments.
## Verification
- Repeat each probe from step 4. Expected: the probe appears as literal text, no element is created, and no script runs. Confirm in the browser developer tools Elements panel.
- Check the response headers in the deployed build: the CSP is present, and the console shows no violations from your own pages.
- Run the new tests; verify they fail against the old code and pass against the fix.
- Search the codebase again for the sinks from step 2. Every remaining use should have a documented sanitizer or constant input.
## Reporting
For each finding: page or endpoint, source, sink, context, probe used, fix, and test. Record any CSP exceptions and why they exist.
## References
- CWE-79: https://cwe.mitre.org/data/definitions/79.html
- OWASP XSS Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
- OWASP Top 10 web, Injection category: https://owasp.org/Top10/
- Companion skills: `insecure-output-handling-review`, `sql-injection-find-and-fix`.
Helper files
LICENSE
MIT License Copyright (c) 2026 Saasment Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
references/context-encoding.md
# XSS context and encoding reference
License: MIT. Copyright (c) 2026 Saasment.
## Context to control
| Output context | Example | Control |
| --- | --- | --- |
| HTML body text | `<p>NAME</p>` | HTML-encode `& < > " '`, or use the framework's default escaping |
| Quoted HTML attribute | `<input value="NAME">` | Encode and always quote the attribute |
| Unquoted attribute | `<input value=NAME>` | Do not use; always quote |
| JavaScript string in inline script | `<script>var n = "NAME"</script>` | Avoid. Put data in a JSON block or data attribute and read it from script |
| Event handler attribute | `onclick="f('NAME')"` | Avoid. Attach handlers in script and pass data via data attributes |
| URL attribute | `<a href="URL">` | Parse the URL and allow only expected schemes |
| CSS value | `style="color: VALUE"` | Allowlist values; avoid user-controlled CSS |
| Rich HTML | user-authored markup | Allowlist sanitizer at output time |
## Dangerous sinks to search for
```text
innerHTML, outerHTML, insertAdjacentHTML, document.write, document.writeln
dangerouslySetInnerHTML, v-html, [innerHTML], bypassSecurityTrustHtml, $(...).html(
eval(, new Function(, setTimeout("...", setInterval("..."
element.setAttribute("on...", location = , location.href = , window.open(
Jinja2: |safe, {% autoescape false %}, Markup(
ERB: raw, html_safe
Razor: @Html.Raw
Go templates: template.HTML(
PHP: echo without htmlspecialchars
```
## Safe patterns
```js
// Text instead of HTML
element.textContent = userValue;
// URL scheme allowlist
function safeUrl(input) {
try {
const url = new URL(input, window.location.origin);
return ["https:", "http:", "mailto:"].includes(url.protocol) ? url.href : "#";
} catch {
return "#";
}
}
// Sanitized HTML when markup is required (DOMPurify)
element.innerHTML = DOMPurify.sanitize(userHtml);
// JSON data block (encode "<" so "</script>" cannot appear)
// const json = JSON.stringify(data).replace(/</g, "\\u003c");
// <script type="application/json" id="page-data">{json}</script>
```
## Harmless probes (test environment only)
- Visible marker: `"><b id=canary>CANARY-7f3a</b>` then confirm in the DOM whether `#canary` exists as an element.
- Attribute break-out check: `" data-canary="7f3a` inside an attribute value, then inspect the element's attributes.
- DOM-based: change the URL fragment or query parameter the client code reads and watch whether the DOM changes in a way that creates elements.
- Script execution check (test browser only): `<img src=x onerror=console.log('CANARY-7f3a')>` and look for the console message. Remove the stored data afterward.
## Content-Security-Policy starting point
```text
Content-Security-Policy-Report-Only:
default-src 'self';
script-src 'self' 'nonce-<per-response-nonce>';
object-src 'none';
base-uri 'self';
frame-ancestors 'none'
```
Run in report-only mode first, review reports, then switch to enforcing. A CSP reduces the impact of XSS but does not replace output encoding.
Related
Companion skills
Questions
How do I install the XSS: find and fix skill?
Download https://www.saasment.com/ai-security/skills/xss-find-and-fix/download.zip and unzip it into your agent's skills directory (for example .cursor/skills, .claude/skills, .agents/skills, or .github/skills) so that xss-find-and-fix/SKILL.md exists. Or connect to https://www.saasment.com/api/mcp and call the get_skill tool with the slug xss-find-and-fix.
What license is the XSS: find and fix skill under?
It is original Saasment content under the MIT license, stated in the SKILL.md frontmatter and in the LICENSE file in the skill folder.
Is it safe to run this skill?
A skill is a set of instructions your agent follows, so read SKILL.md first. It tells the agent to test only systems you own or are authorized to test, to use test environments and synthetic data, and to avoid destructive probes. Downloading it does not run any code on your machine.