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