@cloudbase/oauth 0.1.1-alpha.7 → 0.1.1-alpha.9

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 (54) hide show
  1. package/dist/app/index.d.ts +7 -4
  2. package/dist/app/index.js +7 -4
  3. package/dist/app/internal.js +0 -1
  4. package/dist/app/openuri.d.ts +1 -0
  5. package/dist/app/openuri.js +10 -8
  6. package/dist/app/request.js +0 -1
  7. package/dist/app/storage.js +0 -1
  8. package/dist/auth/consts.d.ts +3 -0
  9. package/dist/auth/consts.js +3 -1
  10. package/dist/auth/index.d.ts +26 -6
  11. package/dist/auth/index.js +64 -43
  12. package/dist/auth/models.js +0 -1
  13. package/dist/captcha/index.d.ts +10 -9
  14. package/dist/captcha/index.js +69 -50
  15. package/dist/function/index.js +0 -1
  16. package/dist/index.js +0 -1
  17. package/dist/oauthclient/consts.js +0 -1
  18. package/dist/oauthclient/index.js +0 -1
  19. package/dist/oauthclient/interface.js +0 -1
  20. package/dist/oauthclient/models.js +0 -1
  21. package/dist/oauthclient/oauthclient.js +0 -1
  22. package/dist/package.json +1 -1
  23. package/dist/utils/base64.js +0 -1
  24. package/dist/utils/mp.d.ts +2 -0
  25. package/dist/utils/mp.js +57 -0
  26. package/dist/utils/promise.js +0 -1
  27. package/dist/utils/uuid.js +0 -1
  28. package/package.json +1 -1
  29. package/src/app/index.ts +64 -64
  30. package/src/app/openuri.ts +14 -7
  31. package/src/auth/consts.ts +69 -66
  32. package/src/auth/index.ts +156 -209
  33. package/src/captcha/index.ts +165 -138
  34. package/src/utils/mp.ts +55 -0
  35. package/tsconfig.json +5 -18
  36. package/dist/app/index.js.map +0 -1
  37. package/dist/app/internal.js.map +0 -1
  38. package/dist/app/openuri.js.map +0 -1
  39. package/dist/app/request.js.map +0 -1
  40. package/dist/app/storage.js.map +0 -1
  41. package/dist/auth/consts.js.map +0 -1
  42. package/dist/auth/index.js.map +0 -1
  43. package/dist/auth/models.js.map +0 -1
  44. package/dist/captcha/index.js.map +0 -1
  45. package/dist/function/index.js.map +0 -1
  46. package/dist/index.js.map +0 -1
  47. package/dist/oauthclient/consts.js.map +0 -1
  48. package/dist/oauthclient/index.js.map +0 -1
  49. package/dist/oauthclient/interface.js.map +0 -1
  50. package/dist/oauthclient/models.js.map +0 -1
  51. package/dist/oauthclient/oauthclient.js.map +0 -1
  52. package/dist/utils/base64.js.map +0 -1
  53. package/dist/utils/promise.js.map +0 -1
  54. package/dist/utils/uuid.js.map +0 -1
@@ -1,13 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Captcha = exports.getCaptcha = void 0;
4
+ const consts_1 = require("../auth/consts");
4
5
  const internal_1 = require("../app/internal");
6
+ const mp_1 = require("../utils/mp");
5
7
  function getCaptcha(app, opts) {
6
- return (0, internal_1._getComponent)(app, "captcha", () => {
8
+ return (0, internal_1._getComponent)(app, 'captcha', () => {
7
9
  const initOpts = {
10
+ ...app.options.captchaOptions,
11
+ clientId: app.options.clientId,
8
12
  request: app.options.request,
9
13
  storage: app.options.storage,
10
- openURIWithCallback: app.options.openURIWithCallback,
11
14
  };
12
15
  if (opts && opts.request) {
13
16
  initOpts.request = opts.request;
@@ -16,15 +19,14 @@ function getCaptcha(app, opts) {
16
19
  });
17
20
  }
18
21
  exports.getCaptcha = getCaptcha;
19
- const GET_CAPTCHA_URL = '/auth/v1/captcha/init';
20
22
  class Captcha {
21
23
  /**
22
24
  * constructor
23
25
  * @param {CaptchaOptions} opts
24
26
  */
25
27
  constructor(opts) {
26
- this._config = opts;
27
- this._tokenSectionName = 'captcha_';
28
+ this.config = opts;
29
+ this.tokenSectionName = `captcha_${opts.clientId || ''}`;
28
30
  }
29
31
  /**
30
32
  * request http like simple fetch api, exp:request('/v1/user/me', {withCredentials:true})
@@ -38,79 +40,97 @@ class Captcha {
38
40
  if (!options.method) {
39
41
  options.method = 'GET';
40
42
  }
41
- const state = options.method + ":" + url;
43
+ const state = `${options.method}:${url}`;
42
44
  let reqURL = url;
43
45
  if (options.withCaptcha) {
44
- reqURL = await this._appendCaptchaTokenToURL(url, state, false);
46
+ reqURL = await this.appendCaptchaTokenToURL(url, state, false);
45
47
  }
46
48
  let resp;
47
49
  try {
48
- resp = await this._config.request(reqURL, options);
50
+ resp = await this.config.request(reqURL, options);
49
51
  }
50
52
  catch (err) {
51
- if (err.error === 'captcha_required' || err.error === 'captcha_invalid') {
52
- url = await this._appendCaptchaTokenToURL(url, state, err.error === 'captcha_invalid');
53
- return this._config.request(url, options);
54
- }
55
- else {
56
- return Promise.reject(err);
53
+ if (err.error === consts_1.ErrorType.CAPTCHA_REQUIRED || err.error === consts_1.ErrorType.CAPTCHA_INVALID) {
54
+ url = await this.appendCaptchaTokenToURL(url, state, err.error === consts_1.ErrorType.CAPTCHA_INVALID);
55
+ return this.config.request(url, options);
57
56
  }
57
+ return Promise.reject(err);
58
58
  }
59
59
  return resp;
60
60
  }
61
61
  /**
62
- * _getCaptchaToken get captcha token
62
+ * getCaptchaToken 获取captchaToken
63
63
  */
64
- async _getCaptchaToken(forceNewToken, state) {
64
+ async getCaptchaToken(forceNewToken, state) {
65
65
  if (!forceNewToken) {
66
- // if local has captcha token then return
67
- const captchaToken = await this._findCaptchaToken();
66
+ // 如果本地存在,则直接返回
67
+ const captchaToken = await this.findCaptchaToken();
68
68
  if (captchaToken) {
69
69
  return captchaToken;
70
70
  }
71
71
  }
72
- const redirectURL = window.location.origin + window.location.pathname;
73
- const captchaTokenResp = await this._config.request(GET_CAPTCHA_URL, {
74
- method: 'POST',
75
- body: {
76
- redirect_uri: redirectURL,
77
- state: state
78
- },
79
- withBasicAuth: true,
80
- });
81
- if (captchaTokenResp.captcha_token) {
82
- const captchaToken = {
83
- captcha_token: captchaTokenResp.captcha_token,
84
- expires_in: captchaTokenResp.expires_in,
72
+ let captchaTokenResp;
73
+ if ((0, mp_1.isMp)() || (0, mp_1.isInMpWebView)()) {
74
+ /**
75
+ * https://iwiki.woa.com/p/4010699417
76
+ */
77
+ const captchaDataResp = await this.config.request(consts_1.ApiUrls.CAPTCHA_DATA_URL, {
78
+ method: 'POST',
79
+ body: {
80
+ state,
81
+ redirect_uri: '',
82
+ },
83
+ withBasicAuth: true,
84
+ withCredentials: false,
85
+ });
86
+ captchaTokenResp = {
87
+ url: `${captchaDataResp.data}?state=${encodeURIComponent(state)}&token=${captchaDataResp.token}`,
85
88
  };
86
- await this._saveCaptchaToken(captchaToken);
87
- return captchaTokenResp.captcha_token;
88
89
  }
89
- const callbackData = await this._config.openURIWithCallback(captchaTokenResp.url, { width: '355px', height: '355px' });
90
- const captchaToken = {
91
- captcha_token: callbackData.captcha_token,
92
- expires_in: Number(callbackData.expires_in)
93
- };
94
- await this._saveCaptchaToken(captchaToken);
90
+ else {
91
+ const redirect_uri = `${window.location.origin + window.location.pathname}?__captcha=on`;
92
+ captchaTokenResp = await this.config.request(consts_1.ApiUrls.GET_CAPTCHA_URL, {
93
+ method: 'POST',
94
+ body: {
95
+ client_id: this.config.clientId,
96
+ redirect_uri,
97
+ state,
98
+ },
99
+ withBasicAuth: true,
100
+ });
101
+ }
102
+ const captchaToken = captchaTokenResp.captcha_token
103
+ ? {
104
+ captcha_token: captchaTokenResp.captcha_token,
105
+ expires_in: captchaTokenResp.expires_in,
106
+ }
107
+ : await this.config.openURIWithCallback(captchaTokenResp.url, {
108
+ width: '355px',
109
+ height: '355px',
110
+ });
111
+ await this.saveCaptchaToken({
112
+ captcha_token: captchaToken.captcha_token,
113
+ expires_in: Number(captchaToken.expires_in),
114
+ });
95
115
  return captchaToken.captcha_token;
96
116
  }
97
- async _appendCaptchaTokenToURL(url, state, forceNewToken) {
98
- const captchaToken = await this._getCaptchaToken(forceNewToken, state);
99
- if (url.indexOf("?") > 0) {
100
- url += "&captcha_token=" + captchaToken;
117
+ async appendCaptchaTokenToURL(url, state, forceNewToken) {
118
+ const captchaToken = await this.getCaptchaToken(forceNewToken, state);
119
+ if (url.indexOf('?') > 0) {
120
+ url += `&captcha_token=${captchaToken}`;
101
121
  }
102
122
  else {
103
- url += "?captcha_token=" + captchaToken;
123
+ url += `?captcha_token=${captchaToken}`;
104
124
  }
105
125
  return url;
106
126
  }
107
- async _saveCaptchaToken(token) {
127
+ async saveCaptchaToken(token) {
108
128
  token.expires_at = new Date(Date.now() + (token.expires_in - 10) * 1000);
109
129
  const tokenStr = JSON.stringify(token);
110
- await this._config.storage.setItem(this._tokenSectionName, tokenStr);
130
+ await this.config.storage.setItem(this.tokenSectionName, tokenStr);
111
131
  }
112
- async _findCaptchaToken() {
113
- const tokenStr = await this._config.storage.getItem(this._tokenSectionName);
132
+ async findCaptchaToken() {
133
+ const tokenStr = await this.config.storage.getItem(this.tokenSectionName);
114
134
  if (tokenStr !== undefined && tokenStr !== null) {
115
135
  try {
116
136
  const captchaToken = JSON.parse(tokenStr);
@@ -124,7 +144,7 @@ class Captcha {
124
144
  return captchaToken.captcha_token;
125
145
  }
126
146
  catch (error) {
127
- await this._config.storage.removeItem(this._tokenSectionName);
147
+ await this.config.storage.removeItem(this.tokenSectionName);
128
148
  return null;
129
149
  }
130
150
  }
@@ -132,4 +152,3 @@ class Captcha {
132
152
  }
133
153
  }
134
154
  exports.Captcha = Captcha;
135
- //# sourceMappingURL=index.js.map
@@ -77,4 +77,3 @@ class Function {
77
77
  }
78
78
  }
79
79
  exports.Function = Function;
80
- //# sourceMappingURL=index.js.map
package/dist/index.js CHANGED
@@ -21,4 +21,3 @@ Object.defineProperty(exports, "initializeApp", { enumerable: true, get: functio
21
21
  var auth_2 = require("./auth");
22
22
  Object.defineProperty(exports, "Auth", { enumerable: true, get: function () { return auth_2.Auth; } });
23
23
  Object.defineProperty(exports, "getAuth", { enumerable: true, get: function () { return auth_2.getAuth; } });
24
- //# sourceMappingURL=index.js.map
@@ -50,4 +50,3 @@ var ErrorType;
50
50
  ErrorType["TEMPORARILY_UNAVAILABLE"] = "temporarily_unavailable";
51
51
  ErrorType["INTERACTION_REQUIRED"] = "interaction_required";
52
52
  })(ErrorType = exports.ErrorType || (exports.ErrorType = {}));
53
- //# sourceMappingURL=consts.js.map
@@ -18,4 +18,3 @@ function getOAuthClient(app, opts) {
18
18
  });
19
19
  }
20
20
  exports.getOAuthClient = getOAuthClient;
21
- //# sourceMappingURL=index.js.map
@@ -7,4 +7,3 @@ exports.AuthClient = void 0;
7
7
  class AuthClient {
8
8
  }
9
9
  exports.AuthClient = AuthClient;
10
- //# sourceMappingURL=interface.js.map
@@ -1,3 +1,2 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=models.js.map
@@ -412,4 +412,3 @@ OAuth2Client._defaultRetry = 2;
412
412
  OAuth2Client._minRetry = 0;
413
413
  OAuth2Client._maxRetry = 5;
414
414
  OAuth2Client._retryInterval = 1000;
415
- //# sourceMappingURL=oauthclient.js.map
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudbase/oauth",
3
- "version": "0.1.1-alpha.7",
3
+ "version": "0.1.1-alpha.9",
4
4
  "description": "auth apis for cloudbase",
5
5
  "author": "xbase",
6
6
  "main": "./dist/index.js",
@@ -91,4 +91,3 @@ function weappJwtDecode(token, options) {
91
91
  }
92
92
  }
93
93
  exports.weappJwtDecode = weappJwtDecode;
94
- //# sourceMappingURL=base64.js.map
@@ -0,0 +1,2 @@
1
+ export declare function isMp(): boolean;
2
+ export declare function isInMpWebView(): boolean;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isInMpWebView = exports.isMp = void 0;
4
+ function isMp() {
5
+ const wx = globalThis.wx;
6
+ if (typeof wx === 'undefined') {
7
+ return false;
8
+ }
9
+ if (globalThis.Page === undefined) {
10
+ return false;
11
+ }
12
+ if (!wx.getSystemInfoSync) {
13
+ return false;
14
+ }
15
+ if (!wx.getStorageSync) {
16
+ return false;
17
+ }
18
+ if (!wx.setStorageSync) {
19
+ return false;
20
+ }
21
+ if (!wx.connectSocket) {
22
+ return false;
23
+ }
24
+ if (!wx.request) {
25
+ return false;
26
+ }
27
+ try {
28
+ if (!wx.getSystemInfoSync()) {
29
+ return false;
30
+ }
31
+ if (wx.getSystemInfoSync().AppPlatform === 'qq') {
32
+ return false;
33
+ }
34
+ }
35
+ catch (e) {
36
+ return false;
37
+ }
38
+ return true;
39
+ }
40
+ exports.isMp = isMp;
41
+ let IS_IN_MP_WEBVIEW = !!navigator.userAgent.match(/miniprogram/i) || window.__wxjs_environment === 'miniprogram';
42
+ if (!isMp()) {
43
+ function ready() {
44
+ IS_IN_MP_WEBVIEW =
45
+ IS_IN_MP_WEBVIEW || (typeof window !== undefined && window.__wxjs_environment === 'miniprogram');
46
+ }
47
+ if (window?.WeixinJSBridge?.invoke) {
48
+ ready();
49
+ }
50
+ else if (typeof document !== 'undefined') {
51
+ document.addEventListener?.('WeixinJSBridgeReady', ready, false);
52
+ }
53
+ }
54
+ function isInMpWebView() {
55
+ return IS_IN_MP_WEBVIEW;
56
+ }
57
+ exports.isInMpWebView = isInMpWebView;
@@ -45,4 +45,3 @@ class PromiseOnce {
45
45
  }
46
46
  }
47
47
  exports.PromiseOnce = PromiseOnce;
48
- //# sourceMappingURL=promise.js.map
@@ -13,4 +13,3 @@ function uuidv4() {
13
13
  });
14
14
  }
15
15
  exports.uuidv4 = uuidv4;
16
- //# sourceMappingURL=uuid.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudbase/oauth",
3
- "version": "0.1.1-alpha.7",
3
+ "version": "0.1.1-alpha.9",
4
4
  "description": "auth apis for cloudbase",
5
5
  "author": "xbase",
6
6
  "main": "./dist/index.js",
package/src/app/index.ts CHANGED
@@ -1,83 +1,83 @@
1
- import {defaultRequest, RequestFn as requestFn, RequestOptions as requestOptions} from "./request";
2
- import {OpenURIWithCallback as openURIWithCallback, defaultOpenURIWithCallback} from "./openuri";
3
- import {DefaultStorage, Storage as storage} from "./storage";
1
+ import { defaultRequest, RequestFn as requestFn, RequestOptions as requestOptions } from './request';
2
+ import { OpenURIWithCallback as openURIWithCallback, defaultOpenURIWithCallback } from './openuri';
3
+ import { DefaultStorage, Storage as storage } from './storage';
4
4
 
5
5
  export interface Options {
6
- env: string,
7
- region?: string,
8
- apiOrigin?: string;
9
- clientId?: string;
10
- clientSecret?: string;
11
- custom?: any;
6
+ env: string;
7
+ region?: string;
8
+ apiOrigin?: string;
9
+ clientId?: string;
10
+ clientSecret?: string;
11
+ custom?: any;
12
12
 
13
- // plugins can set platform functions
14
- request?: requestFn;
15
- storage?: storage;
13
+ // plugins can set platform functions
14
+ request?: requestFn;
15
+ baseRequest?: requestFn;
16
+ storage?: storage;
17
+ captchaOptions?: {
16
18
  openURIWithCallback?: openURIWithCallback;
19
+ };
17
20
  }
18
21
 
19
- export function initializeApp(
20
- options: Options,
21
- ): App {
22
- return new AppImpl(options);
22
+ export function initializeApp(options: Options): App {
23
+ return new AppImpl(options);
23
24
  }
24
25
 
25
26
  export interface App {
26
- readonly options: Options;
27
+ readonly options: Options;
27
28
  }
28
29
 
29
30
  export class AppImpl implements App {
30
- private readonly _options: Options;
31
- private readonly _container = new Map<string, any>();
31
+ private readonly _options: Options;
32
+ private readonly _container = new Map<string, any>();
32
33
 
33
- constructor(options: Options) {
34
- if (!options.region) {
35
- options.region = 'ap-shanghai'
36
- }
37
- if (!options.apiOrigin) {
38
- options.apiOrigin = `https://${options.env}.${options.region}.tcb-api.tencentcloudapi.com`
39
- }
40
- let storageEnv = options.env
41
- if (!options.clientId) {
42
- options.clientId = ''
43
- } else {
44
- storageEnv = options.clientId
45
- }
46
- if (!options.storage) {
47
- options.storage = new DefaultStorage({env: storageEnv});
48
- }
49
- if (!options.openURIWithCallback) {
50
- options.openURIWithCallback = defaultOpenURIWithCallback;
51
- }
52
- let baseRequest = options.request
53
- if (!baseRequest) {
54
- baseRequest = defaultRequest
55
- }
56
- const apiOrigin = options.apiOrigin
57
- options.request = async <T>(
58
- url: string,
59
- options?: RequestOptions,
60
- ): Promise<T> => {
61
- if (url.startsWith('/')) {
62
- url = apiOrigin + url;
63
- }
64
- return baseRequest<T>(url, options)
65
- }
66
- this._options = options;
34
+ constructor(options: Options) {
35
+ if (!options.region) {
36
+ options.region = 'ap-shanghai';
67
37
  }
68
-
69
- get options(): Options {
70
- return this._options;
38
+ if (!options.apiOrigin) {
39
+ options.apiOrigin = `https://${options.env}.${options.region}.tcb-api.tencentcloudapi.com`;
71
40
  }
72
-
73
- get container(): Map<string, any> {
74
- return this._container;
41
+ let storageEnv = options.env;
42
+ if (!options.clientId) {
43
+ options.clientId = '';
44
+ } else {
45
+ storageEnv = options.clientId;
75
46
  }
76
- }
47
+ if (!options.storage) {
48
+ options.storage = new DefaultStorage({ env: storageEnv });
49
+ }
50
+ if (!options.captchaOptions) {
51
+ options.captchaOptions = {};
52
+ }
53
+ if (!options.captchaOptions.openURIWithCallback) {
54
+ // 兼容之前的传参方式,options.openURIWithCallback
55
+ options.captchaOptions.openURIWithCallback = (options as any).openURIWithCallback || defaultOpenURIWithCallback;
56
+ }
57
+ let baseRequest: requestFn = options.baseRequest || options.request || defaultRequest;
58
+ if (!baseRequest) {
59
+ baseRequest = defaultRequest;
60
+ }
61
+ const apiOrigin = options.apiOrigin;
62
+ options.request = async <T>(url: string, options?: RequestOptions): Promise<T> => {
63
+ if (url.startsWith('/')) {
64
+ url = apiOrigin + url;
65
+ }
66
+ return baseRequest<T>(url, options);
67
+ };
68
+ this._options = options;
69
+ }
77
70
 
71
+ get options(): Options {
72
+ return this._options;
73
+ }
78
74
 
79
- export type RequestFn = requestFn
80
- export type RequestOptions = requestOptions
81
- export type OpenURIWithCallback = openURIWithCallback
82
- export type Storage = storage
75
+ get container(): Map<string, any> {
76
+ return this._container;
77
+ }
78
+ }
83
79
 
80
+ export type RequestFn = requestFn;
81
+ export type RequestOptions = requestOptions;
82
+ export type OpenURIWithCallback = openURIWithCallback;
83
+ export type Storage = storage;
@@ -1,8 +1,11 @@
1
+ import { ErrorType } from '../auth/consts';
2
+
1
3
  export type OpenURIWithCallback = (url: string, opts?: OpenURIOptions) => Promise<{ [key: string]: string }>;
2
4
 
3
5
  export interface OpenURIOptions {
4
6
  width: string;
5
7
  height: string;
8
+ request?: any;
6
9
  }
7
10
 
8
11
  /**
@@ -22,15 +25,19 @@ export const defaultOpenURIWithCallback: OpenURIWithCallback = (
22
25
  opts?: OpenURIOptions,
23
26
  ): Promise<{ [key: string]: string }> => {
24
27
  let iframeTag = '__iframe';
28
+ const { width = '355px', height = '355px' } = opts || {};
29
+
30
+ const matched = url.match(/^(data:.*)$/);
31
+ if (matched) {
32
+ return Promise.reject({
33
+ error: ErrorType.UNIMPLEMENTED,
34
+ error_description: `need to impl captcha data`,
35
+ });
36
+ }
37
+
25
38
  if (window.location.search.indexOf(iframeTag) > 0) {
26
39
  document.body.style.display = 'none';
27
40
  }
28
- if (!opts) {
29
- opts = {
30
- width: '355px',
31
- height: '355px',
32
- };
33
- }
34
41
  if (document.getElementById('_iframe_panel_wrap') === null) {
35
42
  var elementDiv = document.createElement('div');
36
43
  elementDiv.style.cssText =
@@ -58,7 +65,7 @@ export const defaultOpenURIWithCallback: OpenURIWithCallback = (
58
65
  }
59
66
  iframe.setAttribute('src', url);
60
67
  iframe.setAttribute('id', '_iframe_panel_wrap_iframe');
61
- iframe.style.cssText = `min-width:${opts.width};display:block;height:${opts.height};margin:0 auto;background-color: rgb(255, 255, 255);border: none;`;
68
+ iframe.style.cssText = `min-width:${width};display:block;height:${height};margin:0 auto;background-color: rgb(255, 255, 255);border: none;`;
62
69
  target.appendChild(iframe);
63
70
  target.style.display = 'block';
64
71