UNPKG

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