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