UNPKG

24.1 kBTypeScriptView Raw
1import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
2import * as querystring from 'querystring';
3import { JwkCertificate } from '../crypto/crypto';
4import { BodyResponseCallback } from '../transporters';
5import { AuthClient, AuthClientOptions } from './authclient';
6import { Credentials } from './credentials';
7import { LoginTicket } from './loginticket';
8/**
9 * The results from the `generateCodeVerifierAsync` method. To learn more,
10 * See the sample:
11 * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js
12 */
13export interface CodeVerifierResults {
14 /**
15 * The code verifier that will be used when calling `getToken` to obtain a new
16 * access token.
17 */
18 codeVerifier: string;
19 /**
20 * The code_challenge that should be sent with the `generateAuthUrl` call
21 * to obtain a verifiable authentication url.
22 */
23 codeChallenge?: string;
24}
25export interface Certificates {
26 [index: string]: string | JwkCertificate;
27}
28export interface PublicKeys {
29 [index: string]: string;
30}
31export interface Headers {
32 [index: string]: string;
33}
34export declare enum CodeChallengeMethod {
35 Plain = "plain",
36 S256 = "S256"
37}
38export declare enum CertificateFormat {
39 PEM = "PEM",
40 JWK = "JWK"
41}
42/**
43 * The client authentication type. Supported values are basic, post, and none.
44 * https://datatracker.ietf.org/doc/html/rfc7591#section-2
45 */
46export declare enum ClientAuthentication {
47 ClientSecretPost = "ClientSecretPost",
48 ClientSecretBasic = "ClientSecretBasic",
49 None = "None"
50}
51export interface GetTokenOptions {
52 code: string;
53 codeVerifier?: string;
54 /**
55 * The client ID for your application. The value passed into the constructor
56 * will be used if not provided. Must match any client_id option passed to
57 * a corresponding call to generateAuthUrl.
58 */
59 client_id?: string;
60 /**
61 * Determines where the API server redirects the user after the user
62 * completes the authorization flow. The value passed into the constructor
63 * will be used if not provided. Must match any redirect_uri option passed to
64 * a corresponding call to generateAuthUrl.
65 */
66 redirect_uri?: string;
67}
68export interface TokenInfo {
69 /**
70 * The application that is the intended user of the access token.
71 */
72 aud: string;
73 /**
74 * This value lets you correlate profile information from multiple Google
75 * APIs. It is only present in the response if you included the profile scope
76 * in your request in step 1. The field value is an immutable identifier for
77 * the logged-in user that can be used to create and manage user sessions in
78 * your application. The identifier is the same regardless of which client ID
79 * is used to retrieve it. This enables multiple applications in the same
80 * organization to correlate profile information.
81 */
82 user_id?: string;
83 /**
84 * An array of scopes that the user granted access to.
85 */
86 scopes: string[];
87 /**
88 * The datetime when the token becomes invalid.
89 */
90 expiry_date: number;
91 /**
92 * An identifier for the user, unique among all Google accounts and never
93 * reused. A Google account can have multiple emails at different points in
94 * time, but the sub value is never changed. Use sub within your application
95 * as the unique-identifier key for the user.
96 */
97 sub?: string;
98 /**
99 * The client_id of the authorized presenter. This claim is only needed when
100 * the party requesting the ID token is not the same as the audience of the ID
101 * token. This may be the case at Google for hybrid apps where a web
102 * application and Android app have a different client_id but share the same
103 * project.
104 */
105 azp?: string;
106 /**
107 * Indicates whether your application can refresh access tokens
108 * when the user is not present at the browser. Valid parameter values are
109 * 'online', which is the default value, and 'offline'. Set the value to
110 * 'offline' if your application needs to refresh access tokens when the user
111 * is not present at the browser. This value instructs the Google
112 * authorization server to return a refresh token and an access token the
113 * first time that your application exchanges an authorization code for
114 * tokens.
115 */
116 access_type?: string;
117 /**
118 * The user's email address. This value may not be unique to this user and
119 * is not suitable for use as a primary key. Provided only if your scope
120 * included the email scope value.
121 */
122 email?: string;
123 /**
124 * True if the user's e-mail address has been verified; otherwise false.
125 */
126 email_verified?: boolean;
127}
128export interface GenerateAuthUrlOpts {
129 /**
130 * Recommended. Indicates whether your application can refresh access tokens
131 * when the user is not present at the browser. Valid parameter values are
132 * 'online', which is the default value, and 'offline'. Set the value to
133 * 'offline' if your application needs to refresh access tokens when the user
134 * is not present at the browser. This value instructs the Google
135 * authorization server to return a refresh token and an access token the
136 * first time that your application exchanges an authorization code for
137 * tokens.
138 */
139 access_type?: string;
140 /**
141 * The hd (hosted domain) parameter streamlines the login process for G Suite
142 * hosted accounts. By including the domain of the G Suite user (for example,
143 * mycollege.edu), you can indicate that the account selection UI should be
144 * optimized for accounts at that domain. To optimize for G Suite accounts
145 * generally instead of just one domain, use an asterisk: hd=*.
146 * Don't rely on this UI optimization to control who can access your app,
147 * as client-side requests can be modified. Be sure to validate that the
148 * returned ID token has an hd claim value that matches what you expect
149 * (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is
150 * contained within a security token from Google, so the value can be trusted.
151 */
152 hd?: string;
153 /**
154 * The 'response_type' will always be set to 'CODE'.
155 */
156 response_type?: string;
157 /**
158 * The client ID for your application. The value passed into the constructor
159 * will be used if not provided. You can find this value in the API Console.
160 */
161 client_id?: string;
162 /**
163 * Determines where the API server redirects the user after the user
164 * completes the authorization flow. The value must exactly match one of the
165 * 'redirect_uri' values listed for your project in the API Console. Note that
166 * the http or https scheme, case, and trailing slash ('/') must all match.
167 * The value passed into the constructor will be used if not provided.
168 */
169 redirect_uri?: string;
170 /**
171 * Required. A space-delimited list of scopes that identify the resources that
172 * your application could access on the user's behalf. These values inform the
173 * consent screen that Google displays to the user. Scopes enable your
174 * application to only request access to the resources that it needs while
175 * also enabling users to control the amount of access that they grant to your
176 * application. Thus, there is an inverse relationship between the number of
177 * scopes requested and the likelihood of obtaining user consent. The
178 * OAuth 2.0 API Scopes document provides a full list of scopes that you might
179 * use to access Google APIs. We recommend that your application request
180 * access to authorization scopes in context whenever possible. By requesting
181 * access to user data in context, via incremental authorization, you help
182 * users to more easily understand why your application needs the access it is
183 * requesting.
184 */
185 scope?: string[] | string;
186 /**
187 * Recommended. Specifies any string value that your application uses to
188 * maintain state between your authorization request and the authorization
189 * server's response. The server returns the exact value that you send as a
190 * name=value pair in the hash (#) fragment of the 'redirect_uri' after the
191 * user consents to or denies your application's access request. You can use
192 * this parameter for several purposes, such as directing the user to the
193 * correct resource in your application, sending nonces, and mitigating
194 * cross-site request forgery. Since your redirect_uri can be guessed, using a
195 * state value can increase your assurance that an incoming connection is the
196 * result of an authentication request. If you generate a random string or
197 * encode the hash of a cookie or another value that captures the client's
198 * state, you can validate the response to additionally ensure that the
199 * request and response originated in the same browser, providing protection
200 * against attacks such as cross-site request forgery. See the OpenID Connect
201 * documentation for an example of how to create and confirm a state token.
202 */
203 state?: string;
204 /**
205 * Optional. Enables applications to use incremental authorization to request
206 * access to additional scopes in context. If you set this parameter's value
207 * to true and the authorization request is granted, then the new access token
208 * will also cover any scopes to which the user previously granted the
209 * application access. See the incremental authorization section for examples.
210 */
211 include_granted_scopes?: boolean;
212 /**
213 * Optional. If your application knows which user is trying to authenticate,
214 * it can use this parameter to provide a hint to the Google Authentication
215 * Server. The server uses the hint to simplify the login flow either by
216 * prefilling the email field in the sign-in form or by selecting the
217 * appropriate multi-login session. Set the parameter value to an email
218 * address or sub identifier, which is equivalent to the user's Google ID.
219 */
220 login_hint?: string;
221 /**
222 * Optional. A space-delimited, case-sensitive list of prompts to present the
223 * user. If you don't specify this parameter, the user will be prompted only
224 * the first time your app requests access. Possible values are:
225 *
226 * 'none' - Donot display any authentication or consent screens. Must not be
227 * specified with other values.
228 * 'consent' - Prompt the user for consent.
229 * 'select_account' - Prompt the user to select an account.
230 */
231 prompt?: string;
232 /**
233 * Recommended. Specifies what method was used to encode a 'code_verifier'
234 * that will be used during authorization code exchange. This parameter must
235 * be used with the 'code_challenge' parameter. The value of the
236 * 'code_challenge_method' defaults to "plain" if not present in the request
237 * that includes a 'code_challenge'. The only supported values for this
238 * parameter are "S256" or "plain".
239 */
240 code_challenge_method?: CodeChallengeMethod;
241 /**
242 * Recommended. Specifies an encoded 'code_verifier' that will be used as a
243 * server-side challenge during authorization code exchange. This parameter
244 * must be used with the 'code_challenge' parameter described above.
245 */
246 code_challenge?: string;
247 /**
248 * A way for developers and/or the auth team to provide a set of key value
249 * pairs to be added as query parameters to the authorization url.
250 */
251 [key: string]: querystring.ParsedUrlQueryInput[keyof querystring.ParsedUrlQueryInput];
252}
253export interface AccessTokenResponse {
254 access_token: string;
255 expiry_date: number;
256}
257export interface GetRefreshHandlerCallback {
258 (): Promise<AccessTokenResponse>;
259}
260export interface GetTokenCallback {
261 (err: GaxiosError | null, token?: Credentials | null, res?: GaxiosResponse | null): void;
262}
263export interface GetTokenResponse {
264 tokens: Credentials;
265 res: GaxiosResponse | null;
266}
267export interface GetAccessTokenCallback {
268 (err: GaxiosError | null, token?: string | null, res?: GaxiosResponse | null): void;
269}
270export interface GetAccessTokenResponse {
271 token?: string | null;
272 res?: GaxiosResponse | null;
273}
274export interface RefreshAccessTokenCallback {
275 (err: GaxiosError | null, credentials?: Credentials | null, res?: GaxiosResponse | null): void;
276}
277export interface RefreshAccessTokenResponse {
278 credentials: Credentials;
279 res: GaxiosResponse | null;
280}
281export interface RequestMetadataResponse {
282 headers: Headers;
283 res?: GaxiosResponse<void> | null;
284}
285export interface RequestMetadataCallback {
286 (err: GaxiosError | null, headers?: Headers, res?: GaxiosResponse<void> | null): void;
287}
288export interface GetFederatedSignonCertsCallback {
289 (err: GaxiosError | null, certs?: Certificates, response?: GaxiosResponse<void> | null): void;
290}
291export interface FederatedSignonCertsResponse {
292 certs: Certificates;
293 format: CertificateFormat;
294 res?: GaxiosResponse<void> | null;
295}
296export interface GetIapPublicKeysCallback {
297 (err: GaxiosError | null, pubkeys?: PublicKeys, response?: GaxiosResponse<void> | null): void;
298}
299export interface IapPublicKeysResponse {
300 pubkeys: PublicKeys;
301 res?: GaxiosResponse<void> | null;
302}
303export interface RevokeCredentialsResult {
304 success: boolean;
305}
306export interface VerifyIdTokenOptions {
307 idToken: string;
308 audience?: string | string[];
309 maxExpiry?: number;
310}
311export interface OAuth2ClientEndpoints {
312 /**
313 * The endpoint for viewing access token information
314 *
315 * @example
316 * 'https://oauth2.googleapis.com/tokeninfo'
317 */
318 tokenInfoUrl: string | URL;
319 /**
320 * The base URL for auth endpoints.
321 *
322 * @example
323 * 'https://accounts.google.com/o/oauth2/v2/auth'
324 */
325 oauth2AuthBaseUrl: string | URL;
326 /**
327 * The base endpoint for token retrieval
328 * .
329 * @example
330 * 'https://oauth2.googleapis.com/token'
331 */
332 oauth2TokenUrl: string | URL;
333 /**
334 * The base endpoint to revoke tokens.
335 *
336 * @example
337 * 'https://oauth2.googleapis.com/revoke'
338 */
339 oauth2RevokeUrl: string | URL;
340 /**
341 * Sign on certificates in PEM format.
342 *
343 * @example
344 * 'https://www.googleapis.com/oauth2/v1/certs'
345 */
346 oauth2FederatedSignonPemCertsUrl: string | URL;
347 /**
348 * Sign on certificates in JWK format.
349 *
350 * @example
351 * 'https://www.googleapis.com/oauth2/v3/certs'
352 */
353 oauth2FederatedSignonJwkCertsUrl: string | URL;
354 /**
355 * IAP Public Key URL.
356 * This URL contains a JSON dictionary that maps the `kid` claims to the public key values.
357 *
358 * @example
359 * 'https://www.gstatic.com/iap/verify/public_key'
360 */
361 oauth2IapPublicKeyUrl: string | URL;
362}
363export interface OAuth2ClientOptions extends AuthClientOptions {
364 clientId?: string;
365 clientSecret?: string;
366 redirectUri?: string;
367 /**
368 * Customizable endpoints.
369 */
370 endpoints?: Partial<OAuth2ClientEndpoints>;
371 /**
372 * The allowed OAuth2 token issuers.
373 */
374 issuers?: string[];
375 /**
376 * The client authentication type. Supported values are basic, post, and none.
377 * Defaults to post if not provided.
378 * https://datatracker.ietf.org/doc/html/rfc7591#section-2
379 */
380 clientAuthentication?: ClientAuthentication;
381}
382export type RefreshOptions = Pick<AuthClientOptions, 'eagerRefreshThresholdMillis' | 'forceRefreshOnFailure'>;
383export declare class OAuth2Client extends AuthClient {
384 private redirectUri?;
385 private certificateCache;
386 private certificateExpiry;
387 private certificateCacheFormat;
388 protected refreshTokenPromises: Map<string, Promise<GetTokenResponse>>;
389 readonly endpoints: Readonly<OAuth2ClientEndpoints>;
390 readonly issuers: string[];
391 readonly clientAuthentication: ClientAuthentication;
392 _clientId?: string;
393 _clientSecret?: string;
394 refreshHandler?: GetRefreshHandlerCallback;
395 /**
396 * Handles OAuth2 flow for Google APIs.
397 *
398 * @param clientId The authentication client ID.
399 * @param clientSecret The authentication client secret.
400 * @param redirectUri The URI to redirect to after completing the auth
401 * request.
402 * @param opts optional options for overriding the given parameters.
403 * @constructor
404 */
405 constructor(options?: OAuth2ClientOptions);
406 constructor(clientId?: string, clientSecret?: string, redirectUri?: string);
407 /**
408 * @deprecated use instance's {@link OAuth2Client.endpoints}
409 */
410 protected static readonly GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo";
411 /**
412 * Clock skew - five minutes in seconds
413 */
414 private static readonly CLOCK_SKEW_SECS_;
415 /**
416 * The default max Token Lifetime is one day in seconds
417 */
418 private static readonly DEFAULT_MAX_TOKEN_LIFETIME_SECS_;
419 /**
420 * Generates URL for consent page landing.
421 * @param opts Options.
422 * @return URL to consent page.
423 */
424 generateAuthUrl(opts?: GenerateAuthUrlOpts): string;
425 generateCodeVerifier(): void;
426 /**
427 * Convenience method to automatically generate a code_verifier, and its
428 * resulting SHA256. If used, this must be paired with a S256
429 * code_challenge_method.
430 *
431 * For a full example see:
432 * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js
433 */
434 generateCodeVerifierAsync(): Promise<CodeVerifierResults>;
435 /**
436 * Gets the access token for the given code.
437 * @param code The authorization code.
438 * @param callback Optional callback fn.
439 */
440 getToken(code: string): Promise<GetTokenResponse>;
441 getToken(options: GetTokenOptions): Promise<GetTokenResponse>;
442 getToken(code: string, callback: GetTokenCallback): void;
443 getToken(options: GetTokenOptions, callback: GetTokenCallback): void;
444 private getTokenAsync;
445 /**
446 * Refreshes the access token.
447 * @param refresh_token Existing refresh token.
448 * @private
449 */
450 protected refreshToken(refreshToken?: string | null): Promise<GetTokenResponse>;
451 protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
452 /**
453 * Retrieves the access token using refresh token
454 *
455 * @param callback callback
456 */
457 refreshAccessToken(): Promise<RefreshAccessTokenResponse>;
458 refreshAccessToken(callback: RefreshAccessTokenCallback): void;
459 private refreshAccessTokenAsync;
460 /**
461 * Get a non-expired access token, after refreshing if necessary
462 *
463 * @param callback Callback to call with the access token
464 */
465 getAccessToken(): Promise<GetAccessTokenResponse>;
466 getAccessToken(callback: GetAccessTokenCallback): void;
467 private getAccessTokenAsync;
468 /**
469 * The main authentication interface. It takes an optional url which when
470 * present is the endpoint being accessed, and returns a Promise which
471 * resolves with authorization header fields.
472 *
473 * In OAuth2Client, the result has the form:
474 * { Authorization: 'Bearer <access_token_value>' }
475 * @param url The optional url being authorized
476 */
477 getRequestHeaders(url?: string): Promise<Headers>;
478 protected getRequestMetadataAsync(url?: string | URL | null): Promise<RequestMetadataResponse>;
479 /**
480 * Generates an URL to revoke the given token.
481 * @param token The existing token to be revoked.
482 *
483 * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL}
484 */
485 static getRevokeTokenUrl(token: string): string;
486 /**
487 * Generates a URL to revoke the given token.
488 *
489 * @param token The existing token to be revoked.
490 */
491 getRevokeTokenURL(token: string): URL;
492 /**
493 * Revokes the access given to token.
494 * @param token The existing token to be revoked.
495 * @param callback Optional callback fn.
496 */
497 revokeToken(token: string): GaxiosPromise<RevokeCredentialsResult>;
498 revokeToken(token: string, callback: BodyResponseCallback<RevokeCredentialsResult>): void;
499 /**
500 * Revokes access token and clears the credentials object
501 * @param callback callback
502 */
503 revokeCredentials(): GaxiosPromise<RevokeCredentialsResult>;
504 revokeCredentials(callback: BodyResponseCallback<RevokeCredentialsResult>): void;
505 private revokeCredentialsAsync;
506 /**
507 * Provides a request implementation with OAuth 2.0 flow. If credentials have
508 * a refresh_token, in cases of HTTP 401 and 403 responses, it automatically
509 * asks for a new access token and replays the unsuccessful request.
510 * @param opts Request options.
511 * @param callback callback.
512 * @return Request object
513 */
514 request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
515 request<T>(opts: GaxiosOptions, callback: BodyResponseCallback<T>): void;
516 protected requestAsync<T>(opts: GaxiosOptions, reAuthRetried?: boolean): Promise<GaxiosResponse<T>>;
517 /**
518 * Verify id token is token by checking the certs and audience
519 * @param options that contains all options.
520 * @param callback Callback supplying GoogleLogin if successful
521 */
522 verifyIdToken(options: VerifyIdTokenOptions): Promise<LoginTicket>;
523 verifyIdToken(options: VerifyIdTokenOptions, callback: (err: Error | null, login?: LoginTicket) => void): void;
524 private verifyIdTokenAsync;
525 /**
526 * Obtains information about the provisioned access token. Especially useful
527 * if you want to check the scopes that were provisioned to a given token.
528 *
529 * @param accessToken Required. The Access Token for which you want to get
530 * user info.
531 */
532 getTokenInfo(accessToken: string): Promise<TokenInfo>;
533 /**
534 * Gets federated sign-on certificates to use for verifying identity tokens.
535 * Returns certs as array structure, where keys are key ids, and values
536 * are certificates in either PEM or JWK format.
537 * @param callback Callback supplying the certificates
538 */
539 getFederatedSignonCerts(): Promise<FederatedSignonCertsResponse>;
540 getFederatedSignonCerts(callback: GetFederatedSignonCertsCallback): void;
541 getFederatedSignonCertsAsync(): Promise<FederatedSignonCertsResponse>;
542 /**
543 * Gets federated sign-on certificates to use for verifying identity tokens.
544 * Returns certs as array structure, where keys are key ids, and values
545 * are certificates in either PEM or JWK format.
546 * @param callback Callback supplying the certificates
547 */
548 getIapPublicKeys(): Promise<IapPublicKeysResponse>;
549 getIapPublicKeys(callback: GetIapPublicKeysCallback): void;
550 getIapPublicKeysAsync(): Promise<IapPublicKeysResponse>;
551 verifySignedJwtWithCerts(): void;
552 /**
553 * Verify the id token is signed with the correct certificate
554 * and is from the correct audience.
555 * @param jwt The jwt to verify (The ID Token in this case).
556 * @param certs The array of certs to test the jwt against.
557 * @param requiredAudience The audience to test the jwt against.
558 * @param issuers The allowed issuers of the jwt (Optional).
559 * @param maxExpiry The max expiry the certificate can be (Optional).
560 * @return Returns a promise resolving to LoginTicket on verification.
561 */
562 verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number): Promise<LoginTicket>;
563 /**
564 * Returns a promise that resolves with AccessTokenResponse type if
565 * refreshHandler is defined.
566 * If not, nothing is returned.
567 */
568 private processAndValidateRefreshHandler;
569 /**
570 * Returns true if a token is expired or will expire within
571 * eagerRefreshThresholdMillismilliseconds.
572 * If there is no expiry time, assumes the token is not expired or expiring.
573 */
574 protected isTokenExpiring(): boolean;
575}