All files / src/lib/auth csrf.ts

40.07% Statements 101/252
100% Branches 0/0
0% Functions 0/11
40.07% Lines 101/252

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 2531x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x 1x 1x 1x                               1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x                                                       1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x                                                   1x 1x 1x 1x 1x 1x 1x 1x                                                                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                            
/**
 * CSRF Protection Module
 *
 * Provides Cross-Site Request Forgery (CSRF) protection for state-changing operations.
 * Uses the Double Submit Cookie pattern combined with token validation.
 *
 * Security features:
 * - Cryptographically secure token generation
 * - Time-limited tokens with configurable expiry
 * - Origin validation
 * - SameSite cookie enforcement
 */
 
import { createHash, randomBytes } from "crypto";
import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
import { TOKEN_CONFIG } from '@/lib/security';
 
const CSRF_COOKIE_NAME = "__csrf_token";
const CSRF_HEADER_NAME = "x-csrf-token";
 
interface CsrfTokenData {
  token: string;
  timestamp: number;
}
 
/**
 * Generate a cryptographically secure CSRF token
 */
export function generateCsrfToken(): string {
  const token = randomBytes(TOKEN_CONFIG.TOKEN_BYTES).toString("hex");
  const timestamp = Date.now();
  const data: CsrfTokenData = { token, timestamp };
  return Buffer.from(JSON.stringify(data)).toString("base64");
}
 
/**
 * Parse a CSRF token to extract its data
 */
function parseCsrfToken(encodedToken: string): CsrfTokenData | null {
  try {
    const decoded = Buffer.from(encodedToken, "base64").toString("utf-8");
    const data = JSON.parse(decoded) as CsrfTokenData;
    if (
      typeof data.token === "string" &&
      typeof data.timestamp === "number"
    ) {
      return data;
    }
    return null;
  } catch {
    return null;
  }
}
 
/**
 * Check if a CSRF token is expired
 */
function isTokenExpired(timestamp: number): boolean {
  return Date.now() - timestamp > TOKEN_CONFIG.CSRF_TOKEN_EXPIRY_MS;
}
 
/**
 * Hash a token for secure comparison
 */
function hashToken(token: string): string {
  return createHash("sha256").update(token).digest("hex");
}
 
/**
 * Validate a CSRF token
 *
 * @param headerToken - Token from X-CSRF-Token header
 * @param cookieToken - Token from __csrf_token cookie
 * @returns boolean indicating if tokens are valid and match
 */
export function validateCsrfToken(
  headerToken: string | null,
  cookieToken: string | null
): boolean {
  if (!headerToken || !cookieToken) {
    return false;
  }

  // Parse both tokens
  const headerData = parseCsrfToken(headerToken);
  const cookieData = parseCsrfToken(cookieToken);

  if (!headerData || !cookieData) {
    return false;
  }

  // Check expiry
  if (isTokenExpired(headerData.timestamp) || isTokenExpired(cookieData.timestamp)) {
    return false;
  }

  // Compare token hashes (timing-safe comparison via hash comparison)
  const headerHash = hashToken(headerData.token);
  const cookieHash = hashToken(cookieData.token);

  return headerHash === cookieHash;
}
 
/**
 * Set CSRF token cookie
 */
export async function setCsrfCookie(token: string): Promise<void> {
  const cookieStore = await cookies();
  cookieStore.set(CSRF_COOKIE_NAME, token, {
    httpOnly: false, // Must be readable by JavaScript
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
    path: "/",
    maxAge: Math.floor(TOKEN_CONFIG.CSRF_TOKEN_EXPIRY_MS / 1000)});
}
 
/**
 * Get CSRF token from cookie
 */
export async function getCsrfTokenFromCookie(): Promise<string | null> {
  const cookieStore = await cookies();
  return cookieStore.get(CSRF_COOKIE_NAME)?.value || null;
}
 
/**
 * Middleware helper to validate CSRF for state-changing requests
 *
 * @param request - NextRequest object
 * @returns Object with validation result and optional error response
 */
export async function validateCsrfRequest(
  request: NextRequest
): Promise<{ valid: boolean; error?: NextResponse }> {
  // Only validate state-changing methods
  if (["GET", "HEAD", "OPTIONS"].includes(request.method)) {
    return { valid: true };
  }

  // Get token from header
  const headerToken = request.headers.get(CSRF_HEADER_NAME);

  // Get token from cookie
  const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value || null;

  // Validate tokens
  if (!validateCsrfToken(headerToken, cookieToken)) {
    return {
      valid: false,
      error: NextResponse.json(
        { error: "Invalid or missing CSRF token" },
        { status: 403 }
      )};
  }

  return { valid: true };
}
 
/**
 * Validate request origin to prevent CSRF from different origins
 *
 * @param request - NextRequest object
 * @param allowedOrigins - List of allowed origins
 * @returns boolean indicating if origin is valid
 */
export function validateOrigin(
  request: NextRequest,
  allowedOrigins?: string[]
): boolean {
  const origin = request.headers.get("origin");
  const referer = request.headers.get("referer");

  // For same-origin requests, origin might be null
  if (!origin && !referer) {
    // Could be same-origin or a direct API call
    // Be cautious but don't block entirely
    return true;
  }

  const requestOrigin = origin || (referer ? new URL(referer).origin : null);

  if (!requestOrigin) {
    return true;
  }

  // Default allowed origins from environment
  const defaultAllowed = process.env.NEXTAUTH_URL
    ? [new URL(process.env.NEXTAUTH_URL).origin]
    : ["http://localhost:3000"];

  const allowed = allowedOrigins || defaultAllowed;

  return allowed.some((allowedOrigin) => {
    try {
      return new URL(allowedOrigin).origin === requestOrigin;
    } catch {
      return allowedOrigin === requestOrigin;
    }
  });
}
 
/**
 * HOC wrapper for API routes requiring CSRF protection
 *
 * Usage:
 * ```typescript
 * import { withCsrfProtection } from "@/lib/auth";
 *
 * async function handler(request: NextRequest) {
 *   // Your handler code
 * }
 *
 * export const POST = withCsrfProtection(handler);
 * ```
 */
export function withCsrfProtection(
  handler: (request: NextRequest) => Promise<NextResponse>
): (request: NextRequest) => Promise<NextResponse> {
  return async (request: NextRequest) => {
    const { valid, error } = await validateCsrfRequest(request);

    if (!valid && error) {
      return error;
    }

    return handler(request);
  };
}
 
/**
 * @deprecated Use NextAuth's built-in CSRF endpoint at /api/auth/csrf instead.
 * This function is kept for backwards compatibility but should not be used
 * for new implementations.
 *
 * NextAuth provides automatic CSRF protection for authentication flows.
 * For custom API routes that need CSRF protection, use the
 * `withCsrfProtection` HOC or `validateCsrfRequest` function instead.
 */
export async function getCsrfTokenResponse(): Promise<NextResponse> {
  const token = generateCsrfToken();
  await setCsrfCookie(token);

  return NextResponse.json(
    { csrfToken: token },
    {
      status: 200,
      headers: {
        "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate",
        Pragma: "no-cache",
        Expires: "0"}}
  );
}