UNPKG

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