| name | security-hardening |
| description | Implement client-side security measures including Content Security Policy, input sanitization, XSS prevention, and secure data handling. Use when handling user input, displaying dynamic content, or storing sensitive data. |
Security Hardening
When to Use This Skill
Use when:
- Handling user-generated content
- Storing sensitive data client-side
- Embedding external content
- Implementing authentication flows
XSS Prevention
Never Use dangerouslySetInnerHTML Unsafely
<div dangerouslySetInnerHTML={{ __html: userContent }} />
import DOMPurify from 'dompurify';
<div
dangerouslySetInnerHTML={{
__html: DOMPurify.sanitize(userContent)
}}
/>
Sanitize with DOMPurify
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(dirty);
const cleanStrict = DOMPurify.sanitize(dirty, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
ALLOWED_ATTR: ['href']
});
const textOnly = DOMPurify.sanitize(dirty, { ALLOWED_TAGS: [] });
Content Security Policy (CSP)
Meta Tag CSP
<meta
http-equiv="Content-Security-Policy"
content="
default-src 'self';
script-src 'self' 'unsafe-inline';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self';
connect-src 'self' https://api.example.com;
"
>
Common CSP Directives
| Directive | Purpose |
|---|
default-src | Fallback for other directives |
script-src | JavaScript sources |
style-src | CSS sources |
img-src | Image sources |
connect-src | XHR, WebSocket, fetch |
frame-src | iframe sources |
Secure Data Storage
Sensitive Data Handling
localStorage.setItem('token', secretToken);
sessionStorage.setItem('token', secretToken);
Encrypt Before Storing (if necessary)
async function encrypt(data: string, key: CryptoKey): Promise<string> {
const iv = crypto.getRandomValues(new Uint8Array(12));
const encoded = new TextEncoder().encode(data);
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
encoded
);
return btoa(
String.fromCharCode(...iv) +
String.fromCharCode(...new Uint8Array(encrypted))
);
}
URL Handling
Validate URLs
function isValidUrl(url: string): boolean {
try {
const parsed = new URL(url);
return ['http:', 'https:'].includes(parsed.protocol);
} catch {
return false;
}
}
function sanitizeHref(href: string): string {
if (href.toLowerCase().startsWith('javascript:')) {
return '#';
}
return href;
}
Open External Links Safely
<a
href={externalUrl}
target="_blank"
rel="noopener noreferrer"
>
External Link
</a>
Input Validation
function validateEmail(email: string): boolean {
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
}
<input
type="text"
maxLength={100}
value={value}
onChange={(e) => setValue(e.target.value.slice(0, 100))}
/>
Iframe Security
<iframe
src={externalContent}
sandbox="allow-scripts allow-same-origin"
referrerPolicy="no-referrer"
/>
Subresource Integrity
<script
src="https://cdn.example.com/library.js"
integrity="sha384-abc123..."
crossorigin="anonymous"
></script>
Security Checklist