import { ApiClient } from '@microsoft/rayfin-lib'; import { SignUpCredentials, SignUpResponse, PasswordGrantCredentials, TokenResponse, SignOutAllResponse, JwksResponse, PasswordResetRequest, PasswordResetResponse, ResendVerificationEmailRequest, ResendVerificationEmailResponse, CompletePasswordResetRequest, EmailVerificationResponse, MagicLinkRequest, MagicLinkResponse, VerificationCodeExchangeRequest, AuthSettingsConfig } from './types.js'; /** * Manages all authentication-related API interactions. */ export declare class AuthApi { private apiClient; /** * @param apiClient - An instance of ApiClient configured for your service. */ constructor(apiClient: ApiClient); /** * Helper to map error responses to AuthError */ private mapError; /** * Attaches a dynamic access token provider used to populate the * `Authorization` header on outgoing requests. Used by {@link Auth} to keep * the access token concealed. * * @param provider - Function returning the current access token, or `null` when signed out. */ setAccessTokenProvider(provider: () => string | null): void; /** * Attaches an automatic token refresh callback invoked on `401` responses * before the request is retried. Used by {@link Auth} for transparent * session refresh. * * @param callback - Async function that refreshes the session. */ setRefreshCallback(callback: () => Promise): void; /** * Registers a new user with email and password. * * After successful signup, clients must call signIn() to obtain an access token. * This design supports future email verification flows where token issuance * occurs only after email verification is complete. * * @param credentials - The email and password for the new user. * @returns A promise that resolves with the signup response (userId, email, role, createdAt). * @throws `AuthError` - If signup fails (e.g., email already registered, invalid request). * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * // Step 1: Sign up * const signupResponse = await authApi.signUp({ email: 'user@example.com', password: 'password123' }); * console.log('User created:', signupResponse.userId); * * // Step 2: Sign in to get access token * const tokenResponse = await authApi.signIn({ email: 'user@example.com', password: 'password123' }); * console.log('Access token:', tokenResponse.accessToken); * ``` */ signUp(credentials: SignUpCredentials): Promise; /** * Authenticates a user with email and password using OAuth 2.1 password grant (ROPC). * * Returns an access token (JWT signed with asymmetric keys) and optionally a refresh token. * * @param credentials - The email and password for authentication. * @returns A promise that resolves with the OAuth 2.1 token response. * @throws `AuthError` - If signin fails due to invalid credentials. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * const tokenResponse = await authApi.signIn({ * email: 'user@example.com', * password: 'password123' * }); * * console.log('Access token:', tokenResponse.accessToken); * console.log('Expires in:', tokenResponse.expiresIn, 'seconds'); * ``` */ signIn(credentials: PasswordGrantCredentials): Promise; /** * Refreshes an access token using a refresh token (OAuth 2.0 Refresh Token Grant per RFC 6749 Section 6). * * @param refreshToken - The refresh token to use for obtaining a new access token. * @returns A promise that resolves with the new token response. * @throws `AuthError` - If the refresh token is invalid or expired. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * const tokenResponse = await authApi.refreshToken(storedRefreshToken); * console.log('New access token:', tokenResponse.accessToken); * ``` */ refreshToken(refreshToken: string): Promise; /** * Revokes an access token (OAuth 2.0 Token Revocation per RFC 7009). * * The client must be authenticated using the Authorization header. * Returns success regardless of token validity (per RFC 7009). * * @param token - The access token to revoke. If not provided, uses the current authenticated token. * @returns A promise that resolves when signout is complete. * @throws `AuthError` - If client authentication fails. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * await authApi.signOut(accessToken); * console.log('Token revoked successfully'); * ``` */ signOut(token: string): Promise; /** * Revokes all active sessions for the authenticated user. * * This invalidates all tokens issued to the user, forcing re-authentication. * Useful for security incidents or password changes. * * @param bearerToken - The current access token for authentication. * @returns A promise that resolves with the count of sessions revoked. * @throws `AuthError` - If client authentication fails. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * const result = await authApi.signOutAll(accessToken); * console.log(`Revoked ${result.count} sessions`); * ``` */ signOutAll(bearerToken: string): Promise; /** * Retrieves the JSON Web Key Set (JWKS) containing public keys for JWT verification. * * This endpoint provides public keys used to verify JWT access tokens issued by * the authorization server. Follows RFC 7517 (JSON Web Key) and OpenID Connect * Discovery standards. * * @returns A promise that resolves with the JWKS containing public keys. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * const jwks = await authApi.getJwks(); * console.log('Public keys:', jwks.keys); * * // Example key structure for ES256: * // { * // kty: "EC", * // use: "sig", * // kid: "rayfin-key-2024", * // alg: "ES256", * // crv: "P-256", * // x: "...", * // y: "..." * // } * ``` */ getJwks(): Promise; /** * Verifies a user's email address with a verification token. * * This method is called after a user clicks the verification link in their email. * Upon success, the user's email is marked as verified and they can sign in. * * @param token - The verification token from the email link. * @returns A promise that resolves with the verification response. * @throws `AuthError` - If the token is invalid, expired, or already used. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * // Extract token from URL query parameter * const urlParams = new URLSearchParams(window.location.search); * const token = urlParams.get('token'); * * if (token) { * const result = await authApi.verifyEmail(token); * console.log(result.message); // "Email verified successfully!" * } * ``` */ verifyEmail(token: string): Promise; /** * Resends the email verification link to the specified email address. * * This allows users to request a new verification email if they didn't receive * the original or if it expired. Previous unused verification tokens are automatically * invalidated. For security, always returns success to prevent email enumeration. * * @param request - The resend request with email address. * @returns A promise that resolves with a success message. * @throws `AuthError` - If the request is invalid. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * const result = await authApi.resendVerificationEmail({ email: 'user@example.com' }); * console.log(result.message); // "If an account exists with this email and is unverified, a verification link has been sent." * ``` */ resendVerificationEmail(request: ResendVerificationEmailRequest): Promise; /** * Requests a password reset email for the specified email address. * * This initiates the password reset flow. If an account exists with the provided * email, a reset link will be sent. For security, always returns success to * prevent email enumeration attacks. * * @param request - The password reset request with email address. * @returns A promise that resolves with a success message. * @throws `AuthError` - If the request is invalid. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * const result = await authApi.requestPasswordReset({ email: 'user@example.com' }); * console.log(result.message); // "If an account exists with this email, a reset link has been sent." * ``` */ requestPasswordReset(request: PasswordResetRequest): Promise; /** * Completes the password reset process with a reset token and new password. * * This method is called after a user clicks the reset link in their email and * submits a new password. Upon success, all existing sessions are invalidated * for security and the user must sign in with the new password. * * @param request - The reset completion request with token and new password. * @returns A promise that resolves with a success message. * @throws `AuthError` - If the token is invalid, expired, or already used. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * // Extract token from URL query parameter * const urlParams = new URLSearchParams(window.location.search); * const token = urlParams.get('token'); * * if (token) { * const result = await authApi.completePasswordReset({ * token, * newPassword: 'newSecurePassword123' * }); * console.log(result.message); // "Password updated successfully." * } * ``` */ completePasswordReset(request: CompletePasswordResetRequest): Promise; /** * Sends a magic link email for passwordless authentication. * * This initiates the magic link authentication flow. The user will receive * an email with a link containing a verification code and state parameter. * When clicked, the link redirects to the specified redirect URI with the * code and state as query parameters. * * PKCE is used to protect the flow: the codeChallenge is sent with this request, * and the corresponding codeVerifier must be provided when exchanging the code * for tokens. * * @param request - The magic link request with email, codeChallenge, state, and redirectUri. * @returns A promise that resolves with success status. * @throws `AuthError` - If magic link is disabled or request is invalid. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * const response = await authApi.sendMagicLink({ * email: 'user@example.com', * codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', * state: 'xyzzy123', * redirectUri: 'https://myapp.com/auth/callback' * }); * console.log(response.success); // true * ``` */ sendMagicLink(request: MagicLinkRequest): Promise; /** * Exchanges a verification code for access and refresh tokens. * * This is the second step of the magic link authentication flow. * Called after the user clicks the magic link and is redirected back * to your application with a verification code. * * Uses PKCE: the codeVerifier must match the codeChallenge sent during sendMagicLink. * The redirectUri must also match the one sent during sendMagicLink. * * @param request - The exchange request with verificationCode, codeVerifier, and redirectUri. * @returns A promise that resolves with the OAuth 2.1 token response. * @throws `AuthError` - If the code is invalid, expired, or PKCE validation fails. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * const tokenResponse = await authApi.exchangeVerificationCode({ * verificationCode: 'abc123...', * codeVerifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk', * redirectUri: 'https://myapp.com/auth/callback' * }); * console.log('Access token:', tokenResponse.accessToken); * ``` */ exchangeVerificationCode(request: VerificationCodeExchangeRequest): Promise; /** * Fetches auth settings from the backend project configuration. * Use this to dynamically configure UI based on enabled auth methods. * * This endpoint is public and does not require authentication. * * @returns A promise that resolves with the auth settings configuration. * @throws `NetworkError` - For network-related issues. * * @example * ```typescript * const settings = await authApi.getAuthSettings(); * * // Check available methods * if (settings.password.enabled) { * // Show password login form * } * if (settings.passwordless.magicLink.enabled) { * // Show magic link option * } * * // Or use the convenience array * settings.availableMethods.forEach(method => { * console.log(`${method} is available`); * }); * ``` */ getAuthSettings(): Promise; } //# sourceMappingURL=AuthApi.d.ts.map