Implement comprehensive security measures in your applications with Google Antigravity
# Security Hardening Guide for Google Antigravity
Implement robust security measures to protect your applications from common vulnerabilities with Google Antigravity IDE.
## Authentication Security
```typescript
// lib/auth/password.ts
import { scrypt, randomBytes, timingSafeEqual } from "crypto";
import { promisify } from "util";
const scryptAsync = promisify(scrypt);
const SALT_LENGTH = 32;
const KEY_LENGTH = 64;
const SCRYPT_PARAMS = { N: 16384, r: 8, p: 1 };
export async function hashPassword(password: string): Promise<string> {
const salt = randomBytes(SALT_LENGTH);
const derivedKey = await scryptAsync(password, salt, KEY_LENGTH, SCRYPT_PARAMS) as Buffer;
return `${salt.toString("hex")}:${derivedKey.toString("hex")}`;
}
export async function verifyPassword(password: string, hash: string): Promise<boolean> {
const [saltHex, keyHex] = hash.split(":");
const salt = Buffer.from(saltHex, "hex");
const storedKey = Buffer.from(keyHex, "hex");
const derivedKey = await scryptAsync(password, salt, KEY_LENGTH, SCRYPT_PARAMS) as Buffer;
return timingSafeEqual(storedKey, derivedKey);
}
// lib/auth/session.ts
import { SignJWT, jwtVerify } from "jose";
import { cookies } from "next/headers";
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET!);
const SESSION_DURATION = 60 * 60 * 24 * 7; // 7 days
export async function createSession(userId: string, role: string): Promise<string> {
const token = await new SignJWT({ sub: userId, role })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime(Math.floor(Date.now() / 1000) + SESSION_DURATION)
.setJti(crypto.randomUUID())
.sign(JWT_SECRET);
cookies().set("session", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: SESSION_DURATION,
path: "/"
});
return token;
}
export async function validateSession() {
const token = cookies().get("session")?.value;
if (!token) return null;
try {
const { payload } = await jwtVerify(token, JWT_SECRET);
return payload;
} catch {
return null;
}
}
```
## Input Sanitization
```typescript
// lib/security/sanitize.ts
import DOMPurify from "isomorphic-dompurify";
import { z } from "zod";
// HTML sanitization
export function sanitizeHTML(dirty: string): string {
return DOMPurify.sanitize(dirty, {
ALLOWED_TAGS: ["b", "i", "em", "strong", "a", "p", "br", "ul", "ol", "li"],
ALLOWED_ATTR: ["href", "target", "rel"],
ALLOW_DATA_ATTR: false
});
}
// SQL injection prevention via parameterized queries
import { sql } from "drizzle-orm";
export function safeQuery(tableName: string, conditions: Record<string, unknown>) {
// Never interpolate user input directly
// Use parameterized queries with the ORM
return sql`SELECT * FROM ${sql.identifier(tableName)} WHERE ${sql.and(
Object.entries(conditions).map(([key, value]) =>
sql`${sql.identifier(key)} = ${value}`
)
)}`;
}
// Path traversal prevention
import path from "path";
export function safePath(userInput: string, baseDir: string): string | null {
const normalized = path.normalize(userInput);
const resolved = path.resolve(baseDir, normalized);
// Ensure path stays within base directory
if (!resolved.startsWith(path.resolve(baseDir))) {
return null;
}
return resolved;
}
// Content type validation
const ALLOWED_MIME_TYPES = ["image/jpeg", "image/png", "image/webp", "application/pdf"];
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
export const fileUploadSchema = z.object({
name: z.string().max(255).regex(/^[a-zA-Z0-9._-]+$/),
type: z.enum(ALLOWED_MIME_TYPES as [string, ...string[]]),
size: z.number().max(MAX_FILE_SIZE)
});
```
## CSRF Protection
```typescript
// lib/security/csrf.ts
import { cookies } from "next/headers";
import { createHmac, randomBytes } from "crypto";
const CSRF_SECRET = process.env.CSRF_SECRET!;
export function generateCSRFToken(): string {
const token = randomBytes(32).toString("hex");
const signature = createHmac("sha256", CSRF_SECRET).update(token).digest("hex");
cookies().set("csrf", `${token}.${signature}`, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
path: "/"
});
return token;
}
export function validateCSRFToken(submittedToken: string): boolean {
const cookieValue = cookies().get("csrf")?.value;
if (!cookieValue) return false;
const [storedToken, signature] = cookieValue.split(".");
const expectedSignature = createHmac("sha256", CSRF_SECRET).update(storedToken).digest("hex");
if (signature !== expectedSignature) return false;
return submittedToken === storedToken;
}
// Middleware usage
import { NextRequest, NextResponse } from "next/server";
export function csrfMiddleware(request: NextRequest) {
if (["POST", "PUT", "DELETE", "PATCH"].includes(request.method)) {
const token = request.headers.get("x-csrf-token");
if (!token || !validateCSRFToken(token)) {
return NextResponse.json({ error: "Invalid CSRF token" }, { status: 403 });
}
}
return NextResponse.next();
}
```
## Security Headers Middleware
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Security headers
response.headers.set("X-Content-Type-Options", "nosniff");
response.headers.set("X-Frame-Options", "DENY");
response.headers.set("X-XSS-Protection", "1; mode=block");
response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
response.headers.set("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
// Content Security Policy
const csp = [
"default-src 'self'",
"script-src 'self' 'strict-dynamic'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"font-src 'self'",
"connect-src 'self' https://api.example.com",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'"
].join("; ");
response.headers.set("Content-Security-Policy", csp);
return response;
}
```
## Best Practices
1. **Hash passwords** with modern algorithms like scrypt or Argon2
2. **Validate all input** at system boundaries
3. **Use parameterized queries** to prevent SQL injection
4. **Implement CSRF protection** for state-changing operations
5. **Set security headers** on all responses
6. **Use HttpOnly cookies** for session tokens
7. **Implement rate limiting** on sensitive endpoints
Google Antigravity helps identify security vulnerabilities and suggests hardening measures throughout your development workflow.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.