@authava/client
Version:
Client library for seamless integration with Authava's white-label authentication service
420 lines (414 loc) • 13.2 kB
TypeScript
/**
* Generated types from the Authava API specification
*/
type Uuid = string;
type OffsetDateTime = string;
interface MinimalUser {
id: Uuid;
email: string;
roles: string[];
permissions: string[];
teams: TeamContext[];
last_login_at?: OffsetDateTime;
}
interface TeamContext {
id: string;
name: string;
is_owner: boolean;
scopes: Scope[];
}
interface Scope {
resource_type: string;
resource_id: string;
action: string;
}
interface User extends MinimalUser {
status: string;
email_verified: boolean;
created_at: OffsetDateTime;
updated_at: OffsetDateTime;
password_hash?: string;
}
interface ScopeInput {
resource_type: string;
resource_id: string;
actions: string[];
resolver?: (resource_type: string, team: TeamContext) => Promise<string[]>;
}
interface LoginRequest {
email: string;
password: string;
next?: string | null;
}
interface LoginResponse {
user: MinimalUser;
redirect_url: string;
authority: string;
tenant_id: string;
}
interface RegisterRequest {
email: string;
password: string;
}
interface ForgotPasswordRequest {
email: string;
}
interface ResetPasswordRequest {
token: string;
password: string;
}
interface MFAMethodInfo {
id: Uuid;
mfa_type: string;
verified: boolean;
created_at: OffsetDateTime;
last_used_at?: OffsetDateTime;
name?: string;
}
interface MFARequiredResponse {
user_id: Uuid;
session_id: Uuid;
mfa_methods: MFAMethodInfo[];
}
interface MFAVerifyRequest {
session_id: Uuid;
method_id: Uuid;
code: string;
}
interface SendMFAEmailRequest {
session_id: Uuid;
method_id: Uuid;
}
interface SetupEmailMFARequest {
name?: string;
}
interface VerifyEmailMFARequest {
code: string;
}
interface SetupTOTPRequest {
name?: string;
}
interface SetupTOTPResponse {
secret: string;
qr_code: string;
method_id: Uuid;
}
interface VerifyTOTPRequest {
method_id: Uuid;
code: string;
}
interface BackupCodesResponse {
codes: string[];
}
interface ProfileResponse {
user: User;
mfa_methods: MFAMethodInfo[];
notification_preferences: UserNotificationPreferences;
recent_security_events: UserSecurityEvent[];
}
interface AdminCreateUserRequest {
email: string;
username?: string;
password?: string;
password_confirm?: string;
roles?: string[];
skip_email_verification?: boolean;
send_set_password_email?: boolean;
}
interface AdminCreateUserResponse {
user_id: Uuid;
email: string;
username?: string;
email_verified: boolean;
set_password_token?: string;
}
interface AdminCreateTokenRequest {
email?: string;
user_id?: Uuid;
}
interface AdminCreateTokenResponse {
session_token: string;
user: MinimalUser;
}
interface ChangeEmailRequest {
new_email: string;
password: string;
}
interface ChangePasswordRequest {
current_password: string;
new_password: string;
}
interface UserNotificationPreferences {
user_id: Uuid;
security_alerts: boolean;
account_activity: boolean;
product_updates: boolean;
marketing_emails: boolean;
created_at: OffsetDateTime;
updated_at: OffsetDateTime;
}
interface UpdateNotificationPreferencesRequest {
security_alerts: boolean;
account_activity: boolean;
product_updates: boolean;
marketing_emails: boolean;
}
interface UserSecurityEvent {
id: Uuid;
user_id: Uuid;
event_type: string;
created_at: OffsetDateTime;
ip_address?: string;
user_agent?: string;
details?: any;
}
interface AuthavaConfig {
domain: string;
resolverDomain?: string;
secure?: boolean;
autoRefresh?: boolean;
refreshBuffer?: number;
customHeaders?: Record<string, string> | (() => Record<string, string>);
debug?: boolean;
}
interface AuthavaUser {
id: string;
email: string;
roles: string[];
permissions: string[];
teams: TeamContext[];
[key: string]: any;
}
type AuthavaResult<T = void> = {
success: true;
data: T;
} | {
success: false;
error: string;
code?: string;
};
interface AuthavaSession {
user: AuthavaUser;
redirect_url: string;
authority: string;
tenant_id: string;
}
type SessionStatus = 'valid' | 'refreshing' | 'expired' | 'error';
interface SessionState {
status: SessionStatus;
user: AuthavaUser | null;
expiresAt?: Date;
error?: Error;
}
type SessionChangeCallback = (state: SessionState) => void;
interface ErrorResponse {
error: string;
}
interface AuthavaAdminConfig {
resolverDomain: string;
domain: string;
apiKey: string;
secure?: boolean;
debug?: boolean;
}
declare class AuthavaClient {
private config;
private refreshTimer?;
private refreshing;
private currentState;
private subscribers;
private broadcastChannel?;
private autoRefreshConfig;
private authApi;
private profileApi;
private mfaApi;
constructor(config: AuthavaConfig);
hasRoles(roles: string[] | string): boolean;
hasPermissions(permissions: string[] | string): boolean;
hasScopes({ resource_type, resource_id, actions, resolver }: ScopeInput): Promise<boolean>;
private teamHasMatchingScope;
private encodeBase64Url;
private setLogoutReason;
private log;
/**
* Log the user out.
* Clears the session cookie, updates the state, and redirects the user.
*/
logout(reason?: string): Promise<void>;
private getLogoutReason;
/**
* Get the current session if it exists.
* If a session error occurs (including CORS errors), logs out the user.
*/
private fetchFailureCount;
private getTokenFromStorage;
getSession(extraHeaders?: Record<string, string>): Promise<AuthavaSession | null>;
/**
* Subscribe to session changes.
* Returns an unsubscribe function.
*/
onSessionChange(callback: SessionChangeCallback): () => void;
private checkSession;
private getTokenFromCookie;
private getTokenExpiration;
private startAutoRefresh;
private refreshSession;
private updateState;
private notifySubscribers;
private handleSessionBroadcast;
/**
* Login with email and password
*/
login(data: LoginRequest): Promise<AuthavaResult<LoginResponse>>;
/**
* Register a new user
*/
register(data: RegisterRequest): Promise<AuthavaResult<void>>;
/**
* Request a password reset
*/
forgotPassword(data: ForgotPasswordRequest): Promise<AuthavaResult<void>>;
/**
* Reset password with token
*/
resetPassword(data: ResetPasswordRequest): Promise<AuthavaResult<void>>;
/**
* Verify MFA code
*/
verifyMfa(data: MFAVerifyRequest): Promise<AuthavaResult<LoginResponse>>;
/**
* Send MFA verification email
*/
sendMfaEmail(data: SendMFAEmailRequest): Promise<AuthavaResult<void>>;
/**
* Get user profile information
*/
getProfile(): Promise<AuthavaResult<ProfileResponse>>;
/**
* Change email address
*/
changeEmail(data: ChangeEmailRequest): Promise<AuthavaResult<void>>;
/**
* Change password
*/
changePassword(data: ChangePasswordRequest): Promise<AuthavaResult<void>>;
/**
* Update notification preferences
*/
updateNotificationPreferences(data: UpdateNotificationPreferencesRequest): Promise<AuthavaResult<UserNotificationPreferences>>;
/**
* Remove an MFA method
*/
removeMfaMethod(methodId: Uuid): Promise<AuthavaResult<void>>;
/**
* Initialize Email MFA setup
*/
setupEmailMfa(data: SetupEmailMFARequest): Promise<AuthavaResult<void>>;
/**
* Verify and activate Email MFA
*/
verifyEmailMfa(data: VerifyEmailMFARequest): Promise<AuthavaResult<BackupCodesResponse>>;
/**
* Initialize TOTP MFA setup
*/
setupTotp(data: SetupTOTPRequest): Promise<AuthavaResult<SetupTOTPResponse>>;
/**
* Verify and activate TOTP MFA
*/
verifyTotp(data: VerifyTOTPRequest): Promise<AuthavaResult<BackupCodesResponse>>;
}
/**
* Authava Admin Client — backend-only operations using API key authentication.
*
* This client is designed for server-side use only (Node.js, Deno, Bun).
* It has NO browser dependencies (no document, localStorage, window, etc.).
*
* Use this for:
* - Creating users without passwords (e.g., admin provisioning)
* - Generating session tokens without passwords (e.g., magic links)
*
* @example
* ```typescript
* import { AuthavaAdminClient } from '@authava/client'
*
* const admin = new AuthavaAdminClient({
* resolverDomain: 'auth.example.com',
* domain: 'app.example.com',
* apiKey: 'ak_clientid_secret',
* })
*
* // Create a user and email them a "set your password" link
* const result = await admin.createUser({
* email: 'user@example.com',
* send_set_password_email: true,
* skip_email_verification: true,
* })
*
* // Generate a magic link token for passwordless login
* const tokenResult = await admin.createToken({
* email: 'user@example.com',
* })
* if (tokenResult.success) {
* // Use tokenResult.data.session_token to set the session cookie
* }
* ```
*/
declare class AuthavaAdminClient {
private api;
constructor(config: AuthavaAdminConfig);
/**
* Create a user without a password.
*
* @param data.email - User's email address (required)
* @param data.username - Optional username
* @param data.roles - Optional role names to assign
* @param data.skip_email_verification - If true, marks email as verified immediately
* @param data.send_set_password_email - If true, sends a "set your password" email
*/
createUser(data: AdminCreateUserRequest): Promise<AuthavaResult<AdminCreateUserResponse>>;
/**
* Generate a session token for a user without requiring a password.
* This enables magic link flows where your application authenticates the user
* through its own mechanism, then obtains an Authava session token.
*
* @param data.email - User's email address (provide either email or user_id)
* @param data.user_id - User's UUID (provide either email or user_id)
*/
createToken(data: AdminCreateTokenRequest): Promise<AuthavaResult<AdminCreateTokenResponse>>;
}
declare class MockAuthavaClient {
private currentState;
private subscribers;
private config;
private mockMfaMethods;
private mockUser;
constructor(config?: Partial<AuthavaConfig> & {
mockUser?: User;
});
private createSuccessResponse;
private createVoidSuccessResponse;
private createErrorResponse;
private log;
getSession(): Promise<AuthavaSession | null>;
setSession(session: AuthavaSession): void;
expireSession(): void;
onSessionChange(callback: SessionChangeCallback): () => void;
private notifySubscribers;
logout(): Promise<AuthavaResult<void>>;
login(data: LoginRequest): Promise<AuthavaResult<LoginResponse>>;
register(data: RegisterRequest): Promise<AuthavaResult<void>>;
forgotPassword(data: ForgotPasswordRequest): Promise<AuthavaResult<void>>;
resetPassword(data: ResetPasswordRequest): Promise<AuthavaResult<void>>;
verifyMfa(data: MFAVerifyRequest): Promise<AuthavaResult<LoginResponse>>;
sendMfaEmail(data: SendMFAEmailRequest): Promise<AuthavaResult<void>>;
getProfile(): Promise<AuthavaResult<ProfileResponse>>;
changeEmail(data: ChangeEmailRequest): Promise<AuthavaResult<void>>;
changePassword(data: ChangePasswordRequest): Promise<AuthavaResult<void>>;
updateNotificationPreferences(data: UpdateNotificationPreferencesRequest): Promise<AuthavaResult<UserNotificationPreferences>>;
removeMfaMethod(methodId: Uuid): Promise<AuthavaResult<void>>;
setupEmailMfa(data: SetupEmailMFARequest): Promise<AuthavaResult<void>>;
verifyEmailMfa(data: VerifyEmailMFARequest): Promise<AuthavaResult<BackupCodesResponse>>;
setupTotp(data: SetupTOTPRequest): Promise<AuthavaResult<SetupTOTPResponse>>;
verifyTotp(data: VerifyTOTPRequest): Promise<AuthavaResult<BackupCodesResponse>>;
}
export { type AdminCreateTokenRequest, type AdminCreateTokenResponse, type AdminCreateUserRequest, type AdminCreateUserResponse, AuthavaAdminClient, type AuthavaAdminConfig, AuthavaClient, type AuthavaConfig, type AuthavaResult, type AuthavaSession, type AuthavaUser, type BackupCodesResponse, type ChangeEmailRequest, type ChangePasswordRequest, type ErrorResponse, type ForgotPasswordRequest, type LoginRequest, type LoginResponse, type MFAMethodInfo, type MFARequiredResponse, type MFAVerifyRequest, type MinimalUser, MockAuthavaClient, type OffsetDateTime, type ProfileResponse, type RegisterRequest, type ResetPasswordRequest, type Scope, type SendMFAEmailRequest, type SessionChangeCallback, type SessionState, type SessionStatus, type SetupEmailMFARequest, type SetupTOTPRequest, type SetupTOTPResponse, type TeamContext, type UpdateNotificationPreferencesRequest, type User, type UserNotificationPreferences, type UserSecurityEvent, type Uuid, type VerifyEmailMFARequest, type VerifyTOTPRequest };