@cloudbase/oauth 2.6.3-beta.0 → 2.6.5-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.
Files changed (68) hide show
  1. package/dist/cjs/auth/apis.d.ts +17 -8
  2. package/dist/cjs/auth/apis.js +166 -23
  3. package/dist/cjs/auth/consts.d.ts +39 -4
  4. package/dist/cjs/auth/consts.js +38 -3
  5. package/dist/cjs/auth/models.d.ts +83 -6
  6. package/dist/cjs/auth/models.js +1 -1
  7. package/dist/cjs/index.d.ts +5 -8
  8. package/dist/cjs/index.js +3 -17
  9. package/dist/cjs/oauth2client/consts.d.ts +1 -48
  10. package/dist/cjs/oauth2client/consts.js +4 -51
  11. package/dist/cjs/oauth2client/models.d.ts +1 -0
  12. package/dist/cjs/oauth2client/models.js +1 -1
  13. package/dist/cjs/oauth2client/oauth2client.d.ts +5 -0
  14. package/dist/cjs/oauth2client/oauth2client.js +24 -18
  15. package/dist/cjs/utils/base64.d.ts +4 -0
  16. package/dist/cjs/utils/base64.js +99 -0
  17. package/dist/cjs/utils/cloudbase-adapter-wx_mp.d.ts +1 -0
  18. package/dist/cjs/utils/cloudbase-adapter-wx_mp.js +40 -0
  19. package/dist/cjs/utils/encrypt.d.ts +2 -2
  20. package/dist/cjs/utils/encrypt.js +5 -5
  21. package/dist/cjs/utils/encryptlong/index.d.ts +537 -145
  22. package/dist/cjs/utils/encryptlong/index.js +2712 -3765
  23. package/dist/esm/auth/apis.d.ts +17 -8
  24. package/dist/esm/auth/apis.js +468 -722
  25. package/dist/esm/auth/consts.d.ts +39 -4
  26. package/dist/esm/auth/consts.js +37 -3
  27. package/dist/esm/auth/models.d.ts +83 -6
  28. package/dist/esm/auth/models.js +0 -1
  29. package/dist/esm/captcha/captcha.js +155 -258
  30. package/dist/esm/index.d.ts +5 -8
  31. package/dist/esm/index.js +17 -31
  32. package/dist/esm/oauth2client/consts.d.ts +1 -48
  33. package/dist/esm/oauth2client/consts.js +1 -50
  34. package/dist/esm/oauth2client/interface.js +2 -7
  35. package/dist/esm/oauth2client/models.d.ts +1 -0
  36. package/dist/esm/oauth2client/models.js +0 -1
  37. package/dist/esm/oauth2client/oauth2client.d.ts +5 -0
  38. package/dist/esm/oauth2client/oauth2client.js +365 -631
  39. package/dist/esm/utils/base64.d.ts +4 -0
  40. package/dist/esm/utils/base64.js +91 -0
  41. package/dist/esm/utils/cloudbase-adapter-wx_mp.d.ts +1 -0
  42. package/dist/esm/utils/cloudbase-adapter-wx_mp.js +35 -0
  43. package/dist/esm/utils/encrypt.d.ts +2 -2
  44. package/dist/esm/utils/encrypt.js +5 -7
  45. package/dist/esm/utils/encryptlong/index.d.ts +537 -145
  46. package/dist/esm/utils/encryptlong/index.js +2605 -3687
  47. package/dist/esm/utils/function/single-promise.js +26 -89
  48. package/dist/esm/utils/index.js +7 -8
  49. package/dist/esm/utils/mp.js +2 -3
  50. package/dist/esm/utils/uuid.js +3 -4
  51. package/dist/miniprogram/index.js +1 -0
  52. package/package.json +11 -6
  53. package/src/auth/apis.ts +179 -36
  54. package/src/auth/consts.ts +37 -3
  55. package/src/auth/models.ts +318 -234
  56. package/src/index.ts +5 -29
  57. package/src/oauth2client/consts.ts +1 -51
  58. package/src/oauth2client/models.ts +1 -0
  59. package/src/oauth2client/oauth2client.ts +31 -17
  60. package/src/utils/base64.ts +100 -0
  61. package/src/utils/cloudbase-adapter-wx_mp.ts +42 -0
  62. package/src/utils/encrypt.ts +8 -6
  63. package/src/utils/encryptlong/index.js +2843 -4895
  64. package/tsconfig.esm.json +8 -19
  65. package/tsconfig.json +5 -16
  66. package/webpack/web.prod.js +100 -0
  67. package/webpack/webpack.miniprogram.js +23 -0
  68. package/src/index.d.ts +0 -1
package/src/index.ts CHANGED
@@ -1,33 +1,10 @@
1
1
  import { OAuth2Client } from './oauth2client/oauth2client'
2
-
3
2
  import { AuthOptions, Auth } from './auth/apis'
4
-
5
- import * as authModels from './auth/models'
6
-
7
- export { Syntax, ErrorType } from './oauth2client/consts'
8
-
9
- export {
10
- defaultStorage,
11
- defaultRequest,
12
- ToResponseErrorOptions,
13
- toResponseError,
14
- generateRequestId,
15
- OAuth2Client,
16
- } from './oauth2client/oauth2client'
17
-
18
- export { AuthClient, SimpleStorage } from './oauth2client/interface'
19
-
20
- export {
21
- Credentials,
22
- ResponseError,
23
- OAuth2ClientOptions,
24
- AuthClientRequestOptions,
25
- } from './oauth2client/models'
26
-
27
- export { AuthOptions, Auth } from './auth/apis'
28
- export { authModels }
29
- export { ApiUrls } from './auth/consts'
30
-
3
+ export { Auth } from './auth/apis'
4
+ export * as authModels from './auth/models'
5
+ export type { ProviderProfile } from './auth/models'
6
+ export type { Credentials, OAuth2ClientOptions, ResponseError, AuthClientRequestOptions } from './oauth2client/models'
7
+ export type { AuthOptions } from './auth/apis'
31
8
 
32
9
  export class CloudbaseOAuth {
33
10
  public oauth2client: OAuth2Client
@@ -53,4 +30,3 @@ export class CloudbaseOAuth {
53
30
  })
54
31
  }
55
32
  }
56
-
@@ -1,4 +1,4 @@
1
- import { ErrorType as _ErrorType } from '../auth/consts'
1
+ export { ErrorType } from '../auth/consts'
2
2
  export enum Syntax {
3
3
  CLIENT_ID = 'client_id',
4
4
  CLIENT_SECRET = 'client_secret',
@@ -18,53 +18,3 @@ export enum Syntax {
18
18
  PASSWORD = 'password',
19
19
  REFRESH_TOKEN = 'refresh_token',
20
20
  }
21
-
22
- export enum ErrorType {
23
- UNREACHABLE = 'unreachable',
24
- LOCAL = 'local',
25
- CANCELLED = 'cancelled',
26
- UNKNOWN = 'unknown',
27
- INVALID_ARGUMENT = 'invalid_argument',
28
- DEADLINE_EXCEEDED = 'deadline_exceeded',
29
- NOT_FOUND = 'not_found',
30
- ALREADY_EXISTS = 'already_exists',
31
- PERMISSION_DENIED = 'permission_denied',
32
- UNAUTHENTICATED = 'unauthenticated',
33
- RESOURCE_EXHAUSTED = 'resource_exhausted',
34
- FAILED_PRECONDITION = 'failed_precondition',
35
- ABORTED = 'aborted',
36
- OUT_OF_RANGE = 'out_of_range',
37
- UNIMPLEMENTED = 'unimplemented',
38
- INTERNAL = 'internal',
39
- UNAVAILABLE = 'unavailable',
40
- DATA_LOSS = 'data_loss',
41
- // CommonError
42
- CAPTCHA_REQUIRED = _ErrorType.CAPTCHA_REQUIRED,
43
- CAPTCHA_INVALID = _ErrorType.CAPTCHA_INVALID,
44
- INVALID_PASSWORD = 'invalid_password',
45
- INVALID_STATUS = 'invalid_status',
46
- USER_PENDING = 'user_pending',
47
- USER_BLOCKED = 'user_blocked',
48
- INVALID_VERIFICATION_CODE = 'invalid_verification_code',
49
- TWO_FACTOR_REQUIRED = 'two_factor_required',
50
- INVALID_TWO_FACTOR = 'invalid_two_factor',
51
- INVALID_TWO_FACTOR_RECOVERY = 'invalid_two_factor_recovery',
52
- UNDER_REVIEW = 'under_review',
53
- INVALID_REQUEST = 'invalid_request',
54
- UNAUTHORIZED_CLIENT = 'unauthorized_client',
55
- ACCESS_DENIED = 'access_denied',
56
- UNSUPPORTED_RESPONSE_TYPE = 'unsupported_response_type',
57
- INVALID_SCOPE = 'invalid_scope',
58
- INVALID_GRANT = 'invalid_grant',
59
- SERVER_ERROR = 'server_error',
60
- TEMPORARILY_UNAVAILABLE = 'temporarily_unavailable',
61
- INTERACTION_REQUIRED = 'interaction_required',
62
- LOGIN_REQUIRED = 'login_required',
63
- ACCOUNT_SELECTION_REQUIRED = 'account_selection_required',
64
- CONSENT_REQUIRED = 'consent_required',
65
- INVALID_REQUEST_URI = 'invalid_request_uri',
66
- INVALID_REQUEST_OBJECT = 'invalid_request_object',
67
- REQUEST_NOT_SUPPORTED = 'request_not_supported',
68
- REQUEST_URI_NOT_SUPPORTED = 'request_uri_not_supported',
69
- REGISTRATION_NOT_SUPPORTED = 'registration_not_supported',
70
- }
@@ -41,6 +41,7 @@ export interface AuthClientRequestOptions extends RequestOptions {
41
41
  [key: string]: any;
42
42
  } | null;
43
43
  withCredentials?: boolean;
44
+ withBasicAuth?: boolean;
44
45
  retry?: number;
45
46
  useWxCloud?: boolean;
46
47
 
@@ -1,6 +1,5 @@
1
1
  import { ErrorType } from './consts'
2
2
  import { ApiUrls, ApiUrlsV2 } from '../auth/consts'
3
- import adapterForWxMp from 'cloudbase-adapter-wx_mp'
4
3
 
5
4
  import { AuthClient, SimpleStorage } from './interface'
6
5
 
@@ -17,6 +16,8 @@ import { uuidv4 } from '../utils/uuid'
17
16
  import { getPathName } from '../utils/index'
18
17
 
19
18
  import { SinglePromise } from '../utils/function/single-promise'
19
+ import { weBtoa } from '../utils/base64'
20
+ import { isMatch } from '../utils/cloudbase-adapter-wx_mp'
20
21
 
21
22
  const RequestIdHeaderName = 'x-request-id'
22
23
  const DeviceIdHeaderName = 'x-device-id'
@@ -99,12 +100,20 @@ export function generateRequestId(): string {
99
100
  * Default Storage.
100
101
  */
101
102
  class DefaultStorage implements SimpleStorage {
103
+ /**
104
+ * 缓存key统一使用后缀区分
105
+ */
106
+ private readonly _env: string
107
+
108
+ constructor(opts?: { env: string }) {
109
+ this._env = opts?.env || ''
110
+ }
102
111
  /**
103
112
  * Get item.
104
113
  * @param {string} key
105
114
  */
106
115
  async getItem(key: string): Promise<string | null> {
107
- return window.localStorage.getItem(key)
116
+ return window.localStorage.getItem(`${key}${this._env}`)
108
117
  }
109
118
 
110
119
  /**
@@ -112,7 +121,7 @@ class DefaultStorage implements SimpleStorage {
112
121
  * @param {string} key
113
122
  */
114
123
  async removeItem(key: string): Promise<void> {
115
- window.localStorage.removeItem(key)
124
+ window.localStorage.removeItem(`${key}${this._env}`)
116
125
  }
117
126
 
118
127
  /**
@@ -121,7 +130,7 @@ class DefaultStorage implements SimpleStorage {
121
130
  * @param {string} value
122
131
  */
123
132
  async setItem(key: string, value: string): Promise<void> {
124
- window.localStorage.setItem(key, value)
133
+ window.localStorage.setItem(`${key}${this._env}`, value)
125
134
  }
126
135
 
127
136
  /**
@@ -129,7 +138,7 @@ class DefaultStorage implements SimpleStorage {
129
138
  * @param {string} key
130
139
  */
131
140
  getItemSync(key: string): string | null {
132
- return window.localStorage.getItem(key)
141
+ return window.localStorage.getItem(`${key}${this._env}`)
133
142
  }
134
143
 
135
144
  /**
@@ -137,7 +146,7 @@ class DefaultStorage implements SimpleStorage {
137
146
  * @param {string} key
138
147
  */
139
148
  removeItemSync(key: string): void {
140
- window.localStorage.removeItem(key)
149
+ window.localStorage.removeItem(`${key}${this._env}`)
141
150
  }
142
151
 
143
152
  /**
@@ -146,7 +155,7 @@ class DefaultStorage implements SimpleStorage {
146
155
  * @param {string} value
147
156
  */
148
157
  setItemSync(key: string, value: string): void {
149
- window.localStorage.setItem(key, value)
158
+ window.localStorage.setItem(`${key}${this._env}`, value)
150
159
  }
151
160
  }
152
161
 
@@ -289,6 +298,7 @@ export class OAuth2Client implements AuthClient {
289
298
  private singlePromise: SinglePromise = new SinglePromise()
290
299
  private anonymousSignInFunc: (Credentials) => Promise<Credentials | void>
291
300
  private wxCloud: any
301
+ private basicAuth: string
292
302
 
293
303
  /**
294
304
  * constructor
@@ -312,9 +322,12 @@ export class OAuth2Client implements AuthClient {
312
322
  storage: this.storage,
313
323
  })
314
324
  this.clientSecret = options.clientSecret
325
+ if (options.clientId !== '') {
326
+ this.basicAuth = `Basic ${weBtoa(`${options.clientId}:${options.clientSecret}`)}`
327
+ }
315
328
  this.wxCloud = options.wxCloud
316
329
  try {
317
- if (adapterForWxMp.isMatch() && this.wxCloud === undefined && options.env) {
330
+ if (isMatch() && this.wxCloud === undefined && options.env) {
318
331
  wx.cloud.init({ env: options.env })
319
332
  this.wxCloud = wx.cloud
320
333
  }
@@ -370,6 +383,9 @@ export class OAuth2Client implements AuthClient {
370
383
  const deviceId = await this.getDeviceId()
371
384
  options.headers[DeviceIdHeaderName] = deviceId
372
385
  }
386
+ if (options?.withBasicAuth && this.basicAuth) {
387
+ options.headers.Authorization = this.basicAuth
388
+ }
373
389
  if (options?.withCredentials) {
374
390
  const credentials = await this.getCredentials()
375
391
  if (credentials) {
@@ -416,10 +432,7 @@ export class OAuth2Client implements AuthClient {
416
432
  return response
417
433
  }
418
434
 
419
- public async wxCloudCallFunction<T>(
420
- url: string,
421
- options?: RequestOptions,
422
- ): Promise<T> {
435
+ public async wxCloudCallFunction<T>(url: string, options?: RequestOptions): Promise<T> {
423
436
  let result: T | null = null
424
437
  let responseError: ResponseError | null = null
425
438
  try {
@@ -462,6 +475,9 @@ export class OAuth2Client implements AuthClient {
462
475
  */
463
476
  public async getCredentials(): Promise<Credentials | null> {
464
477
  let credentials: Credentials = await this.localCredentials.getCredentials()
478
+ if (!credentials) {
479
+ return this.unAuthenticatedError('credentials not found')
480
+ }
465
481
  if (isCredentialsExpired(credentials)) {
466
482
  if (credentials && credentials.scope === 'anonymous') {
467
483
  if (this.anonymousSignInFunc) {
@@ -585,12 +601,10 @@ export class OAuth2Client implements AuthClient {
585
601
  return this.unAuthenticatedError('no anonymous in credentials')
586
602
  }
587
603
  try {
588
- const newCredentials: Credentials = await this.request('/auth/v1/signin/anonymously', {
604
+ const newCredentials: Credentials = await this.request(ApiUrls.AUTH_SIGN_IN_ANONYMOUSLY_URL, {
589
605
  method: 'POST',
590
- body: {
591
- client_id: this.clientId,
592
- client_secret: this.clientSecret,
593
- },
606
+ withBasicAuth: true,
607
+ body: {},
594
608
  })
595
609
  await this.localCredentials.setCredentials(newCredentials)
596
610
  return newCredentials
@@ -0,0 +1,100 @@
1
+ /* eslint-disable */
2
+ // weapp jwt-decode
3
+ const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
4
+ const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/
5
+
6
+ // btoa
7
+ export function weBtoa(string: string) {
8
+ string = String(string)
9
+ let bitmap
10
+ let a
11
+ let b
12
+ let c
13
+ let result = ''
14
+ let i = 0
15
+ const rest = string.length % 3
16
+
17
+ for (; i < string.length;) {
18
+ if ((a = string.charCodeAt(i++)) > 255 || (b = string.charCodeAt(i++)) > 255 || (c = string.charCodeAt(i++)) > 255) throw new TypeError('Failed to execute \'btoa\' on \'Window\': The string to be encoded contains characters outside of the Latin1 range.',)
19
+
20
+ bitmap = (a << 16) | (b << 8) | c
21
+ result
22
+ += b64.charAt((bitmap >> 18) & 63)
23
+ + b64.charAt((bitmap >> 12) & 63)
24
+ + b64.charAt((bitmap >> 6) & 63)
25
+ + b64.charAt(bitmap & 63)
26
+ }
27
+
28
+ return rest ? result.slice(0, rest - 3) + '==='.substring(rest) : result
29
+ }
30
+ // atob
31
+ export const weAtob = function (string: string) {
32
+ string = String(string).replace(/[\t\n\f\r ]+/g, '')
33
+ if (!b64re.test(string)) throw new TypeError('Failed to execute \'atob\' on \'Window\': The string to be decoded is not correctly encoded.')
34
+ string += '=='.slice(2 - (string.length & 3))
35
+ let bitmap
36
+ let result = ''
37
+ let r1
38
+ let r2
39
+ let i = 0
40
+ for (; i < string.length;) {
41
+ bitmap = (b64.indexOf(string.charAt(i++)) << 18)
42
+ | (b64.indexOf(string.charAt(i++)) << 12)
43
+ | ((r1 = b64.indexOf(string.charAt(i++))) << 6)
44
+ | (r2 = b64.indexOf(string.charAt(i++)))
45
+
46
+ result
47
+ += r1 === 64
48
+ ? String.fromCharCode((bitmap >> 16) & 255)
49
+ : r2 === 64
50
+ ? String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255)
51
+ : String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255, bitmap & 255)
52
+ }
53
+ return result
54
+ }
55
+
56
+ function b64DecodeUnicode(str: string) {
57
+ return decodeURIComponent(weAtob(str).replace(/(.)/g, (p) => {
58
+ let code = p.charCodeAt(0).toString(16)
59
+ .toUpperCase()
60
+ if (code.length < 2) {
61
+ code = `0${code}`
62
+ }
63
+ return `%${code}`
64
+ }),)
65
+ }
66
+
67
+ export function base64_url_decode(str: string) {
68
+ let output = str.replace(/-/g, '+').replace(/_/g, '/')
69
+ switch (output.length % 4) {
70
+ case 0:
71
+ break
72
+ case 2:
73
+ output += '=='
74
+ break
75
+ case 3:
76
+ output += '='
77
+ break
78
+ default:
79
+ throw new Error('Illegal base64url string!')
80
+ }
81
+
82
+ try {
83
+ return b64DecodeUnicode(output)
84
+ } catch (err) {
85
+ return weAtob(output)
86
+ }
87
+ }
88
+
89
+ export function weappJwtDecode(token: string, options?: any) {
90
+ if (typeof token !== 'string') {
91
+ throw new Error('Invalid token specified')
92
+ }
93
+ options = options || {}
94
+ const pos = options.header === true ? 0 : 1
95
+ try {
96
+ return JSON.parse(base64_url_decode(token.split('.')[pos]))
97
+ } catch (e) {
98
+ throw new Error(`Invalid token specified: ${e}` ? (e as any).message : '')
99
+ }
100
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * 判断是否为小程序runtime
3
+ */
4
+ declare const wx
5
+ declare const Page
6
+ export function isMatch(): boolean {
7
+ if (typeof wx === 'undefined') {
8
+ return false
9
+ }
10
+ if (typeof Page === 'undefined') {
11
+ return false
12
+ }
13
+ if (!wx.getSystemInfoSync) {
14
+ return false
15
+ }
16
+ if (!wx.getStorageSync) {
17
+ return false
18
+ }
19
+ if (!wx.setStorageSync) {
20
+ return false
21
+ }
22
+ if (!wx.connectSocket) {
23
+ return false
24
+ }
25
+ if (!wx.request) {
26
+ return false
27
+ }
28
+
29
+ try {
30
+ if (!wx.getSystemInfoSync()) {
31
+ return false
32
+ }
33
+
34
+ if (wx.getSystemInfoSync().AppPlatform === 'qq') {
35
+ return false
36
+ }
37
+ } catch (e) {
38
+ return false
39
+ }
40
+
41
+ return true
42
+ }
@@ -1,7 +1,9 @@
1
+ /**
2
+ * 魔改的 encryptlong 版本, 只支持 encryptLong 方法
3
+ * 小程序上 JSEncrypt 为空不支持 @important
4
+ */
1
5
  import JSEncrypt from './encryptlong'
2
- // import HmacSHA256 from 'crypto-js/hmac-sha256'
3
- // import WordArray from 'crypto-js/lib-typedarrays'
4
- import { deepClone } from '.'
6
+ import { deepClone } from './index'
5
7
 
6
8
  /**
7
9
  * 生成RSA公钥加密后的数据
@@ -9,13 +11,13 @@ import { deepClone } from '.'
9
11
  * @param param0.payload 加密前的数据
10
12
  * @returns {string} 加密后的数据
11
13
  */
12
- export const getEncryptInfo = ({ publicKey = '', payload = {} } = {}) => {
14
+ export const getEncryptInfo = ({ publicKey = '', payload = {} as any } = {}) => {
13
15
  if (!publicKey) return ''
14
16
 
15
17
  try {
16
18
  const params = deepClone(payload)
17
19
  // 生成RSA实例
18
- const rsaInstance = new JSEncrypt()
20
+ const rsaInstance = new JSEncrypt({})
19
21
  // 设置公钥
20
22
  rsaInstance.setPublicKey(publicKey)
21
23
  // 生成时间戳
@@ -31,7 +33,7 @@ export const getEncryptInfo = ({ publicKey = '', payload = {} } = {}) => {
31
33
  // params.nonce = nonce
32
34
  // params.signMethod = signMethod
33
35
  // rsa公钥加密
34
- const encrypted = rsaInstance.encryptLong(JSON.stringify(params))
36
+ const encrypted = rsaInstance.encryptLong(typeof params === 'object' ? JSON.stringify(params) : params)
35
37
 
36
38
  return encrypted
37
39
  } catch (error) {