Security Best Practices
Complete security guide for the AI Store application.
Security Headers
Content Security Policy (CSP)
// next.config.ts
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'Content-Security-Policy',
value: [
"default-src 'self'",
"script-src 'self' 'unsafe-inline'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"font-src 'self' data:",
"connect-src 'self' https://api.example.com",
].join('; '),
},
],
},
];
}
Other Security Headers
{
key: 'X-Frame-Options',
value: 'DENY',
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
{
key: 'X-XSS-Protection',
value: '1; mode=block',
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin',
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=()',
},
Input Validation
Sanitize User Input
import { sanitizeHTML } from '@/lib/security-advanced';
const safeInput = sanitizeHTML(userInput);
Validate Input
import { validateInput } from '@/lib/security-advanced';
const result = validateInput(input, {
required: true,
minLength: 3,
maxLength: 100,
pattern: /^[a-zA-Z0-9]+$/,
});
if (!result.valid) {
// Handle error
}
Email Validation
import { validateEmail } from '@/lib/security';
if (!validateEmail(email)) {
// Invalid email
}
URL Validation
import { validateURL } from '@/lib/security-advanced';
if (validateURL(url, ['example.com'])) {
// Safe URL
}
XSS Prevention
Sanitize HTML
import { sanitizeHTML } from '@/lib/security-advanced';
const safeHTML = sanitizeHTML(userHTML);
Use React Safely
// Safe: React escapes by default
<div>{userInput}</div>
// Dangerous: Only use with sanitized input
<div dangerouslySetInnerHTML={{ __html: sanitizedHTML }} />
Avoid eval()
// Never use eval()
// eval(userCode); // DANGEROUS
// Use safe alternatives
const result = safeEval(userCode);
CSRF Protection
Generate CSRF Token
import { generateCSRFToken } from '@/lib/security';
const token = generateCSRFToken();
Verify CSRF Token
// In API route
import { verifyCSRFToken } from '@/lib/security';
export async function POST(request: Request) {
const token = request.headers.get('X-CSRF-Token');
if (!verifyCSRFToken(token)) {
return NextResponse.json({ error: 'Invalid token' }, { status: 403 });
}
// Process request
}
Rate Limiting
API Rate Limiting
import { rateLimiter } from '@/lib/rate-limit';
export async function POST(request: Request) {
const clientId = request.headers.get('x-forwarded-for') || 'unknown';
const result = rateLimiter.check(clientId, 100, 60000);
if (!result.allowed) {
return NextResponse.json(
{ error: 'Rate limit exceeded' },
{ status: 429 }
);
}
// Process request
}
IP Rate Limiting
import { ipRateLimiter } from '@/lib/security-advanced';
const result = ipRateLimiter.check(ipAddress);
if (!result.allowed) {
// Rate limited
}
Data Encryption
Encrypt Sensitive Data
import { encryptData } from '@/lib/security-advanced';
const encrypted = await encryptData(sensitiveData, secretKey);
Hash Data
import { hashData } from '@/lib/security-advanced';
const hash = await hashData(data);
Authentication & Authorization
Secure Cookies
// Set secure cookie
response.cookies.set('session', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 7, // 7 days
});
Token Validation
import { verifyToken } from '@/lib/security';
const isValid = await verifyToken(token);
Environment Variables
Secure Storage
# Never commit these
SECRET_KEY=your-secret-key
DATABASE_URL=your-database-url
API_KEY=your-api-key
Access Control
// Server-only variables (no NEXT_PUBLIC_)
const secret = process.env.SECRET_KEY;
// Client-accessible variables (NEXT_PUBLIC_)
const publicUrl = process.env.NEXT_PUBLIC_SITE_URL;
API Security
Validate Requests
export async function POST(request: Request) {
// Validate request body
const body = await request.json();
if (!body || !body.data) {
return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
}
// Validate data
if (!validateInput(body.data)) {
return NextResponse.json({ error: 'Invalid data' }, { status: 400 });
}
// Process request
}
CORS Configuration
export async function GET() {
return NextResponse.json(data, {
headers: {
'Access-Control-Allow-Origin': 'https://example.com',
'Access-Control-Allow-Methods': 'GET, POST',
'Access-Control-Allow-Headers': 'Content-Type',
},
});
}
File Upload Security
Validate Files
import { isValidImage } from '@/lib/image-handling';
if (!isValidImage(file)) {
// Invalid file type
}
Size Limits
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
if (file.size > MAX_FILE_SIZE) {
// File too large
}
Scan Files
// Scan uploaded files for malware
// Use antivirus service
const isSafe = await scanFile(file);
SQL Injection Prevention
Use Parameterized Queries
// Never use string concatenation
// const query = `SELECT * FROM users WHERE id = ${userId}`; // DANGEROUS
// Use parameterized queries
const query = 'SELECT * FROM users WHERE id = ?';
const result = await db.query(query, [userId]);
Dependency Security
Audit Dependencies
npm audit
Update Dependencies
npm update
Use Security Advisories
npm audit fix
Logging Security
Don't Log Sensitive Data
// Don't log passwords, tokens, etc.
console.log('User logged in'); // OK
console.log('Password:', password); // DANGEROUS
Sanitize Logs
import { sanitizeLog } from '@/lib/security';
const safeLog = sanitizeLog(sensitiveData);
console.log(safeLog);
Error Handling
Don't Expose Internal Errors
// In production
if (process.env.NODE_ENV === 'production') {
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
// In development
return NextResponse.json({ error: error.message }, { status: 500 });
Secure Error Messages
// Generic error messages for users
return NextResponse.json({ error: 'An error occurred' }, { status: 500 });
// Detailed errors only in logs
errorLogger.log(error, 'high', { context });
HTTPS
Enforce HTTPS
// next.config.ts
async redirects() {
return [
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-forwarded-proto',
value: 'http',
},
],
destination: 'https://your-domain.com/:path*',
permanent: true,
},
];
}
Security Checklist
- [ ] Security headers configured
- [ ] Input validation implemented
- [ ] XSS prevention in place
- [ ] CSRF protection enabled
- [ ] Rate limiting configured
- [ ] Data encryption used
- [ ] Secure authentication
- [ ] Environment variables secured
- [ ] API security implemented
- [ ] File upload security
- [ ] Dependencies audited
- [ ] Error handling secure
- [ ] HTTPS enforced
- [ ] Security monitoring active
Security Monitoring
Monitor Security Events
import { errorLogger } from '@/lib/error-logger';
errorLogger.log(securityEvent, 'critical', {
type: 'security',
severity: 'high',
});
Security Alerts
// Set up alerts for:
// - Failed login attempts
// - Rate limit violations
// - Suspicious activity
// - Security errors