@authorizerdev/authorizer-js 3.0.1 → 3.0.2
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/authorizer.min.js +13 -13
- package/lib/index.d.mts +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +148 -40
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +148 -40
- package/lib/index.mjs.map +1 -1
- package/package.json +18 -17
package/lib/authorizer.min.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
var authorizerdev=(()=>{var
|
|
2
|
-
`)===0?l.substr(1,l.length):l}).forEach(function(l){var p=l.split(":"),u=p.shift().trim();if(u){var D=p.join(":").trim();try{n.append(u,D)}catch(j){console.warn("Response "+j.message)}}}),n}a(_e,"parseHeaders"),Z.call(v.prototype);function R(t,n){if(!(this instanceof R))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(n||(n={}),this.type="default",this.status=n.status===void 0?200:n.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=n.statusText===void 0?"":""+n.statusText,this.headers=new y(n.headers),this.url=n.url||"",this._initBody(t)}a(R,"Response"),Z.call(R.prototype),R.prototype.clone=function(){return new R(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},R.error=function(){var t=new R(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};var me=[301,302,303,307,308];R.redirect=function(t,n){if(me.indexOf(n)===-1)throw new RangeError("Invalid status code");return new R(null,{status:n,headers:{location:t}})},o.DOMException=s.DOMException;try{new o.DOMException}catch(t){o.DOMException=function(n,h){this.message=n,this.name=h;var l=Error(n);this.stack=l.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function P(t,n){return new Promise(function(h,l){var p=new v(t,n);if(p.signal&&p.signal.aborted)return l(new o.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function D(){u.abort()}a(D,"abortXhr"),u.onload=function(){var m={statusText:u.statusText,headers:_e(u.getAllResponseHeaders()||"")};p.url.indexOf("file://")===0&&(u.status<200||u.status>599)?m.status=200:m.status=u.status,m.url="responseURL"in u?u.responseURL:m.headers.get("X-Request-URL");var U="response"in u?u.response:u.responseText;setTimeout(function(){h(new R(U,m))},0)},u.onerror=function(){setTimeout(function(){l(new TypeError("Network request failed"))},0)},u.ontimeout=function(){setTimeout(function(){l(new TypeError("Network request timed out"))},0)},u.onabort=function(){setTimeout(function(){l(new o.DOMException("Aborted","AbortError"))},0)};function j(m){try{return m===""&&s.location.href?s.location.href:m}catch(U){return m}}if(a(j,"fixUrl"),u.open(p.method,j(p.url),!0),p.credentials==="include"?u.withCredentials=!0:p.credentials==="omit"&&(u.withCredentials=!1),"responseType"in u&&(r.blob?u.responseType="blob":r.arrayBuffer&&(u.responseType="arraybuffer")),n&&typeof n.headers=="object"&&!(n.headers instanceof y||s.Headers&&n.headers instanceof s.Headers)){var X=[];Object.getOwnPropertyNames(n.headers).forEach(function(m){X.push(_(m)),u.setRequestHeader(m,g(n.headers[m]))}),p.headers.forEach(function(m,U){X.indexOf(U)===-1&&u.setRequestHeader(U,m)})}else p.headers.forEach(function(m,U){u.setRequestHeader(U,m)});p.signal&&(p.signal.addEventListener("abort",D),u.onreadystatechange=function(){u.readyState===4&&p.signal.removeEventListener("abort",D)}),u.send(typeof p._bodyInit=="undefined"?null:p._bodyInit)})}return a(P,"fetch"),P.polyfill=!0,s.fetch||(s.fetch=P,s.Headers=y,s.Request=v,s.Response=R),o.Headers=y,o.Request=v,o.Response=R,o.fetch=P,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(S);S.fetch.ponyfill=!0;delete S.fetch.polyfill;var O=B.fetch?B:S;E=O.fetch;E.default=O.fetch;E.fetch=O.fetch;E.Headers=O.Headers;E.Request=O.Request;E.Response=O.Response;te.exports=E});var De={};ke(De,{Authorizer:()=>V,OAuthProviders:()=>H,ResponseTypes:()=>$});var he=Ae(oe());var H=(function(i){return i.Apple="apple",i.Github="github",i.Google="google",i.Facebook="facebook",i.LinkedIn="linkedin",i.Twitter="twitter",i.Microsoft="microsoft",i.Twitch="twitch",i.Roblox="roblox",i.Discord="discord",i})({}),$=(function(i){return i.Code="code",i.Token="token",i})({});var k=a(()=>typeof window!="undefined","hasWindow"),M=a(i=>{let e=i.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),se=a(()=>k()?window.crypto||window.msCrypto:null,"getCrypto"),Oe=a(()=>{let i=se();return i&&i.subtle||i.webkitSubtle},"getCryptoSubtle"),A=a(()=>{let i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",o=se();return o&&Array.from(o.getRandomValues(new Uint8Array(43))).forEach(r=>e+=i[r%i.length]),e},"createRandomString"),T=a(i=>k()?btoa(i):Buffer.from(i).toString("base64"),"encode");var ne=a(i=>Object.keys(i).filter(e=>typeof i[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(i[e])}`).join("&"),"createQueryParams"),ie=a(i=>d(null,null,function*(){let e=Oe().digest({name:"SHA-256"},new TextEncoder().encode(i));return window.msCrypto?new Promise((o,s)=>{e.oncomplete=r=>{o(r.target.result)},e.onerror=r=>{s(r.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Ie=a(i=>{let e={"+":"-","/":"_","=":""};return i.replace(/[+/=]/g,o=>e[o])},"urlEncodeB64");var ae=a(i=>{let e=new Uint8Array(i);return Ie(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),ce=a((i,e,o=60)=>new Promise((s,r)=>{let c=window.document.createElement("iframe");c.setAttribute("id","authorizer-iframe"),c.setAttribute("width","0"),c.setAttribute("height","0"),c.style.display="none";let b=a(()=>{window.document.body.contains(c)&&(window.document.body.removeChild(c),window.removeEventListener("message",_,!1))},"removeIframe"),w=setTimeout(()=>{r(new Error("Authorization timeout")),b()},o*1e3),_=a(function(g){if(g.origin!==e||!g.data||!g.data.response)return;let q=g.source;q&&q.close(),g.data.response.error?r(g.data.response):s(g.data.response),clearTimeout(w),window.removeEventListener("message",_,!1),setTimeout(b,2*1e3)},"iframeEventHandler");window.addEventListener("message",_,!1),window.document.body.appendChild(c),c.setAttribute("src",i)}),"executeIframe");var Q="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",I=`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 { ${Q} }`,N=a(()=>k()?window.fetch:he.default,"getFetcher"),J=class J{constructor(e){f(this,"config");f(this,"codeVerifier");f(this,"authorize",a(e=>d(this,null,function*(){var c;if(!k())return this.errorResponse([new Error("this feature is only supported in browser")]);let o=["openid","profile","email"];e.use_refresh_token&&o.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:T(A()),nonce:T(A()),response_type:e.response_type,scope:o.join(" "),client_id:((c=this.config)==null?void 0:c.clientID)||""};if(e.response_type===$.Code){this.codeVerifier=A();let b=yield ie(this.codeVerifier),w=ae(b);s.code_challenge=w}let r=`${this.config.authorizerURL}/authorize?${ne(s)}`;if(s.response_mode!=="web_message")return window.location.replace(r),this.okResponse(void 0);try{let b=yield ce(r,this.config.authorizerURL,60);if(e.response_type===$.Code){let w=yield this.getToken({code:b.code});return w.errors.length?this.errorResponse(w.errors):this.okResponse(w.data)}return this.okResponse(b)}catch(b){return b.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${T(JSON.stringify({clientID:this.config.clientID,redirectURL:this.config.redirectURL,authorizerURL:this.config.authorizerURL}))}&redirect_uri=${encodeURIComponent(this.config.redirectURL||"")}`),this.errorResponse(b)}}),"authorize"));f(this,"browserLogin",a(()=>d(this,null,function*(){try{let e=yield this.getSession();return e.errors.length?this.errorResponse(e.errors):this.okResponse(e.data)}catch(e){return k()?(window.location.replace(`${this.config.authorizerURL}/app?state=${T(JSON.stringify({clientID:this.config.clientID,redirectURL:this.config.redirectURL,authorizerURL:this.config.authorizerURL}))}&redirect_uri=${encodeURIComponent(this.config.redirectURL||"")}`),this.errorResponse(e)):{data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}}),"browserLogin"));f(this,"forgotPassword",a(e=>d(this,null,function*(){var o;e.state||(e.state=T(A())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let s=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordRequest!) { forgot_password(params: $data) { message should_show_mobile_otp_screen } }",variables:{data:e}});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}}),"forgotPassword"));f(this,"getMetaData",a(()=>d(this,null,function*(){var e;try{let o=yield 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(e=o==null?void 0:o.errors)!=null&&e.length?this.errorResponse(o.errors):this.okResponse(o.data.meta)}catch(o){return this.errorResponse([o])}}),"getMetaData"));f(this,"getProfile",a(e=>d(this,null,function*(){var o;try{let s=yield this.graphqlQuery({query:`query { profile { ${Q} } }`,headers:e});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}}),"getProfile"));f(this,"getSession",a((e,o)=>d(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:`query getSession($params: SessionQueryRequest){session(params: $params) { ${I} } }`,headers:e,variables:{params:o}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.session)}catch(c){return this.errorResponse(c)}}),"getSession"));f(this,"getToken",a(e=>d(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let o={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let r=yield N()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(o),headers:x({},this.config.extraHeaders),credentials:"include"}),c=yield r.json();return r.status>=400?this.errorResponse([new Error(c.error_description||c.error)]):this.okResponse(c)}catch(s){return this.errorResponse(s)}}),"getToken"));f(this,"login",a(e=>d(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
|
|
3
|
-
mutation login($data: LoginRequest!) { login(params: $data) { ${
|
|
4
|
-
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.login)}catch(r){return this.errorResponse(
|
|
1
|
+
var authorizerdev=(()=>{var we=Object.create;var q=Object.defineProperty,be=Object.defineProperties,Re=Object.getOwnPropertyDescriptor,ve=Object.getOwnPropertyDescriptors,Ee=Object.getOwnPropertyNames,K=Object.getOwnPropertySymbols,Te=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty,Ue=Object.prototype.propertyIsEnumerable;var N=(n,e,o)=>e in n?q(n,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[e]=o,O=(n,e)=>{for(var o in e||(e={}))Y.call(e,o)&&N(n,o,e[o]);if(K)for(var o of K(e))Ue.call(e,o)&&N(n,o,e[o]);return n},ee=(n,e)=>be(n,ve(e)),a=(n,e)=>q(n,"name",{value:e,configurable:!0});var ke=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ae=(n,e)=>{for(var o in e)q(n,o,{get:e[o],enumerable:!0})},re=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ee(e))!Y.call(n,r)&&r!==o&&q(n,r,{get:()=>e[r],enumerable:!(s=Re(e,r))||s.enumerable});return n};var xe=(n,e,o)=>(o=n!=null?we(Te(n)):{},re(e||!n||!n.__esModule?q(o,"default",{value:n,enumerable:!0}):o,n)),qe=n=>re(q({},"__esModule",{value:!0}),n);var d=(n,e,o)=>N(n,typeof e!="symbol"?e+"":e,o);var p=(n,e,o)=>new Promise((s,r)=>{var c=m=>{try{y(o.next(m))}catch(b){r(b)}},f=m=>{try{y(o.throw(m))}catch(b){r(b)}},y=m=>m.done?s(m.value):Promise.resolve(m.value).then(c,f);y((o=o.apply(n,e)).next())});var oe=ke((T,te)=>{var $=typeof globalThis!="undefined"&&globalThis||typeof self!="undefined"&&self||typeof global!="undefined"&&global,B=(function(){function n(){this.fetch=!1,this.DOMException=$.DOMException}return a(n,"F"),n.prototype=$,new n})();(function(n){var e=(function(o){var s=typeof n!="undefined"&&n||typeof self!="undefined"&&self||typeof global!="undefined"&&global||{},r={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&(function(){try{return new Blob,!0}catch(t){return!1}})(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function c(t){return t&&DataView.prototype.isPrototypeOf(t)}if(a(c,"isDataView"),r.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],y=ArrayBuffer.isView||function(t){return t&&f.indexOf(Object.prototype.toString.call(t))>-1};function m(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||t==="")throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}a(m,"normalizeName");function b(t){return typeof t!="string"&&(t=String(t)),t}a(b,"normalizeValue");function R(t){var i={next:a(function(){var u=t.shift();return{done:u===void 0,value:u}},"next")};return r.iterable&&(i[Symbol.iterator]=function(){return i}),i}a(R,"iteratorFor");function _(t){this.map={},t instanceof _?t.forEach(function(i,u){this.append(u,i)},this):Array.isArray(t)?t.forEach(function(i){if(i.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+i.length);this.append(i[0],i[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(i){this.append(i,t[i])},this)}a(_,"Headers"),_.prototype.append=function(t,i){t=m(t),i=b(i);var u=this.map[t];this.map[t]=u?u+", "+i:i},_.prototype.delete=function(t){delete this.map[m(t)]},_.prototype.get=function(t){return t=m(t),this.has(t)?this.map[t]:null},_.prototype.has=function(t){return this.map.hasOwnProperty(m(t))},_.prototype.set=function(t,i){this.map[m(t)]=b(i)},_.prototype.forEach=function(t,i){for(var u in this.map)this.map.hasOwnProperty(u)&&t.call(i,this.map[u],u,this)},_.prototype.keys=function(){var t=[];return this.forEach(function(i,u){t.push(u)}),R(t)},_.prototype.values=function(){var t=[];return this.forEach(function(i){t.push(i)}),R(t)},_.prototype.entries=function(){var t=[];return this.forEach(function(i,u){t.push([u,i])}),R(t)},r.iterable&&(_.prototype[Symbol.iterator]=_.prototype.entries);function C(t){if(!t._noBody){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}}a(C,"consumed");function G(t){return new Promise(function(i,u){t.onload=function(){i(t.result)},t.onerror=function(){u(t.error)}})}a(G,"fileReaderReady");function fe(t){var i=new FileReader,u=G(i);return i.readAsArrayBuffer(t),u}a(fe,"readBlobAsArrayBuffer");function de(t){var i=new FileReader,u=G(i),l=/charset=([A-Za-z0-9_-]+)/.exec(t.type),g=l?l[1]:"utf-8";return i.readAsText(t,g),u}a(de,"readBlobAsText");function le(t){for(var i=new Uint8Array(t),u=new Array(i.length),l=0;l<i.length;l++)u[l]=String.fromCharCode(i[l]);return u.join("")}a(le,"readArrayBufferAsText");function W(t){if(t.slice)return t.slice(0);var i=new Uint8Array(t.byteLength);return i.set(new Uint8Array(t)),i.buffer}a(W,"bufferClone");function Z(){return this.bodyUsed=!1,this._initBody=function(t){this.bodyUsed=this.bodyUsed,this._bodyInit=t,t?typeof t=="string"?this._bodyText=t:r.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:r.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:r.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():r.arrayBuffer&&r.blob&&c(t)?(this._bodyArrayBuffer=W(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||y(t))?this._bodyArrayBuffer=W(t):this._bodyText=t=Object.prototype.toString.call(t):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof t=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},r.blob&&(this.blob=function(){var t=C(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var t=C(this);return t||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(r.blob)return this.blob().then(fe);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var t=C(this);if(t)return t;if(this._bodyBlob)return de(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(le(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r.formData&&(this.formData=function(){return this.text().then(_e)}),this.json=function(){return this.text().then(JSON.parse)},this}a(Z,"Body");var pe=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function ye(t){var i=t.toUpperCase();return pe.indexOf(i)>-1?i:t}a(ye,"normalizeMethod");function E(t,i){if(!(this instanceof E))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');i=i||{};var u=i.body;if(t instanceof E){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,i.headers||(this.headers=new _(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!u&&t._bodyInit!=null&&(u=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=i.credentials||this.credentials||"same-origin",(i.headers||!this.headers)&&(this.headers=new _(i.headers)),this.method=ye(i.method||this.method||"GET"),this.mode=i.mode||this.mode||null,this.signal=i.signal||this.signal||(function(){if("AbortController"in s){var h=new AbortController;return h.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&u)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(u),(this.method==="GET"||this.method==="HEAD")&&(i.cache==="no-store"||i.cache==="no-cache")){var l=/([?&])_=[^&]*/;if(l.test(this.url))this.url=this.url.replace(l,"$1_="+new Date().getTime());else{var g=/\?/;this.url+=(g.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}a(E,"Request"),E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function _e(t){var i=new FormData;return t.trim().split("&").forEach(function(u){if(u){var l=u.split("="),g=l.shift().replace(/\+/g," "),h=l.join("=").replace(/\+/g," ");i.append(decodeURIComponent(g),decodeURIComponent(h))}}),i}a(_e,"decode");function ge(t){var i=new _,u=t.replace(/\r?\n[\t ]+/g," ");return u.split("\r").map(function(l){return l.indexOf(`
|
|
2
|
+
`)===0?l.substr(1,l.length):l}).forEach(function(l){var g=l.split(":"),h=g.shift().trim();if(h){var I=g.join(":").trim();try{i.append(h,I)}catch(H){console.warn("Response "+H.message)}}}),i}a(ge,"parseHeaders"),Z.call(E.prototype);function v(t,i){if(!(this instanceof v))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(i||(i={}),this.type="default",this.status=i.status===void 0?200:i.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=i.statusText===void 0?"":""+i.statusText,this.headers=new _(i.headers),this.url=i.url||"",this._initBody(t)}a(v,"Response"),Z.call(v.prototype),v.prototype.clone=function(){return new v(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new _(this.headers),url:this.url})},v.error=function(){var t=new v(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};var me=[301,302,303,307,308];v.redirect=function(t,i){if(me.indexOf(i)===-1)throw new RangeError("Invalid status code");return new v(null,{status:i,headers:{location:t}})},o.DOMException=s.DOMException;try{new o.DOMException}catch(t){o.DOMException=function(i,u){this.message=i,this.name=u;var l=Error(i);this.stack=l.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function P(t,i){return new Promise(function(u,l){var g=new E(t,i);if(g.signal&&g.signal.aborted)return l(new o.DOMException("Aborted","AbortError"));var h=new XMLHttpRequest;function I(){h.abort()}a(I,"abortXhr"),h.onload=function(){var w={statusText:h.statusText,headers:ge(h.getAllResponseHeaders()||"")};g.url.indexOf("file://")===0&&(h.status<200||h.status>599)?w.status=200:w.status=h.status,w.url="responseURL"in h?h.responseURL:w.headers.get("X-Request-URL");var k="response"in h?h.response:h.responseText;setTimeout(function(){u(new v(k,w))},0)},h.onerror=function(){setTimeout(function(){l(new TypeError("Network request failed"))},0)},h.ontimeout=function(){setTimeout(function(){l(new TypeError("Network request timed out"))},0)},h.onabort=function(){setTimeout(function(){l(new o.DOMException("Aborted","AbortError"))},0)};function H(w){try{return w===""&&s.location.href?s.location.href:w}catch(k){return w}}if(a(H,"fixUrl"),h.open(g.method,H(g.url),!0),g.credentials==="include"?h.withCredentials=!0:g.credentials==="omit"&&(h.withCredentials=!1),"responseType"in h&&(r.blob?h.responseType="blob":r.arrayBuffer&&(h.responseType="arraybuffer")),i&&typeof i.headers=="object"&&!(i.headers instanceof _||s.Headers&&i.headers instanceof s.Headers)){var X=[];Object.getOwnPropertyNames(i.headers).forEach(function(w){X.push(m(w)),h.setRequestHeader(w,b(i.headers[w]))}),g.headers.forEach(function(w,k){X.indexOf(k)===-1&&h.setRequestHeader(k,w)})}else g.headers.forEach(function(w,k){h.setRequestHeader(k,w)});g.signal&&(g.signal.addEventListener("abort",I),h.onreadystatechange=function(){h.readyState===4&&g.signal.removeEventListener("abort",I)}),h.send(typeof g._bodyInit=="undefined"?null:g._bodyInit)})}return a(P,"fetch"),P.polyfill=!0,s.fetch||(s.fetch=P,s.Headers=_,s.Request=E,s.Response=v),o.Headers=_,o.Request=E,o.Response=v,o.fetch=P,o})({})})(B);B.fetch.ponyfill=!0;delete B.fetch.polyfill;var L=$.fetch?$:B;T=L.fetch;T.default=L.fetch;T.fetch=L.fetch;T.Headers=L.Headers;T.Request=L.Request;T.Response=L.Response;te.exports=T});var Be={};Ae(Be,{Authorizer:()=>V,OAuthProviders:()=>F,ResponseTypes:()=>D});var he=xe(oe());var F=(function(n){return 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",n.Discord="discord",n})({}),D=(function(n){return n.Code="code",n.Token="token",n})({});var A=a(()=>typeof window!="undefined","hasWindow"),z=a(n=>{let e=n.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),se=a(()=>A()?window.crypto||window.msCrypto:null,"getCrypto"),Se=a(()=>{let n=se();return n&&n.subtle||n.webkitSubtle},"getCryptoSubtle"),x=a(()=>{let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",o=se();return o&&Array.from(o.getRandomValues(new Uint8Array(43))).forEach(r=>e+=n[r%n.length]),e},"createRandomString"),U=a(n=>A()?btoa(n):Buffer.from(n).toString("base64"),"encode");var ne=a(n=>Object.keys(n).filter(e=>typeof n[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(n[e])}`).join("&"),"createQueryParams"),ie=a(n=>p(null,null,function*(){let e=Se();if(!e)throw new Error("Web Crypto API is not available");let o=e.digest({name:"SHA-256"},new TextEncoder().encode(n));return window.msCrypto?new Promise((s,r)=>{o.oncomplete=c=>{s(c.target.result)},o.onerror=c=>{r(c.error)},o.onabort=()=>{r(new Error("The digest operation was aborted"))}}):yield o}),"sha256"),Ie=a(n=>{let e={"+":"-","/":"_","=":""};return n.replace(/[+/=]/g,o=>e[o])},"urlEncodeB64");var ae=a(n=>{let e=new Uint8Array(n);return Ie(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),$e=a(n=>{try{return new URL(n).origin}catch(e){return n}},"originFromAuthorizerUrl"),ce=a((n,e,o=60)=>new Promise((s,r)=>{let c=$e(e),f=window.document.createElement("iframe");f.setAttribute("id","authorizer-iframe"),f.setAttribute("width","0"),f.setAttribute("height","0"),f.style.display="none";let y=a(()=>{window.document.body.contains(f)&&(window.document.body.removeChild(f),window.removeEventListener("message",b,!1))},"removeIframe"),m=setTimeout(()=>{r(new Error("Authorization timeout")),y()},o*1e3),b=a(function(R){if(R.origin!==c||!R.data||!R.data.response)return;let _=R.source;_&&_.close(),R.data.response.error?r(R.data.response):s(R.data.response),clearTimeout(m),window.removeEventListener("message",b,!1),setTimeout(y,2*1e3)},"iframeEventHandler");window.addEventListener("message",b,!1),window.document.body.appendChild(f),f.setAttribute("src",n)}),"executeIframe");var Q="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",S=`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 { ${Q} }`,M=a(()=>A()?window.fetch:he.default,"getFetcher");function ue(n){if(Array.isArray(n))return n.map(e=>e instanceof Error?e:e&&typeof e=="object"&&"message"in e?new Error(String(e.message)):new Error(String(e)));if(n instanceof Error)return[n];if(n!==null&&typeof n=="object"){let e=n;if(typeof e.error_description=="string")return[new Error(e.error_description)];if(typeof e.error=="string"){let o=typeof e.error_description=="string"?`: ${e.error_description}`:"";return[new Error(`${e.error}${o}`)]}if(typeof e.message=="string")return[new Error(e.message)]}return n==null?[new Error("Unknown error")]:[new Error(String(n))]}a(ue,"toErrorList");var J=class J{constructor(e){d(this,"config");d(this,"codeVerifier");d(this,"authorize",a(e=>p(this,null,function*(){var c;if(!A())return this.errorResponse([new Error("this feature is only supported in browser")]);let o=["openid","profile","email"];e.use_refresh_token&&o.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:U(x()),nonce:U(x()),response_type:e.response_type,scope:o.join(" "),client_id:((c=this.config)==null?void 0:c.clientID)||""};if(e.response_type===D.Code){this.codeVerifier=x();let f=yield ie(this.codeVerifier),y=ae(f);s.code_challenge=y,s.code_challenge_method="S256"}let r=`${this.config.authorizerURL}/authorize?${ne(s)}`;if(s.response_mode!=="web_message")return window.location.replace(r),this.okResponse(void 0);try{let f=yield ce(r,this.config.authorizerURL,60);if(e.response_type===D.Code){let y=yield this.getToken({code:f.code});return y.errors.length?this.errorResponse(y.errors):this.okResponse(y.data)}return this.okResponse(f)}catch(f){return f.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${U(JSON.stringify({clientID:this.config.clientID,redirectURL:this.config.redirectURL,authorizerURL:this.config.authorizerURL}))}&redirect_uri=${encodeURIComponent(this.config.redirectURL||"")}`),this.errorResponse(f)}}),"authorize"));d(this,"browserLogin",a(()=>p(this,null,function*(){try{let e=yield this.getSession();return e.errors.length?this.errorResponse(e.errors):this.okResponse(e.data)}catch(e){return A()?(window.location.replace(`${this.config.authorizerURL}/app?state=${U(JSON.stringify({clientID:this.config.clientID,redirectURL:this.config.redirectURL,authorizerURL:this.config.authorizerURL}))}&redirect_uri=${encodeURIComponent(this.config.redirectURL||"")}`),this.errorResponse(e)):{data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}}),"browserLogin"));d(this,"forgotPassword",a(e=>p(this,null,function*(){var o,s;e.state||(e.state=U(x())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let r=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordRequest!) { forgot_password(params: $data) { message should_show_mobile_otp_screen } }",variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r==null?void 0:r.data)==null?void 0:s.forgot_password)}catch(r){return this.errorResponse([r])}}),"forgotPassword"));d(this,"getMetaData",a(()=>p(this,null,function*(){var e;try{let o=yield 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(e=o==null?void 0:o.errors)!=null&&e.length?this.errorResponse(o.errors):this.okResponse(o.data.meta)}catch(o){return this.errorResponse([o])}}),"getMetaData"));d(this,"getProfile",a(e=>p(this,null,function*(){var o;try{let s=yield this.graphqlQuery({query:`query { profile { ${Q} } }`,headers:e});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}}),"getProfile"));d(this,"getSession",a((e,o)=>p(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:`query getSession($params: SessionQueryRequest){session(params: $params) { ${S} } }`,headers:e,variables:{params:o}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.session)}catch(c){return this.errorResponse(c)}}),"getSession"));d(this,"getToken",a(e=>p(this,null,function*(){var s;if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!((s=e.refresh_token)!=null&&s.trim()))return this.errorResponse([new Error("Invalid refresh_token")]);if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let o={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let c=yield M()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(o),headers:O({},this.config.extraHeaders),credentials:"include"}),f=yield c.text(),y={};if(f)try{y=JSON.parse(f)}catch(m){return this.errorResponse([new Error(c.ok?"Invalid JSON from token endpoint":`HTTP ${c.status}`)])}return c.ok?this.okResponse(y):this.errorResponse([new Error(String(y.error_description||y.error||`HTTP ${c.status}`))])}catch(r){return this.errorResponse(r)}}),"getToken"));d(this,"login",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
|
|
3
|
+
mutation login($data: LoginRequest!) { login(params: $data) { ${S}}}
|
|
4
|
+
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.login)}catch(r){return this.errorResponse(r)}}),"login"));d(this,"logout",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.logout)}catch(r){return this.errorResponse([r])}}),"logout"));d(this,"magicLinkLogin",a(e=>p(this,null,function*(){var o,s;try{e.state||(e.state=U(x())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=yield this.graphqlQuery({query:`
|
|
5
5
|
mutation magicLinkLogin($data: MagicLinkLoginRequest!) { magic_link_login(params: $data) { message }}
|
|
6
|
-
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.magic_link_login)}catch(r){return this.errorResponse([r])}}),"magicLinkLogin"));
|
|
6
|
+
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.magic_link_login)}catch(r){return this.errorResponse([r])}}),"magicLinkLogin"));d(this,"oauthLogin",a((e,o,s,r)=>p(this,null,function*(){let c=r;c||(c=U(x()));let f=Object.values(F);if(!f.includes(e))throw new Error(`only following oauth providers are supported: ${f.join(", ")}`);if(!A())throw new Error("oauthLogin is only supported for browsers");o&&o.length&&(c+=`&roles=${o.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${encodeURIComponent(s||this.config.redirectURL||"")}&state=${encodeURIComponent(c)}`)}),"oauthLogin"));d(this,"resendOtp",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
|
|
7
7
|
mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
|
|
8
|
-
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.resend_otp)}catch(r){return this.errorResponse([r])}}),"resendOtp"));
|
|
9
|
-
mutation signup($data: SignUpRequest!) { signup(params: $data) { ${
|
|
10
|
-
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.signup)}catch(r){return this.errorResponse([r])}}),"signup"));
|
|
11
|
-
mutation verifyEmail($data: VerifyEmailRequest!) { verify_email(params: $data) { ${
|
|
12
|
-
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}}),"verifyEmail"));
|
|
8
|
+
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.resend_otp)}catch(r){return this.errorResponse([r])}}),"resendOtp"));d(this,"resetPassword",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordRequest!) { reset_password(params: $data) { message } }",variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.reset_password)}catch(r){return this.errorResponse([r])}}),"resetPassword"));d(this,"revokeToken",a(e=>p(this,null,function*(){var o;if(!((o=e.refresh_token)!=null&&o.trim()))return this.errorResponse([new Error("Invalid refresh_token")]);try{let r=yield M()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:O({},this.config.extraHeaders),body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})}),c=yield r.text(),f={};if(c)try{f=JSON.parse(c)}catch(y){return this.errorResponse([new Error(r.ok?"Invalid JSON from revoke endpoint":`HTTP ${r.status}`)])}if(!r.ok){let y=f;return this.errorResponse([new Error(String(y.error_description||y.error||`HTTP ${r.status}`))])}return this.okResponse(f)}catch(s){return this.errorResponse(s)}}),"revokeToken"));d(this,"signup",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
|
|
9
|
+
mutation signup($data: SignUpRequest!) { signup(params: $data) { ${S}}}
|
|
10
|
+
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.signup)}catch(r){return this.errorResponse([r])}}),"signup"));d(this,"updateProfile",a((e,o)=>p(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileRequest!) { update_profile(params: $data) { message } }",headers:o,variables:{data:e}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.update_profile)}catch(c){return this.errorResponse([c])}}),"updateProfile"));d(this,"deactivateAccount",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.deactivate_account)}catch(r){return this.errorResponse([r])}}),"deactivateAccount"));d(this,"validateJWTToken",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenRequest!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.validate_jwt_token)}catch(r){return this.errorResponse([r])}}),"validateJWTToken"));d(this,"validateSession",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`query validateSession($params: ValidateSessionRequest){validate_session(params: $params) { is_valid user { ${Q} } } }`,variables:{params:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.validate_session)}catch(r){return this.errorResponse([r])}}),"validateSession"));d(this,"verifyEmail",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
|
|
11
|
+
mutation verifyEmail($data: VerifyEmailRequest!) { verify_email(params: $data) { ${S}}}
|
|
12
|
+
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}}),"verifyEmail"));d(this,"resendVerifyEmail",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
|
|
13
13
|
mutation resendVerifyEmail($data: ResendVerifyEmailRequest!) { resend_verify_email(params: $data) { message }}
|
|
14
|
-
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.resend_verify_email)}catch(r){return this.errorResponse([r])}}),"resendVerifyEmail"));
|
|
15
|
-
mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${
|
|
16
|
-
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_otp)}catch(r){return this.errorResponse([r])}}),"verifyOtp"));
|
|
14
|
+
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.resend_verify_email)}catch(r){return this.errorResponse([r])}}),"resendVerifyEmail"));d(this,"verifyOtp",a(e=>p(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
|
|
15
|
+
mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${S}}}
|
|
16
|
+
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_otp)}catch(r){return this.errorResponse([r])}}),"verifyOtp"));d(this,"graphqlQuery",a(e=>p(this,null,function*(){var f;let s=yield M()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:O(O({},this.config.extraHeaders),e.headers||{}),credentials:"include"}),r=yield s.text(),c={};if(r)try{c=JSON.parse(r)}catch(y){return{data:void 0,errors:[new Error(s.ok?"Invalid JSON from GraphQL endpoint":`HTTP ${s.status}`)]}}else if(!s.ok)return{data:void 0,errors:[new Error(`HTTP ${s.status}`)]};return(f=c==null?void 0:c.errors)!=null&&f.length?{data:void 0,errors:ue(c.errors)}:s.ok?{data:c.data,errors:[]}:{data:void 0,errors:[new Error(`HTTP ${s.status}`)]}}),"graphqlQuery"));d(this,"errorResponse",a(e=>({data:void 0,errors:ue(e)}),"errorResponse"));d(this,"okResponse",a(e=>({data:e,errors:[]}),"okResponse"));var o,s;if(!e)throw new Error("Configuration is required");if(this.config=e,!((o=e.authorizerURL)!=null&&o.trim()))throw new Error("Invalid authorizerURL");if(this.config.authorizerURL=z(e.authorizerURL),!((s=e.redirectURL)!=null&&s.trim()))throw new Error("Invalid redirectURL");this.config.redirectURL=z(e.redirectURL),this.config.clientID=((e==null?void 0:e.clientID)||"").trim(),this.config.extraHeaders=ee(O({},e.extraHeaders||{}),{"x-authorizer-url":e.authorizerURL,"x-authorizer-client-id":e.clientID||"","Content-Type":"application/json"})}};a(J,"Authorizer");var V=J;return qe(Be);})();
|
|
17
17
|
if (typeof window !== "undefined") { window.authorizerdev = authorizerdev; }
|
package/lib/index.d.mts
CHANGED
|
@@ -333,7 +333,7 @@ declare class Authorizer {
|
|
|
333
333
|
resendVerifyEmail: (data: ResendVerifyEmailRequest) => Promise<ApiResponse<GenericResponse>>;
|
|
334
334
|
verifyOtp: (data: VerifyOtpRequest) => Promise<ApiResponse<AuthToken>>;
|
|
335
335
|
graphqlQuery: (data: GraphqlQueryRequest) => Promise<GrapQlResponseType>;
|
|
336
|
-
errorResponse: (errors:
|
|
336
|
+
errorResponse: (errors: unknown) => ApiResponse<any>;
|
|
337
337
|
okResponse: (data: any) => ApiResponse<any>;
|
|
338
338
|
}
|
|
339
339
|
|
package/lib/index.d.ts
CHANGED
|
@@ -333,7 +333,7 @@ declare class Authorizer {
|
|
|
333
333
|
resendVerifyEmail: (data: ResendVerifyEmailRequest) => Promise<ApiResponse<GenericResponse>>;
|
|
334
334
|
verifyOtp: (data: VerifyOtpRequest) => Promise<ApiResponse<AuthToken>>;
|
|
335
335
|
graphqlQuery: (data: GraphqlQueryRequest) => Promise<GrapQlResponseType>;
|
|
336
|
-
errorResponse: (errors:
|
|
336
|
+
errorResponse: (errors: unknown) => ApiResponse<any>;
|
|
337
337
|
okResponse: (data: any) => ApiResponse<any>;
|
|
338
338
|
}
|
|
339
339
|
|
package/lib/index.js
CHANGED
|
@@ -91,7 +91,9 @@ var createQueryParams = /* @__PURE__ */ __name((params) => {
|
|
|
91
91
|
return Object.keys(params).filter((k) => typeof params[k] !== "undefined").map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`).join("&");
|
|
92
92
|
}, "createQueryParams");
|
|
93
93
|
var sha256 = /* @__PURE__ */ __name(async (s) => {
|
|
94
|
-
const
|
|
94
|
+
const subtle = getCryptoSubtle();
|
|
95
|
+
if (!subtle) throw new Error("Web Crypto API is not available");
|
|
96
|
+
const digestOp = subtle.digest({
|
|
95
97
|
name: "SHA-256"
|
|
96
98
|
}, new TextEncoder().encode(s));
|
|
97
99
|
if (window.msCrypto) {
|
|
@@ -121,8 +123,16 @@ var bufferToBase64UrlEncoded = /* @__PURE__ */ __name((input) => {
|
|
|
121
123
|
const ie11SafeInput = new Uint8Array(input);
|
|
122
124
|
return urlEncodeB64(window.btoa(String.fromCharCode(...Array.from(ie11SafeInput))));
|
|
123
125
|
}, "bufferToBase64UrlEncoded");
|
|
126
|
+
var originFromAuthorizerUrl = /* @__PURE__ */ __name((authorizerUrl) => {
|
|
127
|
+
try {
|
|
128
|
+
return new URL(authorizerUrl).origin;
|
|
129
|
+
} catch {
|
|
130
|
+
return authorizerUrl;
|
|
131
|
+
}
|
|
132
|
+
}, "originFromAuthorizerUrl");
|
|
124
133
|
var executeIframe = /* @__PURE__ */ __name((authorizeUrl, eventOrigin, timeoutInSeconds = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) => {
|
|
125
134
|
return new Promise((resolve, reject) => {
|
|
135
|
+
const expectedOrigin = originFromAuthorizerUrl(eventOrigin);
|
|
126
136
|
const iframe = window.document.createElement("iframe");
|
|
127
137
|
iframe.setAttribute("id", "authorizer-iframe");
|
|
128
138
|
iframe.setAttribute("width", "0");
|
|
@@ -139,11 +149,12 @@ var executeIframe = /* @__PURE__ */ __name((authorizeUrl, eventOrigin, timeoutIn
|
|
|
139
149
|
removeIframe();
|
|
140
150
|
}, timeoutInSeconds * 1e3);
|
|
141
151
|
const iframeEventHandler = /* @__PURE__ */ __name(function(e) {
|
|
142
|
-
if (e.origin !==
|
|
152
|
+
if (e.origin !== expectedOrigin) return;
|
|
143
153
|
if (!e.data || !e.data.response) return;
|
|
144
154
|
const eventSource = e.source;
|
|
145
155
|
if (eventSource) eventSource.close();
|
|
146
|
-
e.data.response.error
|
|
156
|
+
if (e.data.response.error) reject(e.data.response);
|
|
157
|
+
else resolve(e.data.response);
|
|
147
158
|
clearTimeout(timeoutSetTimeoutId);
|
|
148
159
|
window.removeEventListener("message", iframeEventHandler, false);
|
|
149
160
|
setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1e3);
|
|
@@ -158,25 +169,60 @@ var executeIframe = /* @__PURE__ */ __name((authorizeUrl, eventOrigin, timeoutIn
|
|
|
158
169
|
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";
|
|
159
170
|
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} }`;
|
|
160
171
|
var getFetcher = /* @__PURE__ */ __name(() => hasWindow() ? window.fetch : import_cross_fetch.default, "getFetcher");
|
|
172
|
+
function toErrorList(errors) {
|
|
173
|
+
if (Array.isArray(errors)) {
|
|
174
|
+
return errors.map((item) => {
|
|
175
|
+
if (item instanceof Error) return item;
|
|
176
|
+
if (item && typeof item === "object" && "message" in item) return new Error(String(item.message));
|
|
177
|
+
return new Error(String(item));
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
if (errors instanceof Error) return [
|
|
181
|
+
errors
|
|
182
|
+
];
|
|
183
|
+
if (errors !== null && typeof errors === "object") {
|
|
184
|
+
const o = errors;
|
|
185
|
+
if (typeof o.error_description === "string") return [
|
|
186
|
+
new Error(o.error_description)
|
|
187
|
+
];
|
|
188
|
+
if (typeof o.error === "string") {
|
|
189
|
+
const desc = typeof o.error_description === "string" ? `: ${o.error_description}` : "";
|
|
190
|
+
return [
|
|
191
|
+
new Error(`${o.error}${desc}`)
|
|
192
|
+
];
|
|
193
|
+
}
|
|
194
|
+
if (typeof o.message === "string") return [
|
|
195
|
+
new Error(o.message)
|
|
196
|
+
];
|
|
197
|
+
}
|
|
198
|
+
if (errors === void 0 || errors === null) return [
|
|
199
|
+
new Error("Unknown error")
|
|
200
|
+
];
|
|
201
|
+
return [
|
|
202
|
+
new Error(String(errors))
|
|
203
|
+
];
|
|
204
|
+
}
|
|
205
|
+
__name(toErrorList, "toErrorList");
|
|
161
206
|
var _Authorizer = class _Authorizer {
|
|
162
207
|
// class variable
|
|
163
208
|
config;
|
|
164
209
|
codeVerifier;
|
|
165
210
|
// constructor
|
|
166
211
|
constructor(config) {
|
|
212
|
+
var _a, _b;
|
|
167
213
|
if (!config) throw new Error("Configuration is required");
|
|
168
214
|
this.config = config;
|
|
169
|
-
if (!config.authorizerURL
|
|
170
|
-
|
|
171
|
-
if (!config.redirectURL
|
|
172
|
-
|
|
215
|
+
if (!((_a = config.authorizerURL) == null ? void 0 : _a.trim())) throw new Error("Invalid authorizerURL");
|
|
216
|
+
this.config.authorizerURL = trimURL(config.authorizerURL);
|
|
217
|
+
if (!((_b = config.redirectURL) == null ? void 0 : _b.trim())) throw new Error("Invalid redirectURL");
|
|
218
|
+
this.config.redirectURL = trimURL(config.redirectURL);
|
|
219
|
+
this.config.clientID = ((config == null ? void 0 : config.clientID) || "").trim();
|
|
173
220
|
this.config.extraHeaders = {
|
|
174
221
|
...config.extraHeaders || {},
|
|
175
|
-
"x-authorizer-url":
|
|
176
|
-
"x-authorizer-client-id":
|
|
222
|
+
"x-authorizer-url": config.authorizerURL,
|
|
223
|
+
"x-authorizer-client-id": config.clientID || "",
|
|
177
224
|
"Content-Type": "application/json"
|
|
178
225
|
};
|
|
179
|
-
this.config.clientID = ((config == null ? void 0 : config.clientID) || "").trim();
|
|
180
226
|
}
|
|
181
227
|
authorize = /* @__PURE__ */ __name(async (data) => {
|
|
182
228
|
var _a;
|
|
@@ -203,6 +249,7 @@ var _Authorizer = class _Authorizer {
|
|
|
203
249
|
const sha = await sha256(this.codeVerifier);
|
|
204
250
|
const codeChallenge = bufferToBase64UrlEncoded(sha);
|
|
205
251
|
requestData.code_challenge = codeChallenge;
|
|
252
|
+
requestData.code_challenge_method = "S256";
|
|
206
253
|
}
|
|
207
254
|
const authorizeURL = `${this.config.authorizerURL}/authorize?${createQueryParams(requestData)}`;
|
|
208
255
|
if (requestData.response_mode !== "web_message") {
|
|
@@ -251,7 +298,7 @@ var _Authorizer = class _Authorizer {
|
|
|
251
298
|
}
|
|
252
299
|
}, "browserLogin");
|
|
253
300
|
forgotPassword = /* @__PURE__ */ __name(async (data) => {
|
|
254
|
-
var _a;
|
|
301
|
+
var _a, _b;
|
|
255
302
|
if (!data.state) data.state = encode(createRandomString());
|
|
256
303
|
if (!data.redirect_uri) data.redirect_uri = this.config.redirectURL;
|
|
257
304
|
try {
|
|
@@ -261,7 +308,7 @@ var _Authorizer = class _Authorizer {
|
|
|
261
308
|
data
|
|
262
309
|
}
|
|
263
310
|
});
|
|
264
|
-
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);
|
|
311
|
+
return ((_a = forgotPasswordResp == null ? void 0 : forgotPasswordResp.errors) == null ? void 0 : _a.length) ? this.errorResponse(forgotPasswordResp.errors) : this.okResponse((_b = forgotPasswordResp == null ? void 0 : forgotPasswordResp.data) == null ? void 0 : _b.forgot_password);
|
|
265
312
|
} catch (error) {
|
|
266
313
|
return this.errorResponse([
|
|
267
314
|
error
|
|
@@ -312,8 +359,9 @@ var _Authorizer = class _Authorizer {
|
|
|
312
359
|
}
|
|
313
360
|
}, "getSession");
|
|
314
361
|
getToken = /* @__PURE__ */ __name(async (data) => {
|
|
362
|
+
var _a;
|
|
315
363
|
if (!data.grant_type) data.grant_type = "authorization_code";
|
|
316
|
-
if (data.grant_type === "refresh_token" && !data.refresh_token) return this.errorResponse([
|
|
364
|
+
if (data.grant_type === "refresh_token" && !((_a = data.refresh_token) == null ? void 0 : _a.trim())) return this.errorResponse([
|
|
317
365
|
new Error("Invalid refresh_token")
|
|
318
366
|
]);
|
|
319
367
|
if (data.grant_type === "authorization_code" && !this.codeVerifier) return this.errorResponse([
|
|
@@ -336,10 +384,22 @@ var _Authorizer = class _Authorizer {
|
|
|
336
384
|
},
|
|
337
385
|
credentials: "include"
|
|
338
386
|
});
|
|
339
|
-
const
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
387
|
+
const text = await res.text();
|
|
388
|
+
let json = {};
|
|
389
|
+
if (text) {
|
|
390
|
+
try {
|
|
391
|
+
json = JSON.parse(text);
|
|
392
|
+
} catch {
|
|
393
|
+
return this.errorResponse([
|
|
394
|
+
new Error(res.ok ? "Invalid JSON from token endpoint" : `HTTP ${res.status}`)
|
|
395
|
+
]);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
if (!res.ok) {
|
|
399
|
+
return this.errorResponse([
|
|
400
|
+
new Error(String(json.error_description || json.error || `HTTP ${res.status}`))
|
|
401
|
+
]);
|
|
402
|
+
}
|
|
343
403
|
return this.okResponse(json);
|
|
344
404
|
} catch (err) {
|
|
345
405
|
return this.errorResponse(err);
|
|
@@ -358,9 +418,7 @@ var _Authorizer = class _Authorizer {
|
|
|
358
418
|
});
|
|
359
419
|
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);
|
|
360
420
|
} catch (err) {
|
|
361
|
-
return this.errorResponse(
|
|
362
|
-
new Error(err)
|
|
363
|
-
]);
|
|
421
|
+
return this.errorResponse(err);
|
|
364
422
|
}
|
|
365
423
|
}, "login");
|
|
366
424
|
logout = /* @__PURE__ */ __name(async (headers) => {
|
|
@@ -370,7 +428,7 @@ var _Authorizer = class _Authorizer {
|
|
|
370
428
|
query: " mutation { logout { message } } ",
|
|
371
429
|
headers
|
|
372
430
|
});
|
|
373
|
-
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.
|
|
431
|
+
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.logout);
|
|
374
432
|
} catch (err) {
|
|
375
433
|
return this.errorResponse([
|
|
376
434
|
err
|
|
@@ -402,8 +460,9 @@ var _Authorizer = class _Authorizer {
|
|
|
402
460
|
if (!urlState) {
|
|
403
461
|
urlState = encode(createRandomString());
|
|
404
462
|
}
|
|
405
|
-
|
|
406
|
-
|
|
463
|
+
const oauthProviderIds = Object.values(OAuthProviders);
|
|
464
|
+
if (!oauthProviderIds.includes(oauthProvider)) {
|
|
465
|
+
throw new Error(`only following oauth providers are supported: ${oauthProviderIds.join(", ")}`);
|
|
407
466
|
}
|
|
408
467
|
if (!hasWindow()) throw new Error("oauthLogin is only supported for browsers");
|
|
409
468
|
if (roles && roles.length) urlState += `&roles=${roles.join(",")}`;
|
|
@@ -444,22 +503,43 @@ var _Authorizer = class _Authorizer {
|
|
|
444
503
|
}
|
|
445
504
|
}, "resetPassword");
|
|
446
505
|
revokeToken = /* @__PURE__ */ __name(async (data) => {
|
|
447
|
-
|
|
506
|
+
var _a;
|
|
507
|
+
if (!((_a = data.refresh_token) == null ? void 0 : _a.trim())) return this.errorResponse([
|
|
448
508
|
new Error("Invalid refresh_token")
|
|
449
509
|
]);
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
510
|
+
try {
|
|
511
|
+
const fetcher = getFetcher();
|
|
512
|
+
const res = await fetcher(`${this.config.authorizerURL}/oauth/revoke`, {
|
|
513
|
+
method: "POST",
|
|
514
|
+
headers: {
|
|
515
|
+
...this.config.extraHeaders
|
|
516
|
+
},
|
|
517
|
+
body: JSON.stringify({
|
|
518
|
+
refresh_token: data.refresh_token,
|
|
519
|
+
client_id: this.config.clientID
|
|
520
|
+
})
|
|
521
|
+
});
|
|
522
|
+
const text = await res.text();
|
|
523
|
+
let responseData = {};
|
|
524
|
+
if (text) {
|
|
525
|
+
try {
|
|
526
|
+
responseData = JSON.parse(text);
|
|
527
|
+
} catch {
|
|
528
|
+
return this.errorResponse([
|
|
529
|
+
new Error(res.ok ? "Invalid JSON from revoke endpoint" : `HTTP ${res.status}`)
|
|
530
|
+
]);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
if (!res.ok) {
|
|
534
|
+
const errBody = responseData;
|
|
535
|
+
return this.errorResponse([
|
|
536
|
+
new Error(String(errBody.error_description || errBody.error || `HTTP ${res.status}`))
|
|
537
|
+
]);
|
|
538
|
+
}
|
|
539
|
+
return this.okResponse(responseData);
|
|
540
|
+
} catch (err) {
|
|
541
|
+
return this.errorResponse(err);
|
|
542
|
+
}
|
|
463
543
|
}, "revokeToken");
|
|
464
544
|
signup = /* @__PURE__ */ __name(async (data) => {
|
|
465
545
|
var _a, _b;
|
|
@@ -613,11 +693,39 @@ var _Authorizer = class _Authorizer {
|
|
|
613
693
|
},
|
|
614
694
|
credentials: "include"
|
|
615
695
|
});
|
|
616
|
-
const
|
|
696
|
+
const text = await res.text();
|
|
697
|
+
let json = {};
|
|
698
|
+
if (text) {
|
|
699
|
+
try {
|
|
700
|
+
json = JSON.parse(text);
|
|
701
|
+
} catch {
|
|
702
|
+
return {
|
|
703
|
+
data: void 0,
|
|
704
|
+
errors: [
|
|
705
|
+
new Error(res.ok ? "Invalid JSON from GraphQL endpoint" : `HTTP ${res.status}`)
|
|
706
|
+
]
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
} else if (!res.ok) {
|
|
710
|
+
return {
|
|
711
|
+
data: void 0,
|
|
712
|
+
errors: [
|
|
713
|
+
new Error(`HTTP ${res.status}`)
|
|
714
|
+
]
|
|
715
|
+
};
|
|
716
|
+
}
|
|
617
717
|
if ((_a = json == null ? void 0 : json.errors) == null ? void 0 : _a.length) {
|
|
618
718
|
return {
|
|
619
719
|
data: void 0,
|
|
620
|
-
errors: json.errors
|
|
720
|
+
errors: toErrorList(json.errors)
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
if (!res.ok) {
|
|
724
|
+
return {
|
|
725
|
+
data: void 0,
|
|
726
|
+
errors: [
|
|
727
|
+
new Error(`HTTP ${res.status}`)
|
|
728
|
+
]
|
|
621
729
|
};
|
|
622
730
|
}
|
|
623
731
|
return {
|
|
@@ -628,7 +736,7 @@ var _Authorizer = class _Authorizer {
|
|
|
628
736
|
errorResponse = /* @__PURE__ */ __name((errors) => {
|
|
629
737
|
return {
|
|
630
738
|
data: void 0,
|
|
631
|
-
errors
|
|
739
|
+
errors: toErrorList(errors)
|
|
632
740
|
};
|
|
633
741
|
}, "errorResponse");
|
|
634
742
|
okResponse = /* @__PURE__ */ __name((data) => {
|