import { OAuth2Client, type TokenPayload } from 'google-auth-library'; export type GoogleIdTokenPayloadType = TokenPayload & { email: string; }; /** * Verifies a Google ID token and returns the email address if the token is valid and the email is authorized. * @param googleClientId - The client ID of the Google application. * @param idToken - The ID token to verify. * @returns The email address if the token is valid and the email is authorized, or null if not. */ export async function decodeGoogleIdToken(googleClientId: string, idToken: string): Promise { const oauth2Client = new OAuth2Client(googleClientId); const ticket = await oauth2Client.verifyIdToken({ audience: googleClientId, idToken: idToken.trim(), }); const payload = ticket.getPayload(); if (!payload) { throw new Error('Invalid token', { cause: 'INVALID_GOOGLE_ID_TOKEN', }); } return payload as GoogleIdTokenPayloadType; }