UNPKG

11 kBTypeScriptView Raw
1import { AsyncOptionalCreatable } from '@salesforce/kit';
2import { Nullable } from '@salesforce/ts-types';
3import { JwtOAuth2Config, OAuth2 } from 'jsforce';
4import { Connection } from './connection';
5import { Org } from './org';
6/**
7 * Fields for authorization, org, and local information.
8 */
9export declare type AuthFields = {
10 accessToken?: string;
11 alias?: string;
12 authCode?: string;
13 clientId?: string;
14 clientSecret?: string;
15 created?: string;
16 createdOrgInstance?: string;
17 devHubUsername?: string;
18 instanceUrl?: string;
19 instanceApiVersion?: string;
20 instanceApiVersionLastRetrieved?: string;
21 isDevHub?: boolean;
22 loginUrl?: string;
23 orgId?: string;
24 password?: string;
25 privateKey?: string;
26 refreshToken?: string;
27 scratchAdminUsername?: string;
28 snapshot?: string;
29 userId?: string;
30 username?: string;
31 usernames?: string[];
32 userProfileName?: string;
33 expirationDate?: string;
34 tracksSource?: boolean;
35 [Org.Fields.NAME]?: string;
36 [Org.Fields.INSTANCE_NAME]?: string;
37 [Org.Fields.NAMESPACE_PREFIX]?: Nullable<string>;
38 [Org.Fields.IS_SANDBOX]?: boolean;
39 [Org.Fields.IS_SCRATCH]?: boolean;
40 [Org.Fields.TRIAL_EXPIRATION_DATE]?: Nullable<string>;
41};
42export declare type OrgAuthorization = {
43 orgId: string;
44 username: string;
45 oauthMethod: 'jwt' | 'web' | 'token' | 'unknown';
46 aliases: Nullable<string[]>;
47 configs: Nullable<string[]>;
48 isScratchOrg?: boolean;
49 isDevHub?: boolean;
50 isSandbox?: boolean;
51 instanceUrl?: string;
52 accessToken?: string;
53 error?: string;
54 isExpired: boolean | 'unknown';
55};
56/**
57 * Options for access token flow.
58 */
59export interface AccessTokenOptions {
60 accessToken?: string;
61 loginUrl?: string;
62 instanceUrl?: string;
63}
64export declare type AuthSideEffects = {
65 alias?: string;
66 setDefault: boolean;
67 setDefaultDevHub: boolean;
68 setTracksSource?: boolean;
69};
70/**
71 * A function to update a refresh token when the access token is expired.
72 */
73export declare type RefreshFn = (conn: Connection, callback: (err: Nullable<Error>, accessToken?: string, res?: Record<string, unknown>) => Promise<void>) => Promise<void>;
74/**
75 * Options for {@link Connection}.
76 */
77export declare type ConnectionOptions = AuthFields & {
78 /**
79 * OAuth options.
80 */
81 oauth2?: Partial<JwtOAuth2Config>;
82 /**
83 * Refresh token callback.
84 */
85 refreshFn?: RefreshFn;
86};
87export declare const DEFAULT_CONNECTED_APP_INFO: {
88 clientId: string;
89 legacyClientId: string;
90 legacyClientSecret: string;
91};
92/**
93 * Handles persistence and fetching of user authentication information using
94 * JWT, OAuth, or refresh tokens. Sets up the refresh flows that jsForce will
95 * use to keep tokens active. An AuthInfo can also be created with an access
96 * token, but AuthInfos created with access tokens can't be persisted to disk.
97 *
98 * **See** [Authorization](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_auth.htm)
99 *
100 * **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)
101 *
102 * ```
103 * // Creating a new authentication file.
104 * const authInfo = await AuthInfo.create({
105 * username: myAdminUsername,
106 * oauth2Options: {
107 * loginUrl, authCode, clientId, clientSecret
108 * }
109 * );
110 * authInfo.save();
111 *
112 * // Creating an authorization info with an access token.
113 * const authInfo = await AuthInfo.create({
114 * username: accessToken
115 * });
116 *
117 * // Using an existing authentication file.
118 * const authInfo = await AuthInfo.create({
119 * username: myAdminUsername
120 * });
121 *
122 * // Using the AuthInfo
123 * const connection = await Connection.create({ authInfo });
124 * ```
125 */
126export declare class AuthInfo extends AsyncOptionalCreatable<AuthInfo.Options> {
127 private usingAccessToken;
128 private logger;
129 private stateAggregator;
130 private username;
131 private options;
132 /**
133 * Constructor
134 * **Do not directly construct instances of this class -- use {@link AuthInfo.create} instead.**
135 *
136 * @param options The options for the class instance
137 */
138 constructor(options?: AuthInfo.Options);
139 /**
140 * Returns the default instance url
141 *
142 * @returns {string}
143 */
144 static getDefaultInstanceUrl(): string;
145 /**
146 * Get a list of all authorizations based on auth files stored in the global directory.
147 * One can supply a filter (see @param orgAuthFilter) and calling this function without
148 * a filter will return all authorizations.
149 *
150 * @param orgAuthFilter A predicate function that returns true for those org authorizations that are to be retained.
151 *
152 * @returns {Promise<OrgAuthorization[]>}
153 */
154 static listAllAuthorizations(orgAuthFilter?: (orgAuth: OrgAuthorization) => boolean): Promise<OrgAuthorization[]>;
155 /**
156 * Returns true if one or more authentications are persisted.
157 */
158 static hasAuthentications(): Promise<boolean>;
159 /**
160 * Get the authorization URL.
161 *
162 * @param options The options to generate the URL.
163 */
164 static getAuthorizationUrl(options: JwtOAuth2Config & {
165 scope?: string;
166 }, oauth2?: OAuth2): string;
167 /**
168 * Parse a sfdx auth url, usually obtained by `authInfo.getSfdxAuthUrl`.
169 *
170 * @example
171 * ```
172 * await AuthInfo.create(AuthInfo.parseSfdxAuthUrl(sfdxAuthUrl));
173 * ```
174 * @param sfdxAuthUrl
175 */
176 static parseSfdxAuthUrl(sfdxAuthUrl: string): Pick<AuthFields, 'clientId' | 'clientSecret' | 'refreshToken' | 'loginUrl'>;
177 /**
178 * Given a set of decrypted fields and an authInfo, determine if the org belongs to an available
179 * dev hub.
180 *
181 * @param fields
182 * @param orgAuthInfo
183 */
184 static identifyPossibleScratchOrgs(fields: AuthFields, orgAuthInfo: AuthInfo): Promise<void>;
185 /**
186 * Find all dev hubs available in the local environment.
187 */
188 static getDevHubAuthInfos(): Promise<OrgAuthorization[]>;
189 private static queryScratchOrg;
190 /**
191 * Get the username.
192 */
193 getUsername(): string;
194 /**
195 * Returns true if `this` is using the JWT flow.
196 */
197 isJwt(): boolean;
198 /**
199 * Returns true if `this` is using an access token flow.
200 */
201 isAccessTokenFlow(): boolean;
202 /**
203 * Returns true if `this` is using the oauth flow.
204 */
205 isOauth(): boolean;
206 /**
207 * Returns true if `this` is using the refresh token flow.
208 */
209 isRefreshTokenFlow(): boolean;
210 /**
211 * Updates the cache and persists the authentication fields (encrypted).
212 *
213 * @param authData New data to save.
214 */
215 save(authData?: AuthFields): Promise<AuthInfo>;
216 /**
217 * Update the authorization fields, encrypting sensitive fields, but do not persist.
218 * For convenience `this` object is returned.
219 *
220 * @param authData Authorization fields to update.
221 */
222 update(authData?: AuthFields): AuthInfo;
223 /**
224 * Get the auth fields (decrypted) needed to make a connection.
225 */
226 getConnectionOptions(): ConnectionOptions;
227 getClientId(): string;
228 getRedirectUri(): string;
229 /**
230 * Get the authorization fields.
231 *
232 * @param decrypt Decrypt the fields.
233 */
234 getFields(decrypt?: boolean): AuthFields;
235 /**
236 * Get the org front door (used for web based oauth flows)
237 */
238 getOrgFrontDoorUrl(): string;
239 /**
240 * Returns true if this org is using access token auth.
241 */
242 isUsingAccessToken(): boolean;
243 /**
244 * Get the SFDX Auth URL.
245 *
246 * **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)
247 */
248 getSfdxAuthUrl(): string;
249 /**
250 * Convenience function to handle typical side effects encountered when dealing with an AuthInfo.
251 * Given the values supplied in parameter sideEffects, this function will set auth alias, default auth
252 * and default dev hub.
253 *
254 * @param sideEffects - instance of AuthSideEffects
255 */
256 handleAliasAndDefaultSettings(sideEffects: AuthSideEffects): Promise<void>;
257 /**
258 * Set the target-env (default) or the target-dev-hub to the alias if
259 * it exists otherwise to the username. Method will try to set the local
260 * config first but will default to global config if that fails.
261 *
262 * @param options
263 */
264 setAsDefault(options?: {
265 org?: boolean;
266 devHub?: boolean;
267 }): Promise<void>;
268 /**
269 * Sets the provided alias to the username
270 *
271 * @param alias alias to set
272 */
273 setAlias(alias: string): Promise<void>;
274 /**
275 * Initializes an instance of the AuthInfo class.
276 */
277 init(): Promise<void>;
278 private getInstanceUrl;
279 /**
280 * Initialize this AuthInfo instance with the specified options. If options are not provided, initialize it from cache
281 * or by reading from the persistence store. For convenience `this` object is returned.
282 *
283 * @param options Options to be used for creating an OAuth2 instance.
284 *
285 * **Throws** *{@link SfError}{ name: 'NamedOrgNotFoundError' }* Org information does not exist.
286 * @returns {Promise<AuthInfo>}
287 */
288 private initAuthOptions;
289 private loadDecryptedAuthFromConfig;
290 private isTokenOptions;
291 private refreshFn;
292 private readJwtKey;
293 private authJwt;
294 private tryJwtAuth;
295 private buildRefreshTokenConfig;
296 /**
297 * Performs an authCode exchange but the Oauth2 feature of jsforce is extended to include a code_challenge
298 *
299 * @param options The oauth options
300 * @param oauth2 The oauth2 extension that includes a code_challenge
301 */
302 private exchangeToken;
303 private retrieveUserInfo;
304 /**
305 * Given an error while getting the User object, handle different possibilities of response.body.
306 *
307 * @param response
308 * @private
309 */
310 private throwUserGetException;
311 /**
312 * Returns `true` if the org is a Dev Hub.
313 *
314 * Check access to the ScratchOrgInfo object to determine if the org is a dev hub.
315 */
316 private determineIfDevHub;
317}
318export declare namespace AuthInfo {
319 /**
320 * Constructor options for AuthInfo.
321 */
322 interface Options {
323 /**
324 * Org signup username.
325 */
326 username?: string;
327 /**
328 * OAuth options.
329 */
330 oauth2Options?: JwtOAuth2Config;
331 /**
332 * Options for the access token auth.
333 */
334 accessTokenOptions?: AccessTokenOptions;
335 oauth2?: OAuth2;
336 /**
337 * In certain situations, a new auth info wants to use the connected app
338 * information from another parent org. Typically for scratch org or sandbox
339 * creation.
340 */
341 parentUsername?: string;
342 isDevHub?: boolean;
343 }
344}