UNPKG

js-pkce

Version:

A package that makes using the OAuth2 PKCE flow easier

2 lines (1 loc) 14.1 kB
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).PKCE=t()}}((function(){return function t(e,n,r){function o(s,a){if(!n[s]){if(!e[s]){var c="function"==typeof require&&require;if(!a&&c)return c(s,!0);if(i)return i(s,!0);var f=new Error("Cannot find module '"+s+"'");throw f.code="MODULE_NOT_FOUND",f}var u=n[s]={exports:{}};e[s][0].call(u.exports,(function(t){return o(e[s][1][t]||t)}),u,u.exports,t,e,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s<r.length;s++)o(r[s]);return o}({1:[function(t,e,n){},{}],2:[function(t,e,n){(function(r){(function(){var o,i;o=this,i=function(){var e=e||function(e,n){var o;if("undefined"!=typeof window&&window.crypto&&(o=window.crypto),"undefined"!=typeof self&&self.crypto&&(o=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(o=globalThis.crypto),!o&&"undefined"!=typeof window&&window.msCrypto&&(o=window.msCrypto),!o&&void 0!==r&&r.crypto&&(o=r.crypto),!o&&"function"==typeof t)try{o=t("crypto")}catch(t){}var i=function(){if(o){if("function"==typeof o.getRandomValues)try{return o.getRandomValues(new Uint32Array(1))[0]}catch(t){}if("function"==typeof o.randomBytes)try{return o.randomBytes(4).readInt32LE()}catch(t){}}throw new Error("Native crypto module could not be used to get secure random number.")},s=Object.create||function(){function t(){}return function(e){var n;return t.prototype=e,n=new t,t.prototype=null,n}}(),a={},c=a.lib={},f=c.Base={extend:function(t){var e=s(this);return t&&e.mixIn(t),e.hasOwnProperty("init")&&this.init!==e.init||(e.init=function(){e.$super.init.apply(this,arguments)}),e.init.prototype=e,e.$super=this,e},create:function(){var t=this.extend();return t.init.apply(t,arguments),t},init:function(){},mixIn:function(t){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e]);t.hasOwnProperty("toString")&&(this.toString=t.toString)},clone:function(){return this.init.prototype.extend(this)}},u=c.WordArray=f.extend({init:function(t,e){t=this.words=t||[],this.sigBytes=null!=e?e:4*t.length},toString:function(t){return(t||p).stringify(this)},concat:function(t){var e=this.words,n=t.words,r=this.sigBytes,o=t.sigBytes;if(this.clamp(),r%4)for(var i=0;i<o;i++){var s=n[i>>>2]>>>24-i%4*8&255;e[r+i>>>2]|=s<<24-(r+i)%4*8}else for(var a=0;a<o;a+=4)e[r+a>>>2]=n[a>>>2];return this.sigBytes+=o,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var t=f.clone.call(this);return t.words=this.words.slice(0),t},random:function(t){for(var e=[],n=0;n<t;n+=4)e.push(i());return new u.init(e,t)}}),h=a.enc={},p=h.Hex={stringify:function(t){for(var e=t.words,n=t.sigBytes,r=[],o=0;o<n;o++){var i=e[o>>>2]>>>24-o%4*8&255;r.push((i>>>4).toString(16)),r.push((15&i).toString(16))}return r.join("")},parse:function(t){for(var e=t.length,n=[],r=0;r<e;r+=2)n[r>>>3]|=parseInt(t.substr(r,2),16)<<24-r%8*4;return new u.init(n,e/2)}},l=h.Latin1={stringify:function(t){for(var e=t.words,n=t.sigBytes,r=[],o=0;o<n;o++){var i=e[o>>>2]>>>24-o%4*8&255;r.push(String.fromCharCode(i))}return r.join("")},parse:function(t){for(var e=t.length,n=[],r=0;r<e;r++)n[r>>>2]|=(255&t.charCodeAt(r))<<24-r%4*8;return new u.init(n,e)}},d=h.Utf8={stringify:function(t){try{return decodeURIComponent(escape(l.stringify(t)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(t){return l.parse(unescape(encodeURIComponent(t)))}},y=c.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new u.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=d.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(t){var n,r=this._data,o=r.words,i=r.sigBytes,s=this.blockSize,a=i/(4*s),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*s,f=e.min(4*c,i);if(c){for(var h=0;h<c;h+=s)this._doProcessBlock(o,h);n=o.splice(0,c),r.sigBytes-=f}return new u.init(n,f)},clone:function(){var t=f.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0}),g=(c.Hasher=y.extend({cfg:f.extend(),init:function(t){this.cfg=this.cfg.extend(t),this.reset()},reset:function(){y.reset.call(this),this._doReset()},update:function(t){return this._append(t),this._process(),this},finalize:function(t){return t&&this._append(t),this._doFinalize()},blockSize:16,_createHelper:function(t){return function(e,n){return new t.init(n).finalize(e)}},_createHmacHelper:function(t){return function(e,n){return new g.HMAC.init(t,n).finalize(e)}}}),a.algo={});return a}(Math);return e},"object"==typeof n?e.exports=n=i():o.CryptoJS=i()}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{crypto:1}],3:[function(t,e,n){var r,o;r=this,o=function(t){var e,n;return n=(e=t).lib.WordArray,e.enc.Base64={stringify:function(t){var e=t.words,n=t.sigBytes,r=this._map;t.clamp();for(var o=[],i=0;i<n;i+=3)for(var s=(e[i>>>2]>>>24-i%4*8&255)<<16|(e[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|e[i+2>>>2]>>>24-(i+2)%4*8&255,a=0;a<4&&i+.75*a<n;a++)o.push(r.charAt(s>>>6*(3-a)&63));var c=r.charAt(64);if(c)for(;o.length%4;)o.push(c);return o.join("")},parse:function(t){var e=t.length,r=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var i=0;i<r.length;i++)o[r.charCodeAt(i)]=i}var s=r.charAt(64);if(s){var a=t.indexOf(s);-1!==a&&(e=a)}return function(t,e,r){for(var o=[],i=0,s=0;s<e;s++)if(s%4){var a=r[t.charCodeAt(s-1)]<<s%4*2|r[t.charCodeAt(s)]>>>6-s%4*2;o[i>>>2]|=a<<24-i%4*8,i++}return n.create(o,i)}(t,e,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},t.enc.Base64},"object"==typeof n?e.exports=n=o(t("./core")):o(r.CryptoJS)},{"./core":2}],4:[function(t,e,n){var r,o;r=this,o=function(t){return function(){if("function"==typeof ArrayBuffer){var e=t.lib.WordArray,n=e.init,r=e.init=function(t){if(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),(t instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array)&&(t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),t instanceof Uint8Array){for(var e=t.byteLength,r=[],o=0;o<e;o++)r[o>>>2]|=t[o]<<24-o%4*8;n.call(this,r,e)}else n.apply(this,arguments)};r.prototype=e}}(),t.lib.WordArray},"object"==typeof n?e.exports=n=o(t("./core")):o(r.CryptoJS)},{"./core":2}],5:[function(t,e,n){var r,o;r=this,o=function(t){return function(e){var n=t,r=n.lib,o=r.WordArray,i=r.Hasher,s=n.algo,a=[],c=[];!function(){function t(t){for(var n=e.sqrt(t),r=2;r<=n;r++)if(!(t%r))return!1;return!0}function n(t){return 4294967296*(t-(0|t))|0}for(var r=2,o=0;o<64;)t(r)&&(o<8&&(a[o]=n(e.pow(r,.5))),c[o]=n(e.pow(r,1/3)),o++),r++}();var f=[],u=s.SHA256=i.extend({_doReset:function(){this._hash=new o.init(a.slice(0))},_doProcessBlock:function(t,e){for(var n=this._hash.words,r=n[0],o=n[1],i=n[2],s=n[3],a=n[4],u=n[5],h=n[6],p=n[7],l=0;l<64;l++){if(l<16)f[l]=0|t[e+l];else{var d=f[l-15],y=(d<<25|d>>>7)^(d<<14|d>>>18)^d>>>3,g=f[l-2],v=(g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10;f[l]=y+f[l-7]+v+f[l-16]}var w=r&o^r&i^o&i,_=(r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22),m=p+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&u^~a&h)+c[l]+f[l];p=h,h=u,u=a,a=s+m|0,s=i,i=o,o=r,r=m+(_+w)|0}n[0]=n[0]+r|0,n[1]=n[1]+o|0,n[2]=n[2]+i|0,n[3]=n[3]+s|0,n[4]=n[4]+a|0,n[5]=n[5]+u|0,n[6]=n[6]+h|0,n[7]=n[7]+p|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,o=8*t.sigBytes;return n[o>>>5]|=128<<24-o%32,n[14+(o+64>>>9<<4)]=e.floor(r/4294967296),n[15+(o+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var t=i.clone.call(this);return t._hash=this._hash.clone(),t}});n.SHA256=i._createHelper(u),n.HmacSHA256=i._createHmacHelper(u)}(Math),t.SHA256},"object"==typeof n?e.exports=n=o(t("./core")):o(r.CryptoJS)},{"./core":2}],PKCE:[function(t,e,n){"use strict";var r=this&&this.__assign||function(){return r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},r.apply(this,arguments)},o=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function s(t){try{c(r.next(t))}catch(t){i(t)}}function a(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}c((r=r.apply(t,e||[])).next())}))},i=this&&this.__generator||function(t,e){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}},s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(n,"__esModule",{value:!0});var a=s(t("crypto-js/sha256")),c=s(t("crypto-js/enc-base64")),f=s(t("crypto-js/lib-typedarrays")),u=function(){function t(t){this.STATE_KEY="pkce_state",this.CODE_VERIFIER_KEY="pkce_code_verifier",this.corsRequestOptions={},this.config=t}return t.prototype.authorizeUrl=function(t){void 0===t&&(t={}),this.setCodeVerifier(),this.setState(t.state||null);var e=this.pkceChallengeFromVerifier(),n=new URLSearchParams(r({response_type:"code",client_id:this.config.client_id,state:this.getState(),scope:this.config.requested_scopes,redirect_uri:this.config.redirect_uri,code_challenge:e,code_challenge_method:"S256"},t)).toString();return"".concat(this.config.authorization_endpoint,"?").concat(n)},t.prototype.enableCorsCredentials=function(t){return this.corsRequestOptions=t?{credentials:"include",mode:"cors"}:{},this.corsRequestOptions},t.prototype.exchangeForAccessToken=function(t,e){return void 0===e&&(e={}),o(this,void 0,void 0,(function(){var n;return i(this,(function(o){switch(o.label){case 0:return[4,this.parseAuthResponseUrl(t)];case 1:return n=o.sent().code,[4,fetch(this.config.token_endpoint,r({method:"POST",body:new URLSearchParams(r({grant_type:"authorization_code",code:n,client_id:this.config.client_id,redirect_uri:this.config.redirect_uri,code_verifier:this.getCodeVerifier()},e)),headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"}},this.corsRequestOptions))];case 2:return[4,o.sent().json()];case 3:return[2,o.sent()]}}))}))},t.prototype.getCodeVerifier=function(){var t=this.getStore().getItem(this.CODE_VERIFIER_KEY);if(null===t)throw new Error("Code Verifier not set.");return t},t.prototype.getState=function(){var t=this.getStore().getItem(this.STATE_KEY);if(null===t)throw new Error("State not set.");return t},t.prototype.refreshAccessToken=function(t){return o(this,void 0,void 0,(function(){return i(this,(function(e){switch(e.label){case 0:return[4,fetch(this.config.token_endpoint,{method:"POST",body:new URLSearchParams({grant_type:"refresh_token",client_id:this.config.client_id,refresh_token:t}),headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"}})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},t.prototype.revokeToken=function(t,e){return void 0===e&&(e=""),o(this,void 0,void 0,(function(){var n;return i(this,(function(r){switch(r.label){case 0:return this.checkEndpoint("revoke_endpoint"),n=new URLSearchParams({token:t,client_id:this.config.client_id}),e.length&&n.append("token_type_hint",e),[4,fetch(this.config.revoke_endpoint,{method:"POST",body:n,headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"}})];case 1:return[2,r.sent().ok]}}))}))},t.prototype.checkEndpoint=function(t){if(!this.config.hasOwnProperty(t))throw new Error("".concat(t," not configured."));var e=new URL(this.config[t]),n=-1!==["localhost","127.0.0.1"].indexOf(e.hostname);if("https:"!==e.protocol&&!n)throw new Error("Protocol ".concat(e.protocol," not allowed with this action."))},t.prototype.generateRandomString=function(){return f.default.random(64)},t.prototype.parseAuthResponseUrl=function(t){var e=new URL(t).searchParams;return this.validateAuthResponse({error:e.get("error"),query:e.get("query"),state:e.get("state"),code:e.get("code")})},t.prototype.pkceChallengeFromVerifier=function(){var t=(0,a.default)(this.getCodeVerifier());return c.default.stringify(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},t.prototype.setCodeVerifier=function(){this.getStore().setItem(this.CODE_VERIFIER_KEY,this.generateRandomString())},t.prototype.setState=function(t){void 0===t&&(t=null);var e=null!==t?t:this.generateRandomString();this.getStore().setItem(this.STATE_KEY,e)},t.prototype.validateAuthResponse=function(t){var e=this;return new Promise((function(n,r){return t.error?r({error:t.error}):t.state!==e.getState()?r({error:"Invalid State"}):n(t)}))},t.prototype.getStore=function(){var t;return(null===(t=this.config)||void 0===t?void 0:t.storage)||sessionStorage},t}();n.default=u,e.exports=u},{"crypto-js/enc-base64":3,"crypto-js/lib-typedarrays":4,"crypto-js/sha256":5}]},{},[])("PKCE")}));