/** * ============================================================================ * @amaster.ai/auth-client - Type Definitions * ============================================================================ * * πŸ€– AI NAVIGATION - Read these files based on your task: * * 1. Need LOGIN/REGISTER/LOGOUT? β†’ Read: ./auth.d.ts * 2. Need PERMISSION checks? β†’ Read: ./permissions.d.ts * 3. Need USER profile management? β†’ Read: ./user.d.ts * 4. Need OAUTH binding? β†’ Read: ./oauth.d.ts * 5. Need SESSION management? β†’ Read: ./sessions.d.ts * * ============================================================================ */ import { MiniProgramRuntime } from '@amaster.ai/http-client'; /** * Authentication SDK Types */ /** * Authentication client configuration options * * @example * Minimal configuration (recommended): * ```typescript * const authClient = createAuthClient(); * ``` * * @example * With callbacks: * ```typescript * const authClient = createAuthClient({ * onTokenExpired: () => window.location.href = "/login", * onUnauthorized: () => alert("Session expired"), * }); * ``` * */ interface AuthClientOptions { /** * API base URL (defaults to window.location.origin) * @example "https://api.example.com" */ baseURL?: string; /** * Default headers to include in all requests * Useful for adding tenant IDs, API keys, or other common headers * @example { "x-tenant-id": "tenant123", "x-api-key": "key123" } */ headers?: Record; /** * Callback when token expires * @example () => window.location.href = "/login" */ onTokenExpired?: () => void; /** * Callback when server returns 401 Unauthorized * @example () => alert("Session expired") */ onUnauthorized?: () => void; /** * Automatically handle OAuth callback on initialization * When enabled, the client will automatically detect and process OAuth callback URLs with #access_token * @default true * @example * ```typescript * // Enable auto-handling (default) * const authClient = createAuthClient({ * autoHandleOAuthCallback: true, * }); * * // Disable if you want to handle OAuth callback manually * const authClient = createAuthClient({ * autoHandleOAuthCallback: false, * }); * await authClient.handleOAuthCallback(); // Call manually when needed * ``` */ autoHandleOAuthCallback?: boolean; /** * Automatically redirect to the current page's `?redirect=...` target after any successful login * * This applies to password login, code login, registration auto-login, mini-program login, * and OAuth callback processing. Set to `false` if your application wants to fully control * post-login navigation. * * @default true */ autoRedirectAfterLogin?: boolean; /** * Explicitly provide the Taro runtime object when it is not exposed on `globalThis`. */ runtime?: Partial; } /** * User information with roles and permissions * * Note: This is an optimized format for client-side use. * - roles: Only role codes (e.g., ["admin", "user"]) * - permissions: Only permission names (e.g., ["user.read", "user.write"]) * - dataScopes: Not included * * @example * ```typescript * const user: User = { * uid: "123", * email: "user@example.com", * displayName: "John Doe", * roles: ["admin", "user"], * permissions: ["user.read", "user.write", "order.read"], * // ... other fields * }; * * // Check permissions * if (user.permissions.includes("user.delete")) { * // Can delete users * } * ``` */ interface User { /** Unique user ID */ uid: string; /** Username (null if not set) */ username: string | null; /** Email address (null if not set) */ email: string | null; /** Phone number (null if not set) */ phone: string | null; /** Display name for UI */ displayName: string | null; /** Avatar image URL */ avatarUrl: string | null; /** Whether account is active */ isActive: boolean; /** Whether email is verified */ emailVerified: boolean; /** Whether phone is verified */ phoneVerified: boolean; /** Email verification timestamp */ emailVerifiedAt: string | null; /** Phone verification timestamp */ phoneVerifiedAt: string | null; /** * Role codes assigned to user * @example ["admin", "user", "manager"] */ roles: string[]; /** * Permission names granted to user * @example ["user.read", "user.write", "order.read"] */ permissions: string[]; /** Account creation timestamp */ createdAt: string; /** Last update timestamp */ updatedAt: string; } /** Detailed role information (for admin/management use) */ interface RoleDetail { id: number; code: string; displayName: string; description?: string; isSystem: boolean; } /** Detailed permission information (for admin/management use) */ interface PermissionDetail { id: number; name: string; resource: string; action: string; description?: string; sourceType: "system" | "role" | "direct"; } /** @deprecated Use string[] for roles in User type */ interface Role { id: number; code: string; displayName: string; description?: string; isSystem: boolean; } /** @deprecated Use string[] for permissions in User type */ interface Permission { id: number; name: string; resource: string; action: string; description?: string; sourceType: "system" | "role" | "direct"; } /** * User registration parameters * At least one of username/email/phone must be provided * * @example * Register with email: * ```typescript * const params: RegisterParams = { * email: "user@example.com", * password: "Password@123", * displayName: "John Doe", * }; * ``` * * @example * Register with captcha: * ```typescript * const captcha = await authClient.getCaptcha(); * const userInput = "AB12"; // User enters this * const params: RegisterParams = { * email: "user@example.com", * password: "Password@123", * captcha: `${captcha.data.captchaId}:${userInput}`, * }; * ``` */ interface RegisterParams { /** Username (optional, at least one of username/email/phone required) */ username?: string; /** Email address (optional, at least one of username/email/phone required) */ email?: string; /** Phone number (optional, at least one of username/email/phone required) */ phone?: string; /** * Password (required) * @example "Password@123" */ password: string; /** * Display name for UI * @example "John Doe" */ displayName?: string; /** * Captcha verification (optional) * Format: "captchaId:userInput" * @example "uuid-123:AB12" */ captcha?: string; } /** * Login type: username, email, or phone */ type LoginType = "username" | "email" | "phone"; /** * Login parameters for password-based authentication * * @example * Login with email (auto-detect loginType): * ```typescript * const params: LoginParams = { * email: "user@example.com", * password: "Password@123", * }; * ``` * * @example * Login with username (explicit loginType): * ```typescript * const params: LoginParams = { * loginType: "username", * username: "john_doe", * password: "Password@123", * }; * ``` */ interface LoginParams { /** * Login method: "username" | "email" | "phone" * Optional: Will be auto-detected based on provided fields */ loginType?: LoginType; /** Username (required if loginType="username") */ username?: string; /** Email (required if loginType="email") */ email?: string; /** Phone (required if loginType="phone") */ phone?: string; /** Password (always required) */ password: string; } type CodeLoginType = "email" | "phone"; /** * Code login parameters * * @example * Login with email code (auto-detect loginType): * ```typescript * const params: CodeLoginParams = { * email: "user@example.com", * code: "123456", * }; * ``` */ interface CodeLoginParams { /** * Login method: "email" | "phone" * Optional: Will be auto-detected based on provided fields */ loginType?: CodeLoginType; email?: string; phone?: string; code: string; } type SendCodeType = "email" | "phone"; interface SendCodeParams { type: SendCodeType; email?: string; phone?: string; } /** * Login response with user info and access token * Both user and accessToken are required for successful login * * @example * ```typescript * const result = await authClient.login({ ... }); * if (result.data) { * const { user, accessToken } = result.data; * console.log(`Welcome ${user.displayName}`); * console.log(`Token: ${accessToken}`); * } * ``` */ interface LoginResponse { /** User information with roles and permissions */ user: User; /** Access token (JWT) for API authentication */ accessToken: string; /** Token expiration time in seconds */ expiresIn?: number; /** * Whether the SDK has already consumed the current page's `?redirect=...` * and started browser navigation. * * Use this to avoid running application-level success redirects twice. */ redirectHandled?: boolean; /** * The redirect target consumed by the SDK when `redirectHandled` is `true`. */ redirectTarget?: string; } /** * Register response - user and accessToken are optional * depending on backend configuration: * - Both returned: Auto-login after registration * - Only user: Registration successful but requires email verification * - Neither: Registration successful, user must login separately * * @example * ```typescript * const result = await authClient.register({ ... }); * if (result.data?.user && result.data?.accessToken) { * console.log("Registered and logged in:", result.data.user); * } else { * console.log("Registered, please verify email or login manually"); * } * ``` */ interface RegisterResponse { /** User information with roles and permissions (optional) */ user?: User; /** Access token (JWT) for API authentication (optional) */ accessToken?: string; } /** * Captcha response with image and verification ID * * @example * ```typescript * const result = await authClient.getCaptcha(); * if (result.data) { * // Display image to user * document.getElementById("img").src = result.data.captchaImage; * * // After user inputs code, verify with: * const captcha = `${result.data.captchaId}:${userInputCode}`; * } * ``` */ interface CaptchaResponse { /** Unique captcha ID for verification */ captchaId: string; /** Base64 encoded captcha image (data:image/png;base64,...) */ captchaImage: string; /** Expiration time in seconds (typically 300 = 5 minutes) */ expiresIn: number; } interface RefreshTokenResponse { accessToken: string; } interface UpdateMeParams { displayName?: string; avatarUrl?: string; } interface ChangePasswordParams { oldPassword: string; newPassword: string; } /** * OAuth provider types * - google: Google OAuth * - github: GitHub OAuth * - wechat: WeChat Open Platform OAuth (for web/mobile apps) * - wechat_mini: legacy mini-program provider marker kept for compatibility * - platform: AMaster Platform OAuth */ type OAuthProvider = "google" | "github" | "wechat" | "wechat_mini" | "platform"; interface OAuthBinding { provider: OAuthProvider; providerId: string; email: string; displayName: string; avatarUrl: string | null; createdAt: string; } /** * Mini Program platform type * - wechat: WeChat Mini Program * - douyin: Douyin Mini Program */ type MiniProgramPlatform = "wechat" | "douyin"; /** * Unified Mini Program login options */ interface MiniLoginParams { /** * Optional explicit platform override. * When omitted, the SDK auto-detects the current mini-program runtime. */ platform?: MiniProgramPlatform; } /** * Mini Program login parameters * @example * ```typescript * // WeChat * await authClient.miniLogin(); * * // Douyin * await authClient.miniLogin({ * platform: "douyin", * }); * ``` */ interface MiniProgramLoginParams { /** Code from mini-program login API, valid for a short time */ code: string; /** * Optional explicit platform override * When omitted, the SDK will auto-detect the current mini-program runtime. */ platform?: MiniProgramPlatform; } /** * Mini Program phone number parameters * @example * ```typescript * // WeChat WXML * * * // JS * async onGetPhoneNumber(e) { * await authClient.miniGetPhone(e); * } * * // Douyin * await authClient.miniGetPhone({ * code, * platform: "douyin", * }); * ``` */ interface MiniProgramPhoneParams { /** Code from getPhoneNumber button event */ code: string; /** * Optional explicit platform override * When omitted, the SDK will auto-detect the current mini-program runtime. */ platform?: MiniProgramPlatform; } /** * Mini Program phone event-like payload * Compatible with WeChat `wx`, Douyin `tt`, and Taro event objects. */ interface MiniGetPhoneEvent { code?: string; platform?: MiniProgramPlatform; detail?: { code?: string; } | null; } /** * Unified Mini Program phone input */ type MiniGetPhoneParams = string | MiniProgramPhoneParams | MiniGetPhoneEvent; /** * WeChat Mini Program phone number response */ interface MiniProgramPhoneResponse { /** Phone number with country code (e.g., "+8613800138000") */ phone: string; /** Whether the phone number is verified by WeChat */ phoneVerified: boolean; } /** * Session information for multi-device management * * @example * ```typescript * { * id: 241, * sessionName: "Chrome on MacOS", * ipAddress: "175.22.9.4", * location: "Beijing, China", * userAgent: "Mozilla/5.0...", * lastUsedAt: "2024-01-01T12:00:00Z", * createdAt: "2024-01-01T00:00:00Z", * isCurrent: true * } * ``` */ interface Session { /** Session ID (numeric) */ id: number; /** Session name (e.g., "Chrome on MacOS") - optional */ sessionName?: string; /** IP address - optional */ ipAddress?: string; /** Login location (e.g., "Beijing, China") - optional */ location?: string; /** User agent string - optional */ userAgent?: string; /** Last used timestamp - optional */ lastUsedAt?: string; /** Session creation timestamp */ createdAt: string; /** Whether this is the current session */ isCurrent: boolean; } type AuthEvent = "login" | "logout" | "tokenExpired" | "tokenRefreshed" | "unauthorized"; type EventHandler = (...args: any[]) => void; /** * Standard success response from backend * @example * ```typescript * { * statusCode: 200, * message: "ζ“δ½œζˆεŠŸ", * timestamp: "2026-02-02T08:17:11.045072301Z" * } * ``` */ interface SuccessResponse { statusCode: number; message?: string; timestamp?: string; } /** * Revoke all sessions response * @example * ```typescript * { * statusCode: 200, * message: "ε·²ζ’€ι”€ζ‰€ζœ‰δΌšθ―", * timestamp: "2026-02-02T08:17:11.045072301Z", * revokedCount: 3 * } * ``` */ interface RevokeAllSessionsResponse { statusCode: number; message?: string; timestamp?: string; revokedCount: number; } export type { AuthClientOptions as A, ChangePasswordParams as C, EventHandler as E, LoginParams as L, MiniGetPhoneEvent as M, OAuthBinding as O, Permission as P, RefreshTokenResponse as R, SendCodeParams as S, UpdateMeParams as U, AuthEvent as a, CaptchaResponse as b, CodeLoginParams as c, CodeLoginType as d, LoginResponse as e, LoginType as f, MiniGetPhoneParams as g, MiniLoginParams as h, MiniProgramLoginParams as i, MiniProgramPlatform as j, MiniProgramPhoneParams as k, MiniProgramPhoneResponse as l, OAuthProvider as m, PermissionDetail as n, RegisterParams as o, RegisterResponse as p, RevokeAllSessionsResponse as q, Role as r, RoleDetail as s, SendCodeType as t, Session as u, SuccessResponse as v, User as w };