@turinhub/tale-js-sdk 2.3.0 → 2.4.1

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.
@@ -22,8 +22,9 @@ export declare function createTaleAppClient(options: TaleAppClientOptions): {
22
22
  auth: {
23
23
  login: (credentials: Parameters<typeof Auth.login>[0], request?: OptionalRequest<typeof Auth.login, 1>) => Promise<Auth.LoginResponse>;
24
24
  validateToken: (token: Parameters<typeof Auth.validateToken>[0], request?: OptionalRequest<typeof Auth.validateToken, 1>) => Promise<boolean>;
25
- loginWithSms: (phone: Parameters<typeof Auth.loginWithSms>[0]) => Promise<Auth.SendSmsResponse>;
25
+ loginWithSms: (phone: Parameters<typeof Auth.loginWithSms>[0], request?: OptionalRequest<typeof Auth.loginWithSms, 1>) => Promise<Auth.SendSmsResponse>;
26
26
  verifySmsCode: (request: Parameters<typeof Auth.verifySmsCode>[0], optionsOverride?: OptionalRequest<typeof Auth.verifySmsCode, 1>) => Promise<Auth.SmsLoginResponse>;
27
+ verifyPasswordChangeSmsAndUpdatePassword: (request: Parameters<typeof Auth.verifyPasswordChangeSmsAndUpdatePassword>[0], optionsOverride?: OptionalRequest<typeof Auth.verifyPasswordChangeSmsAndUpdatePassword, 1>) => Promise<Auth.PasswordChangeSmsResponse>;
27
28
  registerWithSms: (request: Parameters<typeof Auth.registerWithSms>[0], optionsOverride?: OptionalRequest<typeof Auth.registerWithSms, 1>) => Promise<Auth.SmsLoginResponse>;
28
29
  };
29
30
  users: {
@@ -24,8 +24,9 @@ export function createTaleAppClient(options) {
24
24
  ...(request ?? {}),
25
25
  baseUrl: options.baseUrl,
26
26
  }),
27
- loginWithSms: (phone) => Auth.loginWithSms(phone, { appToken: options.appToken }),
27
+ loginWithSms: (phone, request) => Auth.loginWithSms(phone, mergeRequest(request)),
28
28
  verifySmsCode: (request, optionsOverride) => Auth.verifySmsCode(request, mergeRequest(optionsOverride)),
29
+ verifyPasswordChangeSmsAndUpdatePassword: (request, optionsOverride) => Auth.verifyPasswordChangeSmsAndUpdatePassword(request, mergeRequest(optionsOverride)),
29
30
  registerWithSms: (request, optionsOverride) => Auth.registerWithSms(request, mergeRequest(optionsOverride)),
30
31
  },
31
32
  users: {
@@ -1,5 +1,5 @@
1
- import type { LoginRequest, LoginOptions, LoginWithSmsOptions, VerifySmsOptions, AppInfo, AuthUser, UserToken, AuthRole, AuthPrivilege, UserGroup, AuthUserLoginMethod, LoginResponse, LoginJson, SendSmsResponse, SendSmsJson, VerifySmsRequest, SmsLoginResponse, SmsLoginJson } from "./types.js";
2
- export type { LoginRequest, LoginOptions, LoginWithSmsOptions, VerifySmsOptions, AppInfo, AuthUser, UserToken, AuthRole, AuthPrivilege, UserGroup, AuthUserLoginMethod, LoginResponse, LoginJson, SendSmsResponse, SendSmsJson, VerifySmsRequest, SmsLoginResponse, SmsLoginJson, };
1
+ import type { LoginRequest, LoginOptions, LoginWithSmsOptions, VerifySmsOptions, AppInfo, AuthUser, UserToken, AuthRole, AuthPrivilege, UserGroup, AuthUserLoginMethod, LoginResponse, LoginJson, LoginOrRegisterSmsType, PasswordChangeSmsType, PasswordChangeSmsSendType, SmsType, SendSmsResponse, SendSmsJson, VerifySmsRequest, PasswordChangeSmsRequest, PasswordChangeSmsResponse, PasswordChangeSmsJson, SmsLoginResponse, SmsLoginJson } from "./types.js";
2
+ export type { LoginRequest, LoginOptions, LoginWithSmsOptions, VerifySmsOptions, AppInfo, AuthUser, UserToken, AuthRole, AuthPrivilege, UserGroup, AuthUserLoginMethod, LoginResponse, LoginJson, LoginOrRegisterSmsType, PasswordChangeSmsType, PasswordChangeSmsSendType, SmsType, SendSmsResponse, SendSmsJson, VerifySmsRequest, PasswordChangeSmsRequest, PasswordChangeSmsResponse, PasswordChangeSmsJson, SmsLoginResponse, SmsLoginJson, };
3
3
  /**
4
4
  * Authenticates a user with username and password.
5
5
  *
@@ -99,7 +99,7 @@ export declare function validateToken(token: string, options?: {
99
99
  * try {
100
100
  * const result = await loginWithSms('+8613800138000');
101
101
  * console.log('SMS sent:', result.smsId);
102
- * console.log('Type:', result.type); // 'login' or 'register'
102
+ * console.log('Type:', result.type); // 'login', 'register', or 'changePassword'
103
103
  * } catch (error) {
104
104
  * console.error('SMS sending failed:', error.message);
105
105
  * }
@@ -134,6 +134,17 @@ export declare function loginWithSms(phone: string, options?: LoginWithSmsOption
134
134
  * ```
135
135
  */
136
136
  export declare function verifySmsCode(request: VerifySmsRequest, options?: VerifySmsOptions): Promise<SmsLoginResponse>;
137
+ /**
138
+ * Verifies password-change SMS code and updates user password.
139
+ *
140
+ * @param request - Password change SMS verification request
141
+ * @param options - Optional configuration for the request
142
+ * @returns Promise resolving to password update result
143
+ * @throws {ConfigurationError} When required environment variables are missing
144
+ * @throws {ApiError} When verification or password update fails
145
+ * @throws {NetworkError} When network request fails
146
+ */
147
+ export declare function verifyPasswordChangeSmsAndUpdatePassword(request: PasswordChangeSmsRequest, options?: VerifySmsOptions): Promise<PasswordChangeSmsResponse>;
137
148
  /**
138
149
  * Registers a new user with SMS verification and optional additional information.
139
150
  *
@@ -1,5 +1,16 @@
1
1
  import { getAppToken } from "../token.js";
2
2
  import { ApiError, ConfigurationError, NetworkError } from "../errors.js";
3
+ const LOGIN_OR_REGISTER_SMS_TYPES = [
4
+ "login",
5
+ "register",
6
+ ];
7
+ const PASSWORD_CHANGE_SMS_TYPES = [
8
+ "changePassword",
9
+ "reset_password",
10
+ ];
11
+ const PASSWORD_CHANGE_SMS_SEND_TYPES = [
12
+ "changePassword",
13
+ ];
3
14
  /**
4
15
  * Authenticates a user with username and password.
5
16
  *
@@ -151,6 +162,7 @@ export async function login(credentials, options) {
151
162
  userPrivileges: responseData.userPrivileges || [],
152
163
  userGroups: responseData.userGroups || [],
153
164
  userLoginMethods: responseData.userLoginMethods || [],
165
+ userAttributes: responseData.userAttributes || [],
154
166
  };
155
167
  return loginResponse;
156
168
  }
@@ -224,7 +236,7 @@ export async function validateToken(token, options) {
224
236
  * try {
225
237
  * const result = await loginWithSms('+8613800138000');
226
238
  * console.log('SMS sent:', result.smsId);
227
- * console.log('Type:', result.type); // 'login' or 'register'
239
+ * console.log('Type:', result.type); // 'login', 'register', or 'changePassword'
228
240
  * } catch (error) {
229
241
  * console.error('SMS sending failed:', error.message);
230
242
  * }
@@ -237,14 +249,21 @@ export async function loginWithSms(phone, options) {
237
249
  }
238
250
  // Determine base URL from environment variables
239
251
  const env = globalThis?.process?.env ?? import.meta?.env ?? undefined;
240
- const base = env?.TALE_BASE_URL;
252
+ const base = options?.baseUrl ?? env?.TALE_BASE_URL;
241
253
  if (!base) {
242
254
  throw new ConfigurationError("Missing required environment variable: TALE_BASE_URL");
243
255
  }
256
+ if (options?.smsType &&
257
+ !PASSWORD_CHANGE_SMS_SEND_TYPES.includes(options.smsType)) {
258
+ throw new ApiError('smsType must be "changePassword"', 400, "9400");
259
+ }
244
260
  // Use provided app token or get one from token service
245
- const authToken = options?.appToken ?? (await getAppToken());
261
+ const authToken = options?.appToken ?? (await getAppToken(options));
246
262
  const url = new URL(String(base).replace(/\/+$/, "") + "/auth/v2/sms/login-or-register");
247
263
  url.searchParams.append("phone", phone.trim());
264
+ if (options?.smsType) {
265
+ url.searchParams.append("smsType", options.smsType);
266
+ }
248
267
  let response;
249
268
  try {
250
269
  response = await globalThis.fetch(url.toString(), {
@@ -332,8 +351,9 @@ export async function verifySmsCode(request, options) {
332
351
  if (!request.smsId || request.smsId.trim() === "") {
333
352
  throw new ApiError("smsId is required", 400, "9400");
334
353
  }
335
- if (!request.smsType || !["login", "register"].includes(request.smsType)) {
336
- throw new ApiError('smsType must be "login" or "register"', 400, "9400");
354
+ if (!request.smsType ||
355
+ !LOGIN_OR_REGISTER_SMS_TYPES.includes(request.smsType)) {
356
+ throw new ApiError('smsType must be "login" or "register". Use verifyPasswordChangeSmsAndUpdatePassword for password changes', 400, "9400");
337
357
  }
338
358
  if (!request.verificationCode || request.verificationCode.trim() === "") {
339
359
  throw new ApiError("verificationCode is required", 400, "9400");
@@ -409,6 +429,91 @@ export async function verifySmsCode(request, options) {
409
429
  };
410
430
  return smsLoginResponse;
411
431
  }
432
+ /**
433
+ * Verifies password-change SMS code and updates user password.
434
+ *
435
+ * @param request - Password change SMS verification request
436
+ * @param options - Optional configuration for the request
437
+ * @returns Promise resolving to password update result
438
+ * @throws {ConfigurationError} When required environment variables are missing
439
+ * @throws {ApiError} When verification or password update fails
440
+ * @throws {NetworkError} When network request fails
441
+ */
442
+ export async function verifyPasswordChangeSmsAndUpdatePassword(request, options) {
443
+ if (!request.smsId || request.smsId.trim() === "") {
444
+ throw new ApiError("smsId is required", 400, "9400");
445
+ }
446
+ if (!request.smsType ||
447
+ !PASSWORD_CHANGE_SMS_TYPES.includes(request.smsType)) {
448
+ throw new ApiError('smsType must be "changePassword" or "reset_password"', 400, "9400");
449
+ }
450
+ if (!request.verificationCode || request.verificationCode.trim() === "") {
451
+ throw new ApiError("verificationCode is required", 400, "9400");
452
+ }
453
+ if (!request.passwordEncrypted ||
454
+ request.passwordEncrypted.trim() === "") {
455
+ throw new ApiError("passwordEncrypted is required", 400, "9400");
456
+ }
457
+ const env = globalThis?.process?.env ?? import.meta?.env ?? undefined;
458
+ const base = options?.baseUrl ?? env?.TALE_BASE_URL ?? undefined;
459
+ if (!base) {
460
+ throw new ConfigurationError("Missing required environment variable: TALE_BASE_URL");
461
+ }
462
+ const authToken = options?.appToken ?? (await getAppToken(options));
463
+ const url = String(base).replace(/\/+$/, "") + "/auth/v2/sms/password/verify";
464
+ const requestBody = {
465
+ smsId: request.smsId.trim(),
466
+ smsType: request.smsType,
467
+ verificationCode: request.verificationCode.trim(),
468
+ passwordEncrypted: request.passwordEncrypted,
469
+ };
470
+ let response;
471
+ try {
472
+ response = await globalThis.fetch(url, {
473
+ method: "POST",
474
+ headers: {
475
+ "x-t-token": authToken,
476
+ "Content-Type": "application/json",
477
+ },
478
+ body: JSON.stringify(requestBody),
479
+ });
480
+ }
481
+ catch (error) {
482
+ throw new NetworkError(`Failed to verify password change SMS: ${error instanceof Error ? error.message : "Unknown error"}`);
483
+ }
484
+ let json;
485
+ try {
486
+ const responseJson = await response.json();
487
+ json = responseJson;
488
+ }
489
+ catch (error) {
490
+ throw new ApiError(`Failed to parse password change SMS response: ${error instanceof Error ? error.message : "Invalid JSON"}`, response.status);
491
+ }
492
+ if (response.status === 400) {
493
+ const errorMsg = typeof json === "object" &&
494
+ json !== null &&
495
+ ("message" in json || "msg" in json)
496
+ ? String(json.message || json.msg)
497
+ : "Password change SMS verification failed";
498
+ throw new ApiError(errorMsg, response.status, "9400");
499
+ }
500
+ if (response.status === 403) {
501
+ throw new ApiError("Account is frozen or access forbidden", response.status, "9403");
502
+ }
503
+ if (!response.ok) {
504
+ const errorMsg = typeof json === "object" &&
505
+ json !== null &&
506
+ ("message" in json || "msg" in json)
507
+ ? String(json.message || json.msg)
508
+ : "Password change SMS verification failed";
509
+ throw new ApiError(errorMsg, response.status);
510
+ }
511
+ const responseData = json.data || json;
512
+ return {
513
+ success: true,
514
+ message: typeof responseData === "string" ? responseData : undefined,
515
+ };
516
+ }
412
517
  /**
413
518
  * Registers a new user with SMS verification and optional additional information.
414
519
  *
@@ -1,4 +1,5 @@
1
1
  import type { AppInfo, User, UserGroup, Role, Privilege, CommonOptions } from "../common/types.js";
2
+ import type { UserAttributeItemDTO } from "../user-attribute/types.js";
2
3
  export type { AppInfo, UserGroup };
3
4
  /**
4
5
  * Auth user information (extends User with non-null remark)
@@ -68,6 +69,7 @@ export interface LoginResponse {
68
69
  userPrivileges: AuthPrivilege[];
69
70
  userGroups: UserGroup[];
70
71
  userLoginMethods: AuthUserLoginMethod[];
72
+ userAttributes?: UserAttributeItemDTO[];
71
73
  }
72
74
  export interface LoginJson {
73
75
  app: AppInfo;
@@ -77,9 +79,14 @@ export interface LoginJson {
77
79
  userPrivileges: AuthPrivilege[];
78
80
  userGroups: UserGroup[];
79
81
  userLoginMethods: AuthUserLoginMethod[];
82
+ userAttributes?: UserAttributeItemDTO[];
80
83
  }
81
- export interface LoginWithSmsOptions {
82
- appToken?: string;
84
+ export type SmsType = "login" | "register" | "changePassword";
85
+ export type LoginOrRegisterSmsType = "login" | "register";
86
+ export type PasswordChangeSmsType = "changePassword" | "reset_password";
87
+ export type PasswordChangeSmsSendType = "changePassword";
88
+ export interface LoginWithSmsOptions extends CommonOptions {
89
+ smsType?: PasswordChangeSmsSendType;
83
90
  }
84
91
  export interface VerifySmsOptions extends CommonOptions {
85
92
  deviceName?: string;
@@ -89,24 +96,40 @@ export interface VerifySmsOptions extends CommonOptions {
89
96
  export interface SendSmsResponse {
90
97
  appKey: string;
91
98
  phone: string;
92
- type: "login" | "register";
99
+ type: SmsType;
93
100
  smsId: string;
94
101
  expiredAt: string;
95
102
  }
96
103
  export interface SendSmsJson {
97
104
  appKey: string;
98
105
  phone: string;
99
- type: "login" | "register";
106
+ type: SmsType;
100
107
  smsId: string;
101
108
  expiredAt: string;
102
109
  }
103
110
  export interface VerifySmsRequest {
104
111
  smsId: string;
105
- smsType: "login" | "register";
112
+ smsType: LoginOrRegisterSmsType;
106
113
  verificationCode: string;
107
114
  username?: string;
108
115
  passwordEncrypted?: string;
109
116
  }
117
+ export interface PasswordChangeSmsRequest {
118
+ smsId: string;
119
+ smsType: PasswordChangeSmsType;
120
+ verificationCode: string;
121
+ passwordEncrypted: string;
122
+ }
123
+ export interface PasswordChangeSmsResponse {
124
+ success: boolean;
125
+ message?: string;
126
+ }
127
+ export interface PasswordChangeSmsJson {
128
+ data?: string;
129
+ code?: number;
130
+ msg?: string;
131
+ message?: string;
132
+ }
110
133
  export interface SmsLoginResponse {
111
134
  app: AppInfo;
112
135
  user: AuthUser;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turinhub/tale-js-sdk",
3
- "version": "2.3.0",
3
+ "version": "2.4.1",
4
4
  "description": "Official TypeScript SDK for Tale backend services",
5
5
  "keywords": [
6
6
  "tale",