import { Credentials } from './credentials' ; import { Headers , OAuth2Client , RequestMetadataResponse } from './oauth2client' ; export interface IdTokenOptions { /**
     * The client to make the request to fetch an ID token.
     */ idTokenProvider : IdTokenProvider ; /**
     * The audience to use when requesting an ID token.
     */ targetAudience : string ; } export interface IdTokenProvider { fetchIdToken : ( targetAudience : string ) => Promise < string > ; } export class IdTokenClient extends OAuth2Client { targetAudience : string ; idTokenProvider : IdTokenProvider ; /**
     * Google ID Token client
     *
     * Retrieve access token from the metadata server.
     * See: https://developers.google.com/compute/docs/authentication
     */ constructor ( options ) { super ( ) ; this . targetAudience = options . targetAudience ; this . idTokenProvider = options . idTokenProvider ; } protected async getRequestMetadataAsync ( url ? ) { if ( ! this . credentials . id_token || ( this . credentials . expiry_date || 0 ) < Date . now ( ) ) { const idToken = await this . idTokenProvider . fetchIdToken ( this . targetAudience ) ; this . credentials = { id_token : idToken , expiry_date : this . getIdTokenExpiryDate ( idToken ) , } as Credentials ; } const headers = { Authorization : 'Bearer ' + this . credentials . id_token , } ; return { headers } ; } private getIdTokenExpiryDate ( idToken ) { const payloadB64 = idToken . split ( '.' ) [ 1 ] ; if ( payloadB64 ) { const payload = JSON . parse ( Buffer . from ( payloadB64 , 'base64' ) . toString ( 'ascii' ) ) ; return payload . exp * 1000 ; } } }