This prompt is designed for security engineers and DevSecOps pipelines that need to perform a deep, structured analysis of a specific code snippet to determine if user-controlled data reaches a dangerous browser sink without adequate output encoding. The core job-to-be-done is not broad vulnerability scanning; it is a focused, evidence-backed trace of a single suspected Cross-Site Scripting (XSS) vector. The ideal user is a security reviewer who has already identified a potential source of user input—such as a URLSearchParams getter, a postMessage listener, or a server-rendered template variable—and needs to rigorously map its flow through JavaScript functions, DOM manipulations, or template expressions to a known dangerous sink like innerHTML, eval, or document.write.
Prompt
Cross-Site Scripting Sink Analysis Prompt

When to Use This Prompt
Defines the precise job-to-be-done, the ideal user profile, required inputs, and the boundaries where this prompt should not be applied.
To use this prompt effectively, you must provide a complete and self-contained code snippet as the [CODE_SNIPPET] input. The prompt assumes you have already isolated the suspicious code path; it will not scan a large codebase for vulnerabilities. You should also specify the [SOURCE] (the exact user-controlled input point) and the [SINK] (the suspected dangerous function or property) to focus the analysis. The prompt requires you to define an [OUTPUT_SCHEMA] that structures the response into a machine-readable format, typically JSON, with fields for the data flow trace, encoding assessment, CSP evaluation, and a final exploitability verdict. This structured output is critical for integrating the analysis into automated CI/CD security gates or vulnerability management systems.
Do not use this prompt as a general-purpose code reviewer, a substitute for dynamic analysis with a browser, or a comprehensive SAST tool. It is ineffective for analyzing highly obfuscated or minified code without deobfuscation, and it cannot reason about client-side JavaScript that is dynamically constructed on the server. The prompt's value is in its structured reasoning about encoding contexts and CSP bypasses, not in discovering new sinks. After running the analysis, you must validate its findings with a manual review or a dynamic test, as the model may hallucinate data flows in complex, callback-heavy asynchronous code. The next step is to take the structured finding and feed it into your vulnerability management workflow for tracking and remediation.
Use Case Fit
Where the Cross-Site Scripting Sink Analysis Prompt delivers reliable results and where it introduces unacceptable risk.
Good Fit: JavaScript and Template Sink Tracing
Use when: you need to trace user-controlled data from input sources (URL params, postMessage, localStorage) to dangerous sinks (innerHTML, eval, document.write) in frontend JavaScript or server-side template code. Why it works: the prompt excels at identifying missing output encoding and incomplete sanitization in DOM-based and reflected XSS patterns when provided with clear data flow context.
Bad Fit: Full Application Security Audit
Avoid when: you expect the prompt to perform a comprehensive security review of an entire codebase or replace a SAST tool. Risk: the prompt analyzes only the code context provided and cannot discover sinks in files you did not include. It will miss vulnerabilities in uninspected code paths. Guardrail: use this prompt for targeted sink analysis within a specific data flow, not as a standalone audit replacement.
Required Inputs: Source-to-Sink Path
What the prompt needs: the complete code path from user-controlled input to the dangerous sink, including any intermediate transformations, sanitization calls, or encoding functions. Minimum viable input: the source declaration, the sink call, and all transformation logic between them. Guardrail: if you cannot trace the full path, flag the analysis as incomplete and request additional code context before relying on the output.
Operational Risk: CSP Bypass Overconfidence
What to watch: the prompt may assess that Content Security Policy would mitigate a finding, but CSP bypass techniques evolve rapidly and policy misconfigurations are common. Risk: a finding marked as 'CSP-mitigated' may still be exploitable if the policy has gaps, allows unsafe-inline, or uses report-only mode. Guardrail: always verify the actual deployed CSP headers against the prompt's mitigation claim before closing a finding.
Operational Risk: Framework-Specific Encoding Blind Spots
What to watch: the prompt may not recognize framework-specific auto-escaping contexts (React JSX, Angular templates, Svelte) and could flag safe code as vulnerable or miss unsafe escape hatches like dangerouslySetInnerHTML. Guardrail: always include framework and templating engine context in the input. Pair the prompt output with a framework-aware manual review for escape hatch patterns.
Boundary: Stored XSS Requires Full Data Lifecycle
What to watch: for stored XSS analysis, the prompt needs both the storage write path and the rendering output path. Risk: analyzing only the rendering sink without the input validation at the storage boundary produces an incomplete assessment that may recommend output encoding when input validation is the stronger control. Guardrail: provide both the ingestion and rendering code paths for stored XSS analysis, and flag any finding where only one side of the lifecycle was reviewed.
Copy-Ready Prompt Template
A reusable prompt template for tracing user-controlled data to dangerous browser sinks and assessing XSS exploitability.
This prompt template is designed to be pasted directly into your AI tool of choice. It instructs the model to act as a security engineer performing a focused Cross-Site Scripting (XSS) sink analysis. The core job is to trace a suspected data flow from a user-controlled source to a potentially dangerous browser sink, assess the adequacy of any output encoding, and determine the real-world exploitability. Replace the bracketed placeholders with the specific code snippet, the identified source, the identified sink, and your application's Content Security Policy (CSP) before running the analysis.
markdownYou are a senior application security engineer specializing in client-side web security and Cross-Site Scripting (XSS) analysis. Your task is to perform a rigorous sink analysis on the provided code. **INPUT CONTEXT** - **Code Snippet:** ```[LANGUAGE] [CODE_SNIPPET]
- Identified Source: [USER_CONTROLLED_SOURCE, e.g.,
window.location.hash,document.referrer, a specific API response field] - Identified Sink: [DANGEROUS_BROWSER_SINK, e.g.,
element.innerHTML,eval(),document.write(), a jQueryhtml()call] - Active Content Security Policy (CSP): [CSP_HEADER_VALUE or 'No CSP is present']
ANALYSIS CONSTRAINTS
- Trace the complete data flow from the identified source to the identified sink.
- Determine the XSS context: HTML context, attribute context, JavaScript context, or URL context.
- Assess whether any output encoding, sanitization, or transformation is applied to the data before it reaches the sink. State explicitly if it is missing, inadequate for the context, or correctly implemented.
- Evaluate the exploitability of this specific data flow. If it is not exploitable, explain the precise mitigating factor (e.g., a strong sanitizer, a browser API restriction).
- Analyze the provided CSP to determine if it would mitigate a successful injection. State if the CSP can be bypassed.
- Classify the XSS type as DOM-based, Reflected, or Stored based on the source and data flow.
OUTPUT SCHEMA You must produce a JSON object with the following structure. Do not include any text outside the JSON block. { "finding_id": "string, a unique identifier for this finding", "xss_type": "string, one of: 'DOM-based', 'Reflected', 'Stored'", "source": "string, the confirmed user-controlled source", "sink": "string, the confirmed dangerous sink", "data_flow_summary": "string, a step-by-step trace of the data from source to sink", "context": "string, one of: 'HTML', 'Attribute', 'JavaScript', 'URL'", "encoding_assessment": { "is_present": "boolean", "method": "string or null, e.g., 'HTML entity encoding', 'JS string escaping'", "is_adequate": "boolean or null, is the encoding sufficient to prevent XSS in this context?" }, "exploitability": { "is_exploitable": "boolean", "reasoning": "string, a clear explanation of why it is or is not exploitable" }, "csp_mitigation_assessment": { "would_mitigate": "boolean", "reasoning": "string, explain if the CSP would stop the injection and if there are bypasses" }, "remediation": "string, a concrete, context-appropriate fix (e.g., 'Use textContent instead of innerHTML', 'Apply JS string escaping before passing to eval')", "confidence": "string, one of: 'high', 'medium', 'low'" }
To adapt this prompt, start by replacing the placeholders in the INPUT CONTEXT section. The [CODE_SNIPPET] should be a focused block of code, not an entire file, to keep the analysis sharp. The [USER_CONTROLLED_SOURCE] and [DANGEROUS_BROWSER_SINK] are your starting hypotheses; the model's job is to confirm and trace the path between them. The [CSP_HEADER_VALUE] is critical for a realistic assessment—if you don't provide it, the model cannot evaluate the defense-in-depth layer. For high-risk applications, always follow this automated analysis with a manual penetration test to confirm the finding and rule out bypasses the model may have missed.
Prompt Variables
Required inputs for the XSS sink analysis prompt. Each placeholder must be populated with concrete data before the prompt is sent. Missing or malformed inputs are the most common cause of false negatives.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CODE_SNIPPET] | The JavaScript or template code block containing the suspected sink | element.innerHTML = decodeURIComponent(window.location.hash.slice(1)); | Must be non-empty and contain at least one browser API call. Reject if only HTML markup without script context. |
[SINK_FUNCTION] | The specific DOM property or function where user data lands | innerHTML | Must match a known XSS sink list: innerHTML, outerHTML, document.write, eval, setTimeout(string), location.href, etc. Warn if sink is not in the standard catalog. |
[DATA_SOURCE] | The origin of user-controlled data flowing into the sink | window.location.hash | Must identify a tainted source: URL parts, postMessage, WebSocket, localStorage, input.value, etc. Reject if source is hardcoded or server-rendered without user influence. |
[OUTPUT_CONTEXT] | The parsing context where the sink executes: HTML body, attribute, script, style, or URL | HTML body | Must be one of: HTML body, HTML attribute, JavaScript string, CSS, URL. Context misidentification causes incorrect encoding recommendations. |
[CSP_POLICY] | The Content-Security-Policy header or meta tag active on the page, or null if absent | default-src 'self'; script-src 'nonce-abc123' | If null, note that CSP provides zero mitigation. If present, parse for unsafe-inline, unsafe-eval, wildcard sources, and nonce/hash coverage of the sink. |
[FRAMEWORK] | The JavaScript framework or library in use, or vanilla | React 18 | Must be one of: vanilla, React, Vue, Angular, Svelte, jQuery, or other with version. Framework choice determines whether built-in sanitization applies. |
[SANITIZER_USED] | Any sanitization function applied before the sink, or null | DOMPurify.sanitize(userInput) | If null, flag as unsanitized. If present, verify the sanitizer is configured correctly for the output context and is not bypassable. |
Implementation Harness Notes
How to wire the XSS sink analysis prompt into a CI/CD pipeline or manual review workflow with validation, retries, and human escalation gates.
Integrating this prompt into an application requires treating it as a deterministic analysis step within a larger security review pipeline. The prompt is designed to be called programmatically, receiving a structured input payload containing the code snippet, identified sources, and identified sinks. The calling application—whether a CI/CD plugin, a custom security bot, or a manual review CLI tool—is responsible for assembling this context before invoking the model. The model's response must be parsed as structured JSON and validated against a strict schema before any downstream action, such as posting a finding to a security dashboard or blocking a pull request, is taken.
The implementation should follow a validate-retry-escalate pattern. First, parse the model's JSON output and validate it against the expected schema (fields like data_flow_path, output_encoding_assessment, csp_mitigation_analysis, and final_risk must be present and correctly typed). If validation fails, implement a single retry with a repair prompt that includes the raw output and the specific schema violation errors. If the retry also fails, the finding should be flagged for mandatory human review rather than silently dropped. For high-risk code paths (e.g., authentication flows, payment processing), consider always requiring human approval for final_risk ratings of high or critical, regardless of model confidence. Log every request, response, and validation result to an immutable audit trail to support post-review analysis and model performance evaluation over time.
When choosing a model, prefer those with strong code reasoning capabilities and reliable JSON mode. The prompt is structured to work with tool-calling APIs by defining the output schema as a function, which is the most reliable way to enforce structured output. Avoid using this prompt with small, general-purpose models that may hallucinate data flow paths or misclassify encoding contexts. For runtime efficiency in CI/CD, cache the system prompt and consider batching multiple sink analyses for a single file into one request to reduce latency. Do not use this prompt's output as the sole gate for a production deployment; it is an expert triage assistant that accelerates human review, not a replacement for penetration testing or runtime protection mechanisms like strict Content Security Policies.
Expected Output Contract
The model must return a structured JSON object. Validate each field against these rules before accepting the response in your application pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
sinks | Array of objects | Array length >= 0. If empty, confirm no sinks were found in [CODE_INPUT]. | |
sinks[].sink_function | String | Must match a known dangerous DOM or server-side sink (e.g., innerHTML, eval, document.write). Validate against a hardcoded allowlist of sink signatures. | |
sinks[].source_parameter | String | Must reference a variable or parameter name traceable to user-controlled input in the provided [DATA_FLOW_GRAPH] or source code. | |
sinks[].output_encoding_present | Boolean | Must be true if any encoding function (e.g., DOMPurify.sanitize, encodeURIComponent) is applied before the sink, false otherwise. Parse the AST or data flow, do not guess. | |
sinks[].csp_mitigation_applicable | Boolean | Must be true only if a nonce-based or hash-based CSP policy is present in [CSP_HEADER] and would block this specific injection. Default to false if CSP is absent or uses only domain allowlists. | |
sinks[].xss_type | Enum: DOM | Reflected | Stored | Must be inferred from the data flow. DOM if source is client-side (e.g., location.hash). Reflected if source is a request parameter echoed immediately. Stored if source is retrieved from a database or cache. | |
sinks[].confidence | Enum: high | medium | low | Must be 'low' if the data flow is incomplete or encoding is ambiguous. Retry with more context if confidence is 'low' on a critical path. | |
remediation_summary | String | Must be a concise, actionable sentence per sink. Null or generic advice like 'sanitize input' is a validation failure. Check for specific function or library recommendations. |
Common Failure Modes
XSS sink analysis is precise but brittle. These are the most common ways the prompt fails in production and how to guard against them before findings reach a developer's queue.
Context Window Truncation
What to watch: The model receives only a partial data flow because the code snippet exceeds the context window. It then analyzes an incomplete source-to-sink path and misses the actual dangerous assignment. Guardrail: Chunk files by function or template block before analysis. If a flow crosses a chunk boundary, flag it as 'incomplete' rather than guessing.
Framework-Specific Sanitizer Blindness
What to watch: The model treats a framework's built-in auto-escaping (e.g., React's JSX, Angular's interpolation) as a complete mitigation and fails to flag dangerous innerHTML, dangerouslySetInnerHTML, or bypassable pipes. Guardrail: Explicitly list framework-specific dangerous sinks and bypass patterns in the prompt's [CONTEXT]. Require the model to justify why a sanitizer is sufficient for each specific sink.
CSP Over-Reliance
What to watch: The model marks a finding as 'mitigated by CSP' without verifying that the CSP is actually enforced, lacks 'unsafe-inline' or 'unsafe-eval', and covers the specific injection context. Guardrail: Require the model to output the exact CSP directive that would block the payload. If the directive is missing or permissive, the finding must remain open.
DOM vs. Reflected Misclassification
What to watch: The model misclassifies a DOM-based XSS sink as reflected because it sees user input in the URL, or vice versa, leading to incorrect remediation advice. Guardrail: Add a required output field for 'xss_type' with strict enum values (DOM, Reflected, Stored). Instruct the model to trace whether the payload reaches the sink via server-side reflection or client-side processing only.
Encoding Adequacy False Confidence
What to watch: The model sees an encoding function (e.g., escapeHtml) and declares the output safe without checking the encoding context (HTML body vs. attribute vs. JavaScript string). Guardrail: Require the model to state the specific encoding context and verify that the applied encoder is correct for that context. Flag any mismatch between encoder type and output context as a finding.
Template Engine Bypass Oversight
What to watch: The model misses template engine-specific bypasses, such as Sandbox escapes in older template libraries or delimiter injection, and assumes the engine's escaping is airtight. Guardrail: Include a [TEMPLATE_ENGINE] variable in the prompt. When populated, append known bypass techniques for that engine version to the analysis instructions.
Evaluation Rubric
Use this rubric to test the Cross-Site Scripting Sink Analysis Prompt before integrating it into a security review pipeline. Each criterion targets a specific failure mode observed in XSS sink analysis. Run these tests against a golden dataset of known XSS-positive and XSS-negative code samples.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Sink Identification Recall | All dangerous sinks (innerHTML, eval, document.write, etc.) in the sample are identified in the output. | Output misses a known dangerous sink present in the code sample. | Run against 20 code samples with pre-labeled sinks. Recall must be >= 0.95. |
Source-to-Sink Flow Completeness | For each identified sink, the output traces the full data flow from a user-controllable source (e.g., location.hash, URL parameter). | Output identifies a sink but fails to connect it to a source, or traces an incorrect data flow path. | Manual review of flow graphs for 10 samples. Automated check: each sink must have at least one associated source in the output. |
Output Encoding Assessment Accuracy | Correctly classifies the encoding applied to the data as 'None', 'Insufficient', or 'Adequate' for the specific sink context. | Classifies a missing or HTML-entity-only encoding as 'Adequate' for a JavaScript sink (e.g., event handler). | Compare output encoding classification against a pre-determined answer key for 15 mixed-context samples. Accuracy must be >= 0.90. |
CSP Mitigation Evaluation | Correctly determines if a present CSP would block the exploit, noting if 'unsafe-inline' or 'unsafe-eval' is required. | States a CSP would block an exploit when the policy includes 'unsafe-inline' and the sink is an inline script. | Test against 10 samples with provided CSP headers. Output must match the expected mitigation verdict. |
XSS Type Classification | Correctly classifies the finding as DOM-based, Reflected, or Stored based on the data flow and source. | Classifies a DOM-based XSS (source: location.hash, sink: innerHTML) as Reflected. | Validate classification against a labeled dataset of 20 findings. Cohen's Kappa >= 0.85. |
False Positive Rate on Safe Code | Returns an empty finding list or explicit 'No XSS sink found' for code samples with no user-controlled data reaching a sink. | Flags a safe pattern (e.g., setting textContent with a constant string) as a potential XSS vulnerability. | Run against 30 known-safe code samples. False positive rate must be <= 0.05. |
Output Schema Compliance | Output is valid JSON matching the defined [OUTPUT_SCHEMA] without extra fields or missing required fields. | Output is missing the 'data_flow' array or contains an unparseable JSON structure. | Automated schema validation check on 100% of test runs. Pass/fail on strict validation. |
Confidence Score Calibration | High-confidence scores (>=0.8) correlate with correct findings; low-confidence scores (<0.5) correlate with ambiguous or noisy code. | A clearly vulnerable eval() sink is assigned a confidence score below 0.6. | Brier score calculated on 50 predictions. Score must be <= 0.15. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add strict JSON schema validation, retry logic for malformed outputs, and structured logging of every analysis. Include a confidence threshold below which the finding is queued for human review. Integrate with SAST tool output for correlation.
code[SYSTEM] You are a security analysis tool. Return ONLY valid JSON matching the [OUTPUT_SCHEMA]. If confidence is below 0.7, set requires_human_review to true. [OUTPUT_SCHEMA] { "sink_type": "innerHTML|eval|document.write|...", "source_trace": ["user_input -> function_a -> sink"], "encoding_assessment": "none|partial|contextual|auto-escaped", "csp_mitigation": "none|nonce-strict|unsafe-inline|...", "confidence": 0.0-1.0, "requires_human_review": true/false }
Watch for
- Silent format drift when models change JSON key names
- Over-confident assessments on framework code with implicit sanitization
- CSP header parsing errors when headers are non-standard

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us