Securing web applications with CSP, CSRF protection, input validation, and authentication
# Web Security Best Practices for Google Antigravity
Secure your applications with Google Antigravity's Gemini 3 engine. This guide covers Content Security Policy, CSRF protection, input validation, and secure authentication.
## Content Security Policy
```typescript
// next.config.js
const ContentSecurityPolicy = `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline' https://www.googletagmanager.com;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
img-src 'self' data: https: blob:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://*.supabase.co wss://*.supabase.co https://api.example.com;
frame-src 'self' https://www.youtube.com;
media-src 'self' https://www.youtube.com;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
`;
const securityHeaders = [
{
key: 'Content-Security-Policy',
value: ContentSecurityPolicy.replace(/\s{2,}/g, ' ').trim(),
},
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload',
},
{
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=()',
},
];
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: securityHeaders,
},
];
},
};
```
## CSRF Protection
```typescript
// lib/csrf.ts
import { randomBytes, createHmac } from 'crypto';
const CSRF_SECRET = process.env.CSRF_SECRET!;
const TOKEN_EXPIRY = 60 * 60 * 1000; // 1 hour
export function generateCSRFToken(): { token: string; expires: number } {
const expires = Date.now() + TOKEN_EXPIRY;
const data = `${randomBytes(32).toString('hex')}.${expires}`;
const signature = createHmac('sha256', CSRF_SECRET).update(data).digest('hex');
return {
token: `${data}.${signature}`,
expires,
};
}
export function validateCSRFToken(token: string): boolean {
try {
const parts = token.split('.');
if (parts.length !== 3) return false;
const [random, expiresStr, signature] = parts;
const expires = parseInt(expiresStr, 10);
// Check expiration
if (Date.now() > expires) return false;
// Verify signature
const data = `${random}.${expiresStr}`;
const expectedSignature = createHmac('sha256', CSRF_SECRET)
.update(data)
.digest('hex');
return signature === expectedSignature;
} catch {
return false;
}
}
// middleware/csrf.ts
import { NextRequest, NextResponse } from 'next/server';
import { validateCSRFToken, generateCSRFToken } from '@/lib/csrf';
export function csrfMiddleware(request: NextRequest) {
// Skip for GET, HEAD, OPTIONS
if (['GET', 'HEAD', 'OPTIONS'].includes(request.method)) {
const response = NextResponse.next();
const { token } = generateCSRFToken();
response.cookies.set('csrf-token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
});
return response;
}
// Validate token for state-changing requests
const cookieToken = request.cookies.get('csrf-token')?.value;
const headerToken = request.headers.get('x-csrf-token');
if (!cookieToken || !headerToken || cookieToken !== headerToken) {
return NextResponse.json(
{ error: 'Invalid CSRF token' },
{ status: 403 }
);
}
if (!validateCSRFToken(cookieToken)) {
return NextResponse.json(
{ error: 'CSRF token expired' },
{ status: 403 }
);
}
return NextResponse.next();
}
```
## Input Sanitization
```typescript
// lib/sanitize.ts
import DOMPurify from 'isomorphic-dompurify';
import { z } from 'zod';
// HTML sanitization
export function sanitizeHTML(html: string): string {
return DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br', 'ul', 'ol', 'li'],
ALLOWED_ATTR: ['href', 'target', 'rel'],
ALLOW_DATA_ATTR: false,
});
}
// SQL-safe string (for dynamic queries)
export function escapeSQL(str: string): string {
return str.replace(/['\\]/g, char => '\\' + char);
}
// URL validation schema
export const urlSchema = z.string().url().refine(
(url) => {
try {
const parsed = new URL(url);
return ['http:', 'https:'].includes(parsed.protocol);
} catch {
return false;
}
},
{ message: 'Invalid URL' }
);
// Email validation with additional checks
export const emailSchema = z
.string()
.email()
.max(254)
.refine(
(email) => !email.includes('++') && !email.includes('..'),
{ message: 'Invalid email format' }
);
// Filename sanitization
export function sanitizeFilename(filename: string): string {
return filename
.replace(/[^a-zA-Z0-9.-]/g, '_')
.replace(/\.{2,}/g, '.')
.slice(0, 255);
}
// Generic text sanitization
export function sanitizeText(text: string): string {
return text
.replace(/[<>]/g, '')
.trim()
.slice(0, 10000);
}
```
## Rate Limiting
```typescript
// lib/rate-limit.ts
import { Redis } from '@upstash/redis';
const redis = new Redis({
url: process.env.UPSTASH_REDIS_URL!,
token: process.env.UPSTASH_REDIS_TOKEN!,
});
interface RateLimitConfig {
maxRequests: number;
windowMs: number;
}
export async function rateLimit(
identifier: string,
config: RateLimitConfig
): Promise<{
success: boolean;
remaining: number;
reset: number;
}> {
const { maxRequests, windowMs } = config;
const key = `rate_limit:${identifier}`;
const now = Date.now();
const windowStart = now - windowMs;
// Remove old entries
await redis.zremrangebyscore(key, 0, windowStart);
// Count recent requests
const count = await redis.zcard(key);
if (count >= maxRequests) {
const oldest = await redis.zrange(key, 0, 0, { withScores: true });
const reset = oldest[0] ? (oldest[0].score as number) + windowMs : now + windowMs;
return {
success: false,
remaining: 0,
reset,
};
}
// Add current request
await redis.zadd(key, { score: now, member: `${now}-${Math.random()}` });
await redis.expire(key, Math.ceil(windowMs / 1000));
return {
success: true,
remaining: maxRequests - count - 1,
reset: now + windowMs,
};
}
// Presets
export const rateLimitPresets = {
api: { maxRequests: 100, windowMs: 60 * 1000 },
auth: { maxRequests: 5, windowMs: 15 * 60 * 1000 },
upload: { maxRequests: 10, windowMs: 60 * 60 * 1000 },
};
```
## Secure Password Hashing
```typescript
// lib/password.ts
import { hash, verify, argon2id } from 'argon2';
const ARGON2_CONFIG = {
type: argon2id,
memoryCost: 65536, // 64 MB
timeCost: 3,
parallelism: 4,
hashLength: 32,
};
export async function hashPassword(password: string): Promise<string> {
return hash(password, ARGON2_CONFIG);
}
export async function verifyPassword(
password: string,
hashedPassword: string
): Promise<boolean> {
try {
return await verify(hashedPassword, password);
} catch {
return false;
}
}
// Password strength validation
export function validatePasswordStrength(password: string): {
valid: boolean;
errors: string[];
} {
const errors: string[] = [];
if (password.length < 12) {
errors.push('Password must be at least 12 characters');
}
if (!/[a-z]/.test(password)) {
errors.push('Password must contain lowercase letters');
}
if (!/[A-Z]/.test(password)) {
errors.push('Password must contain uppercase letters');
}
if (!/[0-9]/.test(password)) {
errors.push('Password must contain numbers');
}
if (!/[^a-zA-Z0-9]/.test(password)) {
errors.push('Password must contain special characters');
}
return { valid: errors.length === 0, errors };
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these security patterns: Implement Content Security Policy headers. Use CSRF tokens for state-changing requests. Validate and sanitize all user input. Apply rate limiting to sensitive endpoints. Hash passwords with Argon2id algorithm.This Security prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their security implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Security projects, consider mentioning your framework version, coding style, and any specific libraries you're using.