-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathauthInfo.ts
1289 lines (1162 loc) · 44.9 KB
/
authInfo.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 (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
/* eslint-disable class-methods-use-this */
import { randomBytes } from 'node:crypto';
import { resolve as pathResolve } from 'node:path';
import * as os from 'node:os';
import * as fs from 'node:fs';
import { Record as RecordType } from '@jsforce/jsforce-node';
import { AsyncOptionalCreatable, env, isEmpty, parseJson, parseJsonMap } from '@salesforce/kit';
import {
AnyJson,
asString,
ensure,
ensureJsonMap,
ensureString,
isArray,
isPlainObject,
isString,
JsonMap,
Many,
Nullable,
Optional,
} from '@salesforce/ts-types';
import { OAuth2Config, OAuth2, TokenResponse } from '@jsforce/jsforce-node';
import Transport from '@jsforce/jsforce-node/lib/transport';
import * as jwt from 'jsonwebtoken';
import { Config } from '../config/config';
import { ConfigAggregator } from '../config/configAggregator';
import { Logger } from '../logger/logger';
import { SfError } from '../sfError';
import { matchesAccessToken, trimTo15 } from '../util/sfdc';
import { StateAggregator } from '../stateAggregator/stateAggregator';
import { filterSecrets } from '../logger/filters';
import { Messages } from '../messages';
import { getLoginAudienceCombos, SfdcUrl } from '../util/sfdcUrl';
import { findSuggestion } from '../util/findSuggestion';
import { Connection, SFDX_HTTP_HEADERS } from './connection';
import { OrgConfigProperties } from './orgConfigProperties';
import { Org, SandboxFields } from './org';
Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/core', 'core');
/**
* Fields for authorization, org, and local information.
*/
export type AuthFields = {
accessToken?: string;
alias?: string;
authCode?: string;
clientId?: string;
clientSecret?: string;
created?: string;
createdOrgInstance?: string;
devHubUsername?: string;
instanceUrl?: string;
instanceApiVersion?: string;
instanceApiVersionLastRetrieved?: string;
isDevHub?: boolean;
loginUrl?: string;
orgId?: string;
password?: string;
privateKey?: string;
refreshToken?: string;
scratchAdminUsername?: string;
snapshot?: string;
userId?: string;
username?: string;
usernames?: string[];
userProfileName?: string;
expirationDate?: string;
tracksSource?: boolean;
[Org.Fields.NAME]?: string;
[Org.Fields.INSTANCE_NAME]?: string;
[Org.Fields.NAMESPACE_PREFIX]?: Nullable<string>;
[Org.Fields.IS_SANDBOX]?: boolean;
[Org.Fields.IS_SCRATCH]?: boolean;
[Org.Fields.TRIAL_EXPIRATION_DATE]?: Nullable<string>;
};
export type OrgAuthorization = {
orgId: string;
username: string;
oauthMethod: 'jwt' | 'web' | 'token' | 'unknown';
aliases: Nullable<string[]>;
configs: Nullable<string[]>;
isScratchOrg?: boolean;
isDevHub?: boolean;
isSandbox?: boolean;
instanceUrl?: string;
accessToken?: string;
error?: string;
isExpired: boolean | 'unknown';
};
/**
* Options for access token flow.
*/
export type AccessTokenOptions = {
accessToken?: string;
loginUrl?: string;
instanceUrl?: string;
};
export type AuthSideEffects = {
alias?: string;
setDefault: boolean;
setDefaultDevHub: boolean;
setTracksSource?: boolean;
};
export type JwtOAuth2Config = OAuth2Config & {
privateKey?: string;
privateKeyFile?: string;
authCode?: string;
refreshToken?: string;
username?: string;
};
type UserInfo = AnyJson & {
username: string;
organizationId: string;
};
/* eslint-disable camelcase */
type UserInfoResult = AnyJson & {
preferred_username: string;
organization_id: string;
user_id: string;
};
/* eslint-enable camelcase */
type User = AnyJson & {
Username: string;
};
type AuthOptions = JwtOAuth2Config & AccessTokenOptions;
/**
* A function to update a refresh token when the access token is expired.
*/
export type RefreshFn = (
conn: Connection,
callback: (err: Nullable<Error>, accessToken?: string, res?: Record<string, unknown>) => Promise<void>
) => Promise<void>;
/**
* Options for {@link Connection}.
*/
export type ConnectionOptions = AuthFields & {
/**
* OAuth options.
*/
oauth2?: Partial<JwtOAuth2Config>;
/**
* Refresh token callback.
*/
refreshFn?: RefreshFn;
};
// parses the id field returned from jsForce oauth2 methods to get
// user ID and org ID.
function parseIdUrl(idUrl: string): { userId: string | undefined; orgId: string | undefined; url: string } {
const idUrls = idUrl.split('/');
const userId = idUrls.pop();
const orgId = idUrls.pop();
return {
userId,
orgId,
url: idUrl,
};
}
export const DEFAULT_CONNECTED_APP_INFO = {
clientId: 'PlatformCLI',
clientSecret: '',
};
/**
* Handles persistence and fetching of user authentication information using
* JWT, OAuth, or refresh tokens. Sets up the refresh flows that jsForce will
* use to keep tokens active. An AuthInfo can also be created with an access
* token, but AuthInfos created with access tokens can't be persisted to disk.
*
* **See** [Authorization](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_auth.htm)
*
* **See** [Salesforce DX Usernames and Orgs](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm)
*
* ```
* // Creating a new authentication file.
* const authInfo = await AuthInfo.create({
* username: myAdminUsername,
* oauth2Options: {
* loginUrl, authCode, clientId, clientSecret
* }
* );
* authInfo.save();
*
* // Creating an authorization info with an access token.
* const authInfo = await AuthInfo.create({
* username: accessToken
* });
*
* // Using an existing authentication file.
* const authInfo = await AuthInfo.create({
* username: myAdminUsername
* });
*
* // Using the AuthInfo
* const connection = await Connection.create({ authInfo });
* ```
*/
export class AuthInfo extends AsyncOptionalCreatable<AuthInfo.Options> {
// Possibly overridden in create
private usingAccessToken = false;
// Initialized in init
private logger!: Logger;
private stateAggregator!: StateAggregator;
private username!: string;
private options: AuthInfo.Options;
/**
* Constructor
* **Do not directly construct instances of this class -- use {@link AuthInfo.create} instead.**
*
* @param options The options for the class instance
*/
public constructor(options?: AuthInfo.Options) {
super(options);
this.options = options ?? {};
}
/**
* Returns the default instance url
*
* @returns {string}
*/
public static getDefaultInstanceUrl(): string {
const configuredInstanceUrl = ConfigAggregator.getValue(OrgConfigProperties.ORG_INSTANCE_URL)?.value as string;
return configuredInstanceUrl ?? SfdcUrl.PRODUCTION;
}
/**
* Get a list of all authorizations based on auth files stored in the global directory.
* One can supply a filter (see @param orgAuthFilter) and calling this function without
* a filter will return all authorizations.
*
* @param orgAuthFilter A predicate function that returns true for those org authorizations that are to be retained.
*
* @returns {Promise<OrgAuthorization[]>}
*/
public static async listAllAuthorizations(
orgAuthFilter = (orgAuth: OrgAuthorization): boolean => !!orgAuth
): Promise<OrgAuthorization[]> {
const stateAggregator = await StateAggregator.getInstance();
const config = (await ConfigAggregator.create()).getConfigInfo();
const orgs = await stateAggregator.orgs.readAll();
const final: OrgAuthorization[] = [];
for (const org of orgs) {
const username = ensureString(org.username);
const aliases = stateAggregator.aliases.getAll(username) ?? undefined;
// Get a list of configuration values that are set to either the username or one
// of the aliases
const configs = config
.filter((c) => aliases.includes(c.value as string) || c.value === username)
.map((c) => c.key);
try {
// prevent ConfigFile collision bug
// eslint-disable-next-line no-await-in-loop
const authInfo = await AuthInfo.create({ username });
const { orgId, instanceUrl, devHubUsername, expirationDate, isDevHub } = authInfo.getFields();
final.push({
aliases,
configs,
username,
instanceUrl,
isScratchOrg: Boolean(devHubUsername),
isDevHub: isDevHub ?? false,
// eslint-disable-next-line no-await-in-loop
isSandbox: await stateAggregator.sandboxes.hasFile(orgId as string),
orgId: orgId as string,
accessToken: authInfo.getConnectionOptions().accessToken,
oauthMethod: authInfo.isJwt() ? 'jwt' : authInfo.isOauth() ? 'web' : 'token',
isExpired:
Boolean(devHubUsername) && expirationDate
? new Date(ensureString(expirationDate)).getTime() < new Date().getTime()
: 'unknown',
});
} catch (err) {
final.push({
aliases,
configs,
username,
orgId: org.orgId as string,
instanceUrl: org.instanceUrl,
accessToken: undefined,
oauthMethod: 'unknown',
error: (err as Error).message,
isExpired: 'unknown',
});
}
}
return final.filter(orgAuthFilter);
}
/**
* Returns true if one or more authentications are persisted.
*/
public static async hasAuthentications(): Promise<boolean> {
try {
const auths = await (await StateAggregator.getInstance()).orgs.list();
return !isEmpty(auths);
} catch (err) {
const error = err as SfError;
if (error.name === 'OrgDataNotAvailableError' || error.code === 'ENOENT') {
return false;
}
throw error;
}
}
/**
* Get the authorization URL.
*
* @param options The options to generate the URL.
*/
public static getAuthorizationUrl(options: JwtOAuth2Config & { scope?: string }, oauth2?: OAuth2): string {
// Unless explicitly turned off, use a code verifier for enhanced security
const oauth2Verifier = oauth2 ?? new OAuth2({ useVerifier: true, ...options });
// The state parameter allows the redirectUri callback listener to ignore request
// that don't contain the state value.
const params = {
state: randomBytes(Math.ceil(6)).toString('hex'),
prompt: 'login',
// Default connected app is 'refresh_token api web'
scope: options.scope ?? env.getString('SFDX_AUTH_SCOPES', 'refresh_token api web'),
};
return oauth2Verifier.getAuthorizationUrl(params);
}
/**
* Parse a sfdx auth url, usually obtained by `authInfo.getSfdxAuthUrl`.
*
* @example
* ```
* await AuthInfo.create(AuthInfo.parseSfdxAuthUrl(sfdxAuthUrl));
* ```
* @param sfdxAuthUrl
*/
public static parseSfdxAuthUrl(
sfdxAuthUrl: string
): Pick<AuthFields, 'clientId' | 'clientSecret' | 'refreshToken' | 'loginUrl'> {
const match = sfdxAuthUrl.match(
/^force:\/\/([a-zA-Z0-9._-]+={0,2}):([a-zA-Z0-9._-]*={0,2}):([a-zA-Z0-9._-]+={0,2})@([a-zA-Z0-9:._-]+)/
);
if (!match) {
throw new SfError(messages.getMessage('invalidSfdxAuthUrlError'), 'INVALID_SFDX_AUTH_URL');
}
const [, clientId, clientSecret, refreshToken, loginUrl] = match;
return {
clientId,
clientSecret,
refreshToken,
loginUrl: `https://${loginUrl}`,
};
}
/**
* Given a set of decrypted fields and an authInfo, determine if the org belongs to an available
* dev hub, or if the org is a sandbox of another CLI authed production org.
*
* @param fields
* @param orgAuthInfo
*/
public static async identifyPossibleScratchOrgs(fields: AuthFields, orgAuthInfo: AuthInfo): Promise<void> {
// fields property is passed in because the consumers of this method have performed the decrypt.
// This is so we don't have to call authInfo.getFields(true) and decrypt again OR accidentally save an
// authInfo before it is necessary.
const logger = await Logger.child('Common', { tag: 'identifyPossibleScratchOrgs' });
// return if we already know the hub org, we know it is a devhub or prod-like, or no orgId present
if (Boolean(fields.isDevHub) || Boolean(fields.devHubUsername) || !fields.orgId) return;
logger.debug('getting devHubs and prod orgs to identify scratch orgs and sandboxes');
// TODO: return if url is not sandbox-like to avoid constantly asking about production orgs
// TODO: someday we make this easier by asking the org if it is a scratch org
const hubAuthInfos = await AuthInfo.getDevHubAuthInfos();
// Get a list of org auths that are known not to be scratch orgs or sandboxes.
const possibleProdOrgs = await AuthInfo.listAllAuthorizations(
(orgAuth) => orgAuth && !orgAuth.isScratchOrg && !orgAuth.isSandbox
);
logger.debug(`found ${hubAuthInfos.length} DevHubs`);
logger.debug(`found ${possibleProdOrgs.length} possible prod orgs`);
if (hubAuthInfos.length === 0 && possibleProdOrgs.length === 0) {
return;
}
// ask all those orgs if they know this orgId
await Promise.all([
...hubAuthInfos.map(async (hubAuthInfo) => {
try {
const soi = await AuthInfo.queryScratchOrg(hubAuthInfo.username, fields.orgId as string);
// if any return a result
logger.debug(`found orgId ${fields.orgId} in devhub ${hubAuthInfo.username}`);
try {
await orgAuthInfo.save({
...fields,
devHubUsername: hubAuthInfo.username,
expirationDate: soi.ExpirationDate,
isScratch: true,
});
logger.debug(
`set ${hubAuthInfo.username} as devhub and expirationDate ${
soi.ExpirationDate
} for scratch org ${orgAuthInfo.getUsername()}`
);
} catch (error) {
logger.debug(`error updating auth file for ${orgAuthInfo.getUsername()}`, error);
}
} catch (error) {
if (error instanceof Error && error.name === 'NoActiveScratchOrgFound') {
logger.error(`devhub ${hubAuthInfo.username} has no scratch orgs`, error);
} else {
logger.error(`Error connecting to devhub ${hubAuthInfo.username}`, error);
}
}
}),
...possibleProdOrgs.map(async (pOrgAuthInfo) => {
await AuthInfo.identifyPossibleSandbox(pOrgAuthInfo, fields, orgAuthInfo, logger);
}),
]);
}
/**
* Find all dev hubs available in the local environment.
*/
public static async getDevHubAuthInfos(): Promise<OrgAuthorization[]> {
return AuthInfo.listAllAuthorizations((possibleHub) => possibleHub?.isDevHub ?? false);
}
private static async identifyPossibleSandbox(
possibleProdOrg: OrgAuthorization,
fields: AuthFields,
orgAuthInfo: AuthInfo,
logger: Logger
): Promise<void> {
if (!fields.orgId) {
return;
}
try {
const prodOrg = await Org.create({ aliasOrUsername: possibleProdOrg.username });
const sbxProcess = await prodOrg.querySandboxProcessByOrgId(fields.orgId);
if (!sbxProcess?.SandboxInfoId) {
return;
}
logger.debug(`${fields.orgId} is a sandbox of ${possibleProdOrg.username}`);
try {
await orgAuthInfo.save({
...fields,
isScratch: false,
isSandbox: true,
});
} catch (err) {
logger.debug(`error updating auth file for: ${orgAuthInfo.getUsername()}`, err);
throw err; // rethrow; don't want a sandbox config file with an invalid auth file
}
try {
// set the sandbox config value
const sfSandbox: SandboxFields = {
sandboxUsername: fields.username,
sandboxOrgId: fields.orgId,
prodOrgUsername: possibleProdOrg.username,
sandboxName: sbxProcess.SandboxName,
sandboxProcessId: sbxProcess.Id,
sandboxInfoId: sbxProcess.SandboxInfoId,
timestamp: new Date().toISOString(),
};
const stateAggregator = await StateAggregator.getInstance();
stateAggregator.sandboxes.set(fields.orgId, sfSandbox);
logger.debug(`writing sandbox auth file for: ${orgAuthInfo.getUsername()} with ID: ${fields.orgId}`);
await stateAggregator.sandboxes.write(fields.orgId);
} catch (e) {
logger.debug(`error writing sandbox auth file for: ${orgAuthInfo.getUsername()}`, e);
}
} catch (err) {
logger.debug(`${fields.orgId} is not a sandbox of ${possibleProdOrg.username}`);
}
}
/**
* Checks active scratch orgs to match by the ScratchOrg field (the 15-char org id)
* if you pass an 18-char scratchOrgId, it will be trimmed to 15-char for query purposes
* Throws is no matching scratch org is found
*/
private static async queryScratchOrg(
devHubUsername: string | undefined,
scratchOrgId: string
): Promise<{ Id: string; ExpirationDate: string }> {
const devHubOrg = await Org.create({ aliasOrUsername: devHubUsername });
const trimmedId = trimTo15(scratchOrgId);
const conn = devHubOrg.getConnection();
const data = await conn.query<{ Id: string; ExpirationDate: string; ScratchOrg: string }>(
`select Id, ExpirationDate, ScratchOrg from ScratchOrgInfo where ScratchOrg = '${trimmedId}' and Status = 'Active'`
);
// where ScratchOrg='00DDE00000485Lg' will return a record for both 00DDE00000485Lg and 00DDE00000485LG.
// this is our way of enforcing case sensitivity on a 15-char Id (which is unfortunately how ScratchOrgInfo stores it)
const result = data.records.filter((r) => r.ScratchOrg === trimmedId)[0];
if (result) return result;
throw new SfError(
`DevHub ${devHubUsername} has no active scratch orgs that match ${trimmedId}`,
'NoActiveScratchOrgFound'
);
}
/**
* Get the username.
*/
public getUsername(): string {
return this.username;
}
/**
* Returns true if `this` is using the JWT flow.
*/
public isJwt(): boolean {
const { refreshToken, privateKey } = this.getFields();
return !refreshToken && !!privateKey;
}
/**
* Returns true if `this` is using an access token flow.
*/
public isAccessTokenFlow(): boolean {
const { refreshToken, privateKey } = this.getFields();
return !refreshToken && !privateKey;
}
/**
* Returns true if `this` is using the oauth flow.
*/
public isOauth(): boolean {
return !this.isAccessTokenFlow() && !this.isJwt();
}
/**
* Returns true if `this` is using the refresh token flow.
*/
public isRefreshTokenFlow(): boolean {
const { refreshToken, authCode } = this.getFields();
return !authCode && !!refreshToken;
}
/**
* Updates the cache and persists the authentication fields (encrypted).
*
* @param authData New data to save.
*/
public async save(authData?: AuthFields): Promise<AuthInfo> {
this.update(authData);
const username = ensure(this.getUsername());
if (matchesAccessToken(username)) {
this.logger.debug('Username is an accesstoken. Skip saving authinfo to disk.');
return this;
}
await this.stateAggregator.orgs.write(username);
this.logger.info(`Saved auth info for username: ${username}`);
return this;
}
/**
* Update the authorization fields, encrypting sensitive fields, but do not persist.
* For convenience `this` object is returned.
*
* @param authData Authorization fields to update.
*/
public update(authData?: AuthFields): AuthInfo {
if (authData && isPlainObject(authData)) {
this.username = authData.username ?? this.username;
this.stateAggregator.orgs.update(this.username, authData);
this.logger.info(`Updated auth info for username: ${this.username}`);
}
return this;
}
/**
* Get the auth fields (decrypted) needed to make a connection.
*/
public getConnectionOptions(): ConnectionOptions {
const decryptedCopy = this.getFields(true);
const { accessToken, instanceUrl, loginUrl } = decryptedCopy;
if (this.isAccessTokenFlow()) {
this.logger.info('Returning fields for a connection using access token.');
// Just auth with the accessToken
return { accessToken, instanceUrl, loginUrl };
}
if (this.isJwt()) {
this.logger.info('Returning fields for a connection using JWT config.');
return {
accessToken,
instanceUrl,
refreshFn: this.refreshFn.bind(this),
};
}
// @TODO: figure out loginUrl and redirectUri (probably get from config class)
//
// redirectUri: org.config.getOauthCallbackUrl()
// loginUrl: this.fields.instanceUrl || this.config.getAppConfig().sfdcLoginUrl
this.logger.info('Returning fields for a connection using OAuth config.');
// Decrypt a user provided client secret or use the default.
return {
oauth2: {
loginUrl: instanceUrl ?? SfdcUrl.PRODUCTION,
clientId: this.getClientId(),
redirectUri: this.getRedirectUri(),
},
accessToken,
instanceUrl,
refreshFn: this.refreshFn.bind(this),
};
}
public getClientId(): string {
return this.getFields()?.clientId ?? DEFAULT_CONNECTED_APP_INFO.clientId;
}
public getRedirectUri(): string {
return 'http://localhost:1717/OauthRedirect';
}
/**
* Get the authorization fields.
*
* @param decrypt Decrypt the fields.
*
* Returns a ReadOnly object of the fields. If you need to modify the fields, use AuthInfo.update()
*/
public getFields(decrypt?: boolean): Readonly<AuthFields> {
return this.stateAggregator.orgs.get(this.username, decrypt) ?? {};
}
/**
* Get the org front door (used for web based oauth flows)
*/
public getOrgFrontDoorUrl(): string {
const authFields = this.getFields(true);
const base = ensureString(authFields.instanceUrl).replace(/\/+$/, '');
const accessToken = ensureString(authFields.accessToken);
return `${base}/secur/frontdoor.jsp?sid=${accessToken}`;
}
/**
* Returns true if this org is using access token auth.
*/
public isUsingAccessToken(): boolean {
return this.usingAccessToken;
}
/**
* Get the SFDX Auth URL.
*
* **See** [SFDX Authorization](https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_force_auth.htm#cli_reference_force_auth)
*/
public getSfdxAuthUrl(): string {
const { clientId, clientSecret, refreshToken, instanceUrl } = this.getFields(true);
// host includes an optional port on the instanceUrl
const url = new URL(ensure(instanceUrl, 'undefined instanceUrl')).host;
const clientIdAndSecret = clientId ? `${clientId}:${clientSecret ?? ''}` : '';
const token = ensure(refreshToken, 'undefined refreshToken');
return `force://${clientIdAndSecret}:${token}@${url}`;
}
/**
* Convenience function to handle typical side effects encountered when dealing with an AuthInfo.
* Given the values supplied in parameter sideEffects, this function will set auth alias, default auth
* and default dev hub.
*
* @param sideEffects - instance of AuthSideEffects
*/
public async handleAliasAndDefaultSettings(sideEffects: AuthSideEffects): Promise<void> {
if (
Boolean(sideEffects.alias) ||
sideEffects.setDefault ||
sideEffects.setDefaultDevHub ||
typeof sideEffects.setTracksSource === 'boolean'
) {
if (sideEffects.alias) await this.setAlias(sideEffects.alias);
if (sideEffects.setDefault) await this.setAsDefault({ org: true });
if (sideEffects.setDefaultDevHub) await this.setAsDefault({ devHub: true });
if (typeof sideEffects.setTracksSource === 'boolean') {
await this.save({ tracksSource: sideEffects.setTracksSource });
} else {
await this.save();
}
}
}
/**
* Set the target-env (default) or the target-dev-hub to the alias if
* it exists otherwise to the username. Method will try to set the local
* config first but will default to global config if that fails.
*
* @param options
*/
public async setAsDefault(options: { org?: boolean; devHub?: boolean } = { org: true }): Promise<void> {
let config: Config;
// if we fail to create the local config, default to the global config
try {
config = await Config.create({ isGlobal: false });
} catch {
config = await Config.create({ isGlobal: true });
}
const username = ensureString(this.getUsername());
const alias = this.stateAggregator.aliases.get(username);
const value = alias ?? username;
if (options.org) {
config.set(OrgConfigProperties.TARGET_ORG, value);
}
if (options.devHub) {
config.set(OrgConfigProperties.TARGET_DEV_HUB, value);
}
await config.write();
}
/**
* Sets the provided alias to the username
*
* @param alias alias to set
*/
public async setAlias(alias: string): Promise<void> {
return this.stateAggregator.aliases.setAndSave(alias, this.getUsername());
}
/**
* Initializes an instance of the AuthInfo class.
*/
public async init(): Promise<void> {
this.stateAggregator = await StateAggregator.getInstance();
const username = this.options.username;
const authOptions: AuthOptions | undefined = this.options.oauth2Options ?? this.options.accessTokenOptions;
// Must specify either username and/or options
if (!username && !authOptions) {
throw messages.createError('authInfoCreationError');
}
// If a username AND oauth options, ensure an authorization for the username doesn't
// already exist. Throw if it does so we don't overwrite the authorization.
if (username && authOptions) {
if (await this.stateAggregator.orgs.hasFile(username)) {
throw messages.createError('authInfoOverwriteError');
}
}
const oauthUsername = username ?? authOptions?.username;
if (oauthUsername) {
this.username = oauthUsername;
await this.stateAggregator.orgs.read(oauthUsername, false, false);
} // Else it will be set in initAuthOptions below.
// If the username is an access token, use that for auth and don't persist
if (isString(oauthUsername) && matchesAccessToken(oauthUsername)) {
// Need to initAuthOptions the logger and authInfoCrypto since we don't call init()
this.logger = await Logger.child('AuthInfo');
const aggregator = await ConfigAggregator.create();
const instanceUrl = this.getInstanceUrl(aggregator, authOptions);
this.update({
accessToken: oauthUsername,
instanceUrl,
orgId: oauthUsername.split('!')[0],
loginUrl: instanceUrl,
});
this.usingAccessToken = true;
}
// If a username with NO oauth options, ensure authorization already exist.
else if (username && !authOptions && !(await this.stateAggregator.orgs.exists(username))) {
const likeName = findSuggestion(username, [
...(await this.stateAggregator.orgs.list()).map((f) => f.split('.json')[0]),
...Object.keys(this.stateAggregator.aliases.getAll()),
]);
throw SfError.create({
name: 'NamedOrgNotFoundError',
message: messages.getMessage('namedOrgNotFound', [username]),
actions:
likeName === ''
? undefined
: [`It looks like you mistyped the username or alias. Did you mean "${likeName}"?`],
});
} else {
await this.initAuthOptions(authOptions);
}
}
private getInstanceUrl(aggregator: ConfigAggregator, options?: AuthOptions): string {
const instanceUrl =
options?.instanceUrl ?? (aggregator.getPropertyValue(OrgConfigProperties.ORG_INSTANCE_URL) as string);
return instanceUrl ?? SfdcUrl.PRODUCTION;
}
/**
* Initialize this AuthInfo instance with the specified options. If options are not provided, initialize it from cache
* or by reading from the persistence store. For convenience `this` object is returned.
*
* @param options Options to be used for creating an OAuth2 instance.
*
* **Throws** *{@link SfError}{ name: 'NamedOrgNotFoundError' }* Org information does not exist.
* @returns {Promise<AuthInfo>}
*/
private async initAuthOptions(options?: JwtOAuth2Config | AccessTokenOptions): Promise<AuthInfo> {
this.logger = await Logger.child('AuthInfo');
// If options were passed, use those before checking cache and reading an auth file.
let authConfig: AuthFields;
if (options) {
options = structuredClone(options);
if (this.isTokenOptions(options)) {
authConfig = options;
const userInfo = await this.retrieveUserInfo(
ensureString(options.instanceUrl),
ensureString(options.accessToken)
);
this.update({ username: userInfo?.username, orgId: userInfo?.organizationId });
} else {
if (this.options.parentUsername) {
const parentFields = await this.loadDecryptedAuthFromConfig(this.options.parentUsername);
options.clientId = parentFields.clientId;
if (process.env.SFDX_CLIENT_SECRET) {
options.clientSecret = process.env.SFDX_CLIENT_SECRET;
} else {
// Grab whatever flow is defined
Object.assign(options, {
clientSecret: parentFields.clientSecret,
privateKey: parentFields.privateKey ? pathResolve(parentFields.privateKey) : parentFields.privateKey,
});
}
}
// jwt flow
// Support both sfdx and jsforce private key values
if (!options.privateKey && options.privateKeyFile) {
options.privateKey = pathResolve(options.privateKeyFile);
}
if (options.privateKey) {
authConfig = await this.authJwt(options);
} else if (!options.authCode && options.refreshToken) {
// refresh token flow (from sfdxUrl or OAuth refreshFn)
authConfig = await this.buildRefreshTokenConfig(options);
} else if (this.options.oauth2 instanceof OAuth2) {
// authcode exchange / web auth flow
authConfig = await this.exchangeToken(options, this.options.oauth2);
} else {
authConfig = await this.exchangeToken(options);
}
}
authConfig.isDevHub = await this.determineIfDevHub(
ensureString(authConfig.instanceUrl),
ensureString(authConfig.accessToken)
);
const namespacePrefix = await this.getNamespacePrefix(
ensureString(authConfig.instanceUrl),
ensureString(authConfig.accessToken)
);
if (namespacePrefix) {
authConfig.namespacePrefix = namespacePrefix;
}
if (authConfig.username) await this.stateAggregator.orgs.read(authConfig.username, false, false);
// Update the auth fields WITH encryption
this.update(authConfig);
}
return this;
}
// eslint-disable-next-line @typescript-eslint/require-await
private async loadDecryptedAuthFromConfig(username: string): Promise<AuthFields> {
// Fetch from the persisted auth file
const authInfo = this.stateAggregator.orgs.get(username, true);
if (!authInfo) {
throw messages.createError('namedOrgNotFound', [username]);
}
return authInfo;
}
private isTokenOptions(options: JwtOAuth2Config | AccessTokenOptions): options is AccessTokenOptions {
// Although OAuth2Config does not contain refreshToken, privateKey, or privateKeyFile, a JS consumer could still pass those in
// which WILL have an access token as well, but it should be considered an OAuth2Config at that point.
return (
'accessToken' in options &&
!('refreshToken' in options) &&
!('privateKey' in options) &&
!('privateKeyFile' in options) &&
!('authCode' in options)
);
}
// A callback function for a connection to refresh an access token. This is used
// both for a JWT connection and an OAuth connection.
private async refreshFn(
conn: Connection,
callback: (err: Nullable<Error | SfError>, accessToken?: string, res?: Record<string, unknown>) => Promise<void>
): Promise<void> {
this.logger.info('Access token has expired. Updating...');
try {
const fields = this.getFields(true);
await this.initAuthOptions(fields);
await this.save();
return await callback(null, fields.accessToken);
} catch (err) {
const error = err as Error;
if (error?.message?.includes('Data Not Available')) {
// Set cause to keep original stacktrace
return await callback(messages.createError('orgDataNotAvailableError', [this.getUsername()], [], error));
}
return await callback(error);
}
}
private async readJwtKey(keyFile: string): Promise<string> {
return fs.promises.readFile(keyFile, 'utf8');
}
// Build OAuth config for a JWT auth flow
private async authJwt(options: JwtOAuth2Config): Promise<AuthFields> {
if (!options.clientId) {
throw messages.createError('missingClientId');
}
const privateKeyContents = await this.readJwtKey(ensureString(options.privateKey));
const { loginUrl = SfdcUrl.PRODUCTION } = options;
const url = new SfdcUrl(loginUrl);
const createdOrgInstance = (this.getFields().createdOrgInstance ?? '').trim().toLowerCase();
const audienceUrl = await url.getJwtAudienceUrl(createdOrgInstance);
let authFieldsBuilder: JsonMap | undefined;
const authErrors = [];
// given that we can no longer depend on instance names or URls to determine audience, let's try them all
const loginAndAudienceUrls = getLoginAudienceCombos(audienceUrl, loginUrl);
for (const [login, audience] of loginAndAudienceUrls) {
try {
// sequentially, in probabilistic order
// eslint-disable-next-line no-await-in-loop
authFieldsBuilder = await this.tryJwtAuth(options.clientId, login, audience, privateKeyContents);
break;
} catch (err) {
const error = err as Error;
const message = error.message.includes('audience')
? `${error.message} [audience=${audience} login=${login}]`
: error.message;
authErrors.push(message);
}
}
if (!authFieldsBuilder) {
// messages.createError expects names to end in `error` and this one says Errors so do it manually.
throw new SfError(messages.getMessage('jwtAuthErrors', [authErrors.join('\n')]), 'JwtAuthError');
}
const authFields: AuthFields = {
accessToken: asString(authFieldsBuilder.access_token),