@lemoncloud/lemon-web-core
Version:
Core Web-based Library for signing request at LEMONCLOUD
1,333 lines (1,320 loc) • 54.1 kB
TypeScript
import { AxiosInstance, AxiosRequestConfig } from 'axios';
import { JwtPayload } from 'jwt-decode';
import AWS from 'aws-sdk/global.js';
/**
* Interface representing a web core service.
*/
interface WebCoreService {
/**
* Gets the saved token.
* @returns {Promise<{ [key: string]: string }>} - A promise that resolves to an object containing the saved token.
*/
getSavedToken(): Promise<{
[key: string]: string;
}>;
/**
* Checks if the user is authenticated.
* @returns {Promise<boolean>} - A promise that resolves to true if the user is authenticated, false otherwise.
*/
isAuthenticated(): Promise<boolean>;
/**
* Logs out the user.
* @returns {Promise<void>} - A promise that resolves when the user is logged out.
*/
logout(): Promise<void>;
/**
* Sets the use of X-Lemon-Identity.
* @param {boolean} use - Whether to use X-Lemon-Identity.
*/
setUseXLemonIdentity(use: boolean): void;
/**
* Sets the use of X-Lemon-Language.
* @param {boolean} use - Whether to use X-Lemon-Language.
* @param {string} key? - language key name of local storage
*/
setUseXLemonLanguage(use: boolean, key?: string): void;
/**
* Gets the shared axios instance
* @returns The shared axios instance
*/
getSharedAxiosInstance(): AxiosInstance;
}
/**
* Type representing a map of web core services.
*/
type WebCoreServiceMap = {
aws: AWSWebCore;
azure: AzureWebCore;
};
/**
* Type representing a cloud provider.
*/
type CloudProvider = keyof WebCoreServiceMap;
/**
* Type representing the configuration for the web core.
* @template T - The cloud provider type.
*/
type WebCoreConfig<T extends CloudProvider> = {
cloud: T;
project: string;
oAuthEndpoint: string;
region?: string;
storage?: Storage;
};
/**
* Type representing a constructor for a web core service.
* @template T - The web core service type.
*/
type WebCoreConstructor<T extends WebCoreService> = new (config: WebCoreConfig<CloudProvider>) => T;
/**
* Represents the state of the AWS Web Core service.
*/
type AWSWebCoreState = 'no-token' | 'refreshed' | 'build';
/**
* Represents the state of the Azure Web Core service.
*/
type AzureWebCoreState = 'no-token' | 'has-token';
/**
* Represents the ARN of a KMS key in AWS.
*/
interface LemonKMS {
arn: string;
}
/**
* Represents an OAuth token returned by Lemon.
*/
interface LemonOAuthToken {
/**
* The account ID associated with the token.
*/
accountId: string;
/**
* The authentication ID associated with the token.
*/
authId: string;
/**
* The credentials associated with the token.
*/
credential: LemonCredentials;
/**
* The identity ID associated with the token.
*/
identityId: string;
/**
* The identity token associated with the token.
*/
identityToken: string;
/**
* The identity pool ID associated with the token (optional).
*/
identityPoolId?: string;
/**
* Any error information associated with the token (optional).
*/
error?: any;
/**
* The access token associated with the token (optional).
*/
accessToken?: string;
/**
* The access token associated with the token (optional).
*/
Token?: LemonOAuthToken;
}
/**
* Represents the credentials associated with an OAuth token.
*/
interface LemonCredentials {
/**
* The Access Key ID.
*/
AccessKeyId: string;
/**
* The Secret Key.
*/
SecretKey: string;
/**
* The expiration time of the credentials (optional).
*/
Expiration?: string;
/**
* The session token associated with the credentials (optional).
*/
SessionToken?: string;
/**
* The host key associated with the credentials for Azure (optional).
*/
hostKey?: string;
/**
* The host key associated with the credentials for Azure (optional).
* @deprecated Use hostKey instead
*/
HostKey?: string;
/**
* The client id for Azure (optional).
*/
clientId?: string;
}
/**
* Interface representing a Lemon refresh token.
*/
interface LemonRefreshToken {
/**
* The authentication ID associated with the refresh token.
*/
authId: string;
/**
* The account ID associated with the refresh token.
*/
accountId: string;
/**
* The identity ID associated with the refresh token.
*/
identityId: string;
/**
* The credentials associated with the refresh token.
*/
credential: LemonCredentials;
}
/**
* The payload used for signature generation.
*/
interface SignaturePayload {
/**
* The authentication ID.
*/
authId?: string;
/**
* The account ID.
*/
accountId?: string;
/**
* The identity ID.
*/
identityId?: string;
/**
* The identity token.
*/
identityToken?: string;
}
/**
* Interface for storage operations.
*/
interface Storage$1 {
/**
* Get the value associated with the given key.
*
* @param key The key to retrieve the value for.
* @param params Additional parameters for the operation.
* @returns The value associated with the given key.
*/
getItem(key: string, ...params: any): any;
/**
* Set the value for the given key.
*
* @param key The key to set the value for.
* @param value The value to be stored.
* @param params Additional parameters for the operation.
*/
setItem(key: string, value: string, ...params: any): any;
/**
* Remove the value associated with the given key.
*
* @param key The key to remove the value for.
* @param params Additional parameters for the operation.
*/
removeItem(key: string, ...params: any): any;
}
/**
* Options for configuring the logger behavior.
*/
interface LoggerOption {
/**
* Whether to show timestamps in the log output.
*/
showTimestamp?: boolean;
/**
* Whether to show log types (e.g., info, error) in the log output.
*/
showLogType?: boolean;
}
/**
* Interface representing the body of a refresh token request.
*/
interface RefreshTokenBody {
/**
* The current token.
*/
current: string;
/**
* The signature of the token.
*/
signature: string;
/**
* Optional. The domain of the token.
*/
domain?: string;
}
/**
* The token signature object.
*/
interface TokenSignature {
/**
* The authentication ID.
*/
authId: string;
/**
* The current token.
*/
current: string;
/**
* The signature of the token.
*/
signature: string;
/**
* The original token.
*/
originToken: LemonOAuthToken;
}
/**
* Represents a token signature.
*/
interface TokenSignature {
/**
* The authentication ID associated with the token signature.
* @type {string}
*/
authId: string;
/**
* The current token or status associated with the token signature.
* @type {string}
*/
current: string;
/**
* The signature string associated with the token signature.
* @type {string}
*/
signature: string;
/**
* The original Lemon OAuth token associated with the token signature.
* @type {LemonOAuthToken}
*/
originToken: LemonOAuthToken;
}
/**
* Represents the body of the request to change the user site.
*/
interface ChangeSiteBody {
/**
* The ID of the user.
*/
userId: string;
/**
* The ID of the site to switch to.
*/
siteId: string;
}
/**
* Represents the body of an HTTP request, which can contain any key-value pairs.
*/
declare type Body = {
[key: string]: any;
};
/**
* Represents the headers of an HTTP request, which can contain any key-value pairs.
*/
declare type Headers = {
[key: string]: any;
};
/**
* Represents the query parameters of an HTTP request, which can contain any key-value pairs.
*/
declare type Params = {
[key: string]: any;
};
/**
* Defines the structure of an HTTP request.
*/
interface HttpRequestData {
/**
* The HTTP method (e.g., GET, POST, PUT, etc.).
*/
method: string;
/**
* The path of the request URL.
*/
path?: string;
/**
* The query parameters of the request.
*/
params?: Params;
/**
* The request body.
*/
body?: Body;
}
interface HttpResponse<T = any> {
data: T;
status: number;
statusText: string;
headers?: any;
config?: any;
request?: any;
}
declare const USE_X_LEMON_IDENTITY_KEY = "use_x_lemon_identity_key";
declare const USE_X_LEMON_LANGUAGE_KEY = "use_x_lemon_language_key";
declare const REGION_KEY = "region";
/**
* Abstract class representing a token storage service.
* Provides methods to set and get items in storage, and abstract methods
* to check and manage cached tokens.
*/
declare abstract class TokenStorageService {
protected readonly config: WebCoreConfig<CloudProvider>;
protected prefix: string;
protected storage: Storage$1;
/**
* Constructs a TokenStorageService instance.
* @param {WebCoreConfig<CloudProvider>} config - The configuration for the web core.
*/
constructor(config: WebCoreConfig<CloudProvider>);
/**
* Updates the prefix used in storage keys.
* @param {string} prefix - The new prefix to use.
*/
updatePrefix(prefix: string): void;
/**
* Sets an item in the storage.
* @param {string} key - The key to set.
* @param {string} value - The value to set.
* @returns {Promise<void>} - A promise that resolves when the item is set.
*/
setItem(key: string, value: string): Promise<void>;
/**
* Gets an item from the storage.
* @param {string} key - The key to get.
* @returns {Promise<string>} - A promise that resolves to the value of the item.
*/
getItem(key: string): Promise<string>;
/**
* Gets all items from the storage.
* @returns {Promise<{ [key: string]: string }>} - A promise that resolves to an object containing all items.
*/
abstract getAllItems(): Promise<{
[key: string]: string;
}>;
/**
* Checks if there is a cached token in the storage.
* @returns {Promise<boolean>} - A promise that resolves to true if a cached token exists, false otherwise.
*/
abstract hasCachedToken(): Promise<boolean>;
/**
* Checks if the cached token should be refreshed.
* Abstract method that must be implemented by subclasses to define refresh logic.
* @returns {Promise<boolean>} Promise that resolves to true if the token should be refreshed, false otherwise
*/
abstract shouldRefreshToken(): Promise<boolean>;
/**
* Calculates the token expiration timestamp with built-in safety buffer.
* Uses a priority-based approach: server expiration first, then JWT expiration, finally fallback duration.
* Automatically applies a 5-minute safety buffer to prevent token expiry during requests.
* @param {string} [serverExpiration] - ISO string or date string from server response
* @param {string} [jwtToken] - JWT token string to extract expiration from
* @returns {number} Unix timestamp (milliseconds) when the token should be considered expired
*/
calculateTokenExpiration(serverExpiration?: string, jwtToken?: string): number;
/**
* Extracts the issued time from a JWT token for token lifecycle tracking.
* Used to calculate token age and determine refresh timing based on token lifetime.
* @param {string} [jwtToken] - JWT token string to extract issued time from
* @returns {number | string} Unix timestamp in milliseconds if found, empty string if not available or on error
*/
calculateTokenIssuedTime(jwtToken?: string): number | string;
/**
* Safely decodes a JWT token and extracts its payload.
* Provides error-safe JWT parsing without throwing exceptions on malformed tokens.
* @param {string} jwt - JWT token string to decode
* @returns {JwtPayload | null} Decoded JWT payload object, or null if decoding fails
*/
extractJWT(jwt: string): JwtPayload | null;
}
/**
* AWS-specific token storage service that manages OAuth tokens, credentials, and KMS configuration.
* Extends TokenStorageService to provide AWS Cognito and STS token management capabilities.
*/
declare class AWSStorageService extends TokenStorageService {
readonly config: WebCoreConfig<'aws'>;
/**
* List of credential keys stored in the token storage.
* These keys represent the complete set of AWS authentication data.
*/
private credentialKeys;
/**
* Gets the storage key (always snake_case).
*/
private getKey;
/**
* Gets a value from storage, checking both snake_case and camelCase formats for backward compatibility.
*/
private getStorageItem;
/**
* Creates an instance of AWSStorageService.
* @param {WebCoreConfig<'aws'>} config - AWS-specific web core configuration
*/
constructor(config: WebCoreConfig<'aws'>);
/**
* Initializes Lemon configuration by setting default values for identity usage and region.
* Sets up the storage with required configuration flags and regional settings.
* @returns {Promise<void>} Promise that resolves when initialization is complete
*/
initLemonConfig(): Promise<void>;
/**
* Retrieves all stored credential items as a key-value map.
* Useful for debugging or bulk operations on stored credentials.
* @returns {Promise<{[key: string]: string}>} Promise resolving to object with all credential key-value pairs
*/
getAllItems(): Promise<{}>;
/**
* Checks if valid cached tokens exist in storage.
* Validates the presence of essential token components required for AWS authentication.
* @returns {Promise<boolean>} Promise resolving to true if all required tokens are cached
*/
hasCachedToken(): Promise<boolean>;
/**
* Determines whether the stored token should be refreshed based on expiration time.
* Returns true if token has expired or expiration info is missing.
* @returns {Promise<boolean>} Promise resolving to true if token should be refreshed
*/
shouldRefreshToken(): Promise<boolean>;
/**
* Retrieves cached AWS credentials (access key, secret key, session token).
* Returns the credentials in the format expected by AWS SDK.
* @returns {Promise<LemonCredentials>} Promise resolving to AWS credentials object
*/
getCachedCredentials(): Promise<LemonCredentials>;
/**
* Retrieves and transforms cached OAuth token data.
* Converts snake_case storage keys to camelCase and structures the data for OAuth usage.
* Excludes sensitive credential details from the returned object.
* @returns {Promise<LemonOAuthToken>} Promise resolving to formatted OAuth token object
*/
getCachedOAuthToken(): Promise<LemonOAuthToken>;
/**
* Saves OAuth token and associated AWS credentials to storage.
* Calculates and stores expiration and issued times for token lifecycle management.
* @param {LemonOAuthToken} token - OAuth token object containing credentials and metadata
* @returns {Promise<void>} Promise that resolves when save operation is complete
*/
saveOAuthToken(token: LemonOAuthToken): Promise<void>;
/**
* Removes all stored OAuth tokens and credentials from storage.
* Performs complete cleanup of all credential-related storage keys.
* @returns {Promise<void>} Promise that resolves when all tokens are cleared
*/
clearOAuthToken(): Promise<void>;
/**
* Saves KMS (Key Management Service) configuration to storage.
* Stores the KMS ARN for encryption/decryption operations.
* @param {LemonKMS} kms - KMS configuration object containing ARN
* @returns {Promise<void>} Promise that resolves when KMS data is saved
*/
saveKMS(kms: LemonKMS): Promise<void>;
}
/**
* A service to manage Azure-specific storage operations.
*/
declare class AzureStorageService extends TokenStorageService {
readonly config: WebCoreConfig<'azure'>;
/**
* The list of keys used to store credentials in the storage.
*/
private credentialKeys;
/**
* Gets the storage key (always snake_case).
*/
private getKey;
/**
* Gets a value from storage, checking both snake_case and camelCase formats for backward compatibility.
*/
private getStorageItem;
constructor(config: WebCoreConfig<'azure'>);
/**
* Retrieves all items from the storage.
*
* @returns An object containing all the stored items.
*/
getAllItems(): Promise<{
[key: string]: string;
}>;
/**
* Checks if there is a cached OAuth token in the storage.
*
* @returns A boolean indicating whether a cached token exists.
*/
hasCachedToken(): Promise<boolean>;
/**
* Checks if the cached OAuth token needs to be refreshed.
*
* @returns A boolean indicating whether the token should be refreshed.
*/
shouldRefreshToken(): Promise<boolean>;
/**
* Retrieves the cached OAuth token from the storage.
*
* @returns The cached OAuth token or `null` if not found.
*/
getCachedOAuthToken(): Promise<LemonOAuthToken | null>;
/**
* Saves the provided OAuth token to the storage.
*
* @param token The OAuth token to be saved.
*/
saveOAuthToken(token: LemonOAuthToken): Promise<void>;
/**
* Clears all the cached OAuth tokens from the storage.
*/
clearOAuthToken(): Promise<void>;
}
/**
* Class to build and execute HTTP requests
* @example
* ```ts
* const response: HttpResponse<OAuthResponse> = await new HttpRequestBuilder({
* method: 'GET',
* baseURL: `https://api.lemoncloud.io/v1/oauth`,
* })
* .setHeaders({ Cookie: this.cookie })
* .setParams({ page: 0 })
* .execute();
* ```
*/
declare class HttpRequestBuilder {
private axiosInstance;
private config;
/**
* @constructor
* @param {AxiosRequestConfig} [config={}] - Initial configuration
* @param {AxiosInstance} - Axios Instance
* @throws {Error} If the method is not defined
* @throws {Error} If the baseURL is not defined
*/
constructor(config: AxiosRequestConfig, axiosInstance?: AxiosInstance);
/**
* Sets the request headers
* @param {Headers} headers - Headers to set
* @returns {HttpRequestBuilder} - Returns the current instance to allow method chaining
*/
setHeaders(headers: Headers): HttpRequestBuilder;
/**
* Sets the request parameters
* @param {Params} params - Parameters to set
* @returns {HttpRequestBuilder} - Returns the current instance to allow method chaining
*/
setParams(params: Params): HttpRequestBuilder;
/**
* Sets the request body
* @param {Body} data - Body data to set
* @returns {HttpRequestBuilder} - Returns the current instance to allow method chaining
*/
setBody(data: Body): HttpRequestBuilder;
/**
* Sets the request method
* @param {string} method - HTTP method to set
* @returns {HttpRequestBuilder} - Returns the current instance to allow method chaining
*/
setMethod(method: string): HttpRequestBuilder;
/**
* Adds additional headers to the request.
* @param {Headers} headers - Headers to add.
* @returns {HttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
addHeaders(headers?: Headers): HttpRequestBuilder;
/**
* Adds additional Axios request configuration.
* @param {AxiosRequestConfig} config - The configuration to add.
* @returns {HttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
addAxiosRequestConfig(config: AxiosRequestConfig): HttpRequestBuilder;
/**
* Executes the HTTP request
* @template T
* @returns {Promise<HttpResponse<T>>} - Promise containing the response
* @throws {Error} If an error occurs during the request
*/
execute<T>(): Promise<HttpResponse<T>>;
}
/**
* Class to build and execute HTTP requests with AWS signing
* @example
* ```ts
* const response: HttpResponse<OAuthResponse> = await new AWSHttpRequestBuilder({
* method: 'GET',
* baseURL: `https://api.lemoncloud.io/v1/oauth`,
* })
* .addHeaders({ Cookie: this.cookie })
* .setParams({ page: 0 })
* .execute();
* ```
*/
declare class AWSHttpRequestBuilder {
private readonly tokenStorage;
private axiosInstance;
private logger;
private config;
/**
* Creates an instance of AWSHttpRequestBuilder.
* @param {AWSStorageService} tokenStorage - The AWS storage service for token management.
* @param {AxiosRequestConfig} config - The Axios request configuration.
* @param {AxiosInstance} axiosInstance - The Axios instance.
* @throws {Error} If tokenStorage, method, or baseURL are not defined.
*/
constructor(tokenStorage: AWSStorageService, config: AxiosRequestConfig, axiosInstance?: AxiosInstance);
/**
* Sets the request headers.
* @param {Headers} headers - Headers to set.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
setHeaders(headers: Headers): AWSHttpRequestBuilder;
/**
* Sets the request parameters.
* @param {Params} params - Parameters to set.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
setParams(params: Params): AWSHttpRequestBuilder;
/**
* Sets the request body.
* @param {Body} data - Body data to set.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
setBody(data: Body): AWSHttpRequestBuilder;
/**
* Sets the request method.
* @param {string} method - HTTP method to set.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
setMethod(method: string): AWSHttpRequestBuilder;
/**
* Adds additional headers to the request.
* @param {Headers} headers - Headers to add.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
addHeaders(headers?: Headers): AWSHttpRequestBuilder;
/**
* Adds additional Axios request configuration.
* @param {AxiosRequestConfig} config - The configuration to add.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
addAxiosRequestConfig(config: AxiosRequestConfig): AWSHttpRequestBuilder;
/**
* Executes the HTTP request.
* @template T
* @returns {Promise<HttpResponse<T>>} - Promise containing the response.
* @throws {Error} If an error occurs during the request.
*/
execute<T>(): Promise<HttpResponse<T>>;
/**
* Gets the signed AWS client.
* @private
* @param {string} endpoint - The endpoint for the client.
* @returns {Promise<any>} - The signed AWS client.
* @throws {Error} If endpoint is not provided or signed client is not available.
*/
private getSignedClient;
/**
* Gets the signed headers for the request.
* @private
* @param {any} signedClient - The signed AWS client.
* @param {HttpRequestData} data - The request data.
* @returns {Promise<any>} - The signed headers.
*/
private getSignedHeader;
/**
* Adds x-lemon-identity to the header.
* @param header The header to be added
* @returns The header with x-lemon-identity added
*/
private addXLemonIdentityToHeader;
/**
* Adds x-lemon-language to the header.
* @param header The header to be added
* @returns The header with x-lemon-language added
*/
private addXLemonLanguageToHeader;
/**
* Extracts the hostname from a URL.
* @private
* @param {string} url - The URL to extract the hostname from.
* @returns {string} - The extracted hostname.
*/
private extractHostname;
}
/**
* Class to build and execute HTTP requests with AWS signing
* @example
* ```ts
* const response: HttpResponse<OAuthResponse> = await new AzureHttpRequestBuilder({
* method: 'GET',
* baseURL: `https://api.lemoncloud.io/v1/oauth`,
* })
* .addHeaders({ Cookie: this.cookie })
* .setParams({ page: 0 })
* .execute();
* ```
*/
declare class AzureHttpRequestBuilder {
private readonly tokenStorage;
private axiosInstance;
private config;
/**
* Creates an instance of AWSHttpRequestBuilder.
* @param {AzureStorageService} tokenStorage - The AWS storage service for token management.
* @param {AxiosRequestConfig} config - The Axios request configuration.
* @throws {Error} If tokenStorage, method, or baseURL are not defined.
*/
constructor(tokenStorage: AzureStorageService, config: AxiosRequestConfig);
/**
* Sets the request headers.
* @param {Headers} headers - Headers to set.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
setHeaders(headers: Headers): AzureHttpRequestBuilder;
/**
* Sets the request parameters.
* @param {Params} params - Parameters to set.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
setParams(params: Params): AzureHttpRequestBuilder;
/**
* Sets the request body.
* @param {Body} data - Body data to set.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
setBody(data: Body): AzureHttpRequestBuilder;
/**
* Sets the request method.
* @param {string} method - HTTP method to set.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
setMethod(method: string): AzureHttpRequestBuilder;
/**
* Adds additional headers to the request.
* @param {Headers} headers - Headers to add.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
addHeaders(headers?: Headers): AzureHttpRequestBuilder;
/**
* Adds additional Axios request configuration.
* @param {AxiosRequestConfig} config - The configuration to add.
* @returns {AWSHttpRequestBuilder} - Returns the current instance to allow method chaining.
*/
addAxiosRequestConfig(config: AxiosRequestConfig): AzureHttpRequestBuilder;
/**
* Executes the HTTP request.
* @template T
* @returns {Promise<HttpResponse<T>>} - Promise containing the response.
* @throws {Error} If an error occurs during the request.
*/
execute<T>(): Promise<HttpResponse<T>>;
/**
* Adds code parameters to the request configuration.
* Retrieves the `hostKey` and `clientId` from the token storage and sets them as request parameters.
* @private
* @async
* @returns {Promise<void>} - A promise that resolves when the parameters are added.
*/
private addCodeParams;
/**
* Adds a Bearer token to the request headers.
* Retrieves the `identityToken` from the token storage and sets it as the `Authorization` header.
* @private
* @async
* @returns {Promise<void>} - A promise that resolves when the token is added.
*/
private addBearerTokenToHeader;
/**
* Adds the x-lemon-identity token to the request headers if required.
* Checks if the `USE_X_LEMON_IDENTITY_KEY` is set in the token storage and, if true,
* retrieves the `identityToken` and sets it as the `x-lemon-identity` header.
* @private
* @async
* @returns {Promise<void>} - A promise that resolves when the token is added.
*/
private addXLemonIdentityToHeader;
/**
* Adds the x-lemon-language header to the request if required.
* First checks if a language key is set in storage, then retrieves the corresponding language value.
* If both exist, adds the language as 'x-lemon-language' header.
* @private
* @async
* @returns {Promise<void>} - A promise that resolves when the language header is added.
*/
private addXLemonLanguageToHeader;
}
/**
* AWSWebCore class implements AWS-based operations for Lemoncloud authentication logic.
* Provides comprehensive token management, credential building, and authenticated request capabilities.
*/
declare class AWSWebCore implements WebCoreService {
private readonly config;
private readonly tokenStorage;
private readonly logger;
private sharedAxiosInstance;
/**
* Creates an instance of AWSWebCore with the specified configuration.
* Initializes internal services including token storage, logging, and HTTP client.
*
* @param {WebCoreConfig<'aws'>} config - The AWS-specific configuration object containing
* OAuth endpoints, region settings, and other AWS parameters
*/
constructor(config: WebCoreConfig<'aws'>);
/**
* Retrieves the shared Axios instance used for HTTP requests.
* This instance is pre-configured and shared across all requests to maintain consistency.
*
* @returns {AxiosInstance} The configured Axios instance for making HTTP requests
*/
getSharedAxiosInstance(): AxiosInstance;
/**
* Initializes the AWS WebCore service by validating cached tokens and setting up credentials.
* Performs token refresh if necessary or builds credentials from cached data.
* This method should be called before using any authenticated operations.
*
* @returns {Promise<AWSWebCoreState>} A promise that resolves to the initialization state:
* - 'no-token': No valid token found
* - 'refreshed': Token was refreshed successfully
* - 'build': Credentials built from existing valid token
* @throws {Error} Throws an error if token refresh fails or credentials cannot be built
*
* @example
* ```typescript
* const webCore = new AWSWebCore(config);
* const state = await webCore.init();
* if (state === 'no-token') {
* // Handle authentication required
* }
* ```
*/
init(): Promise<AWSWebCoreState>;
/**
* Retrieves the token storage service instance.
* Provides access to the underlying storage service for advanced token management operations.
*
* @returns {AWSStorageService} The storage service that manages OAuth tokens and credentials
*/
getTokenStorage(): AWSStorageService;
/**
* Creates an HTTP request builder for unsigned requests.
* Use this for requests that don't require AWS signature authentication.
*
* @param {AxiosRequestConfig} config - The Axios request configuration object containing
* method, URL, headers, and other request parameters
* @returns {HttpRequestBuilder} A configured HTTP request builder instance
*
* @example
* ```typescript
* const builder = webCore.buildRequest({
* method: 'GET',
* url: '/api/public-endpoint'
* });
* const response = await builder.execute();
* ```
*/
buildRequest(config: AxiosRequestConfig): HttpRequestBuilder;
/**
* Executes an HTTP request without AWS signature authentication.
* Suitable for public endpoints or non-AWS services.
*
* @template T - The expected response data type
* @param {string} method - The HTTP method (GET, POST, PUT, DELETE, etc.)
* @param {string} url - The complete request URL or base URL
* @param {Params} [params={}] - Query parameters to append to the URL
* @param {Body} [body] - The request body for POST/PUT requests
* @param {AxiosRequestConfig} [config] - Additional Axios configuration options
* @returns {Promise<HttpResponse<T>>} Promise resolving to the HTTP response with typed data
* @throws {Error} Throws on network errors, HTTP errors, or request configuration issues
*
* @example
* ```typescript
* const response = await webCore.request<UserData>(
* 'GET',
* '/api/users/123',
* { include: 'profile' }
* );
* ```
*/
request<T>(method: string, url: string, params?: Params, body?: Body, config?: AxiosRequestConfig): Promise<HttpResponse<T>>;
/**
* Creates an HTTP request builder with AWS signature authentication.
* Use this for requests to AWS services or signed API endpoints.
*
* @param {AxiosRequestConfig} config - The Axios request configuration object
* @returns {AWSHttpRequestBuilder} A configured AWS HTTP request builder with signature capabilities
*
* @example
* ```typescript
* const builder = webCore.buildSignedRequest({
* method: 'POST',
* url: '/api/aws-protected-endpoint'
* });
* ```
*/
buildSignedRequest(config: AxiosRequestConfig): AWSHttpRequestBuilder;
/**
* Executes an HTTP request with AWS signature authentication.
* Automatically signs the request using stored AWS credentials.
*
* @template T - The expected response data type
* @param {string} method - The HTTP method (GET, POST, PUT, DELETE, etc.)
* @param {string} url - The complete request URL or base URL
* @param {Params} [params={}] - Query parameters to append to the URL
* @param {Body} [body] - The request body for POST/PUT requests
* @param {AxiosRequestConfig} [config] - Additional Axios configuration options
* @returns {Promise<HttpResponse<T>>} Promise resolving to the signed HTTP response
* @throws {Error} Throws on authentication errors, network errors, or signature failures
*
* @example
* ```typescript
* const response = await webCore.signedRequest<ApiResponse>(
* 'POST',
* '/api/protected-resource',
* {},
* { data: 'sensitive information' }
* );
* ```
*/
signedRequest<T>(method: string, url: string, params?: Params, body?: Body, config?: AxiosRequestConfig): Promise<HttpResponse<T>>;
/**
* Retrieves all saved tokens from storage as a key-value map.
* Useful for debugging, backup, or migration purposes.
*
* @returns {Promise<{ [key: string]: string }>} Promise resolving to an object containing
* all stored token data with keys and values
*/
getSavedToken(): Promise<{
[key: string]: string;
}>;
/**
* Checks if the user is currently authenticated with valid credentials.
* Performs token validation and refresh if necessary before determining authentication status.
*
* @returns {Promise<boolean>} Promise resolving to true if authenticated with valid credentials,
* false if no token exists or authentication fails
* @throws {Error} Logs errors but doesn't throw, returning false on any authentication failure
*
* @example
* ```typescript
* if (await webCore.isAuthenticated()) {
* // User is authenticated, proceed with protected operations
* } else {
* // Redirect to login or handle unauthenticated state
* }
* ```
*/
isAuthenticated(): Promise<boolean>;
/**
* Builds AWS credentials from an OAuth token and sets them in AWS.config.
* Saves the token to storage and creates AWS credentials for subsequent API calls.
*
* @param {LemonOAuthToken} token - The OAuth token containing AWS credential information
* @returns {Promise<AWS.Credentials>} Promise resolving to the built AWS credentials
* @throws {Error} Throws if token is invalid or AWS credentials cannot be created
*
* @example
* ```typescript
* const credentials = await webCore.buildCredentialsByToken(oauthToken);
* // AWS.config.credentials is now set and ready for use
* ```
*/
buildCredentialsByToken(token: LemonOAuthToken): Promise<AWS.Credentials>;
/**
* Builds AWS credentials from cached storage data and sets them in AWS.config.
* Uses previously stored credential information to recreate AWS credentials.
*
* @returns {Promise<AWS.Credentials>} Promise resolving to the built AWS credentials
* @throws {Error} Throws if cached credentials are invalid or AWS credentials cannot be created
*
* @example
* ```typescript
* const credentials = await webCore.buildCredentialsByStorage();
* // AWS.config.credentials is now set from cached data
* ```
*/
buildCredentialsByStorage(): Promise<AWS.Credentials>;
/**
* Saves KMS (Key Management Service) configuration to storage.
* Stores KMS ARN and other encryption-related configuration for later use.
*
* @param {LemonKMS} kms - The KMS configuration object containing ARN and encryption settings
* @returns {Promise<void>} Promise that resolves when KMS configuration is successfully saved
* @throws {Error} Throws if KMS configuration cannot be saved to storage
*/
saveKMS(kms: LemonKMS): Promise<void>;
/**
* Refreshes the cached OAuth token by calling the refresh endpoint.
* Obtains new credentials and updates AWS.config with fresh authentication data.
*
* @param {string} [domain=''] - Optional domain parameter for multi-tenant refresh requests
* @param {string} [url=''] - Optional custom URL for the refresh endpoint, defaults to config.oAuthEndpoint
* @returns {Promise<AWS.Credentials | null>} Promise resolving to new AWS credentials on success,
* null if refresh fails or token is invalid
* @throws {Error} Logs errors but returns null instead of throwing
*
* @example
* ```typescript
* const newCredentials = await webCore.refreshCachedToken();
* if (newCredentials) {
* // Token successfully refreshed
* } else {
* // Refresh failed, user may need to re-authenticate
* }
* ```
*/
refreshCachedToken(domain?: string, url?: string): Promise<AWS.Credentials>;
/**
* Changes the user's active site and obtains new credentials for the target site.
* Useful for multi-tenant applications where users can switch between different sites/organizations.
*
* @param {ChangeSiteBody} changeSiteBody - Object containing siteId and userId for the target site
* @param {string} changeSiteBody.siteId - The identifier of the target site to switch to
* @param {string} changeSiteBody.userId - The user identifier for the site change operation
* @param {string} [url] - Optional custom URL for the site change endpoint
* @returns {Promise<AWS.Credentials>} Promise resolving to new AWS credentials for the target site
* @throws {Error} Throws if changeSiteBody is invalid, authId is missing, or site change fails
*
* @example
* ```typescript
* const credentials = await webCore.changeUserSite({
* siteId: 'new-site-123',
* userId: 'user-456'
* });
* // User is now authenticated for the new site
* ```
*/
changeUserSite(changeSiteBody: ChangeSiteBody, url?: string): Promise<AWS.Credentials>;
/**
* Logs out the user by clearing AWS credentials and removing stored tokens.
* Performs complete cleanup of authentication state.
*
* @returns {Promise<void>} Promise that resolves when logout is complete
* @throws {Error} Throws if token cleanup fails
*
* @example
* ```typescript
* await webCore.logout();
* // User is now logged out, all credentials cleared
* ```
*/
logout(): Promise<void>;
/**
* Configures whether to use the X-Lemon-Identity header in requests.
* Controls identity header inclusion for request identification and tracking.
*
* @param {boolean} use - True to include X-Lemon-Identity header, false to exclude it
* @returns {Promise<void>} Promise that resolves when setting is saved
*/
setUseXLemonIdentity(use: boolean): Promise<void>;
/**
* Configures whether to use the X-Lemon-Language header with a specific key.
* Controls language header inclusion for localization and language preference tracking.
*
* @param {boolean} use - True to include X-Lemon-Language header, false to exclude it
* @param {string} [key] - The language key to use when use is true; required if use is true
* @returns {Promise<void>} Promise that resolves when setting is saved
*
* @example
* ```typescript
* await webCore.setUseXLemonLanguage(true, 'en-US');
* // X-Lemon-Language header will be included with 'en-US' value
* ```
*/
setUseXLemonLanguage(use: boolean, key?: string): Promise<void>;
/**
* Generates a cryptographic signature for token-based operations.
* Creates a time-based signature using stored token information for secure API calls.
*
* @returns {Promise<TokenSignature>} Promise resolving to signature object containing:
* - authId: Authentication identifier
* - current: Current timestamp in ISO format
* - signature: Calculated cryptographic signature
* - originToken: Original token data used for signature
* @throws {Error} Throws if cached token is invalid or signature calculation fails
*/
getTokenSignature(): Promise<TokenSignature>;
/**
* Retrieves current AWS credentials, refreshing them if necessary.
* Checks token validity and performs refresh if the token is expired or near expiration.
*
* @returns {Promise<AWS.Credentials | null>} Promise resolving to current AWS credentials,
* or null if no valid token exists or refresh fails
* @throws {Error} Logs errors but returns null instead of throwing
*
* @example
* ```typescript
* const credentials = await webCore.getCredentials();
* if (credentials) {
* // Use credentials for AWS API calls
* } else {
* // No valid credentials, authentication required
* }
* ```
*/
getCredentials(): Promise<AWS.Credentials | null>;
/**
* Builds AWS credentials from cached storage data.
* Private method that creates AWS.Credentials object from stored credential data.
*
* @private
* @returns {Promise<void>} Promise that resolves when credentials are built and set
* @throws {Error} Throws if cached credentials are missing or invalid
*/
private buildAWSCredentialsByStorage;
/**
* Retrieves the current AWS credentials from AWS.config.
* Private method that validates and returns the currently configured AWS credentials.
*
* @private
* @returns {Promise<AWS.Credentials>} Promise resolving to current AWS credentials
* @throws {Error} Throws if no credentials are configured or credential validation fails
*/
private getCurrentCredentials;
/**
* Builds AWS credentials from an OAuth token and saves to storage.
* Private method that processes token data, saves it to storage, and creates AWS credentials.
*
* @private
* @param {LemonOAuthToken} token - The OAuth token containing credential information
* @returns {Promise<void>} Promise that resolves when token is saved and credentials are created
* @throws {Error} Throws if token is missing required fields or credential creation fails
*/
private buildAWSCredentialsByToken;
/**
* Creates and sets AWS credentials in the global AWS configuration.
* Private method that instantiates AWS.Credentials and assigns it to AWS.config.credentials.
*
* @private
* @param {LemonCredentials} credentials - The credential object containing AWS access keys
* @param {string} credentials.AccessKeyId - AWS access key identifier
* @param {string} credentials.SecretKey - AWS secret access key
* @param {string} [credentials.SessionToken] - Optional AWS session token for temporary credentials
* @returns {void} No return value, sets AWS.config.credentials directly
*/
private createAWSCredentials;
}
/**
* Class to handle Azure-specific web core operations.
* Implements the WebCoreService interface.
*/
declare class AzureWebCore implements WebCoreService {
private readonly config;
private readonly tokenStorage;
private readonly logger;
private sharedAxiosInstance;
/**
* Creates an instance of AzureWebCore.
* @param {WebCoreConfig<'azure'>} config - The configuration for the Azure web core.
*/
constructor(config: WebCoreConfig<'azure'>);
/**
* Initializes the Azure web core by checking for cached tokens.
* @returns {Promise<AzureWebCoreState>} - The state of the Azure web core after initialization.
*/
init(): Promise<AzureWebCoreState>;
/**
* Retrieves the token storage service.
*
* @returns {AzureStorageService} - The storage service that manages OAuth tokens.
*/
getTokenStorage(): AzureStorageService;
/**
* Gets the shared axios instance
* @returns The shared axios instance
*/
getSharedAxiosInstance(): AxiosInstance;
/**
* Builds a request using HttpRequestBuilder without Credentials.
* @param {AxiosRequestConfig} config - The Axios request configuration.
* @returns {HttpRequestBuilder} - The HttpRequestBuilder instance.
*/
buildRequest(config: AxiosRequestConfig): HttpRequestBuilder;
/**
* Executes a HTTP request without Credentials.
* @template T
* @param {string} method - The HTTP method.
* @param {string} url - The request URL.
* @param {Params} [params={}] - The request parameters.
* @param {Body} body - The request body.
* @param {AxiosRequestConfig} [config] - Additional Axios request configuration.
* @returns {Promise<HttpResponse<T>>} - The Axios response.
*/
request<T>(method: string, url: string, params?: Params, body?: Body, config?: AxiosRequestConfig): Promise<HttpResponse<T>>;
/**
* Builds a signed request using the provided Axios configuration.
* @param {AxiosRequestConfig} config - The Axios request configuration.
* @returns {AzureHttpRequestBuilder} - The request builder for the signed request.
*/
buildSignedRequest(config: AxiosRequestConfig): AzureHttpRequestBuilder;
/**
* Executes a signed HTTP request.
* @template T
* @param {string} method - The HTTP method to use for the request.
* @param {string} url - The URL for the request.
* @param {Params} [params={}] - The URL parameters for the request.
* @param {Body} [body] - The request body.
* @param {AxiosRequestConfig} [config] - Additional Axios request configuration.
* @returns {Promise<HttpResponse<T>>} - The Axios response.
*/
signedRequest<T>(method: string, url: string, params?: Params, body?: Body, config?: AxiosRequestConfig): Promise<HttpResponse<T>>;
/**
* Retrieves all saved tokens from the storage.
* @returns {Promise<{ [key: string]: string }>} - An object containing all saved tokens.
*/
getSavedToken(): Promise<{
[key: string]: string;
}>;
/**
* Checks if the user is authenticated.
* @returns {Promise<boolean>} - True if authenticated, otherwise false.
*/
isAuthenticated(): Promise<boolean>;
/**
* Saves an OAuth token to the storage.
* @param {LemonOAuthToken} token - The OAuth token to save.
* @returns {Promise<void>} - A promise that resolves when the token is saved.
*/
saveOAuthToken(token: LemonOAuthToken): Promise<void>;
/**
* Logs the user out by clearing the OAuth token from the storage.
* @returns {Promise<void>} - A promise that resolves when the user is logged out.
*/
logout(): Promise<void>;
/**
* Sets whether to use the x-lemon-identity header.
* @param {boolean} use - True to use the x-lemon-identity header, otherwise false.
* @returns {Promise<void>} - A promise that resolves when the setting is updated.
*/
setUseXLemonIdentity(use: boolean): Promise<void>;
/**
* Sets whether to use the X-Lemon-Language header with a specific key.
* @param {boolean} use - Whether to use the X-Lemon-Language header.
* @param {string} key? - The storage key to set.
*/
setUseXLemonLanguage(use: boolean, key?: string): Promise<void>;
}
/**
* A factory class to create instances of {@link WebCoreService} based on the cloud provider.
*/
declare class WebCoreFactory {
/**
* Creates an instance of {@link WebCoreService} based on the provided configuration.
*
* @param config The configuration for the WebCore service.
* @returns An instance of {@link WebCoreService} specific to the cloud provider.
* @throws Error if the cloud provider is not supported.
*/
static create<T extends CloudProvider>(config: WebCoreConfig<T>): WebCoreServiceMap[T];
}
declare class LocalStorageService {
private storage;
constructor();
setItem(key: string, value: string): void;
getItem