UNPKG

@narangcia-oss/cryptic-auth-client-plain-ts

Version:

A TypeScript client for interacting with a cryptic-auth host web server, crafted by Narangcia OSS.

274 lines (265 loc) 8.21 kB
import { AxiosInstance } from 'axios'; /** * Core authentication types for the auth package */ interface AuthTokens { access_token: string; refresh_token?: string; user_id?: string; token_type?: string; expires_in?: number; } interface UserCredentials { username: string; password: string; } interface SignupResponse { id: string; identifier: string; } interface LoginResponse { id: string; identifier: string; access_token: string; refresh_token: string; } interface TokenValidationResponse { valid: boolean; claims: { sub: string; exp: number; }; } interface OAuthAuthResponse { auth_url: string; } interface OAuthSignupResponse { id: string; access_token: string; refresh_token: string; oauth_info: { provider: string; email: string; name: string; }; } interface OAuthCallbackParams { code: string; state: string; } interface AuthConfig { baseURL: string; enableAutoRefresh?: boolean; tokenStorage?: "memory" | "localStorage" | "sessionStorage" | "custom"; } interface AuthState { isAuthenticated: boolean; isLoading: boolean; user: AuthUser | null; tokens: AuthTokens | null; } interface AuthUser { id: string; identifier: string; oauth_info?: { provider: string; email: string; name: string; }; } interface AuthContextValue extends AuthState { login: (credentials: UserCredentials) => Promise<void>; signup: (credentials: UserCredentials) => Promise<void>; logout: () => void; oauthLogin: (provider: string) => Promise<void>; refreshToken: () => Promise<void>; } /** * Token utility functions */ /** * Checks if a token is expired based on its timestamp */ declare function isTokenExpired(exp: number): boolean; /** * Extracts tokens from auth response */ declare function extractTokens(response: LoginResponse | OAuthSignupResponse): AuthTokens; /** * Stores tokens securely (placeholder for future custom storage) */ declare function storeTokens(tokens: AuthTokens, storage?: "memory" | "localStorage" | "sessionStorage"): void; /** * Retrieves stored tokens */ declare function retrieveTokens(storage?: "memory" | "localStorage" | "sessionStorage"): AuthTokens | null; /** * Clears stored tokens */ declare function clearStoredTokens(storage?: "memory" | "localStorage" | "sessionStorage"): void; /** * Extract token expiration time from JWT token */ declare function getTokenExpiration(token: string): Date | null; /** * Check if a token is expired or will expire within a certain timeframe */ declare function isTokenExpiring(token: string, bufferMinutes?: number): boolean; /** * Get token payload without verification (client-side only) */ declare function getTokenPayload(token: string): Record<string, any> | null; /** * Format tokens for secure storage */ declare function formatTokensForStorage(tokens: AuthTokens): string; /** * Parse tokens from secure storage */ declare function parseTokensFromStorage(stored: string): AuthTokens | null; /** * Core authentication client for handling all auth flows * Handles login, signup, OAuth, token refresh, and validation */ declare class AuthClient { private api; private accessToken; private refreshToken; private isRefreshing; private failedQueue; private config; constructor(config: AuthConfig); private setupInterceptors; private processQueue; setTokens(accessToken: string, refreshToken?: string): void; clearTokens(): void; getAccessToken(): string | null; getRefreshToken(): string | null; isAuthenticated(): boolean; login(credentials: UserCredentials): Promise<LoginResponse>; signup(credentials: UserCredentials): Promise<SignupResponse>; private refreshTokenFlow; validateToken(token: string): Promise<TokenValidationResponse>; healthCheck(): Promise<unknown>; generateOAuthAuthUrl(provider: string, state: string, scopes: string[]): Promise<string>; oauthLoginCallback(provider: string, params: OAuthCallbackParams): Promise<LoginResponse>; oauthSignupCallback(provider: string, params: OAuthCallbackParams): Promise<OAuthSignupResponse>; getAxiosInstance(): AxiosInstance; static extractTokens: typeof extractTokens; static isTokenExpired: typeof isTokenExpired; } interface OAuthCallbackResult { success: boolean; tokens?: AuthTokens; user?: AuthUser; error?: string; } /** * Core OAuth callback handler - framework agnostic * Handles the OAuth callback flow logic without any UI dependencies */ declare class OAuthCallbackHandler { private authClient; constructor(authClient: AuthClient); /** * Checks if the current URL is an OAuth callback URL */ isOAuthCallback(): boolean; /** * Processes the OAuth callback from the current URL * Returns the result without any UI side effects */ processCallback(): Promise<OAuthCallbackResult>; /** * Extracts the OAuth provider from the current URL * Override this method for custom provider detection logic */ protected extractProviderFromUrl(): string; /** * Cleans the OAuth parameters from the current URL */ cleanUrl(): void; } /** * OAuth utility functions */ /** * Generates a secure random state for OAuth CSRF protection */ declare function generateOAuthState(): string; /** * Stores OAuth state securely for validation */ declare function storeOAuthState(state: string): void; /** * Retrieves stored OAuth state for validation */ declare function getStoredOAuthState(): string | null; /** * Clears stored OAuth state */ declare function clearOAuthState(): void; /** * Validates OAuth state to prevent CSRF attacks */ declare function validateOAuthState(receivedState: string): boolean; /** * Extracts OAuth callback parameters from URL */ declare function extractOAuthParams(): { code: string | null; state: string | null; error: string | null; }; /** * Checks if current URL is an OAuth callback */ declare function isOAuthCallback(): boolean; /** * Cleans OAuth parameters from URL */ declare function cleanOAuthUrl(): void; interface OAuth2FragmentResult { success: boolean; tokens?: AuthTokens; error?: string; errorDescription?: string; } /** * OAuth2 Fragment Handler for processing tokens from URL fragments * This handles the new OAuth2 flow where the backend redirects to frontend with tokens */ declare class OAuth2FragmentHandler { private static hasProcessed; private static currentFragment; /** * Checks if the current URL contains OAuth2 fragment parameters */ static isOAuth2Fragment(): boolean; /** * Resets the processing state (for testing or manual reset) */ static resetProcessingState(): void; /** * Processes OAuth2 tokens from URL fragment */ static processFragment(): OAuth2FragmentResult; /** * Clears OAuth2 parameters from URL fragment for security */ static clearFragment(): void; /** * Complete OAuth2 fragment processing - process and clean up */ static processAndClear(): OAuth2FragmentResult; } /** * Utility function to check if current page is an OAuth2 callback */ declare function isOAuth2Callback(): boolean; /** * Utility function to extract OAuth2 tokens from URL fragment */ declare function extractOAuth2Tokens(): OAuth2FragmentResult; export { AuthClient, OAuth2FragmentHandler, OAuthCallbackHandler, cleanOAuthUrl, clearOAuthState, clearStoredTokens, extractOAuth2Tokens, extractOAuthParams, extractTokens, formatTokensForStorage, generateOAuthState, getStoredOAuthState, getTokenExpiration, getTokenPayload, isOAuth2Callback, isOAuthCallback, isTokenExpired, isTokenExpiring, parseTokensFromStorage, retrieveTokens, storeOAuthState, storeTokens, validateOAuthState }; export type { AuthConfig, AuthContextValue, AuthState, AuthTokens, AuthUser, LoginResponse, OAuth2FragmentResult, OAuthAuthResponse, OAuthCallbackParams, OAuthCallbackResult, OAuthSignupResponse, SignupResponse, TokenValidationResponse, UserCredentials };