( authType: AuthType, config: Config, )
| 70 | const oauthClientPromises = new Map<AuthType, Promise<OAuth2Client>>(); |
| 71 | |
| 72 | async function initOauthClient( |
| 73 | authType: AuthType, |
| 74 | config: Config, |
| 75 | ): Promise<OAuth2Client> { |
| 76 | const client = new OAuth2Client({ |
| 77 | clientId: OAUTH_CLIENT_ID, |
| 78 | clientSecret: OAUTH_CLIENT_SECRET, |
| 79 | transporterOptions: { |
| 80 | proxy: config.getProxy(), |
| 81 | }, |
| 82 | }); |
| 83 | |
| 84 | if ( |
| 85 | process.env['GOOGLE_GENAI_USE_GCA'] && |
| 86 | process.env['GOOGLE_CLOUD_ACCESS_TOKEN'] |
| 87 | ) { |
| 88 | client.setCredentials({ |
| 89 | access_token: process.env['GOOGLE_CLOUD_ACCESS_TOKEN'], |
| 90 | }); |
| 91 | await fetchAndCacheUserInfo(client); |
| 92 | return client; |
| 93 | } |
| 94 | |
| 95 | client.on('tokens', async (tokens: Credentials) => { |
| 96 | await cacheCredentials(tokens); |
| 97 | }); |
| 98 | |
| 99 | // If there are cached creds on disk, they always take precedence |
| 100 | if (await loadCachedCredentials(client)) { |
| 101 | // Found valid cached credentials. |
| 102 | // Check if we need to retrieve Google Account ID or Email |
| 103 | if (!getCachedGoogleAccount()) { |
| 104 | try { |
| 105 | await fetchAndCacheUserInfo(client); |
| 106 | } catch { |
| 107 | // Non-fatal, continue with existing auth. |
| 108 | } |
| 109 | } |
| 110 | console.log('Loaded cached credentials.'); |
| 111 | return client; |
| 112 | } |
| 113 | |
| 114 | // In Google Cloud Shell, we can use Application Default Credentials (ADC) |
| 115 | // provided via its metadata server to authenticate non-interactively using |
| 116 | // the identity of the user logged into Cloud Shell. |
| 117 | if (authType === AuthType.CLOUD_SHELL) { |
| 118 | try { |
| 119 | console.log("Attempting to authenticate via Cloud Shell VM's ADC."); |
| 120 | const computeClient = new Compute({ |
| 121 | // We can leave this empty, since the metadata server will provide |
| 122 | // the service account email. |
| 123 | }); |
| 124 | await computeClient.getAccessToken(); |
| 125 | console.log('Authentication successful.'); |
| 126 | |
| 127 | // Do not cache creds in this case; note that Compute client will handle its own refresh |
| 128 | return computeClient; |
| 129 | } catch (e) { |
no test coverage detected