All files / src/platform/identity/social-auth google-auth.provider.ts

0% Statements 0/72
0% Branches 0/46
0% Functions 0/11
0% Lines 0/69

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import {
  Injectable,
  Logger,
  UnauthorizedException,
  BadRequestException,
} from '@nestjs/common';
import * as crypto from 'crypto';
import * as https from 'https';
 
/**
 * Google Auth Provider — Verifies Google ID tokens for web, Android, and iOS/Flutter.
 *
 * Validates:
 * - Token signature (RS256 via Google's public keys)
 * - Issuer (accounts.google.com or https://accounts.google.com)
 * - Audience (matches configured client IDs)
 * - Expiration
 * - Email verification status
 *
 * Environment variables expected:
 * - GOOGLE_CLIENT_ID_WEB
 * - GOOGLE_CLIENT_ID_ANDROID
 * - GOOGLE_CLIENT_ID_IOS
 */
 
export interface GoogleIdTokenPayload {
  iss: string; // accounts.google.com or https://accounts.google.com
  azp: string; // Authorized party
  aud: string; // Audience (client ID)
  sub: string; // Google user ID (stable, unique)
  email: string;
  email_verified: boolean;
  name?: string;
  picture?: string;
  given_name?: string;
  family_name?: string;
  locale?: string;
  iat: number;
  exp: number;
  nonce?: string;
}
 
export interface GoogleAuthResult {
  providerUserId: string;
  email: string;
  emailVerified: boolean;
  displayName: string;
  firstName: string;
  lastName: string;
  avatarUrl: string | null;
  rawProfile: GoogleIdTokenPayload;
}
 
@Injectable()
export class GoogleAuthProvider {
  private readonly logger = new Logger(GoogleAuthProvider.name);
  private readonly allowedIssuers = [
    'accounts.google.com',
    'https://accounts.google.com',
  ];
  private readonly tokenInfoUrl = 'https://oauth2.googleapis.com/tokeninfo';
  private readonly certsUrl = 'https://www.googleapis.com/oauth2/v3/certs';
 
  private cachedKeys: any = null;
  private keysCachedAt = 0;
  private readonly keyCacheTtlMs = 3600000; // 1 hour
 
  /**
   * Returns all configured Google client IDs for audience validation.
   */
  private getAllowedAudiences(): string[] {
    const audiences: string[] = [];
    if (process.env.GOOGLE_CLIENT_ID_WEB)
      audiences.push(process.env.GOOGLE_CLIENT_ID_WEB);
    if (process.env.GOOGLE_CLIENT_ID_ANDROID)
      audiences.push(process.env.GOOGLE_CLIENT_ID_ANDROID);
    if (process.env.GOOGLE_CLIENT_ID_IOS)
      audiences.push(process.env.GOOGLE_CLIENT_ID_IOS);
    return audiences;
  }
 
  /**
   * Verifies a Google ID token and returns the user's identity information.
   *
   * Uses Google's tokeninfo endpoint for verification in production,
   * with local JWT validation as a fallback pattern.
   */
  async verifyIdToken(idToken: string): Promise<GoogleAuthResult> {
    if (!idToken || idToken.trim().length === 0) {
      throw new BadRequestException('Google ID token is required');
    }
 
    const audiences = this.getAllowedAudiences();
    if (audiences.length === 0) {
      throw new BadRequestException(
        'Google OAuth is not configured. Set GOOGLE_CLIENT_ID_* environment variables.',
      );
    }
 
    try {
      // Decode the JWT payload without verification first (for logging on failure)
      const payload = this.decodeJwtPayload(idToken);
 
      // Validate structural requirements
      this.validateTokenStructure(payload, audiences);
 
      // Verify via Google's tokeninfo endpoint (server-side verification)
      const verified = await this.verifyViaTokenInfo(idToken);
 
      // Cross-validate the verified payload
      this.validateTokenStructure(verified, audiences);
 
      return this.mapToAuthResult(verified);
    } catch (error) {
      if (
        error instanceof UnauthorizedException ||
        error instanceof BadRequestException
      ) {
        throw error;
      }
      this.logger.error(
        `Google ID token verification failed: ${error.message}`,
      );
      throw new UnauthorizedException('Invalid Google ID token');
    }
  }
 
  /**
   * Decodes a JWT payload without verifying the signature.
   * Used for initial structural validation and error diagnostics.
   */
  private decodeJwtPayload(token: string): GoogleIdTokenPayload {
    const parts = token.split('.');
    if (parts.length !== 3) {
      throw new UnauthorizedException('Malformed Google ID token');
    }
 
    try {
      const payloadJson = Buffer.from(parts[1], 'base64url').toString('utf8');
      return JSON.parse(payloadJson);
    } catch {
      throw new UnauthorizedException(
        'Unable to decode Google ID token payload',
      );
    }
  }
 
  /**
   * Validates token structure: issuer, audience, expiration, email verification.
   */
  private validateTokenStructure(
    payload: GoogleIdTokenPayload,
    audiences: string[],
  ): void {
    // Issuer validation
    if (!this.allowedIssuers.includes(payload.iss)) {
      throw new UnauthorizedException(`Invalid token issuer: ${payload.iss}`);
    }
 
    // Audience validation
    if (!audiences.includes(payload.aud)) {
      throw new UnauthorizedException(
        'Token audience does not match any configured Google client ID',
      );
    }
 
    // Expiration validation (with 5-minute clock skew tolerance)
    const now = Math.floor(Date.now() / 1000);
    if (payload.exp < now - 300) {
      throw new UnauthorizedException('Google ID token has expired');
    }
 
    // Email must be verified
    if (!payload.email_verified) {
      throw new UnauthorizedException('Google account email is not verified');
    }
 
    // Subject must be present
    if (!payload.sub) {
      throw new UnauthorizedException(
        'Google ID token is missing subject (sub) claim',
      );
    }
  }
 
  /**
   * Verifies a Google ID token via Google's tokeninfo endpoint.
   * This is the most reliable server-side verification method.
   */
  private verifyViaTokenInfo(idToken: string): Promise<GoogleIdTokenPayload> {
    return new Promise((resolve, reject) => {
      const url = `${this.tokenInfoUrl}?id_token=${encodeURIComponent(idToken)}`;
 
      https
        .get(url, (res) => {
          let data = '';
          res.on('data', (chunk) => (data += chunk));
          res.on('end', () => {
            if (res.statusCode !== 200) {
              reject(
                new UnauthorizedException('Google token verification failed'),
              );
              return;
            }
            try {
              const payload = JSON.parse(data);
              // tokeninfo returns email_verified as string "true"/"false"
              payload.email_verified =
                payload.email_verified === 'true' ||
                payload.email_verified === true;
              payload.iat = parseInt(payload.iat, 10);
              payload.exp = parseInt(payload.exp, 10);
              resolve(payload);
            } catch (err) {
              reject(
                new UnauthorizedException(
                  'Failed to parse Google tokeninfo response',
                ),
              );
            }
          });
        })
        .on('error', (err) => {
          reject(
            new UnauthorizedException(
              `Google tokeninfo request failed: ${err.message}`,
            ),
          );
        });
    });
  }
 
  /**
   * Maps the verified Google payload to our standard AuthResult.
   */
  private mapToAuthResult(payload: GoogleIdTokenPayload): GoogleAuthResult {
    return {
      providerUserId: payload.sub,
      email: payload.email.toLowerCase(),
      emailVerified: payload.email_verified,
      displayName:
        payload.name ||
        `${payload.given_name || ''} ${payload.family_name || ''}`.trim(),
      firstName: payload.given_name || payload.name?.split(' ')[0] || '',
      lastName:
        payload.family_name ||
        payload.name?.split(' ').slice(1).join(' ') ||
        '',
      avatarUrl: payload.picture || null,
      rawProfile: payload,
    };
  }
}