@authorizerdev/authorizer-js 2.0.3 → 3.0.0-rc.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/lib/index.js CHANGED
@@ -1,15 +1,662 @@
1
- var x=Object.create;var l=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var z=Object.getPrototypeOf,Q=Object.prototype.hasOwnProperty;var i=(o,r)=>l(o,"name",{value:r,configurable:!0});var D=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})},$=(o,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of O(r))!Q.call(o,e)&&e!==t&&l(o,e,{get:()=>r[e],enumerable:!(s=C(r,e))||s.enumerable});return o};var A=(o,r,t)=>(t=o!=null?x(z(o)):{},$(r||!o||!o.__esModule?l(t,"default",{value:o,enumerable:!0}):t,o)),N=o=>$(l({},"__esModule",{value:!0}),o);var H={};D(H,{Authorizer:()=>b,OAuthProviders:()=>_,ResponseTypes:()=>d});module.exports=N(H);var q=A(require("cross-fetch"));var _;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin",o.Twitter="twitter",o.Microsoft="microsoft",o.Twitch="twitch",o.Roblox="roblox"})(_||(_={}));var d;(function(o){o.Code="code",o.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),y=i(o=>{let r=o.trim();return r[r.length-1]==="/"&&(r=r.slice(0,-1)),r},"trimURL"),U=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),F=i(()=>{let o=U();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",r="",t=U();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(e=>r+=o[e%o.length]),r},"createRandomString"),c=i(o=>p()?btoa(o):Buffer.from(o).toString("base64"),"encode");var E=i(o=>Object.keys(o).filter(r=>typeof o[r]<"u").map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(o[r])}`).join("&"),"createQueryParams"),T=i(async o=>{let r=F().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,s)=>{r.oncomplete=e=>{t(e.target.result)},r.onerror=e=>{s(e.error)},r.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await r},"sha256"),M=i(o=>{let r={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>r[t])},"urlEncodeB64");var I=i(o=>{let r=new Uint8Array(o);return M(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),L=i((o,r,t=60)=>new Promise((s,e)=>{let n=window.document.createElement("iframe");n.setAttribute("id","authorizer-iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.style.display="none";let a=i(()=>{window.document.body.contains(n)&&(window.document.body.removeChild(n),window.removeEventListener("message",f,!1))},"removeIframe"),S=setTimeout(()=>{a()},t*1e3),f=i(function(h){if(h.origin!==r||!h.data||!h.data.response)return;let v=h.source;v&&v.close(),h.data.response.error?e(h.data.response):s(h.data.response),clearTimeout(S),window.removeEventListener("message",f,!1),setTimeout(a,2*1e3)},"iframeEventHandler");window.addEventListener("message",f,!1),window.document.body.appendChild(n),n.setAttribute("src",o)}),"executeIframe");var R="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",g=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${R} }`,w=i(()=>p()?window.fetch:q.default,"getFetcher"),k=class k{config;codeVerifier;constructor(r){if(!r)throw new Error("Configuration is required");if(this.config=r,!r.authorizerURL&&!r.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(r.authorizerURL&&(this.config.authorizerURL=y(r.authorizerURL)),!r.redirectURL&&!r.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=y(r.redirectURL),this.config.extraHeaders={...r.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"x-authorizer-client-id":this.config.clientID||"","Content-Type":"application/json"},this.config.clientID=r.clientID.trim()}authorize=async r=>{if(!p())return this.errorResponse([new Error("this feature is only supported in browser")]);let t=["openid","profile","email"];r.use_refresh_token&&t.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:r.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:r.response_type,scope:t.join(" "),client_id:this.config.clientID};if(r.response_type===d.Code){this.codeVerifier=u();let n=await T(this.codeVerifier),a=I(n);s.code_challenge=a}let e=`${this.config.authorizerURL}/authorize?${E(s)}`;if(s.response_mode!=="web_message")return window.location.replace(e),this.okResponse(void 0);try{let n=await L(e,this.config.authorizerURL,60);if(r.response_type===d.Code){let a=await this.getToken({code:n.code});return a.errors.length?this.errorResponse(a.errors):this.okResponse(a.data)}return this.okResponse(n)}catch(n){return n.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(n)}};browserLogin=async()=>{try{let r=await this.getSession();return r.errors.length?this.errorResponse(r.errors):this.okResponse(r.data)}catch(r){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(r)):{data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}};forgotPassword=async r=>{var t;r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);try{let s=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message should_show_mobile_otp_screen } }",variables:{data:r}});return(t=s==null?void 0:s.errors)!=null&&t.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}};getMetaData=async()=>{var r;try{let t=await this.graphqlQuery({query:"query { meta { version client_id is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_roblox_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled is_multi_factor_auth_enabled is_mobile_basic_authentication_enabled is_phone_verification_enabled } }"});return(r=t==null?void 0:t.errors)!=null&&r.length?this.errorResponse(t.errors):this.okResponse(t.data.meta)}catch(t){return this.errorResponse([t])}};getProfile=async r=>{var t;try{let s=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:r});return(t=s==null?void 0:s.errors)!=null&&t.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}};getSession=async(r,t)=>{var s,e;try{let n=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${g} } }`,headers:r,variables:{params:t}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((e=n.data)==null?void 0:e.session)}catch(n){return this.errorResponse(n)}};getToken=async r=>{if(r.grant_type||(r.grant_type="authorization_code"),r.grant_type==="refresh_token"&&!r.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(r.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let t={client_id:this.config.clientID,code:r.code||"",code_verifier:this.codeVerifier||"",grant_type:r.grant_type||"",refresh_token:r.refresh_token||""};try{let e=await w()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:{...this.config.extraHeaders},credentials:"include"}),n=await e.json();return e.status>=400?this.errorResponse([new Error(n.error_description||n.error)]):this.okResponse(n)}catch(s){return this.errorResponse(s)}};login=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
2
- mutation login($data: LoginInput!) { login(params: $data) { ${g}}}
3
- `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.login)}catch(e){return this.errorResponse([new Error(e)])}};logout=async r=>{var t,s;try{let e=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:r});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.response)}catch(e){return this.errorResponse([e])}};magicLinkLogin=async r=>{var t,s;try{r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);let e=await this.graphqlQuery({query:`
4
- mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
5
- `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.magic_link_login)}catch(e){return this.errorResponse([e])}};oauthLogin=async(r,t,s,e)=>{let n=e;if(n||(n=c(u())),!Object.values(_).includes(r))throw new Error(`only following oauth providers are supported: ${Object.values(r).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");t&&t.length&&(n+=`&roles=${t.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${r}?redirect_uri=${s||this.config.redirectURL}&state=${n}`)};resendOtp=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ Authorizer: () => Authorizer,
34
+ OAuthProviders: () => OAuthProviders,
35
+ ResponseTypes: () => ResponseTypes
36
+ });
37
+ module.exports = __toCommonJS(src_exports);
38
+ var import_cross_fetch = __toESM(require("cross-fetch"));
39
+
40
+ // src/constants.ts
41
+ var DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60;
42
+ var CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2;
43
+
44
+ // src/types.ts
45
+ var OAuthProviders;
46
+ (function(OAuthProviders2) {
47
+ OAuthProviders2["Apple"] = "apple";
48
+ OAuthProviders2["Github"] = "github";
49
+ OAuthProviders2["Google"] = "google";
50
+ OAuthProviders2["Facebook"] = "facebook";
51
+ OAuthProviders2["LinkedIn"] = "linkedin";
52
+ OAuthProviders2["Twitter"] = "twitter";
53
+ OAuthProviders2["Microsoft"] = "microsoft";
54
+ OAuthProviders2["Twitch"] = "twitch";
55
+ OAuthProviders2["Roblox"] = "roblox";
56
+ OAuthProviders2["Discord"] = "discord";
57
+ })(OAuthProviders || (OAuthProviders = {}));
58
+ var ResponseTypes;
59
+ (function(ResponseTypes2) {
60
+ ResponseTypes2["Code"] = "code";
61
+ ResponseTypes2["Token"] = "token";
62
+ })(ResponseTypes || (ResponseTypes = {}));
63
+
64
+ // src/utils.ts
65
+ var hasWindow = /* @__PURE__ */ __name(() => typeof window !== "undefined", "hasWindow");
66
+ var trimURL = /* @__PURE__ */ __name((url) => {
67
+ let trimmedData = url.trim();
68
+ const lastChar = trimmedData[trimmedData.length - 1];
69
+ if (lastChar === "/")
70
+ trimmedData = trimmedData.slice(0, -1);
71
+ return trimmedData;
72
+ }, "trimURL");
73
+ var getCrypto = /* @__PURE__ */ __name(() => {
74
+ return hasWindow() ? window.crypto || window.msCrypto : null;
75
+ }, "getCrypto");
76
+ var getCryptoSubtle = /* @__PURE__ */ __name(() => {
77
+ const crypto = getCrypto();
78
+ return crypto && crypto.subtle || crypto.webkitSubtle;
79
+ }, "getCryptoSubtle");
80
+ var createRandomString = /* @__PURE__ */ __name(() => {
81
+ const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";
82
+ let random = "";
83
+ const crypto = getCrypto();
84
+ if (crypto) {
85
+ const randomValues = Array.from(crypto.getRandomValues(new Uint8Array(43)));
86
+ randomValues.forEach((v) => random += charset[v % charset.length]);
87
+ }
88
+ return random;
89
+ }, "createRandomString");
90
+ var encode = /* @__PURE__ */ __name((value) => hasWindow() ? btoa(value) : Buffer.from(value).toString("base64"), "encode");
91
+ var createQueryParams = /* @__PURE__ */ __name((params) => {
92
+ return Object.keys(params).filter((k) => typeof params[k] !== "undefined").map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`).join("&");
93
+ }, "createQueryParams");
94
+ var sha256 = /* @__PURE__ */ __name(async (s) => {
95
+ const digestOp = getCryptoSubtle().digest({
96
+ name: "SHA-256"
97
+ }, new TextEncoder().encode(s));
98
+ if (window.msCrypto) {
99
+ return new Promise((resolve, reject) => {
100
+ digestOp.oncomplete = (e) => {
101
+ resolve(e.target.result);
102
+ };
103
+ digestOp.onerror = (e) => {
104
+ reject(e.error);
105
+ };
106
+ digestOp.onabort = () => {
107
+ reject(new Error("The digest operation was aborted"));
108
+ };
109
+ });
110
+ }
111
+ return await digestOp;
112
+ }, "sha256");
113
+ var urlEncodeB64 = /* @__PURE__ */ __name((input) => {
114
+ const b64Chars = {
115
+ "+": "-",
116
+ "/": "_",
117
+ "=": ""
118
+ };
119
+ return input.replace(/[+/=]/g, (m) => b64Chars[m]);
120
+ }, "urlEncodeB64");
121
+ var bufferToBase64UrlEncoded = /* @__PURE__ */ __name((input) => {
122
+ const ie11SafeInput = new Uint8Array(input);
123
+ return urlEncodeB64(window.btoa(String.fromCharCode(...Array.from(ie11SafeInput))));
124
+ }, "bufferToBase64UrlEncoded");
125
+ var executeIframe = /* @__PURE__ */ __name((authorizeUrl, eventOrigin, timeoutInSeconds = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) => {
126
+ return new Promise((resolve, reject) => {
127
+ const iframe = window.document.createElement("iframe");
128
+ iframe.setAttribute("id", "authorizer-iframe");
129
+ iframe.setAttribute("width", "0");
130
+ iframe.setAttribute("height", "0");
131
+ iframe.style.display = "none";
132
+ const removeIframe = /* @__PURE__ */ __name(() => {
133
+ if (window.document.body.contains(iframe)) {
134
+ window.document.body.removeChild(iframe);
135
+ window.removeEventListener("message", iframeEventHandler, false);
136
+ }
137
+ }, "removeIframe");
138
+ const timeoutSetTimeoutId = setTimeout(() => {
139
+ removeIframe();
140
+ }, timeoutInSeconds * 1e3);
141
+ const iframeEventHandler = /* @__PURE__ */ __name(function(e) {
142
+ if (e.origin !== eventOrigin)
143
+ return;
144
+ if (!e.data || !e.data.response)
145
+ return;
146
+ const eventSource = e.source;
147
+ if (eventSource)
148
+ eventSource.close();
149
+ e.data.response.error ? reject(e.data.response) : resolve(e.data.response);
150
+ clearTimeout(timeoutSetTimeoutId);
151
+ window.removeEventListener("message", iframeEventHandler, false);
152
+ setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1e3);
153
+ }, "iframeEventHandler");
154
+ window.addEventListener("message", iframeEventHandler, false);
155
+ window.document.body.appendChild(iframe);
156
+ iframe.setAttribute("src", authorizeUrl);
157
+ });
158
+ }, "executeIframe");
159
+
160
+ // src/index.ts
161
+ var userFragment = "id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at revoked_timestamp is_multi_factor_auth_enabled app_data";
162
+ var authTokenFragment = `message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${userFragment} }`;
163
+ var getFetcher = /* @__PURE__ */ __name(() => hasWindow() ? window.fetch : import_cross_fetch.default, "getFetcher");
164
+ var _Authorizer = class _Authorizer {
165
+ // class variable
166
+ config;
167
+ codeVerifier;
168
+ // constructor
169
+ constructor(config) {
170
+ if (!config)
171
+ throw new Error("Configuration is required");
172
+ this.config = config;
173
+ if (!config.authorizerURL && !config.authorizerURL.trim())
174
+ throw new Error("Invalid authorizerURL");
175
+ if (config.authorizerURL)
176
+ this.config.authorizerURL = trimURL(config.authorizerURL);
177
+ if (!config.redirectURL && !config.redirectURL.trim())
178
+ throw new Error("Invalid redirectURL");
179
+ else
180
+ this.config.redirectURL = trimURL(config.redirectURL);
181
+ this.config.extraHeaders = {
182
+ ...config.extraHeaders || {},
183
+ "x-authorizer-url": this.config.authorizerURL,
184
+ "x-authorizer-client-id": this.config.clientID || "",
185
+ "Content-Type": "application/json"
186
+ };
187
+ this.config.clientID = ((config == null ? void 0 : config.clientID) || "").trim();
188
+ }
189
+ authorize = async (data) => {
190
+ var _a;
191
+ if (!hasWindow())
192
+ return this.errorResponse([
193
+ new Error("this feature is only supported in browser")
194
+ ]);
195
+ const scopes = [
196
+ "openid",
197
+ "profile",
198
+ "email"
199
+ ];
200
+ if (data.use_refresh_token)
201
+ scopes.push("offline_access");
202
+ const requestData = {
203
+ redirect_uri: this.config.redirectURL,
204
+ response_mode: data.response_mode || "web_message",
205
+ state: encode(createRandomString()),
206
+ nonce: encode(createRandomString()),
207
+ response_type: data.response_type,
208
+ scope: scopes.join(" "),
209
+ client_id: ((_a = this.config) == null ? void 0 : _a.clientID) || ""
210
+ };
211
+ if (data.response_type === ResponseTypes.Code) {
212
+ this.codeVerifier = createRandomString();
213
+ const sha = await sha256(this.codeVerifier);
214
+ const codeChallenge = bufferToBase64UrlEncoded(sha);
215
+ requestData.code_challenge = codeChallenge;
216
+ }
217
+ const authorizeURL = `${this.config.authorizerURL}/authorize?${createQueryParams(requestData)}`;
218
+ if (requestData.response_mode !== "web_message") {
219
+ window.location.replace(authorizeURL);
220
+ return this.okResponse(void 0);
221
+ }
222
+ try {
223
+ const iframeRes = await executeIframe(authorizeURL, this.config.authorizerURL, DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS);
224
+ if (data.response_type === ResponseTypes.Code) {
225
+ const tokenResp = await this.getToken({
226
+ code: iframeRes.code
227
+ });
228
+ return tokenResp.errors.length ? this.errorResponse(tokenResp.errors) : this.okResponse(tokenResp.data);
229
+ }
230
+ return this.okResponse(iframeRes);
231
+ } catch (err) {
232
+ if (err.error) {
233
+ window.location.replace(`${this.config.authorizerURL}/app?state=${encode(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`);
234
+ }
235
+ return this.errorResponse(err);
236
+ }
237
+ };
238
+ browserLogin = async () => {
239
+ try {
240
+ const tokenResp = await this.getSession();
241
+ return tokenResp.errors.length ? this.errorResponse(tokenResp.errors) : this.okResponse(tokenResp.data);
242
+ } catch (err) {
243
+ if (!hasWindow()) {
244
+ return {
245
+ data: void 0,
246
+ errors: [
247
+ new Error("browserLogin is only supported for browsers")
248
+ ]
249
+ };
250
+ }
251
+ window.location.replace(`${this.config.authorizerURL}/app?state=${encode(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`);
252
+ return this.errorResponse(err);
253
+ }
254
+ };
255
+ forgotPassword = async (data) => {
256
+ var _a;
257
+ if (!data.state)
258
+ data.state = encode(createRandomString());
259
+ if (!data.redirect_uri)
260
+ data.redirect_uri = this.config.redirectURL;
261
+ try {
262
+ const forgotPasswordResp = await this.graphqlQuery({
263
+ query: "mutation forgotPassword($data: ForgotPasswordRequest!) { forgot_password(params: $data) { message should_show_mobile_otp_screen } }",
264
+ variables: {
265
+ data
266
+ }
267
+ });
268
+ return ((_a = forgotPasswordResp == null ? void 0 : forgotPasswordResp.errors) == null ? void 0 : _a.length) ? this.errorResponse(forgotPasswordResp.errors) : this.okResponse(forgotPasswordResp == null ? void 0 : forgotPasswordResp.data.forgot_password);
269
+ } catch (error) {
270
+ return this.errorResponse([
271
+ error
272
+ ]);
273
+ }
274
+ };
275
+ getMetaData = async () => {
276
+ var _a;
277
+ try {
278
+ const res = await this.graphqlQuery({
279
+ query: "query { meta { version client_id is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_roblox_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled is_multi_factor_auth_enabled is_mobile_basic_authentication_enabled is_phone_verification_enabled } }"
280
+ });
281
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse(res.data.meta);
282
+ } catch (error) {
283
+ return this.errorResponse([
284
+ error
285
+ ]);
286
+ }
287
+ };
288
+ getProfile = async (headers) => {
289
+ var _a;
290
+ try {
291
+ const profileRes = await this.graphqlQuery({
292
+ query: `query { profile { ${userFragment} } }`,
293
+ headers
294
+ });
295
+ return ((_a = profileRes == null ? void 0 : profileRes.errors) == null ? void 0 : _a.length) ? this.errorResponse(profileRes.errors) : this.okResponse(profileRes.data.profile);
296
+ } catch (error) {
297
+ return this.errorResponse([
298
+ error
299
+ ]);
300
+ }
301
+ };
302
+ // this is used to verify / get session using cookie by default. If using node.js pass authorization header
303
+ getSession = async (headers, params) => {
304
+ var _a, _b;
305
+ try {
306
+ const res = await this.graphqlQuery({
307
+ query: `query getSession($params: SessionQueryRequest){session(params: $params) { ${authTokenFragment} } }`,
308
+ headers,
309
+ variables: {
310
+ params
311
+ }
312
+ });
313
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.session);
314
+ } catch (err) {
315
+ return this.errorResponse(err);
316
+ }
317
+ };
318
+ getToken = async (data) => {
319
+ if (!data.grant_type)
320
+ data.grant_type = "authorization_code";
321
+ if (data.grant_type === "refresh_token" && !data.refresh_token)
322
+ return this.errorResponse([
323
+ new Error("Invalid refresh_token")
324
+ ]);
325
+ if (data.grant_type === "authorization_code" && !this.codeVerifier)
326
+ return this.errorResponse([
327
+ new Error("Invalid code verifier")
328
+ ]);
329
+ const requestData = {
330
+ client_id: this.config.clientID,
331
+ code: data.code || "",
332
+ code_verifier: this.codeVerifier || "",
333
+ grant_type: data.grant_type || "",
334
+ refresh_token: data.refresh_token || ""
335
+ };
336
+ try {
337
+ const fetcher = getFetcher();
338
+ const res = await fetcher(`${this.config.authorizerURL}/oauth/token`, {
339
+ method: "POST",
340
+ body: JSON.stringify(requestData),
341
+ headers: {
342
+ ...this.config.extraHeaders
343
+ },
344
+ credentials: "include"
345
+ });
346
+ const json = await res.json();
347
+ if (res.status >= 400)
348
+ return this.errorResponse([
349
+ new Error(json.error_description || json.error)
350
+ ]);
351
+ return this.okResponse(json);
352
+ } catch (err) {
353
+ return this.errorResponse(err);
354
+ }
355
+ };
356
+ login = async (data) => {
357
+ var _a, _b;
358
+ try {
359
+ const res = await this.graphqlQuery({
360
+ query: `
361
+ mutation login($data: LoginRequest!) { login(params: $data) { ${authTokenFragment}}}
362
+ `,
363
+ variables: {
364
+ data
365
+ }
366
+ });
367
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.login);
368
+ } catch (err) {
369
+ return this.errorResponse([
370
+ new Error(err)
371
+ ]);
372
+ }
373
+ };
374
+ logout = async (headers) => {
375
+ var _a, _b;
376
+ try {
377
+ const res = await this.graphqlQuery({
378
+ query: " mutation { logout { message } } ",
379
+ headers
380
+ });
381
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.response);
382
+ } catch (err) {
383
+ return this.errorResponse([
384
+ err
385
+ ]);
386
+ }
387
+ };
388
+ magicLinkLogin = async (data) => {
389
+ var _a, _b;
390
+ try {
391
+ if (!data.state)
392
+ data.state = encode(createRandomString());
393
+ if (!data.redirect_uri)
394
+ data.redirect_uri = this.config.redirectURL;
395
+ const res = await this.graphqlQuery({
396
+ query: `
397
+ mutation magicLinkLogin($data: MagicLinkLoginRequest!) { magic_link_login(params: $data) { message }}
398
+ `,
399
+ variables: {
400
+ data
401
+ }
402
+ });
403
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.magic_link_login);
404
+ } catch (err) {
405
+ return this.errorResponse([
406
+ err
407
+ ]);
408
+ }
409
+ };
410
+ oauthLogin = async (oauthProvider, roles, redirect_uri, state) => {
411
+ let urlState = state;
412
+ if (!urlState) {
413
+ urlState = encode(createRandomString());
414
+ }
415
+ if (!Object.values(OAuthProviders).includes(oauthProvider)) {
416
+ throw new Error(`only following oauth providers are supported: ${Object.values(oauthProvider).toString()}`);
417
+ }
418
+ if (!hasWindow())
419
+ throw new Error("oauthLogin is only supported for browsers");
420
+ if (roles && roles.length)
421
+ urlState += `&roles=${roles.join(",")}`;
422
+ window.location.replace(`${this.config.authorizerURL}/oauth_login/${oauthProvider}?redirect_uri=${redirect_uri || this.config.redirectURL}&state=${urlState}`);
423
+ };
424
+ resendOtp = async (data) => {
425
+ var _a, _b;
426
+ try {
427
+ const res = await this.graphqlQuery({
428
+ query: `
6
429
  mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
7
- `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.resend_otp)}catch(e){return this.errorResponse([e])}};resetPassword=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.reset_password)}catch(e){return this.errorResponse([e])}};revokeToken=async r=>{if(!r.refresh_token&&!r.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let e=await(await w()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:r.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(e)};signup=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
8
- mutation signup($data: SignUpInput!) { signup(params: $data) { ${g}}}
9
- `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.signup)}catch(e){return this.errorResponse([e])}};updateProfile=async(r,t)=>{var s,e;try{let n=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:t,variables:{data:r}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((e=n.data)==null?void 0:e.update_profile)}catch(n){return this.errorResponse([n])}};deactivateAccount=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:r});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.deactivate_account)}catch(e){return this.errorResponse([e])}};validateJWTToken=async r=>{var t,s;try{let e=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.validate_jwt_token)}catch(e){return this.errorResponse([e])}};validateSession=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${R} } } }`,variables:{params:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.validate_session)}catch(e){return this.errorResponse([e])}};verifyEmail=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
10
- mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${g}}}
11
- `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_email)}catch(e){return this.errorResponse([e])}};resendVerifyEmail=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
12
- mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }}
13
- `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_email)}catch(e){return this.errorResponse([e])}};verifyOtp=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
14
- mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${g}}}
15
- `,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.verify_otp)}catch(e){return this.errorResponse([e])}};graphqlQuery=async r=>{var n;let e=await(await w()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:r.query,variables:r.variables||{}}),headers:{...this.config.extraHeaders,...r.headers||{}},credentials:"include"})).json();return(n=e==null?void 0:e.errors)!=null&&n.length?{data:void 0,errors:e.errors}:{data:e.data,errors:[]}};errorResponse=r=>({data:void 0,errors:r});okResponse=r=>({data:r,errors:[]})};i(k,"Authorizer");var b=k;0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes});
430
+ `,
431
+ variables: {
432
+ data
433
+ }
434
+ });
435
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.resend_otp);
436
+ } catch (err) {
437
+ return this.errorResponse([
438
+ err
439
+ ]);
440
+ }
441
+ };
442
+ resetPassword = async (data) => {
443
+ var _a, _b;
444
+ try {
445
+ const resetPasswordRes = await this.graphqlQuery({
446
+ query: "mutation resetPassword($data: ResetPasswordRequest!) { reset_password(params: $data) { message } }",
447
+ variables: {
448
+ data
449
+ }
450
+ });
451
+ return ((_a = resetPasswordRes == null ? void 0 : resetPasswordRes.errors) == null ? void 0 : _a.length) ? this.errorResponse(resetPasswordRes.errors) : this.okResponse((_b = resetPasswordRes.data) == null ? void 0 : _b.reset_password);
452
+ } catch (error) {
453
+ return this.errorResponse([
454
+ error
455
+ ]);
456
+ }
457
+ };
458
+ revokeToken = async (data) => {
459
+ if (!data.refresh_token && !data.refresh_token.trim())
460
+ return this.errorResponse([
461
+ new Error("Invalid refresh_token")
462
+ ]);
463
+ const fetcher = getFetcher();
464
+ const res = await fetcher(`${this.config.authorizerURL}/oauth/revoke`, {
465
+ method: "POST",
466
+ headers: {
467
+ ...this.config.extraHeaders
468
+ },
469
+ body: JSON.stringify({
470
+ refresh_token: data.refresh_token,
471
+ client_id: this.config.clientID
472
+ })
473
+ });
474
+ const responseData = await res.json();
475
+ return this.okResponse(responseData);
476
+ };
477
+ signup = async (data) => {
478
+ var _a, _b;
479
+ try {
480
+ const res = await this.graphqlQuery({
481
+ query: `
482
+ mutation signup($data: SignUpRequest!) { signup(params: $data) { ${authTokenFragment}}}
483
+ `,
484
+ variables: {
485
+ data
486
+ }
487
+ });
488
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.signup);
489
+ } catch (err) {
490
+ return this.errorResponse([
491
+ err
492
+ ]);
493
+ }
494
+ };
495
+ updateProfile = async (data, headers) => {
496
+ var _a, _b;
497
+ try {
498
+ const updateProfileRes = await this.graphqlQuery({
499
+ query: "mutation updateProfile($data: UpdateProfileRequest!) { update_profile(params: $data) { message } }",
500
+ headers,
501
+ variables: {
502
+ data
503
+ }
504
+ });
505
+ return ((_a = updateProfileRes == null ? void 0 : updateProfileRes.errors) == null ? void 0 : _a.length) ? this.errorResponse(updateProfileRes.errors) : this.okResponse((_b = updateProfileRes.data) == null ? void 0 : _b.update_profile);
506
+ } catch (error) {
507
+ return this.errorResponse([
508
+ error
509
+ ]);
510
+ }
511
+ };
512
+ deactivateAccount = async (headers) => {
513
+ var _a, _b;
514
+ try {
515
+ const res = await this.graphqlQuery({
516
+ query: "mutation deactivateAccount { deactivate_account { message } }",
517
+ headers
518
+ });
519
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.deactivate_account);
520
+ } catch (error) {
521
+ return this.errorResponse([
522
+ error
523
+ ]);
524
+ }
525
+ };
526
+ validateJWTToken = async (params) => {
527
+ var _a, _b;
528
+ try {
529
+ const res = await this.graphqlQuery({
530
+ query: "query validateJWTToken($params: ValidateJWTTokenRequest!){validate_jwt_token(params: $params) { is_valid claims } }",
531
+ variables: {
532
+ params
533
+ }
534
+ });
535
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.validate_jwt_token);
536
+ } catch (error) {
537
+ return this.errorResponse([
538
+ error
539
+ ]);
540
+ }
541
+ };
542
+ validateSession = async (params) => {
543
+ var _a, _b;
544
+ try {
545
+ const res = await this.graphqlQuery({
546
+ query: `query validateSession($params: ValidateSessionRequest){validate_session(params: $params) { is_valid user { ${userFragment} } } }`,
547
+ variables: {
548
+ params
549
+ }
550
+ });
551
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.validate_session);
552
+ } catch (error) {
553
+ return this.errorResponse([
554
+ error
555
+ ]);
556
+ }
557
+ };
558
+ verifyEmail = async (data) => {
559
+ var _a, _b;
560
+ try {
561
+ const res = await this.graphqlQuery({
562
+ query: `
563
+ mutation verifyEmail($data: VerifyEmailRequest!) { verify_email(params: $data) { ${authTokenFragment}}}
564
+ `,
565
+ variables: {
566
+ data
567
+ }
568
+ });
569
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.verify_email);
570
+ } catch (err) {
571
+ return this.errorResponse([
572
+ err
573
+ ]);
574
+ }
575
+ };
576
+ resendVerifyEmail = async (data) => {
577
+ var _a, _b;
578
+ try {
579
+ const res = await this.graphqlQuery({
580
+ query: `
581
+ mutation resendVerifyEmail($data: ResendVerifyEmailRequest!) { resend_verify_email(params: $data) { message }}
582
+ `,
583
+ variables: {
584
+ data
585
+ }
586
+ });
587
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.resend_verify_email);
588
+ } catch (err) {
589
+ return this.errorResponse([
590
+ err
591
+ ]);
592
+ }
593
+ };
594
+ verifyOtp = async (data) => {
595
+ var _a, _b;
596
+ try {
597
+ const res = await this.graphqlQuery({
598
+ query: `
599
+ mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${authTokenFragment}}}
600
+ `,
601
+ variables: {
602
+ data
603
+ }
604
+ });
605
+ return ((_a = res == null ? void 0 : res.errors) == null ? void 0 : _a.length) ? this.errorResponse(res.errors) : this.okResponse((_b = res.data) == null ? void 0 : _b.verify_otp);
606
+ } catch (err) {
607
+ return this.errorResponse([
608
+ err
609
+ ]);
610
+ }
611
+ };
612
+ // helper to execute graphql queries
613
+ // takes in any query or mutation string as value
614
+ graphqlQuery = async (data) => {
615
+ var _a;
616
+ const fetcher = getFetcher();
617
+ const res = await fetcher(`${this.config.authorizerURL}/graphql`, {
618
+ method: "POST",
619
+ body: JSON.stringify({
620
+ query: data.query,
621
+ variables: data.variables || {}
622
+ }),
623
+ headers: {
624
+ ...this.config.extraHeaders,
625
+ ...data.headers || {}
626
+ },
627
+ credentials: "include"
628
+ });
629
+ const json = await res.json();
630
+ if ((_a = json == null ? void 0 : json.errors) == null ? void 0 : _a.length) {
631
+ return {
632
+ data: void 0,
633
+ errors: json.errors
634
+ };
635
+ }
636
+ return {
637
+ data: json.data,
638
+ errors: []
639
+ };
640
+ };
641
+ errorResponse = (errors) => {
642
+ return {
643
+ data: void 0,
644
+ errors
645
+ };
646
+ };
647
+ okResponse = (data) => {
648
+ return {
649
+ data,
650
+ errors: []
651
+ };
652
+ };
653
+ };
654
+ __name(_Authorizer, "Authorizer");
655
+ var Authorizer = _Authorizer;
656
+ // Annotate the CommonJS export names for ESM import in node:
657
+ 0 && (module.exports = {
658
+ Authorizer,
659
+ OAuthProviders,
660
+ ResponseTypes
661
+ });
662
+ //# sourceMappingURL=index.js.map