UNPKG

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