@amaster.ai/client 1.1.0-beta.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,674 @@
1
+ /**
2
+ * ============================================================================
3
+ * Authentication Module - Type Definitions
4
+ * ============================================================================
5
+ *
6
+ * This module provides comprehensive authentication capabilities including:
7
+ * - Password-based login (username/email/phone)
8
+ * - User registration
9
+ * - Verification code login
10
+ * - OAuth/Social login
11
+ * - Token management and refresh
12
+ * - User profile management
13
+ * - Permission and role management
14
+ *
15
+ * @module auth
16
+ */
17
+
18
+ import type { ClientResult } from './common';
19
+
20
+ // ==================== User & Roles ====================
21
+
22
+ /**
23
+ * User information with optimized roles and permissions
24
+ *
25
+ * Roles and permissions are returned as simple string arrays for efficient client-side use:
26
+ * - `roles`: ["admin", "user", "manager"]
27
+ * - `permissions`: ["user:read", "user:write", "order:read"]
28
+ *
29
+ * @example
30
+ * Check user permissions:
31
+ * ```typescript
32
+ * const result = await client.auth.getMe();
33
+ * const user = result.data;
34
+ *
35
+ * if (user.roles.includes('admin')) {
36
+ * console.log('User is an admin');
37
+ * }
38
+ *
39
+ * if (user.permissions.includes('user:delete')) {
40
+ * showDeleteButton();
41
+ * }
42
+ * ```
43
+ */
44
+ export interface User {
45
+ /** Unique user identifier */
46
+ uid: string;
47
+ /** Username (null if not set) */
48
+ username: string | null;
49
+ /** Email address (null if not set) */
50
+ email: string | null;
51
+ /** Phone number (null if not set) */
52
+ phone: string | null;
53
+ /** Display name shown in UI */
54
+ displayName: string | null;
55
+ /** Avatar image URL */
56
+ avatarUrl: string | null;
57
+ /** Whether account is active */
58
+ isActive: boolean;
59
+ /** Whether email is verified */
60
+ emailVerified: boolean;
61
+ /** Whether phone is verified */
62
+ phoneVerified: boolean;
63
+ /** Email verification timestamp (ISO 8601) */
64
+ emailVerifiedAt: string | null;
65
+ /** Phone verification timestamp (ISO 8601) */
66
+ phoneVerifiedAt: string | null;
67
+ /**
68
+ * Role codes assigned to user
69
+ * @example ["admin", "user", "manager"]
70
+ */
71
+ roles: string[];
72
+ /**
73
+ * Permission names granted to user
74
+ * Format: "resource:action"
75
+ * @example ["user:read", "user:write", "order:read", "order:delete"]
76
+ */
77
+ permissions: string[];
78
+ /** Account creation timestamp (ISO 8601) */
79
+ createdAt: string;
80
+ /** Last update timestamp (ISO 8601) */
81
+ updatedAt: string;
82
+ }
83
+
84
+ // ==================== Authentication Parameters ====================
85
+
86
+ /**
87
+ * User registration parameters
88
+ *
89
+ * At least one identifier (username, email, or phone) must be provided.
90
+ *
91
+ * @example
92
+ * Register with email:
93
+ * ```typescript
94
+ * await client.auth.register({
95
+ * email: 'user@example.com',
96
+ * password: 'Password@123',
97
+ * displayName: 'John Doe'
98
+ * });
99
+ * ```
100
+ *
101
+ * @example
102
+ * Register with username and captcha:
103
+ * ```typescript
104
+ * // 1. Get captcha
105
+ * const captcha = await client.auth.getCaptcha();
106
+ *
107
+ * // 2. Show captcha.data.captchaImage to user
108
+ * const userInput = prompt('Enter captcha:');
109
+ *
110
+ * // 3. Register with captcha
111
+ * await client.auth.register({
112
+ * username: 'johndoe',
113
+ * email: 'john@example.com',
114
+ * password: 'Password@123',
115
+ * captcha: `${captcha.data.captchaId}:${userInput}`
116
+ * });
117
+ * ```
118
+ */
119
+ export interface RegisterParams {
120
+ /** Username (optional, but one of username/email/phone required) */
121
+ username?: string;
122
+ /** Email address (optional, but one of username/email/phone required) */
123
+ email?: string;
124
+ /** Phone number (optional, but one of username/email/phone required) */
125
+ phone?: string;
126
+ /**
127
+ * Password (required, 8-128 characters)
128
+ * Must contain at least: uppercase, lowercase, number
129
+ */
130
+ password: string;
131
+ /** Display name for UI */
132
+ displayName?: string;
133
+ /**
134
+ * Captcha verification (optional)
135
+ * Format: "captchaId:userInput"
136
+ * @example "abc-123:XY7K"
137
+ */
138
+ captcha?: string;
139
+ }
140
+
141
+ /**
142
+ * Login method type
143
+ */
144
+ export type LoginType = 'username' | 'email' | 'phone';
145
+
146
+ /**
147
+ * Login parameters for password-based authentication
148
+ *
149
+ * The `loginType` field is optional - it will be auto-detected based on
150
+ * which identifier field (username/email/phone) you provide.
151
+ *
152
+ * @example
153
+ * Login with email (auto-detect):
154
+ * ```typescript
155
+ * await client.auth.login({
156
+ * email: 'user@example.com',
157
+ * password: 'Password@123'
158
+ * });
159
+ * ```
160
+ *
161
+ * @example
162
+ * Login with username (explicit type):
163
+ * ```typescript
164
+ * await client.auth.login({
165
+ * loginType: 'username',
166
+ * username: 'johndoe',
167
+ * password: 'Password@123'
168
+ * });
169
+ * ```
170
+ *
171
+ * @example
172
+ * Login with phone:
173
+ * ```typescript
174
+ * await client.auth.login({
175
+ * phone: '+86-13800138000',
176
+ * password: 'Password@123'
177
+ * });
178
+ * ```
179
+ */
180
+ export interface LoginParams {
181
+ /** Login method (optional, auto-detected if not provided) */
182
+ loginType?: LoginType;
183
+ /** Username (required if loginType='username') */
184
+ username?: string;
185
+ /** Email (required if loginType='email') */
186
+ email?: string;
187
+ /** Phone (required if loginType='phone') */
188
+ phone?: string;
189
+ /** Password (always required) */
190
+ password: string;
191
+ }
192
+
193
+ /**
194
+ * Verification code login type
195
+ */
196
+ export type CodeLoginType = 'email' | 'phone';
197
+
198
+ /**
199
+ * Verification code login parameters
200
+ *
201
+ * @example
202
+ * Email code login:
203
+ * ```typescript
204
+ * // 1. Send verification code
205
+ * await client.auth.sendCode({
206
+ * type: 'email',
207
+ * email: 'user@example.com'
208
+ * });
209
+ *
210
+ * // 2. User receives code via email
211
+ * const code = '123456';
212
+ *
213
+ * // 3. Login with code
214
+ * await client.auth.codeLogin({
215
+ * email: 'user@example.com',
216
+ * code: code
217
+ * });
218
+ * ```
219
+ */
220
+ export interface CodeLoginParams {
221
+ /** Login method (optional, auto-detected) */
222
+ loginType?: CodeLoginType;
223
+ /** Email (required if using email code) */
224
+ email?: string;
225
+ /** Phone (required if using phone code) */
226
+ phone?: string;
227
+ /** Verification code received via email/SMS */
228
+ code: string;
229
+ }
230
+
231
+ /**
232
+ * Update user profile parameters
233
+ *
234
+ * All fields are optional - only update what you want to change.
235
+ *
236
+ * @example
237
+ * Update display name:
238
+ * ```typescript
239
+ * await client.auth.updateProfile({
240
+ * displayName: 'Jane Doe'
241
+ * });
242
+ * ```
243
+ *
244
+ * @example
245
+ * Update multiple fields:
246
+ * ```typescript
247
+ * await client.auth.updateProfile({
248
+ * displayName: 'John Smith',
249
+ * avatarUrl: 'https://cdn.example.com/avatar.jpg',
250
+ * phone: '+86-13900139000'
251
+ * });
252
+ * ```
253
+ */
254
+ export interface UpdateProfileParams {
255
+ /** New display name */
256
+ displayName?: string;
257
+ /** New avatar URL */
258
+ avatarUrl?: string;
259
+ /** New email (may require verification) */
260
+ email?: string;
261
+ /** New phone (may require verification) */
262
+ phone?: string;
263
+ }
264
+
265
+ /**
266
+ * Change password parameters
267
+ *
268
+ * @example
269
+ * ```typescript
270
+ * await client.auth.changePassword({
271
+ * oldPassword: 'OldPassword@123',
272
+ * newPassword: 'NewPassword@456'
273
+ * });
274
+ * ```
275
+ */
276
+ export interface ChangePasswordParams {
277
+ /** Current password (for verification) */
278
+ oldPassword: string;
279
+ /**
280
+ * New password (8-128 characters)
281
+ * Must contain: uppercase, lowercase, number
282
+ */
283
+ newPassword: string;
284
+ }
285
+
286
+ // ==================== Authentication Responses ====================
287
+
288
+ /**
289
+ * Login response with user info and access token
290
+ *
291
+ * @example
292
+ * ```typescript
293
+ * const result = await client.auth.login({
294
+ * email: 'user@example.com',
295
+ * password: 'password123'
296
+ * });
297
+ *
298
+ * if (result.data) {
299
+ * const { user, accessToken } = result.data;
300
+ * console.log(`Welcome ${user.displayName}!`);
301
+ * console.log(`Token: ${accessToken}`);
302
+ *
303
+ * // All subsequent requests now include this token automatically
304
+ * await client.entity.list('default', 'users');
305
+ * }
306
+ * ```
307
+ */
308
+ export interface LoginResponse {
309
+ /** User information */
310
+ user: User;
311
+ /** JWT access token */
312
+ accessToken: string;
313
+ /** Refresh token (if configured) */
314
+ refreshToken?: string;
315
+ /** Token expiration time in seconds */
316
+ expiresIn?: number;
317
+ }
318
+
319
+ /**
320
+ * Token refresh response
321
+ */
322
+ export interface RefreshTokenResponse {
323
+ /** New access token */
324
+ accessToken: string;
325
+ /** Token expiration time in seconds */
326
+ expiresIn?: number;
327
+ }
328
+
329
+ /**
330
+ * Generic success response
331
+ */
332
+ export interface SuccessResponse {
333
+ /** Whether operation was successful */
334
+ success: boolean;
335
+ /** Optional message */
336
+ message?: string;
337
+ }
338
+
339
+ // ==================== Authentication API ====================
340
+
341
+ /**
342
+ * Authentication Client API
343
+ *
344
+ * Provides methods for user authentication and account management.
345
+ * All methods return a `ClientResult<T>` for consistent error handling.
346
+ *
347
+ * @example
348
+ * Complete authentication flow:
349
+ * ```typescript
350
+ * const client = createClient({ baseURL: 'https://api.amaster.ai' });
351
+ *
352
+ * // 1. Register new user
353
+ * await client.auth.register({
354
+ * email: 'user@example.com',
355
+ * password: 'Password@123',
356
+ * displayName: 'John Doe'
357
+ * });
358
+ *
359
+ * // 2. Login (token is automatically stored and attached to all requests)
360
+ * await client.auth.login({
361
+ * email: 'user@example.com',
362
+ * password: 'Password@123'
363
+ * });
364
+ *
365
+ * // 3. Get current user info
366
+ * const userResult = await client.auth.getMe();
367
+ * console.log(userResult.data);
368
+ *
369
+ * // 4. Update profile
370
+ * await client.auth.updateProfile({
371
+ * displayName: 'Jane Doe'
372
+ * });
373
+ *
374
+ * // 5. Logout
375
+ * await client.auth.logout();
376
+ * ```
377
+ */
378
+ export interface AuthClientAPI {
379
+ // ==================== Core Authentication ====================
380
+
381
+ /**
382
+ * Register a new user account
383
+ *
384
+ * Creates a new user account with the provided credentials.
385
+ * Depending on backend configuration, may auto-login after registration.
386
+ *
387
+ * @param params - Registration parameters
388
+ * @returns User info and access token (if auto-login enabled)
389
+ *
390
+ * @example
391
+ * Basic registration:
392
+ * ```typescript
393
+ * const result = await client.auth.register({
394
+ * email: 'user@example.com',
395
+ * password: 'Password@123',
396
+ * displayName: 'John Doe'
397
+ * });
398
+ *
399
+ * if (result.data) {
400
+ * console.log('Registration successful!');
401
+ * console.log('User:', result.data.user);
402
+ * }
403
+ * ```
404
+ *
405
+ * @example
406
+ * Registration with username:
407
+ * ```typescript
408
+ * await client.auth.register({
409
+ * username: 'johndoe',
410
+ * email: 'john@example.com',
411
+ * password: 'Password@123',
412
+ * displayName: 'John Doe'
413
+ * });
414
+ * ```
415
+ */
416
+ register(params: RegisterParams): Promise<ClientResult<LoginResponse>>;
417
+
418
+ /**
419
+ * Login with password
420
+ *
421
+ * Authenticates a user with username/email/phone and password.
422
+ * On success, access token is automatically stored and attached to all subsequent requests.
423
+ *
424
+ * @param params - Login credentials
425
+ * @returns User info and access token
426
+ *
427
+ * @example
428
+ * Login with email:
429
+ * ```typescript
430
+ * const result = await client.auth.login({
431
+ * email: 'user@example.com',
432
+ * password: 'Password@123'
433
+ * });
434
+ *
435
+ * if (result.data) {
436
+ * console.log('Welcome', result.data.user.displayName);
437
+ * // Token is now automatically attached to all requests
438
+ * } else {
439
+ * console.error('Login failed:', result.error?.message);
440
+ * }
441
+ * ```
442
+ *
443
+ * @example
444
+ * Login with username:
445
+ * ```typescript
446
+ * await client.auth.login({
447
+ * loginType: 'username',
448
+ * username: 'johndoe',
449
+ * password: 'Password@123'
450
+ * });
451
+ * ```
452
+ */
453
+ login(params: LoginParams): Promise<ClientResult<LoginResponse>>;
454
+
455
+ /**
456
+ * Login with verification code
457
+ *
458
+ * Authenticates using a verification code sent to email or phone.
459
+ *
460
+ * @param params - Email/phone and verification code
461
+ * @returns User info and access token
462
+ *
463
+ * @example
464
+ * Complete code login flow:
465
+ * ```typescript
466
+ * // 1. Send verification code
467
+ * await client.auth.sendCode({
468
+ * type: 'email',
469
+ * email: 'user@example.com'
470
+ * });
471
+ *
472
+ * // 2. User receives code: "123456"
473
+ *
474
+ * // 3. Login with code
475
+ * const result = await client.auth.codeLogin({
476
+ * email: 'user@example.com',
477
+ * code: '123456'
478
+ * });
479
+ *
480
+ * if (result.data) {
481
+ * console.log('Logged in successfully!');
482
+ * }
483
+ * ```
484
+ */
485
+ codeLogin(params: CodeLoginParams): Promise<ClientResult<LoginResponse>>;
486
+
487
+ /**
488
+ * Logout current user
489
+ *
490
+ * Invalidates the current session and clears local authentication state.
491
+ * All subsequent requests will be unauthenticated until login again.
492
+ *
493
+ * @returns Success status
494
+ *
495
+ * @example
496
+ * ```typescript
497
+ * await client.auth.logout();
498
+ * console.log('Logged out successfully');
499
+ *
500
+ * // Token is cleared, requests are now unauthenticated
501
+ * console.log(client.isAuthenticated()); // false
502
+ * ```
503
+ *
504
+ * @example
505
+ * Logout with redirect:
506
+ * ```typescript
507
+ * await client.auth.logout();
508
+ * window.location.href = '/login';
509
+ * ```
510
+ */
511
+ logout(): Promise<ClientResult<SuccessResponse>>;
512
+
513
+ /**
514
+ * Refresh access token
515
+ *
516
+ * Obtains a new access token using the refresh token.
517
+ * Note: Token refresh is handled automatically by the client.
518
+ * This method is exposed for manual refresh scenarios.
519
+ *
520
+ * @returns New access token
521
+ *
522
+ * @example
523
+ * ```typescript
524
+ * const result = await client.auth.refreshToken();
525
+ * if (result.data) {
526
+ * console.log('Token refreshed:', result.data.accessToken);
527
+ * }
528
+ * ```
529
+ */
530
+ refreshToken(): Promise<ClientResult<RefreshTokenResponse>>;
531
+
532
+ // ==================== User Profile Management ====================
533
+
534
+ /**
535
+ * Get current user information
536
+ *
537
+ * Retrieves the profile of the currently authenticated user.
538
+ *
539
+ * @returns Current user info
540
+ *
541
+ * @example
542
+ * ```typescript
543
+ * const result = await client.auth.getMe();
544
+ * if (result.data) {
545
+ * console.log('Current user:', result.data.displayName);
546
+ * console.log('Roles:', result.data.roles);
547
+ * console.log('Permissions:', result.data.permissions);
548
+ * }
549
+ * ```
550
+ *
551
+ * @example
552
+ * Check permissions:
553
+ * ```typescript
554
+ * const result = await client.auth.getMe();
555
+ * if (result.data?.permissions.includes('user:delete')) {
556
+ * // Show delete button
557
+ * }
558
+ * ```
559
+ */
560
+ getMe(): Promise<ClientResult<User>>;
561
+
562
+ /**
563
+ * Update user profile
564
+ *
565
+ * Updates one or more fields of the current user's profile.
566
+ *
567
+ * @param params - Fields to update
568
+ * @returns Updated user info
569
+ *
570
+ * @example
571
+ * Update display name:
572
+ * ```typescript
573
+ * await client.auth.updateProfile({
574
+ * displayName: 'Jane Smith'
575
+ * });
576
+ * ```
577
+ *
578
+ * @example
579
+ * Update multiple fields:
580
+ * ```typescript
581
+ * await client.auth.updateProfile({
582
+ * displayName: 'John Doe',
583
+ * avatarUrl: 'https://cdn.example.com/avatar.jpg'
584
+ * });
585
+ * ```
586
+ */
587
+ updateProfile(params: UpdateProfileParams): Promise<ClientResult<User>>;
588
+
589
+ /**
590
+ * Change password
591
+ *
592
+ * Changes the password for the current user.
593
+ * Requires the old password for verification.
594
+ *
595
+ * @param params - Old and new passwords
596
+ * @returns Success status
597
+ *
598
+ * @example
599
+ * ```typescript
600
+ * const result = await client.auth.changePassword({
601
+ * oldPassword: 'OldPassword@123',
602
+ * newPassword: 'NewPassword@456'
603
+ * });
604
+ *
605
+ * if (result.data?.success) {
606
+ * console.log('Password changed successfully');
607
+ * } else {
608
+ * console.error('Failed:', result.error?.message);
609
+ * }
610
+ * ```
611
+ */
612
+ changePassword(params: ChangePasswordParams): Promise<ClientResult<SuccessResponse>>;
613
+
614
+ // ==================== Verification & Security ====================
615
+
616
+ /**
617
+ * Send verification code
618
+ *
619
+ * Sends a verification code to the specified email or phone.
620
+ * Used for code login or account verification.
621
+ *
622
+ * @param params - Email or phone to send code to
623
+ * @returns Success status
624
+ *
625
+ * @example
626
+ * Send email verification code:
627
+ * ```typescript
628
+ * await client.auth.sendCode({
629
+ * type: 'email',
630
+ * email: 'user@example.com'
631
+ * });
632
+ * console.log('Code sent to email');
633
+ * ```
634
+ *
635
+ * @example
636
+ * Send SMS verification code:
637
+ * ```typescript
638
+ * await client.auth.sendCode({
639
+ * type: 'phone',
640
+ * phone: '+86-13800138000'
641
+ * });
642
+ * ```
643
+ */
644
+ sendCode(params: {
645
+ type: 'email' | 'phone';
646
+ email?: string;
647
+ phone?: string;
648
+ }): Promise<ClientResult<SuccessResponse>>;
649
+
650
+ /**
651
+ * Get captcha image
652
+ *
653
+ * Retrieves a captcha challenge for verification.
654
+ *
655
+ * @returns Captcha ID and image (base64)
656
+ *
657
+ * @example
658
+ * ```typescript
659
+ * const result = await client.auth.getCaptcha();
660
+ * if (result.data) {
661
+ * // Display image to user
662
+ * const img = document.createElement('img');
663
+ * img.src = result.data.captchaImage;
664
+ *
665
+ * // Save captchaId for later verification
666
+ * const captchaId = result.data.captchaId;
667
+ * }
668
+ * ```
669
+ */
670
+ getCaptcha(): Promise<ClientResult<{
671
+ captchaId: string;
672
+ captchaImage: string; // base64 encoded image
673
+ }>>;
674
+ }