@salesforce/core
Version:
Core libraries to interact with SFDX projects, orgs, and APIs.
360 lines (359 loc) • 11.6 kB
TypeScript
import { AsyncOptionalCreatable } from '@salesforce/kit';
import { Nullable } from '@salesforce/ts-types';
import { OAuth2Config, OAuth2 } from '@jsforce/jsforce-node';
import { Connection } from './connection';
import { Org } from './org';
/**
* 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;
};
/**
* 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;
};
export declare const DEFAULT_CONNECTED_APP_INFO: {
clientId: string;
clientSecret: string;
};
/**
* 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 declare class AuthInfo extends AsyncOptionalCreatable<AuthInfo.Options> {
private usingAccessToken;
private logger;
private stateAggregator;
private username;
private options;
/**
* Constructor
* **Do not directly construct instances of this class -- use {@link AuthInfo.create} instead.**
*
* @param options The options for the class instance
*/
constructor(options?: AuthInfo.Options);
/**
* Returns the default instance url
*
* @returns {string}
*/
static getDefaultInstanceUrl(): string;
/**
* 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[]>}
*/
static listAllAuthorizations(orgAuthFilter?: (orgAuth: OrgAuthorization) => boolean): Promise<OrgAuthorization[]>;
/**
* Returns true if one or more authentications are persisted.
*/
static hasAuthentications(): Promise<boolean>;
/**
* Get the authorization URL.
*
* @param options The options to generate the URL.
*/
static getAuthorizationUrl(options: JwtOAuth2Config & {
scope?: string;
}, oauth2?: OAuth2): string;
/**
* Parse a sfdx auth url, usually obtained by `authInfo.getSfdxAuthUrl`.
*
* @example
* ```
* await AuthInfo.create(AuthInfo.parseSfdxAuthUrl(sfdxAuthUrl));
* ```
* @param sfdxAuthUrl
*/
static parseSfdxAuthUrl(sfdxAuthUrl: string): Pick<AuthFields, 'clientId' | 'clientSecret' | 'refreshToken' | '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
*/
static identifyPossibleScratchOrgs(fields: AuthFields, orgAuthInfo: AuthInfo): Promise<void>;
/**
* Find all dev hubs available in the local environment.
*/
static getDevHubAuthInfos(): Promise<OrgAuthorization[]>;
private static identifyPossibleSandbox;
/**
* 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 queryScratchOrg;
/**
* Get the username.
*/
getUsername(): string;
/**
* Returns true if `this` is using the JWT flow.
*/
isJwt(): boolean;
/**
* Returns true if `this` is using an access token flow.
*/
isAccessTokenFlow(): boolean;
/**
* Returns true if `this` is using the oauth flow.
*/
isOauth(): boolean;
/**
* Returns true if `this` is using the refresh token flow.
*/
isRefreshTokenFlow(): boolean;
/**
* Updates the cache and persists the authentication fields (encrypted).
*
* @param authData New data to save.
*/
save(authData?: AuthFields): Promise<AuthInfo>;
/**
* Update the authorization fields, encrypting sensitive fields, but do not persist.
* For convenience `this` object is returned.
*
* @param authData Authorization fields to update.
*/
update(authData?: AuthFields): AuthInfo;
/**
* Get the auth fields (decrypted) needed to make a connection.
*/
getConnectionOptions(): ConnectionOptions;
getClientId(): string;
getRedirectUri(): string;
/**
* 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()
*/
getFields(decrypt?: boolean): Readonly<AuthFields>;
/**
* Get the org front door (used for web based oauth flows)
*/
getOrgFrontDoorUrl(): string;
/**
* Returns true if this org is using access token auth.
*/
isUsingAccessToken(): boolean;
/**
* 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)
*/
getSfdxAuthUrl(): string;
/**
* 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
*/
handleAliasAndDefaultSettings(sideEffects: AuthSideEffects): Promise<void>;
/**
* 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
*/
setAsDefault(options?: {
org?: boolean;
devHub?: boolean;
}): Promise<void>;
/**
* Sets the provided alias to the username
*
* @param alias alias to set
*/
setAlias(alias: string): Promise<void>;
/**
* Initializes an instance of the AuthInfo class.
*/
init(): Promise<void>;
private getInstanceUrl;
/**
* 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 initAuthOptions;
private loadDecryptedAuthFromConfig;
private isTokenOptions;
private refreshFn;
private readJwtKey;
private authJwt;
private tryJwtAuth;
private buildRefreshTokenConfig;
/**
* Performs an authCode exchange but the Oauth2 feature of jsforce is extended to include a code_challenge
*
* @param options The oauth options
* @param oauth2 The oauth2 extension that includes a code_challenge
*/
private exchangeToken;
private retrieveUserInfo;
/**
* Given an error while getting the User object, handle different possibilities of response.body.
*
* @param response
* @private
*/
private throwUserGetException;
private getNamespacePrefix;
/**
* Returns `true` if the org is a Dev Hub.
*
* Check access to the ScratchOrgInfo object to determine if the org is a dev hub.
*/
private determineIfDevHub;
}
export declare namespace AuthInfo {
/**
* Constructor options for AuthInfo.
*/
type Options = {
/**
* Org signup username.
*/
username?: string;
/**
* OAuth options.
*/
oauth2Options?: JwtOAuth2Config;
/**
* Options for the access token auth.
*/
accessTokenOptions?: AccessTokenOptions;
oauth2?: OAuth2;
/**
* In certain situations, a new auth info wants to use the connected app
* information from another parent org. Typically for scratch org or sandbox
* creation.
*/
parentUsername?: string;
isDevHub?: boolean;
};
}