-
Notifications
You must be signed in to change notification settings - Fork 384
/
oauth2client.ts
1554 lines (1406 loc) Β· 48.9 KB
/
oauth2client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
GaxiosError,
GaxiosOptions,
GaxiosPromise,
GaxiosResponse,
} from 'gaxios';
import * as querystring from 'querystring';
import * as stream from 'stream';
import * as formatEcdsa from 'ecdsa-sig-formatter';
import {createCrypto, JwkCertificate, hasBrowserCrypto} from '../crypto/crypto';
import {BodyResponseCallback} from '../transporters';
import {AuthClient, AuthClientOptions} from './authclient';
import {CredentialRequest, Credentials} from './credentials';
import {LoginTicket, TokenPayload} from './loginticket';
/**
* The results from the `generateCodeVerifierAsync` method. To learn more,
* See the sample:
* https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js
*/
export interface CodeVerifierResults {
/**
* The code verifier that will be used when calling `getToken` to obtain a new
* access token.
*/
codeVerifier: string;
/**
* The code_challenge that should be sent with the `generateAuthUrl` call
* to obtain a verifiable authentication url.
*/
codeChallenge?: string;
}
export interface Certificates {
[index: string]: string | JwkCertificate;
}
export interface PublicKeys {
[index: string]: string;
}
export interface Headers {
[index: string]: string;
}
export enum CodeChallengeMethod {
Plain = 'plain',
S256 = 'S256',
}
export enum CertificateFormat {
PEM = 'PEM',
JWK = 'JWK',
}
/**
* The client authentication type. Supported values are basic, post, and none.
* https://datatracker.ietf.org/doc/html/rfc7591#section-2
*/
export enum ClientAuthentication {
ClientSecretPost = 'ClientSecretPost',
ClientSecretBasic = 'ClientSecretBasic',
None = 'None',
}
export interface GetTokenOptions {
code: string;
codeVerifier?: string;
/**
* The client ID for your application. The value passed into the constructor
* will be used if not provided. Must match any client_id option passed to
* a corresponding call to generateAuthUrl.
*/
client_id?: string;
/**
* Determines where the API server redirects the user after the user
* completes the authorization flow. The value passed into the constructor
* will be used if not provided. Must match any redirect_uri option passed to
* a corresponding call to generateAuthUrl.
*/
redirect_uri?: string;
}
/**
* An interface for preparing {@link GetTokenOptions} as a querystring.
*/
interface GetTokenQuery {
client_id?: string;
client_secret?: string;
code_verifier?: string;
code: string;
grant_type: 'authorization_code';
redirect_uri?: string;
[key: string]: string | undefined;
}
export interface TokenInfo {
/**
* The application that is the intended user of the access token.
*/
aud: string;
/**
* This value lets you correlate profile information from multiple Google
* APIs. It is only present in the response if you included the profile scope
* in your request in step 1. The field value is an immutable identifier for
* the logged-in user that can be used to create and manage user sessions in
* your application. The identifier is the same regardless of which client ID
* is used to retrieve it. This enables multiple applications in the same
* organization to correlate profile information.
*/
user_id?: string;
/**
* An array of scopes that the user granted access to.
*/
scopes: string[];
/**
* The datetime when the token becomes invalid.
*/
expiry_date: number;
/**
* An identifier for the user, unique among all Google accounts and never
* reused. A Google account can have multiple emails at different points in
* time, but the sub value is never changed. Use sub within your application
* as the unique-identifier key for the user.
*/
sub?: string;
/**
* The client_id of the authorized presenter. This claim is only needed when
* the party requesting the ID token is not the same as the audience of the ID
* token. This may be the case at Google for hybrid apps where a web
* application and Android app have a different client_id but share the same
* project.
*/
azp?: string;
/**
* Indicates whether your application can refresh access tokens
* when the user is not present at the browser. Valid parameter values are
* 'online', which is the default value, and 'offline'. Set the value to
* 'offline' if your application needs to refresh access tokens when the user
* is not present at the browser. This value instructs the Google
* authorization server to return a refresh token and an access token the
* first time that your application exchanges an authorization code for
* tokens.
*/
access_type?: string;
/**
* The user's email address. This value may not be unique to this user and
* is not suitable for use as a primary key. Provided only if your scope
* included the email scope value.
*/
email?: string;
/**
* True if the user's e-mail address has been verified; otherwise false.
*/
email_verified?: boolean;
}
interface TokenInfoRequest {
aud: string;
user_id?: string;
scope?: string;
expires_in?: number;
azp?: string;
sub?: string;
exp?: number;
access_type?: string;
}
export interface GenerateAuthUrlOpts {
/**
* Recommended. Indicates whether your application can refresh access tokens
* when the user is not present at the browser. Valid parameter values are
* 'online', which is the default value, and 'offline'. Set the value to
* 'offline' if your application needs to refresh access tokens when the user
* is not present at the browser. This value instructs the Google
* authorization server to return a refresh token and an access token the
* first time that your application exchanges an authorization code for
* tokens.
*/
access_type?: string;
/**
* The hd (hosted domain) parameter streamlines the login process for G Suite
* hosted accounts. By including the domain of the G Suite user (for example,
* mycollege.edu), you can indicate that the account selection UI should be
* optimized for accounts at that domain. To optimize for G Suite accounts
* generally instead of just one domain, use an asterisk: hd=*.
* Don't rely on this UI optimization to control who can access your app,
* as client-side requests can be modified. Be sure to validate that the
* returned ID token has an hd claim value that matches what you expect
* (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is
* contained within a security token from Google, so the value can be trusted.
*/
hd?: string;
/**
* The 'response_type' will always be set to 'CODE'.
*/
response_type?: string;
/**
* The client ID for your application. The value passed into the constructor
* will be used if not provided. You can find this value in the API Console.
*/
client_id?: string;
/**
* Determines where the API server redirects the user after the user
* completes the authorization flow. The value must exactly match one of the
* 'redirect_uri' values listed for your project in the API Console. Note that
* the http or https scheme, case, and trailing slash ('/') must all match.
* The value passed into the constructor will be used if not provided.
*/
redirect_uri?: string;
/**
* Required. A space-delimited list of scopes that identify the resources that
* your application could access on the user's behalf. These values inform the
* consent screen that Google displays to the user. Scopes enable your
* application to only request access to the resources that it needs while
* also enabling users to control the amount of access that they grant to your
* application. Thus, there is an inverse relationship between the number of
* scopes requested and the likelihood of obtaining user consent. The
* OAuth 2.0 API Scopes document provides a full list of scopes that you might
* use to access Google APIs. We recommend that your application request
* access to authorization scopes in context whenever possible. By requesting
* access to user data in context, via incremental authorization, you help
* users to more easily understand why your application needs the access it is
* requesting.
*/
scope?: string[] | string;
/**
* Recommended. Specifies any string value that your application uses to
* maintain state between your authorization request and the authorization
* server's response. The server returns the exact value that you send as a
* name=value pair in the hash (#) fragment of the 'redirect_uri' after the
* user consents to or denies your application's access request. You can use
* this parameter for several purposes, such as directing the user to the
* correct resource in your application, sending nonces, and mitigating
* cross-site request forgery. Since your redirect_uri can be guessed, using a
* state value can increase your assurance that an incoming connection is the
* result of an authentication request. If you generate a random string or
* encode the hash of a cookie or another value that captures the client's
* state, you can validate the response to additionally ensure that the
* request and response originated in the same browser, providing protection
* against attacks such as cross-site request forgery. See the OpenID Connect
* documentation for an example of how to create and confirm a state token.
*/
state?: string;
/**
* Optional. Enables applications to use incremental authorization to request
* access to additional scopes in context. If you set this parameter's value
* to true and the authorization request is granted, then the new access token
* will also cover any scopes to which the user previously granted the
* application access. See the incremental authorization section for examples.
*/
include_granted_scopes?: boolean;
/**
* Optional. If your application knows which user is trying to authenticate,
* it can use this parameter to provide a hint to the Google Authentication
* Server. The server uses the hint to simplify the login flow either by
* prefilling the email field in the sign-in form or by selecting the
* appropriate multi-login session. Set the parameter value to an email
* address or sub identifier, which is equivalent to the user's Google ID.
*/
login_hint?: string;
/**
* Optional. A space-delimited, case-sensitive list of prompts to present the
* user. If you don't specify this parameter, the user will be prompted only
* the first time your app requests access. Possible values are:
*
* 'none' - Donot display any authentication or consent screens. Must not be
* specified with other values.
* 'consent' - Prompt the user for consent.
* 'select_account' - Prompt the user to select an account.
*/
prompt?: string;
/**
* Recommended. Specifies what method was used to encode a 'code_verifier'
* that will be used during authorization code exchange. This parameter must
* be used with the 'code_challenge' parameter. The value of the
* 'code_challenge_method' defaults to "plain" if not present in the request
* that includes a 'code_challenge'. The only supported values for this
* parameter are "S256" or "plain".
*/
code_challenge_method?: CodeChallengeMethod;
/**
* Recommended. Specifies an encoded 'code_verifier' that will be used as a
* server-side challenge during authorization code exchange. This parameter
* must be used with the 'code_challenge' parameter described above.
*/
code_challenge?: string;
/**
* A way for developers and/or the auth team to provide a set of key value
* pairs to be added as query parameters to the authorization url.
*/
[
key: string
]: querystring.ParsedUrlQueryInput[keyof querystring.ParsedUrlQueryInput];
}
export interface AccessTokenResponse {
access_token: string;
expiry_date: number;
}
export interface GetRefreshHandlerCallback {
(): Promise<AccessTokenResponse>;
}
export interface GetTokenCallback {
(
err: GaxiosError | null,
token?: Credentials | null,
res?: GaxiosResponse | null
): void;
}
export interface GetTokenResponse {
tokens: Credentials;
res: GaxiosResponse | null;
}
export interface GetAccessTokenCallback {
(
err: GaxiosError | null,
token?: string | null,
res?: GaxiosResponse | null
): void;
}
export interface GetAccessTokenResponse {
token?: string | null;
res?: GaxiosResponse | null;
}
export interface RefreshAccessTokenCallback {
(
err: GaxiosError | null,
credentials?: Credentials | null,
res?: GaxiosResponse | null
): void;
}
export interface RefreshAccessTokenResponse {
credentials: Credentials;
res: GaxiosResponse | null;
}
export interface RequestMetadataResponse {
headers: Headers;
res?: GaxiosResponse<void> | null;
}
export interface RequestMetadataCallback {
(
err: GaxiosError | null,
headers?: Headers,
res?: GaxiosResponse<void> | null
): void;
}
export interface GetFederatedSignonCertsCallback {
(
err: GaxiosError | null,
certs?: Certificates,
response?: GaxiosResponse<void> | null
): void;
}
export interface FederatedSignonCertsResponse {
certs: Certificates;
format: CertificateFormat;
res?: GaxiosResponse<void> | null;
}
export interface GetIapPublicKeysCallback {
(
err: GaxiosError | null,
pubkeys?: PublicKeys,
response?: GaxiosResponse<void> | null
): void;
}
export interface IapPublicKeysResponse {
pubkeys: PublicKeys;
res?: GaxiosResponse<void> | null;
}
export interface RevokeCredentialsResult {
success: boolean;
}
export interface VerifyIdTokenOptions {
idToken: string;
audience?: string | string[];
maxExpiry?: number;
}
export interface OAuth2ClientEndpoints {
/**
* The endpoint for viewing access token information
*
* @example
* 'https://oauth2.googleapis.com/tokeninfo'
*/
tokenInfoUrl: string | URL;
/**
* The base URL for auth endpoints.
*
* @example
* 'https://accounts.google.com/o/oauth2/v2/auth'
*/
oauth2AuthBaseUrl: string | URL;
/**
* The base endpoint for token retrieval
* .
* @example
* 'https://oauth2.googleapis.com/token'
*/
oauth2TokenUrl: string | URL;
/**
* The base endpoint to revoke tokens.
*
* @example
* 'https://oauth2.googleapis.com/revoke'
*/
oauth2RevokeUrl: string | URL;
/**
* Sign on certificates in PEM format.
*
* @example
* 'https://www.googleapis.com/oauth2/v1/certs'
*/
oauth2FederatedSignonPemCertsUrl: string | URL;
/**
* Sign on certificates in JWK format.
*
* @example
* 'https://www.googleapis.com/oauth2/v3/certs'
*/
oauth2FederatedSignonJwkCertsUrl: string | URL;
/**
* IAP Public Key URL.
* This URL contains a JSON dictionary that maps the `kid` claims to the public key values.
*
* @example
* 'https://www.gstatic.com/iap/verify/public_key'
*/
oauth2IapPublicKeyUrl: string | URL;
}
export interface OAuth2ClientOptions extends AuthClientOptions {
clientId?: string;
clientSecret?: string;
redirectUri?: string;
/**
* Customizable endpoints.
*/
endpoints?: Partial<OAuth2ClientEndpoints>;
/**
* The allowed OAuth2 token issuers.
*/
issuers?: string[];
/**
* The client authentication type. Supported values are basic, post, and none.
* Defaults to post if not provided.
* https://datatracker.ietf.org/doc/html/rfc7591#section-2
*/
clientAuthentication?: ClientAuthentication;
}
// Re-exporting here for backwards compatibility
export type RefreshOptions = Pick<
AuthClientOptions,
'eagerRefreshThresholdMillis' | 'forceRefreshOnFailure'
>;
export class OAuth2Client extends AuthClient {
private redirectUri?: string;
private certificateCache: Certificates = {};
private certificateExpiry: Date | null = null;
private certificateCacheFormat: CertificateFormat = CertificateFormat.PEM;
protected refreshTokenPromises = new Map<string, Promise<GetTokenResponse>>();
readonly endpoints: Readonly<OAuth2ClientEndpoints>;
readonly issuers: string[];
readonly clientAuthentication: ClientAuthentication;
// TODO: refactor tests to make this private
_clientId?: string;
// TODO: refactor tests to make this private
_clientSecret?: string;
refreshHandler?: GetRefreshHandlerCallback;
/**
* Handles OAuth2 flow for Google APIs.
*
* @param clientId The authentication client ID.
* @param clientSecret The authentication client secret.
* @param redirectUri The URI to redirect to after completing the auth
* request.
* @param opts optional options for overriding the given parameters.
* @constructor
*/
constructor(options?: OAuth2ClientOptions);
constructor(clientId?: string, clientSecret?: string, redirectUri?: string);
constructor(
optionsOrClientId?: string | OAuth2ClientOptions,
clientSecret?: string,
redirectUri?: string
) {
const opts =
optionsOrClientId && typeof optionsOrClientId === 'object'
? optionsOrClientId
: {clientId: optionsOrClientId, clientSecret, redirectUri};
super(opts);
this._clientId = opts.clientId;
this._clientSecret = opts.clientSecret;
this.redirectUri = opts.redirectUri;
this.endpoints = {
tokenInfoUrl: 'https://oauth2.googleapis.com/tokeninfo',
oauth2AuthBaseUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
oauth2TokenUrl: 'https://oauth2.googleapis.com/token',
oauth2RevokeUrl: 'https://oauth2.googleapis.com/revoke',
oauth2FederatedSignonPemCertsUrl:
'https://www.googleapis.com/oauth2/v1/certs',
oauth2FederatedSignonJwkCertsUrl:
'https://www.googleapis.com/oauth2/v3/certs',
oauth2IapPublicKeyUrl: 'https://www.gstatic.com/iap/verify/public_key',
...opts.endpoints,
};
this.clientAuthentication =
opts.clientAuthentication || ClientAuthentication.ClientSecretPost;
this.issuers = opts.issuers || [
'accounts.google.com',
'https://accounts.google.com',
this.universeDomain,
];
}
/**
* @deprecated use instance's {@link OAuth2Client.endpoints}
*/
protected static readonly GOOGLE_TOKEN_INFO_URL =
'https://oauth2.googleapis.com/tokeninfo';
/**
* Clock skew - five minutes in seconds
*/
private static readonly CLOCK_SKEW_SECS_ = 300;
/**
* The default max Token Lifetime is one day in seconds
*/
private static readonly DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400;
/**
* Generates URL for consent page landing.
* @param opts Options.
* @return URL to consent page.
*/
generateAuthUrl(opts: GenerateAuthUrlOpts = {}) {
if (opts.code_challenge_method && !opts.code_challenge) {
throw new Error(
'If a code_challenge_method is provided, code_challenge must be included.'
);
}
opts.response_type = opts.response_type || 'code';
opts.client_id = opts.client_id || this._clientId;
opts.redirect_uri = opts.redirect_uri || this.redirectUri;
// Allow scopes to be passed either as array or a string
if (Array.isArray(opts.scope)) {
opts.scope = opts.scope.join(' ');
}
const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString();
return (
rootUrl +
'?' +
querystring.stringify(opts as querystring.ParsedUrlQueryInput)
);
}
generateCodeVerifier(): void {
// To make the code compatible with browser SubtleCrypto we need to make
// this method async.
throw new Error(
'generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.'
);
}
/**
* Convenience method to automatically generate a code_verifier, and its
* resulting SHA256. If used, this must be paired with a S256
* code_challenge_method.
*
* For a full example see:
* https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js
*/
async generateCodeVerifierAsync(): Promise<CodeVerifierResults> {
// base64 encoding uses 6 bits per character, and we want to generate128
// characters. 6*128/8 = 96.
const crypto = createCrypto();
const randomString = crypto.randomBytesBase64(96);
// The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/
// "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just
// swapping out a few chars.
const codeVerifier = randomString
.replace(/\+/g, '~')
.replace(/=/g, '_')
.replace(/\//g, '-');
// Generate the base64 encoded SHA256
const unencodedCodeChallenge =
await crypto.sha256DigestBase64(codeVerifier);
// We need to use base64UrlEncoding instead of standard base64
const codeChallenge = unencodedCodeChallenge
.split('=')[0]
.replace(/\+/g, '-')
.replace(/\//g, '_');
return {codeVerifier, codeChallenge};
}
/**
* Gets the access token for the given code.
* @param code The authorization code.
* @param callback Optional callback fn.
*/
getToken(code: string): Promise<GetTokenResponse>;
getToken(options: GetTokenOptions): Promise<GetTokenResponse>;
getToken(code: string, callback: GetTokenCallback): void;
getToken(options: GetTokenOptions, callback: GetTokenCallback): void;
getToken(
codeOrOptions: string | GetTokenOptions,
callback?: GetTokenCallback
): Promise<GetTokenResponse> | void {
const options =
typeof codeOrOptions === 'string' ? {code: codeOrOptions} : codeOrOptions;
if (callback) {
this.getTokenAsync(options).then(
r => callback(null, r.tokens, r.res),
e => callback(e, null, e.response)
);
} else {
return this.getTokenAsync(options);
}
}
private async getTokenAsync(
options: GetTokenOptions
): Promise<GetTokenResponse> {
const url = this.endpoints.oauth2TokenUrl.toString();
const headers: Headers = {
'Content-Type': 'application/x-www-form-urlencoded',
};
const values: GetTokenQuery = {
client_id: options.client_id || this._clientId,
code_verifier: options.codeVerifier,
code: options.code,
grant_type: 'authorization_code',
redirect_uri: options.redirect_uri || this.redirectUri,
};
if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) {
const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`);
headers['Authorization'] = `Basic ${basic.toString('base64')}`;
}
if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) {
values.client_secret = this._clientSecret;
}
const res = await this.transporter.request<CredentialRequest>({
...OAuth2Client.RETRY_CONFIG,
method: 'POST',
url,
data: querystring.stringify(values),
headers,
});
const tokens = res.data as Credentials;
if (res.data && res.data.expires_in) {
tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;
delete (tokens as CredentialRequest).expires_in;
}
this.emit('tokens', tokens);
return {tokens, res};
}
/**
* Refreshes the access token.
* @param refresh_token Existing refresh token.
* @private
*/
protected async refreshToken(
refreshToken?: string | null
): Promise<GetTokenResponse> {
if (!refreshToken) {
return this.refreshTokenNoCache(refreshToken);
}
// If a request to refresh using the same token has started,
// return the same promise.
if (this.refreshTokenPromises.has(refreshToken)) {
return this.refreshTokenPromises.get(refreshToken)!;
}
const p = this.refreshTokenNoCache(refreshToken).then(
r => {
this.refreshTokenPromises.delete(refreshToken);
return r;
},
e => {
this.refreshTokenPromises.delete(refreshToken);
throw e;
}
);
this.refreshTokenPromises.set(refreshToken, p);
return p;
}
protected async refreshTokenNoCache(
refreshToken?: string | null
): Promise<GetTokenResponse> {
if (!refreshToken) {
throw new Error('No refresh token is set.');
}
const url = this.endpoints.oauth2TokenUrl.toString();
const data = {
refresh_token: refreshToken,
client_id: this._clientId,
client_secret: this._clientSecret,
grant_type: 'refresh_token',
};
let res: GaxiosResponse<CredentialRequest>;
try {
// request for new token
res = await this.transporter.request<CredentialRequest>({
...OAuth2Client.RETRY_CONFIG,
method: 'POST',
url,
data: querystring.stringify(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
});
} catch (e) {
if (
e instanceof GaxiosError &&
e.message === 'invalid_grant' &&
e.response?.data &&
/ReAuth/i.test(e.response.data.error_description)
) {
e.message = JSON.stringify(e.response.data);
}
throw e;
}
const tokens = res.data as Credentials;
// TODO: de-duplicate this code from a few spots
if (res.data && res.data.expires_in) {
tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;
delete (tokens as CredentialRequest).expires_in;
}
this.emit('tokens', tokens);
return {tokens, res};
}
/**
* Retrieves the access token using refresh token
*
* @param callback callback
*/
refreshAccessToken(): Promise<RefreshAccessTokenResponse>;
refreshAccessToken(callback: RefreshAccessTokenCallback): void;
refreshAccessToken(
callback?: RefreshAccessTokenCallback
): Promise<RefreshAccessTokenResponse> | void {
if (callback) {
this.refreshAccessTokenAsync().then(
r => callback(null, r.credentials, r.res),
callback
);
} else {
return this.refreshAccessTokenAsync();
}
}
private async refreshAccessTokenAsync() {
const r = await this.refreshToken(this.credentials.refresh_token);
const tokens = r.tokens as Credentials;
tokens.refresh_token = this.credentials.refresh_token;
this.credentials = tokens;
return {credentials: this.credentials, res: r.res};
}
/**
* Get a non-expired access token, after refreshing if necessary
*
* @param callback Callback to call with the access token
*/
getAccessToken(): Promise<GetAccessTokenResponse>;
getAccessToken(callback: GetAccessTokenCallback): void;
getAccessToken(
callback?: GetAccessTokenCallback
): Promise<GetAccessTokenResponse> | void {
if (callback) {
this.getAccessTokenAsync().then(
r => callback(null, r.token, r.res),
callback
);
} else {
return this.getAccessTokenAsync();
}
}
private async getAccessTokenAsync(): Promise<GetAccessTokenResponse> {
const shouldRefresh =
!this.credentials.access_token || this.isTokenExpiring();
if (shouldRefresh) {
if (!this.credentials.refresh_token) {
if (this.refreshHandler) {
const refreshedAccessToken =
await this.processAndValidateRefreshHandler();
if (refreshedAccessToken?.access_token) {
this.setCredentials(refreshedAccessToken);
return {token: this.credentials.access_token};
}
} else {
throw new Error(
'No refresh token or refresh handler callback is set.'
);
}
}
const r = await this.refreshAccessTokenAsync();
if (!r.credentials || (r.credentials && !r.credentials.access_token)) {
throw new Error('Could not refresh access token.');
}
return {token: r.credentials.access_token, res: r.res};
} else {
return {token: this.credentials.access_token};
}
}
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
* resolves with authorization header fields.
*
* In OAuth2Client, the result has the form:
* { Authorization: 'Bearer <access_token_value>' }
* @param url The optional url being authorized
*/
async getRequestHeaders(url?: string): Promise<Headers> {
const headers = (await this.getRequestMetadataAsync(url)).headers;
return headers;
}
protected async getRequestMetadataAsync(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
url?: string | URL | null
): Promise<RequestMetadataResponse> {
const thisCreds = this.credentials;
if (
!thisCreds.access_token &&
!thisCreds.refresh_token &&
!this.apiKey &&
!this.refreshHandler
) {
throw new Error(
'No access, refresh token, API key or refresh handler callback is set.'
);
}
if (thisCreds.access_token && !this.isTokenExpiring()) {
thisCreds.token_type = thisCreds.token_type || 'Bearer';
const headers = {
Authorization: thisCreds.token_type + ' ' + thisCreds.access_token,
};
return {headers: this.addSharedMetadataHeaders(headers)};
}
// If refreshHandler exists, call processAndValidateRefreshHandler().
if (this.refreshHandler) {
const refreshedAccessToken =
await this.processAndValidateRefreshHandler();
if (refreshedAccessToken?.access_token) {
this.setCredentials(refreshedAccessToken);
const headers = {
Authorization: 'Bearer ' + this.credentials.access_token,
};
return {headers: this.addSharedMetadataHeaders(headers)};
}
}
if (this.apiKey) {
return {headers: {'X-Goog-Api-Key': this.apiKey}};
}
let r: GetTokenResponse | null = null;
let tokens: Credentials | null = null;
try {
r = await this.refreshToken(thisCreds.refresh_token);
tokens = r.tokens;
} catch (err) {
const e = err as GaxiosError;
if (
e.response &&
(e.response.status === 403 || e.response.status === 404)
) {
e.message = `Could not refresh access token: ${e.message}`;
}
throw e;
}
const credentials = this.credentials;
credentials.token_type = credentials.token_type || 'Bearer';
tokens.refresh_token = credentials.refresh_token;
this.credentials = tokens;
const headers: {[index: string]: string} = {
Authorization: credentials.token_type + ' ' + tokens.access_token,
};
return {headers: this.addSharedMetadataHeaders(headers), res: r.res};
}
/**
* Generates an URL to revoke the given token.
* @param token The existing token to be revoked.
*
* @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL}
*/
static getRevokeTokenUrl(token: string): string {
return new OAuth2Client().getRevokeTokenURL(token).toString();
}
/**
* Generates a URL to revoke the given token.
*
* @param token The existing token to be revoked.
*/
getRevokeTokenURL(token: string): URL {
const url = new URL(this.endpoints.oauth2RevokeUrl);
url.searchParams.append('token', token);
return url;
}
/**
* Revokes the access given to token.
* @param token The existing token to be revoked.
* @param callback Optional callback fn.
*/
revokeToken(token: string): GaxiosPromise<RevokeCredentialsResult>;
revokeToken(
token: string,
callback: BodyResponseCallback<RevokeCredentialsResult>
): void;
revokeToken(
token: string,
callback?: BodyResponseCallback<RevokeCredentialsResult>
): GaxiosPromise<RevokeCredentialsResult> | void {
const opts: GaxiosOptions = {