All files / app/api/auth/phone/send-otp route.ts

62.81% Statements 125/199
74.28% Branches 26/35
50% Functions 1/2
62.81% Lines 125/199

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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 2671x                                                                                                                                                 17x 17x 17x 17x     17x 1x 1x   16x   17x 1x 1x     17x                           17x                           15x 15x     17x 3x 1x 1x 1x 1x 1x   2x 3x 1x 1x 1x 1x 1x 3x     13x     13x 13x 13x 13x   17x 1x 1x 1x 1x 1x 1x 1x 1x   17x 1x 1x 1x 1x 1x 1x 1x 1x     17x 2x   2x   2x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x     1x   1x 1x 1x 1x 1x 1x 1x     8x   8x 8x 8x 8x   17x 2x 2x 2x 2x 2x 2x     2x     2x 2x 2x 1x 2x 1x 1x 1x   1x   1x   1x       2x 2x 2x 2x 2x 2x 2x 2x 2x     6x 6x 6x 6x     6x   6x 6x 6x 6x 6x 6x 17x 1x 1x 1x 17x  
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { getAdminClient } from '@/lib/supabase/admin';
import { formatPhoneNumber, validatePhoneNumber } from '@/lib/auth/otp';
import { checkRateLimit, incrementRateLimit } from '@/lib/auth/rate-limit';
import { logOtpSent, getClientInfo, hashIP } from '@/lib/auth/login-events';
import { verifyCaptcha, isCaptchaEnabled } from '@/lib/auth/captcha';
import { sendVerificationCode, isTwilioConfigured } from '@/lib/twilio/verify';
 
/**
 * Check if a phone number is already registered with a user
 */
async function isPhoneRegistered(formattedPhone: string): Promise<boolean> {
  try {
    const adminClient = getAdminClient();
 
    // Try the RPC function first (most reliable)
    const phoneVariations = [
      formattedPhone,
      formattedPhone.replace('+', ''),
      formattedPhone.replace(/\s/g, ''),
    ];
 
    for (const phoneVariant of phoneVariations) {
      try {
        const { data: userId, error: rpcError } = await adminClient.rpc('get_user_by_phone', {
          phone_number: phoneVariant,
        });
 
        if (!rpcError && userId) {
          return true;
        }
        if (rpcError) {
          // RPC function doesn't exist, break and try paginated search
          break;
        }
      } catch {
        break;
      }
    }
 
    // Fallback: paginated search through users
    let page = 1;
    const perPage = 1000;
    const maxPages = 10;
 
    while (page <= maxPages) {
      const { data, error } = await adminClient.auth.admin.listUsers({
        page,
        perPage,
      });
 
      if (error) break;
 
      const users = data?.users || [];
      for (const u of users) {
        if (u.phone && phoneVariations.some((pv) => u.phone === pv)) {
          return true;
        }
      }
 
      if (users.length < perPage) break;
      page++;
    }
 
    return false;
  } catch (error) {
    console.error('Error checking if phone is registered:', error);
    // On error, allow the flow to continue (fail open for better UX)
    return false;
  }
}
 
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { phone, countryCode = '+91', captchaToken, mode } = body;
    // mode can be: 'signup' (new account), 'signin' (existing account), or undefined (either)
 
    if (!phone) {
      return NextResponse.json({ error: 'Phone number is required' }, { status: 400 });
    }
 
    const formattedPhone = formatPhoneNumber(phone, countryCode);
 
    if (!validatePhoneNumber(formattedPhone)) {
      return NextResponse.json({ error: 'Invalid phone number format' }, { status: 400 });
    }
 
    // Check if phone is already registered (for signup mode)
    if (mode === 'signup') {
      const phoneExists = await isPhoneRegistered(formattedPhone);
      if (phoneExists) {
        return NextResponse.json(
          {
            error: 'This phone number is already registered. Please sign in instead.',
            code: 'PHONE_EXISTS',
          },
          { status: 400 }
        );
      }
    }
 
    // Check if phone exists (for signin mode)
    if (mode === 'signin') {
      const phoneExists = await isPhoneRegistered(formattedPhone);
      if (!phoneExists) {
        return NextResponse.json(
          {
            error: 'No account found with this phone number. Please sign up first.',
            code: 'PHONE_NOT_FOUND',
          },
          { status: 400 }
        );
      }
    }
 
    // Verify CAPTCHA (required in production, but skipped for resends)
    const { ipAddress } = getClientInfo(request.headers);
    const isResend = body.isResend === true;
 
    // Skip CAPTCHA for resends - rate limiting already protects against abuse
    if (isCaptchaEnabled() && !isResend) {
      if (!captchaToken) {
        return NextResponse.json(
          { error: 'CAPTCHA verification required', captchaRequired: true },
          { status: 400 }
        );
      }
 
      const captchaResult = await verifyCaptcha(captchaToken, ipAddress);
      if (!captchaResult.success) {
        return NextResponse.json(
          { error: captchaResult.error || 'CAPTCHA verification failed', captchaRequired: true },
          { status: 400 }
        );
      }
    }
 
    // Check rate limit
    const ipHash = hashIP(ipAddress);
 
    // Check both phone and IP rate limits
    const [phoneLimit, ipLimit] = await Promise.all([
      checkRateLimit(formattedPhone, 'phone', 'otp_send'),
      checkRateLimit(ipHash, 'ip', 'otp_send'),
    ]);
 
    if (!phoneLimit.allowed) {
      return NextResponse.json(
        {
          error: 'Too many OTP requests for this phone number. Please try again later.',
          blocked_until: phoneLimit.blocked_until,
        },
        { status: 429 }
      );
    }
 
    if (!ipLimit.allowed) {
      return NextResponse.json(
        {
          error: 'Too many OTP requests. Please try again later.',
          blocked_until: ipLimit.blocked_until,
        },
        { status: 429 }
      );
    }
 
    // Try direct Twilio Verify first (if configured)
    if (isTwilioConfigured()) {
      console.log('Using direct Twilio Verify for:', formattedPhone);
 
      const twilioResult = await sendVerificationCode(formattedPhone);
 
      if (!twilioResult.success) {
        await incrementRateLimit(formattedPhone, 'phone');
        return NextResponse.json(
          { error: twilioResult.error || 'Failed to send OTP' },
          { status: 500 }
        );
      }
 
      // Increment rate limit
      await Promise.all([
        incrementRateLimit(formattedPhone, 'phone'),
        incrementRateLimit(ipHash, 'ip'),
      ]);
 
      // Log the event
      await logOtpSent(formattedPhone, 'phone', request.headers);
 
      return NextResponse.json({
        success: true,
        message: 'OTP sent successfully',
        phone_masked: formattedPhone.slice(0, 4) + '****' + formattedPhone.slice(-2),
        provider: 'twilio_verify',
      });
    }
 
    // Fallback to Supabase Auth (if Twilio not configured)
    console.log('Using Supabase Auth for OTP:', formattedPhone);
 
    const supabase = await createClient();
    const { error: otpError } = await supabase.auth.signInWithOtp({
      phone: formattedPhone,
    });
 
    if (otpError) {
      console.error('OTP send error:', {
        message: otpError.message,
        code: otpError.code,
        status: otpError.status,
        phone: formattedPhone,
      });
 
      // Increment rate limit on failure too
      await incrementRateLimit(formattedPhone, 'phone');
 
      // Provide more specific error messages
      let errorMessage = 'Failed to send OTP. Please try again.';
      if (
        otpError.message?.includes('not enabled') ||
        otpError.message?.includes('Phone provider')
      ) {
        errorMessage =
          'Phone authentication is not enabled. Please configure Twilio in environment variables.';
      } else if (otpError.message?.includes('rate limit') || otpError.status === 429) {
        errorMessage = 'Too many attempts. Please wait a few minutes and try again.';
      } else if (otpError.message?.includes('invalid') || otpError.message?.includes('format')) {
        errorMessage = 'Invalid phone number format. Please check and try again.';
      } else if (otpError.message?.includes('Twilio') || otpError.message?.includes('SMS')) {
        errorMessage = 'SMS service configuration error. Please check Twilio settings.';
      } else if (otpError.message?.includes('credentials') || otpError.message?.includes('auth')) {
        errorMessage = 'SMS provider authentication failed. Please verify Twilio credentials.';
      }
 
      return NextResponse.json(
        {
          error: errorMessage,
          details: process.env.NODE_ENV === 'development' ? otpError.message : undefined,
          code: otpError.code,
        },
        { status: 500 }
      );
    }
 
    // Increment rate limit
    await Promise.all([
      incrementRateLimit(formattedPhone, 'phone'),
      incrementRateLimit(ipHash, 'ip'),
    ]);
 
    // Log the event
    await logOtpSent(formattedPhone, 'phone', request.headers);
 
    return NextResponse.json({
      success: true,
      message: 'OTP sent successfully',
      phone_masked: formattedPhone.slice(0, 4) + '****' + formattedPhone.slice(-2),
      provider: 'supabase',
    });
  } catch (error) {
    console.error('Send OTP API error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}