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