@cloudbase/oauth 2.5.36-beta.0 → 2.5.38-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.
package/src/auth/apis.ts CHANGED
@@ -41,13 +41,15 @@ import {
41
41
  CheckIfUserExistRequest,
42
42
  CheckIfUserExistResponse,
43
43
  WithSudoRequest,
44
+ PublicKey,
45
+ EncryptParams,
44
46
  } from './models'
45
47
  import { SimpleStorage, RequestFunction } from '../oauth2client/interface'
46
48
  import { OAuth2Client, defaultStorage } from '../oauth2client/oauth2client'
47
49
  import { Credentials } from '../oauth2client/models'
48
50
  import { Captcha } from '../captcha/captcha'
49
51
  import { deepClone } from '../utils'
50
-
52
+ import { getEncryptInfo } from '../utils/encrypt'
51
53
 
52
54
  export interface AuthOptions {
53
55
  apiOrigin: string;
@@ -55,7 +57,7 @@ export interface AuthOptions {
55
57
  credentialsClient?: OAuth2Client;
56
58
  request?: RequestFunction;
57
59
  storage?: SimpleStorage;
58
- anonymousSignInFunc?: (Credentials) => Promise<Credentials | void>
60
+ anonymousSignInFunc?: (Credentials) => Promise<Credentials | void>;
59
61
  }
60
62
 
61
63
  /**
@@ -137,14 +139,18 @@ export class Auth {
137
139
  delete res.params.query
138
140
  }
139
141
 
142
+ const body = await this.getEncryptParams(res.params)
140
143
  const credentials: Credentials = await this.config.request<Credentials>(
141
144
  res.url,
142
145
  {
143
146
  method: 'POST',
144
- body: res.params,
145
- },
147
+ body,
148
+ }
146
149
  )
147
- await this.config.credentialsClient.setCredentials({ ...credentials, version })
150
+ await this.config.credentialsClient.setCredentials({
151
+ ...credentials,
152
+ version,
153
+ })
148
154
  return Promise.resolve(credentials)
149
155
  }
150
156
 
@@ -153,14 +159,14 @@ export class Auth {
153
159
  * @return {Promise<Credentials>} A Promise<Credentials> object.
154
160
  */
155
161
  public async signInAnonymously(data: {
156
- provider_token?: string
162
+ provider_token?: string;
157
163
  } = {}): Promise<Credentials> {
158
164
  const credentials: Credentials = await this.config.request<Credentials>(
159
165
  ApiUrls.AUTH_SIGN_IN_ANONYMOUSLY_URL,
160
166
  {
161
167
  method: 'POST',
162
168
  body: data,
163
- },
169
+ }
164
170
  )
165
171
  await this.config.credentialsClient.setCredentials(credentials)
166
172
  return Promise.resolve(credentials)
@@ -177,7 +183,7 @@ export class Auth {
177
183
  {
178
184
  method: 'POST',
179
185
  body: params,
180
- },
186
+ }
181
187
  )
182
188
  await this.config.credentialsClient.setCredentials(data)
183
189
  return Promise.resolve(data)
@@ -188,7 +194,7 @@ export class Auth {
188
194
  * @return {Object} A Promise<void> object.
189
195
  */
190
196
  public async signOut(): Promise<any> {
191
- const accessToken: string = await this.config.credentialsClient.getAccessToken()
197
+ const accessToken: string = await this.config.credentialsClient.getAccessToken()
192
198
  const data = await this.config.request(ApiUrls.AUTH_REVOKE_URL, {
193
199
  method: 'POST',
194
200
  body: {
@@ -204,7 +210,7 @@ export class Auth {
204
210
  * @param {GetVerificationRequest} params A GetVerificationRequest Object.
205
211
  * @return {Promise<GetVerificationResponse>} A Promise<GetVerificationResponse> object.
206
212
  */
207
- public async getVerification(params: GetVerificationRequest,): Promise<GetVerificationResponse> {
213
+ public async getVerification(params: GetVerificationRequest): Promise<GetVerificationResponse> {
208
214
  let withCredentials = false
209
215
  // 发送短信时,如果时给当前用户发,则需要带上鉴权信息
210
216
  if (params.target === 'CUR_USER') {
@@ -222,7 +228,7 @@ export class Auth {
222
228
  body: params,
223
229
  withCaptcha: true,
224
230
  withCredentials,
225
- },
231
+ }
226
232
  )
227
233
  }
228
234
 
@@ -239,7 +245,10 @@ export class Auth {
239
245
  })
240
246
 
241
247
  if (params?.version === 'v2') {
242
- await this.config.credentialsClient.setCredentials({ ...data, version: 'v2' })
248
+ await this.config.credentialsClient.setCredentials({
249
+ ...data,
250
+ version: 'v2',
251
+ })
243
252
  }
244
253
 
245
254
  return data
@@ -250,9 +259,10 @@ export class Auth {
250
259
  * @param {GenProviderRedirectUriRequest} params A GenProviderRedirectUriRequest object.
251
260
  * @return {Promise<GenProviderRedirectUriResponse>} A Promise<GenProviderRedirectUriResponse> object.
252
261
  */
253
- public async genProviderRedirectUri(params: GenProviderRedirectUriRequest,): Promise<GenProviderRedirectUriResponse> {
254
- let url = `${ApiUrls.PROVIDER_URI_URL}?client_id=${this.config.clientId
255
- }&provider_id=${params.provider_id}&redirect_uri=${encodeURIComponent(params.provider_redirect_uri,)}&state=${params.state}`
262
+ public async genProviderRedirectUri(params: GenProviderRedirectUriRequest): Promise<GenProviderRedirectUriResponse> {
263
+ let url = `${ApiUrls.PROVIDER_URI_URL}?client_id=${
264
+ this.config.clientId
265
+ }&provider_id=${params.provider_id}&redirect_uri=${encodeURIComponent(params.provider_redirect_uri)}&state=${params.state}`
256
266
  const { other_params: otherParams } = params
257
267
  if (otherParams) {
258
268
  if (
@@ -272,13 +282,13 @@ export class Auth {
272
282
  * @param {GrantProviderTokenRequest} params A GrantProviderTokenRequest object.
273
283
  * @return {Promise<GrantProviderTokenResponse>} A Promise<GrantProviderTokenResponse> object.
274
284
  */
275
- public async grantProviderToken(params: GrantProviderTokenRequest,): Promise<GrantProviderTokenResponse> {
285
+ public async grantProviderToken(params: GrantProviderTokenRequest): Promise<GrantProviderTokenResponse> {
276
286
  return this.config.request<GrantProviderTokenResponse>(
277
287
  ApiUrls.PROVIDER_TOKEN_URL,
278
288
  {
279
289
  method: 'POST',
280
290
  body: params,
281
- },
291
+ }
282
292
  )
283
293
  }
284
294
 
@@ -287,13 +297,13 @@ export class Auth {
287
297
  * @param {PatchProviderTokenRequest} params A PatchProviderTokenRequest object.
288
298
  * @return {Promise<PatchProviderTokenResponse>} A Promise<PatchProviderTokenResponse> object.
289
299
  */
290
- public async patchProviderToken(params: PatchProviderTokenRequest,): Promise<PatchProviderTokenResponse> {
300
+ public async patchProviderToken(params: PatchProviderTokenRequest): Promise<PatchProviderTokenResponse> {
291
301
  return this.config.request<PatchProviderTokenResponse>(
292
302
  ApiUrls.PROVIDER_TOKEN_URL,
293
303
  {
294
304
  method: 'PATCH',
295
305
  body: params,
296
- },
306
+ }
297
307
  )
298
308
  }
299
309
 
@@ -302,16 +312,22 @@ export class Auth {
302
312
  * @param {SignInWithProviderRequest} params A SignInWithProviderRequest object.
303
313
  * @return {Promise<Credentials>} A Promise<Credentials> object.
304
314
  */
305
- public async signInWithProvider(params: SignInWithProviderRequest,): Promise<Credentials> {
306
- const res = this.getParamsByVersion(params, 'AUTH_SIGN_IN_WITH_PROVIDER_URL')
315
+ public async signInWithProvider(params: SignInWithProviderRequest): Promise<Credentials> {
316
+ const res = this.getParamsByVersion(
317
+ params,
318
+ 'AUTH_SIGN_IN_WITH_PROVIDER_URL'
319
+ )
307
320
  const credentials: Credentials = await this.config.request<Credentials>(
308
321
  res.url,
309
322
  {
310
323
  method: 'POST',
311
324
  body: res.params,
312
- },
325
+ }
313
326
  )
314
- await this.config.credentialsClient.setCredentials({ ...credentials, version: params?.version || 'v1' })
327
+ await this.config.credentialsClient.setCredentials({
328
+ ...credentials,
329
+ version: params?.version || 'v1',
330
+ })
315
331
  return Promise.resolve(credentials)
316
332
  }
317
333
 
@@ -320,7 +336,7 @@ export class Auth {
320
336
  * @param {BindWithProviderRequest} params A BindWithProviderRequest object.
321
337
  * @return {Promise<void>} A Promise<any> object.
322
338
  */
323
- public async bindWithProvider(params: BindWithProviderRequest,): Promise<void> {
339
+ public async bindWithProvider(params: BindWithProviderRequest): Promise<void> {
324
340
  return this.config.request<any>(ApiUrls.PROVIDER_BIND_URL, {
325
341
  method: 'POST',
326
342
  body: params,
@@ -332,7 +348,9 @@ export class Auth {
332
348
  * Get the user profile.
333
349
  * @return {Promise<UserProfile>} A Promise<UserProfile> object.
334
350
  */
335
- public async getUserProfile(params: { version?: string }): Promise<UserProfile> {
351
+ public async getUserProfile(params: {
352
+ version?: string;
353
+ }): Promise<UserProfile> {
336
354
  return this.getUserInfo(params)
337
355
  }
338
356
 
@@ -340,7 +358,7 @@ export class Auth {
340
358
  * Get the user info.
341
359
  * @return {Promise<UserInfo>} A Promise<UserProfile> object.
342
360
  */
343
- public async getUserInfo(params: { version?: string, query?: string } = {}): Promise<UserInfo> {
361
+ public async getUserInfo(params: { version?: string; query?: string } = {}): Promise<UserInfo> {
344
362
  const res = this.getParamsByVersion(params, 'USER_ME_URL')
345
363
 
346
364
  if (res.params?.query) {
@@ -373,9 +391,9 @@ export class Auth {
373
391
  }
374
392
 
375
393
  /**
376
- * Delete me
377
- * @param params
378
- */
394
+ * Delete me
395
+ * @param params
396
+ */
379
397
  public async deleteMe(params: WithSudoRequest): Promise<UserProfile> {
380
398
  const res = this.getParamsByVersion(params, 'USER_ME_URL')
381
399
  const url = `${res.url}?${Auth.parseParamsToSearch(res.params)}`
@@ -412,14 +430,14 @@ export class Auth {
412
430
  * @param {TransByProviderRequest} params A TransByProviderRequest object.
413
431
  * @return {Promise<Credentials>} A Promise<Credentials> object.
414
432
  */
415
- public async transByProvider(params: TransByProviderRequest,): Promise<Credentials> {
433
+ public async transByProvider(params: TransByProviderRequest): Promise<Credentials> {
416
434
  return this.config.request<Credentials>(
417
435
  ApiUrls.USER_TRANS_BY_PROVIDER_URL,
418
436
  {
419
437
  method: 'PATCH',
420
438
  body: params,
421
439
  withCredentials: true,
422
- },
440
+ }
423
441
  )
424
442
  }
425
443
 
@@ -458,7 +476,7 @@ export class Auth {
458
476
  {
459
477
  method: 'DELETE',
460
478
  withCredentials: true,
461
- },
479
+ }
462
480
  )
463
481
  }
464
482
 
@@ -515,10 +533,10 @@ export class Auth {
515
533
  }
516
534
 
517
535
  /**
518
- * updatePasswordByOld 使用旧密码修改密码,如果已经绑定手机号,请先:sudo,再修改密码
519
- * @param {SetPasswordrRequest} params
520
- * @return {Promise<any>}
521
- */
536
+ * updatePasswordByOld 使用旧密码修改密码,如果已经绑定手机号,请先:sudo,再修改密码
537
+ * @param {SetPasswordrRequest} params
538
+ * @return {Promise<any>}
539
+ */
522
540
  public async updatePasswordByOld(params: UpdatePasswordRequest): Promise<void> {
523
541
  const sudoToken = await this.sudo({ password: params.old_password })
524
542
  return this.setPassword({
@@ -527,7 +545,6 @@ export class Auth {
527
545
  })
528
546
  }
529
547
 
530
-
531
548
  /**
532
549
  * sudo
533
550
  * @param {sudo} params
@@ -546,7 +563,7 @@ export class Auth {
546
563
  * @param {GetVerificationRequest} params A GetVerificationRequest Object.
547
564
  * @return {Promise<GetVerificationResponse>} A Promise<GetVerificationResponse> object.
548
565
  */
549
- public async getCurUserVerification(params: GetVerificationRequest,): Promise<GetVerificationResponse> {
566
+ public async getCurUserVerification(params: GetVerificationRequest): Promise<GetVerificationResponse> {
550
567
  params.target = 'CUR_USER'
551
568
  return this.config.request<GetVerificationResponse>(
552
569
  ApiUrls.VERIFICATION_URL,
@@ -555,7 +572,7 @@ export class Auth {
555
572
  body: params,
556
573
  withCredentials: true,
557
574
  withCaptcha: true,
558
- },
575
+ }
559
576
  )
560
577
  }
561
578
 
@@ -564,7 +581,7 @@ export class Auth {
564
581
  * @param {GetVerificationRequest} params A GetVerificationRequest Object.
565
582
  * @return {Promise<GetVerificationResponse>} A Promise<GetVerificationResponse> object.
566
583
  */
567
- public async changeBindedProvider(params: ChangeBindedProviderRequest,): Promise<ChangeBindedProviderResponse> {
584
+ public async changeBindedProvider(params: ChangeBindedProviderRequest): Promise<ChangeBindedProviderResponse> {
568
585
  return this.config.request<ChangeBindedProviderResponse>(
569
586
  `${ApiUrls.PROVIDER_LIST}/${params.provider_id}/trans`,
570
587
  {
@@ -573,7 +590,7 @@ export class Auth {
573
590
  provider_trans_token: params.trans_token,
574
591
  },
575
592
  withCredentials: true,
576
- },
593
+ }
577
594
  )
578
595
  }
579
596
 
@@ -595,14 +612,17 @@ export class Auth {
595
612
  * @param {QueryUserProfileReq} appended_params A QueryUserProfileReq Object.
596
613
  * @return {Promise<UserProfile>} A Promise<UserProfile> object.
597
614
  */
598
- public async queryUserProfile(params: QueryUserProfileRequest,): Promise<QueryUserProfileResponse> {
615
+ public async queryUserProfile(params: QueryUserProfileRequest): Promise<QueryUserProfileResponse> {
599
616
  // let url = new URL(ApiUrls.USER_QUERY_URL);
600
617
  const searchParams = new URLSearchParams(params as any)
601
618
  // url.search = searchParams.toString();
602
- return this.config.request<QueryUserProfileResponse>(`${ApiUrls.USER_QUERY_URL}?${searchParams.toString()}`, {
603
- method: 'GET',
604
- withCredentials: true,
605
- })
619
+ return this.config.request<QueryUserProfileResponse>(
620
+ `${ApiUrls.USER_QUERY_URL}?${searchParams.toString()}`,
621
+ {
622
+ method: 'GET',
623
+ withCredentials: true,
624
+ }
625
+ )
606
626
  }
607
627
 
608
628
  /**
@@ -617,7 +637,9 @@ export class Auth {
617
637
  * SignInWithCustomTicket custom signIn
618
638
  * @constructor
619
639
  */
620
- public async signInWithCustomTicket(params?: { version?: string}): Promise<Credentials> {
640
+ public async signInWithCustomTicket(params?: {
641
+ version?: string;
642
+ }): Promise<Credentials> {
621
643
  const customTicket = await this.getCustomSignTicketFn()
622
644
  return this.signInWithProvider({
623
645
  ...params,
@@ -665,9 +687,12 @@ export class Auth {
665
687
  public async checkIfUserExist(params: CheckIfUserExistRequest): Promise<CheckIfUserExistResponse> {
666
688
  const searchParams = new URLSearchParams(params as any)
667
689
 
668
- return this.config.request<CheckIfUserExistResponse>(`${ApiUrls.CHECK_IF_USER_EXIST}?${searchParams.toString()}`, {
669
- method: 'GET',
670
- })
690
+ return this.config.request<CheckIfUserExistResponse>(
691
+ `${ApiUrls.CHECK_IF_USER_EXIST}?${searchParams.toString()}`,
692
+ {
693
+ method: 'GET',
694
+ }
695
+ )
671
696
  }
672
697
 
673
698
  public async loginScope(): Promise<string> {
@@ -678,12 +703,59 @@ export class Auth {
678
703
  return this.config.credentialsClient.getGroups()
679
704
  }
680
705
 
681
- public async refreshTokenForce(params: { version?: string}) {
682
- const credentials: Credentials = await this.config.credentialsClient.getCredentials()
683
- return await this.config.credentialsClient.refreshToken({ ...credentials, version: params?.version || 'v1' })
706
+ public async refreshTokenForce(params: { version?: string }) {
707
+ const credentials: Credentials = await this.config.credentialsClient.getCredentials()
708
+ return await this.config.credentialsClient.refreshToken({
709
+ ...credentials,
710
+ version: params?.version || 'v1',
711
+ })
684
712
  }
685
713
 
686
714
  public async getCredentials() {
687
715
  return this.config.credentialsClient.getCredentials()
688
716
  }
717
+
718
+ /**
719
+ * get public key for request params encryption
720
+ * @returns
721
+ */
722
+ public async getPublicKey(): Promise<PublicKey> {
723
+ return this.config.request<PublicKey>(ApiUrlsV2.AUTH_PUBLIC_KEY, {
724
+ method: 'POST',
725
+ body: {},
726
+ })
727
+ }
728
+
729
+ /**
730
+ * encrypt request params
731
+ * @param params
732
+ * @returns
733
+ */
734
+ public async getEncryptParams(params: Record<any, any>): Promise<EncryptParams> {
735
+ const payload = deepClone(params)
736
+
737
+ if (!payload.isEncrypt) {
738
+ return params
739
+ }
740
+
741
+ let publicKey = ''
742
+ let public_key_thumbprint = ''
743
+
744
+ try {
745
+ const res = await this.getPublicKey()
746
+ publicKey = res.public_key
747
+ public_key_thumbprint = res.public_key_thumbprint
748
+ } catch (error) {}
749
+
750
+ if (!publicKey || !public_key_thumbprint) {
751
+ throw new Error('public_key or public_key_thumbprint is empty')
752
+ }
753
+
754
+ delete payload.isEncrypt
755
+
756
+ return {
757
+ params: getEncryptInfo({ publicKey, payload }),
758
+ public_key_thumbprint,
759
+ }
760
+ }
689
761
  }
@@ -32,7 +32,8 @@ export enum ApiUrlsV2 {
32
32
  AUTH_TOKEN_URL = '/auth/v2/token',
33
33
  USER_ME_URL = '/auth/v2/user/me',
34
34
  VERIFY_URL = '/auth/v2/signin/verificationcode',
35
- AUTH_SIGN_IN_WITH_PROVIDER_URL = '/auth/v2/signin/with/provider'
35
+ AUTH_SIGN_IN_WITH_PROVIDER_URL = '/auth/v2/signin/with/provider',
36
+ AUTH_PUBLIC_KEY = '/auth/v2/signin/publichkey'
36
37
  }
37
38
 
38
39
  export enum VerificationUsages {
@@ -4,7 +4,7 @@ interface BaseRequest {
4
4
 
5
5
  export type GetCustomSignTicketFn = () => Promise<string>;
6
6
 
7
- export interface SignInRequest extends BaseRequest {
7
+ export interface SignInRequest extends BaseRequest, EncryptParams {
8
8
  username?: string;
9
9
  password?: string;
10
10
  verification_token?: string;
@@ -453,3 +453,14 @@ export interface CheckIfUserExistRequest {
453
453
  export interface CheckIfUserExistResponse {
454
454
  exist: boolean;
455
455
  }
456
+
457
+ export interface PublicKey {
458
+ public_key: string; // 加密的公钥
459
+ public_key_thumbprint: string; // 加密的公钥指纹
460
+ }
461
+
462
+ export interface EncryptParams {
463
+ isEncrypt?: boolean; // 是否需要加密
464
+ public_key_thumbprint?: string; // 加密的公钥指纹
465
+ params?: string; // 加密的数据
466
+ }
@@ -0,0 +1,42 @@
1
+ import JSEncrypt from 'encryptlong'
2
+ import HmacSHA256 from 'crypto-js/hmac-sha256'
3
+ import WordArray from 'crypto-js/lib-typedarrays'
4
+ import { deepClone } from '.'
5
+
6
+ /**
7
+ * 生成RSA公钥加密后的数据
8
+ * @param param0.publicKey RSA公钥
9
+ * @param param0.payload 加密前的数据
10
+ * @returns {string} 加密后的数据
11
+ */
12
+ export const getEncryptInfo = ({ publicKey = '', payload = {} } = {}) => {
13
+ if (!publicKey) return ''
14
+
15
+ try {
16
+ const params = deepClone(payload)
17
+ // 生成RSA实例
18
+ const rsaInstance = new JSEncrypt()
19
+ // 设置公钥
20
+ rsaInstance.setPublicKey(publicKey)
21
+ // 生成时间戳
22
+ params.timestamp = +new Date()
23
+ // 确定签名算法
24
+ const signMethod = 'HmacSHA256'
25
+ // 生成随机数
26
+ const nonce = WordArray.random(16).toString()
27
+ // 生成签名:基本参数、时间戳 + 随机数
28
+ const signature = HmacSHA256(JSON.stringify(params), nonce).toString()
29
+ // 将签名放入参数中
30
+ params.signature = signature
31
+ params.nonce = nonce
32
+ params.signMethod = signMethod
33
+ // rsa公钥加密
34
+ const encrypted = rsaInstance.encryptLong(JSON.stringify(params))
35
+
36
+ return encrypted
37
+ } catch (error) {
38
+ //
39
+ }
40
+
41
+ return ''
42
+ }