@55387.ai/uniauth-client 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,500 @@
1
+ /**
2
+ * HTTP Utilities for UniAuth Client SDK
3
+ * UniAuth 客户端 SDK HTTP 工具
4
+ *
5
+ * Provides robust HTTP request handling with:
6
+ * - Automatic retry with exponential backoff
7
+ * - Timeout handling
8
+ * - Request/response interceptors
9
+ */
10
+ /**
11
+ * HTTP fetch options with retry configuration
12
+ */
13
+ interface FetchWithRetryOptions extends RequestInit {
14
+ /** Maximum number of retry attempts (default: 3) */
15
+ maxRetries?: number;
16
+ /** Base delay in ms between retries (default: 500) */
17
+ baseDelay?: number;
18
+ /** Request timeout in ms (default: 30000) */
19
+ timeout?: number;
20
+ /** HTTP status codes that should trigger a retry (default: [408, 429, 500, 502, 503, 504]) */
21
+ retryStatusCodes?: number[];
22
+ }
23
+ /**
24
+ * Fetch with automatic retry and exponential backoff
25
+ * 带自动重试和指数退避的 fetch
26
+ *
27
+ * @param url - The URL to fetch
28
+ * @param options - Fetch options with retry configuration
29
+ * @returns The fetch response
30
+ * @throws Error if all retries fail
31
+ */
32
+ declare function fetchWithRetry(url: string, options?: FetchWithRetryOptions): Promise<Response>;
33
+ /**
34
+ * PKCE (Proof Key for Code Exchange) utilities
35
+ * PKCE 工具函数
36
+ */
37
+ /**
38
+ * Generate a cryptographically random code verifier
39
+ * 生成加密随机的 code_verifier
40
+ */
41
+ declare function generateCodeVerifier(): string;
42
+ /**
43
+ * Generate code challenge from verifier using SHA-256
44
+ * 使用 SHA-256 从 verifier 生成 code_challenge
45
+ */
46
+ declare function generateCodeChallenge(verifier: string): Promise<string>;
47
+ /**
48
+ * Store PKCE code verifier for later use
49
+ * 存储 PKCE code_verifier 以供后续使用
50
+ */
51
+ declare function storeCodeVerifier(verifier: string, storageKey?: string): void;
52
+ /**
53
+ * Retrieve and clear stored PKCE code verifier
54
+ * 获取并清除存储的 PKCE code_verifier
55
+ */
56
+ declare function getAndClearCodeVerifier(storageKey?: string): string | null;
57
+
58
+ /**
59
+ * UniAuth Client SDK
60
+ * 统一认证前端 SDK
61
+ *
62
+ * Usage:
63
+ * ```typescript
64
+ * import { UniAuthClient } from '@uniauth/client';
65
+ *
66
+ * const auth = new UniAuthClient({
67
+ * baseUrl: 'https://auth.example.com',
68
+ * appKey: 'your-app-key',
69
+ * });
70
+ *
71
+ * // Send verification code
72
+ * await auth.sendCode('+8613800138000');
73
+ *
74
+ * // Login with code
75
+ * const result = await auth.loginWithCode('+8613800138000', '123456');
76
+ *
77
+ * // Get current user
78
+ * const user = await auth.getCurrentUser();
79
+ *
80
+ * // Logout
81
+ * await auth.logout();
82
+ * ```
83
+ */
84
+ interface UniAuthConfig {
85
+ /** API base URL */
86
+ baseUrl: string;
87
+ /** Application key */
88
+ appKey?: string;
89
+ /** OAuth2 Client ID (for OAuth flows) */
90
+ clientId?: string;
91
+ /** Storage type for tokens */
92
+ storage?: 'localStorage' | 'sessionStorage' | 'memory';
93
+ /** Callback when tokens are refreshed */
94
+ onTokenRefresh?: (tokens: TokenPair) => void;
95
+ /** Callback when auth error occurs */
96
+ onAuthError?: (error: AuthError) => void;
97
+ /** Enable request retry with exponential backoff */
98
+ enableRetry?: boolean;
99
+ /** Request timeout in milliseconds */
100
+ timeout?: number;
101
+ }
102
+ interface UserInfo {
103
+ id: string;
104
+ phone: string | null;
105
+ email: string | null;
106
+ nickname: string | null;
107
+ avatar_url: string | null;
108
+ }
109
+ interface TokenPair {
110
+ access_token: string;
111
+ refresh_token: string;
112
+ expires_in: number;
113
+ }
114
+ interface LoginResult {
115
+ user: UserInfo;
116
+ access_token: string;
117
+ refresh_token: string;
118
+ expires_in: number;
119
+ is_new_user: boolean;
120
+ /** MFA is required, use mfa_token with verifyMFA() */
121
+ mfa_required?: boolean;
122
+ /** Temporary token for MFA verification */
123
+ mfa_token?: string;
124
+ /** Available MFA methods */
125
+ mfa_methods?: string[];
126
+ }
127
+ interface SendCodeResult {
128
+ expires_in: number;
129
+ retry_after: number;
130
+ }
131
+ interface AuthError {
132
+ code: string;
133
+ message: string;
134
+ }
135
+ interface ApiResponse<T> {
136
+ success: boolean;
137
+ data?: T;
138
+ message?: string;
139
+ error?: AuthError;
140
+ }
141
+ /**
142
+ * OAuth Provider Information
143
+ * OAuth 提供商信息
144
+ */
145
+ interface OAuthProvider {
146
+ id: string;
147
+ name: string;
148
+ enabled: boolean;
149
+ icon?: string;
150
+ }
151
+ /**
152
+ * Auth state change callback
153
+ * 认证状态变更回调
154
+ */
155
+ type AuthStateChangeCallback = (user: UserInfo | null, isAuthenticated: boolean) => void;
156
+ /**
157
+ * Error codes for UniAuth operations
158
+ * UniAuth 操作错误码
159
+ */
160
+ declare const AuthErrorCode: {
161
+ readonly SEND_CODE_FAILED: "SEND_CODE_FAILED";
162
+ readonly VERIFY_FAILED: "VERIFY_FAILED";
163
+ readonly LOGIN_FAILED: "LOGIN_FAILED";
164
+ readonly OAUTH_FAILED: "OAUTH_FAILED";
165
+ readonly MFA_REQUIRED: "MFA_REQUIRED";
166
+ readonly MFA_FAILED: "MFA_FAILED";
167
+ readonly REGISTER_FAILED: "REGISTER_FAILED";
168
+ readonly NOT_AUTHENTICATED: "NOT_AUTHENTICATED";
169
+ readonly TOKEN_EXPIRED: "TOKEN_EXPIRED";
170
+ readonly REFRESH_FAILED: "REFRESH_FAILED";
171
+ readonly CONFIG_ERROR: "CONFIG_ERROR";
172
+ readonly SSO_NOT_CONFIGURED: "SSO_NOT_CONFIGURED";
173
+ readonly INVALID_STATE: "INVALID_STATE";
174
+ readonly NETWORK_ERROR: "NETWORK_ERROR";
175
+ readonly TIMEOUT: "TIMEOUT";
176
+ readonly INTERNAL_ERROR: "INTERNAL_ERROR";
177
+ };
178
+ type AuthErrorCodeType = typeof AuthErrorCode[keyof typeof AuthErrorCode];
179
+ /**
180
+ * Custom error class for UniAuth operations
181
+ * UniAuth 操作自定义错误类
182
+ */
183
+ declare class UniAuthError extends Error {
184
+ code: AuthErrorCodeType | string;
185
+ statusCode?: number;
186
+ details?: unknown;
187
+ constructor(code: AuthErrorCodeType | string, message: string, statusCode?: number, details?: unknown);
188
+ }
189
+ interface OAuth2AuthorizeOptions {
190
+ redirectUri: string;
191
+ scope?: string;
192
+ state?: string;
193
+ /** Use PKCE (recommended for public clients) */
194
+ usePKCE?: boolean;
195
+ }
196
+ interface OAuth2TokenResult {
197
+ access_token: string;
198
+ token_type: string;
199
+ expires_in: number;
200
+ refresh_token?: string;
201
+ }
202
+ /**
203
+ * SSO Configuration
204
+ * SSO 配置
205
+ */
206
+ interface SSOConfig {
207
+ /** SSO service URL (e.g., https://sso.example.com) */
208
+ ssoUrl: string;
209
+ /** OAuth client ID for this application */
210
+ clientId: string;
211
+ /** Redirect URI after SSO login */
212
+ redirectUri: string;
213
+ /** OAuth scope (default: 'openid profile email') */
214
+ scope?: string;
215
+ }
216
+ /**
217
+ * SSO Login Options
218
+ * SSO 登录选项
219
+ */
220
+ interface SSOLoginOptions {
221
+ /** Use PKCE (recommended, default: true) */
222
+ usePKCE?: boolean;
223
+ /** Custom state parameter */
224
+ state?: string;
225
+ /** Whether to use popup instead of redirect */
226
+ usePopup?: boolean;
227
+ }
228
+ /**
229
+ * UniAuth Client
230
+ * 统一认证客户端
231
+ */
232
+ declare class UniAuthClient {
233
+ private config;
234
+ private storage;
235
+ private refreshPromise;
236
+ constructor(config: UniAuthConfig);
237
+ /**
238
+ * Send verification code to phone number
239
+ * 发送验证码到手机号
240
+ */
241
+ sendCode(phone: string, type?: 'login' | 'register' | 'reset'): Promise<SendCodeResult>;
242
+ /**
243
+ * Send verification code to email
244
+ * 发送验证码到邮箱
245
+ */
246
+ sendEmailCode(email: string, type?: 'login' | 'register' | 'reset' | 'email_verify'): Promise<SendCodeResult>;
247
+ /**
248
+ * Login with phone verification code
249
+ * 使用手机验证码登录
250
+ */
251
+ loginWithCode(phone: string, code: string): Promise<LoginResult>;
252
+ /**
253
+ * Login with email verification code
254
+ * 使用邮箱验证码登录
255
+ */
256
+ loginWithEmailCode(email: string, code: string): Promise<LoginResult>;
257
+ /**
258
+ * Login with email and password
259
+ * 使用邮箱密码登录
260
+ */
261
+ loginWithEmail(email: string, password: string): Promise<LoginResult>;
262
+ /**
263
+ * Handle OAuth callback (for social login)
264
+ * 处理 OAuth 回调(社交登录)
265
+ */
266
+ handleOAuthCallback(provider: string, code: string): Promise<LoginResult>;
267
+ /**
268
+ * Register with email and password
269
+ * 使用邮箱密码注册
270
+ */
271
+ registerWithEmail(email: string, password: string, nickname?: string): Promise<LoginResult>;
272
+ /**
273
+ * Verify MFA code to complete login
274
+ * 验证 MFA 验证码完成登录
275
+ *
276
+ * Call this after login returns mfa_required: true
277
+ * 当登录返回 mfa_required: true 时调用此方法
278
+ *
279
+ * @example
280
+ * ```typescript
281
+ * const result = await auth.loginWithCode(phone, code);
282
+ * if (result.mfa_required) {
283
+ * const mfaCode = prompt('Enter MFA code:');
284
+ * const finalResult = await auth.verifyMFA(result.mfa_token!, mfaCode);
285
+ * }
286
+ * ```
287
+ */
288
+ verifyMFA(mfaToken: string, code: string): Promise<LoginResult>;
289
+ /**
290
+ * Get available OAuth providers
291
+ * 获取可用的 OAuth 提供商列表
292
+ */
293
+ getOAuthProviders(): Promise<OAuthProvider[]>;
294
+ /**
295
+ * Start social login (redirect to OAuth provider)
296
+ * 开始社交登录(重定向到 OAuth 提供商)
297
+ *
298
+ * @param provider - OAuth provider ID (e.g., 'google', 'github', 'wechat')
299
+ * @param redirectUri - Where to redirect after OAuth (optional, uses default)
300
+ *
301
+ * @example
302
+ * ```typescript
303
+ * // Redirect user to Google login
304
+ * auth.startSocialLogin('google');
305
+ * ```
306
+ */
307
+ startSocialLogin(provider: string, redirectUri?: string): void;
308
+ private authStateCallbacks;
309
+ private currentUser;
310
+ /**
311
+ * Subscribe to auth state changes
312
+ * 订阅认证状态变更
313
+ *
314
+ * @returns Unsubscribe function
315
+ *
316
+ * @example
317
+ * ```typescript
318
+ * const unsubscribe = auth.onAuthStateChange((user, isAuthenticated) => {
319
+ * if (isAuthenticated) {
320
+ * console.log('User logged in:', user);
321
+ * } else {
322
+ * console.log('User logged out');
323
+ * }
324
+ * });
325
+ *
326
+ * // Later, to unsubscribe:
327
+ * unsubscribe();
328
+ * ```
329
+ */
330
+ onAuthStateChange(callback: AuthStateChangeCallback): () => void;
331
+ /**
332
+ * Notify all subscribers of auth state change
333
+ * 通知所有订阅者认证状态变更
334
+ */
335
+ private notifyAuthStateChange;
336
+ /**
337
+ * Get cached current user (sync, may be stale)
338
+ * 获取缓存的当前用户(同步,可能过时)
339
+ */
340
+ getCachedUser(): UserInfo | null;
341
+ /**
342
+ * Get access token synchronously (without refresh check)
343
+ * 同步获取访问令牌(不检查刷新)
344
+ */
345
+ getAccessTokenSync(): string | null;
346
+ /**
347
+ * Check if current token is valid (not expired)
348
+ * 检查当前令牌是否有效(未过期)
349
+ */
350
+ isTokenValid(): boolean;
351
+ /**
352
+ * Get current user info
353
+ * 获取当前用户信息
354
+ */
355
+ getCurrentUser(): Promise<UserInfo | null>;
356
+ /**
357
+ * Update user profile
358
+ * 更新用户资料
359
+ */
360
+ updateProfile(updates: Partial<Pick<UserInfo, 'nickname' | 'avatar_url'>>): Promise<UserInfo>;
361
+ /**
362
+ * Get access token (auto-refresh if needed)
363
+ * 获取访问令牌(如需要则自动刷新)
364
+ */
365
+ getAccessToken(): Promise<string | null>;
366
+ /**
367
+ * Check if user is authenticated
368
+ * 检查用户是否已认证
369
+ */
370
+ isAuthenticated(): boolean;
371
+ /**
372
+ * Logout current session
373
+ * 登出当前会话
374
+ */
375
+ logout(): Promise<void>;
376
+ /**
377
+ * Logout from all devices
378
+ * 从所有设备登出
379
+ */
380
+ logoutAll(): Promise<void>;
381
+ /**
382
+ * Start OAuth2 authorization flow
383
+ * 开始 OAuth2 授权流程
384
+ */
385
+ startOAuth2Flow(options: OAuth2AuthorizeOptions): Promise<string>;
386
+ /**
387
+ * Exchange authorization code for tokens (OAuth2 client flow)
388
+ * 使用授权码换取令牌
389
+ */
390
+ exchangeOAuth2Code(code: string, redirectUri: string, clientSecret?: string): Promise<OAuth2TokenResult>;
391
+ private ssoConfig;
392
+ /**
393
+ * Configure SSO settings
394
+ * 配置 SSO 设置
395
+ *
396
+ * @example
397
+ * ```typescript
398
+ * auth.configureSso({
399
+ * ssoUrl: 'https://sso.55387.xyz',
400
+ * clientId: 'my-app',
401
+ * redirectUri: 'https://my-app.com/auth/callback',
402
+ * });
403
+ * ```
404
+ */
405
+ configureSso(config: SSOConfig): void;
406
+ /**
407
+ * Start SSO login flow
408
+ * 开始 SSO 登录流程
409
+ *
410
+ * This will redirect the user to the SSO service.
411
+ * If the user already has an SSO session, they'll be automatically logged in (silent auth).
412
+ *
413
+ * @example
414
+ * ```typescript
415
+ * // Simple usage - redirects to SSO
416
+ * auth.loginWithSSO();
417
+ *
418
+ * // With options
419
+ * auth.loginWithSSO({ usePKCE: true });
420
+ * ```
421
+ */
422
+ loginWithSSO(options?: SSOLoginOptions): void;
423
+ /**
424
+ * Check if current URL is an SSO callback
425
+ * 检查当前 URL 是否是 SSO 回调
426
+ *
427
+ * @example
428
+ * ```typescript
429
+ * if (auth.isSSOCallback()) {
430
+ * await auth.handleSSOCallback();
431
+ * }
432
+ * ```
433
+ */
434
+ isSSOCallback(): boolean;
435
+ /**
436
+ * Handle SSO callback and exchange code for tokens
437
+ * 处理 SSO 回调并交换授权码获取令牌
438
+ *
439
+ * Call this on your callback page after SSO redirects back.
440
+ *
441
+ * @returns LoginResult or null if callback handling failed
442
+ *
443
+ * @example
444
+ * ```typescript
445
+ * // In your callback page component
446
+ * useEffect(() => {
447
+ * if (auth.isSSOCallback()) {
448
+ * auth.handleSSOCallback()
449
+ * .then(result => {
450
+ * if (result) {
451
+ * navigate('/dashboard');
452
+ * }
453
+ * })
454
+ * .catch(err => console.error('SSO login failed:', err));
455
+ * }
456
+ * }, []);
457
+ * ```
458
+ */
459
+ handleSSOCallback(): Promise<LoginResult | null>;
460
+ /**
461
+ * Check if user can be silently authenticated via SSO
462
+ * 检查用户是否可以通过 SSO 静默登录
463
+ *
464
+ * This starts a silent SSO flow using an iframe to check if user has an active SSO session.
465
+ *
466
+ * @returns Promise that resolves to true if silent auth succeeded
467
+ */
468
+ checkSSOSession(): Promise<boolean>;
469
+ private generateRandomState;
470
+ private storeState;
471
+ private getAndClearState;
472
+ /**
473
+ * Exchange SSO authorization code for tokens
474
+ * This is a private method used internally by handleSSOCallback
475
+ */
476
+ private exchangeSSOCode;
477
+ /**
478
+ * Refresh tokens
479
+ * 刷新令牌
480
+ */
481
+ private refreshTokens;
482
+ private doRefreshTokens;
483
+ /**
484
+ * Make an authenticated request
485
+ * 发起已认证的请求
486
+ */
487
+ private authenticatedRequest;
488
+ /**
489
+ * Make a request to the API with retry support
490
+ * 向 API 发起请求(支持重试)
491
+ */
492
+ private request;
493
+ /**
494
+ * Create an error object
495
+ * 创建错误对象
496
+ */
497
+ private createError;
498
+ }
499
+
500
+ export { type ApiResponse, type AuthError, AuthErrorCode, type AuthErrorCodeType, type AuthStateChangeCallback, type LoginResult, type OAuth2AuthorizeOptions, type OAuth2TokenResult, type OAuthProvider, type SSOConfig, type SSOLoginOptions, type SendCodeResult, type TokenPair, UniAuthClient, type UniAuthConfig, UniAuthError, type UserInfo, UniAuthClient as default, fetchWithRetry, generateCodeChallenge, generateCodeVerifier, getAndClearCodeVerifier, storeCodeVerifier };