Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Security Hardening Guide

Security Hardening Guide

Implement comprehensive security measures in your applications with Google Antigravity

securityauthenticationcsrfhardening
by antigravity-team
⭐0Stars
.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.

When to Use This Prompt

This security prompt is ideal for developers working on:

  • security applications requiring modern best practices and optimal performance
  • Projects that need production-ready security code with proper error handling
  • Teams looking to standardize their security development workflow
  • Developers wanting to learn industry-standard security patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the security code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this security prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...