@evervault/react
Advanced tools
Comparing version 0.0.7 to 0.1.7
@@ -1,1 +0,1 @@ | ||
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("react"));else if("function"==typeof define&&define.amd)define(["react"],t);else{var r="object"==typeof exports?t(require("react")):t(e.react);for(var n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(window,(function(e){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=2)}([function(t,r){t.exports=e},function(e,t,r){const n=r(3);e.exports={keyStore:new class{constructor(){let e=void 0;this.encryptString=t=>{const r=n.dataToBuffer(t),o=window.crypto.getRandomValues(new Uint8Array(12));return window.crypto.subtle.encrypt({name:"AES-GCM",iv:o},e,r).then(e=>n.buildEvervaultString(o,e)).catch(e=>{throw new Error("Encryption operation failed.")})},this.decryptString=t=>{if(n.isEvervaultString(t)){const r=n.parseEvervaultString(t),o=n.b64ToBuffer(r.browserData),a=n.b64ToBuffer(r.iv);return window.crypto.subtle.decrypt({name:"AES-GCM",iv:a},e,o).then(e=>n.bufferToString(e)).catch(e=>{throw new Error(e)})}return t},this.updateKey=async t=>{if(!e){const r=await n.getEncryptionKey(t||localStorage.getItem("evervault-privateKey"));e=r}}}},urls:{auth:"https://auth.evervault.com",api:"https://api.evervault.com"},init:function(e,t){if(!e)throw new Error("No appId provided to the evervault sdk");if(this.appId=e,t){const e=/^(http){1}(s)?(:\/{2}){1}/;let r={};Object.keys(t).forEach(n=>{const o=t[n];if(e.test(o))r[n]=o;else if(o)throw new Error(`Invalid URL received in evervault sdk for ${n} url (value: ${o})`)}),Object.assign(this.urls,r)}},set:async function(e){e=await this.encrypt(e,{preserveObjectShape:!0});const t=await this.getValidAccessToken();return fetch(`${this.urls.api}/data/${this.appId}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({data:e})}).then(e=>e.json()).then(e=>{if(!e)throw new Error("Unable to save data");return e}).catch(e=>{throw new Error("Unable to save data",e)})},get:async function(e=""){const t=await this.getValidAccessToken();return await fetch(`${this.urls.api}/data/${this.appId}/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}}).then(e=>e.json()).then(e=>{if(!e)throw new Error("Unable to get data");return this.decrypt(e)}).catch(e=>{throw new Error("Unable to get data",e)})},getValidAccessToken:async function(){if(n.checkAccessToken(localStorage.getItem("evervault-accessToken")))return localStorage.getItem("evervault-accessToken");return(await this.refreshAccessToken(localStorage.getItem("evervault-accessToken"),localStorage.getItem("evervault-refreshToken"))).accessToken},encrypt:function(e,t={}){const r=(e,t)=>{if(e){return(async(e,t)=>{let r=Object.assign({},e);for(let e=0;e<t.length;e++){let o=t[e];r[o]&&(r[o]=await this.keyStore.encryptString(n.ensureString(r[o])))}return r})(e,t)}};if("object"==typeof e&&e&&"Array"!==e.constructor.name&&t.preserveObjectShape){const n=t.fieldsToEncrypt||Object.keys(e);return this.keyStore.updateKey(t.privateKey).then(()=>r(e,n))}if(void 0!==e&&"symbol"!=typeof e)return this.keyStore.updateKey(t.privateKey).then(()=>this.keyStore.encryptString(n.ensureString(e)))},decrypt:function(e,t){const r=e=>(async t=>{let r=new Array(t.length);for(let o=0;o<e.length;o++)r[o]=await this.keyStore.decryptString(n.ensureString(t[o]));return r})(e),o=(e,t)=>{if(e){return(async(e,t)=>{let r=Object.assign({},e);for(let e=0;e<t.length;e++){let o=t[e];r[o]&&(r[o]=await this.keyStore.decryptString(n.ensureString(r[o])))}return r})(e,t)}};return"object"==typeof e?"Array"===e.constructor.name?this.keyStore.updateKey(t).then(()=>r(e)):this.keyStore.updateKey(t).then(()=>o(e,Object.keys(e))):void 0!==e&&"symbol"!=typeof e?this.keyStore.updateKey(t).then(()=>this.keyStore.decryptString(n.ensureString(e))):e},logout:function(e){localStorage.removeItem("evervault-privateKey"),localStorage.removeItem("evervault-accessToken"),localStorage.removeItem("evervault-refreshToken"),localStorage.removeItem("evervault-haiku"),e?window.location.replace(e):n.handleRedirect(`${this.urls.auth}/${this.appId}`)},refreshAccessToken:function(e,t){const r={accessToken:e||localStorage.getItem("evervault-accessToken"),refreshToken:t||localStorage.getItem("evervault-refreshToken")};return fetch(`${this.urls.api}/token/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}).then(e=>e.json()).then(({accessToken:e,refreshToken:t})=>{if(!e)throw new Error("Unable to retrive access token");return localStorage.setItem("evervault-accessToken",e),localStorage.setItem("evervault-refreshToken",t),{accessToken:e,refreshToken:t}}).catch(e=>{throw new Error("Unable to retrieve refresh token",e)})},checkAuth:function(){const e=window.location.hash.substring(2);window.location.hash="/";const t=localStorage.getItem("evervault-privateKey"),r=localStorage.getItem("evervault-accessToken"),o=localStorage.getItem("evervault-refreshToken"),a=Boolean(r&&o&&t);if(a||e){if(e)return n.setUserKeysInStorage(e),!0}else n.handleRedirect(`${this.urls.auth}/${this.appId}`);return a}}},function(e,t,r){"use strict";r.r(t),r.d(t,"EvervaultContext",(function(){return p})),r.d(t,"EvervaultProvider",(function(){return h})),r.d(t,"EvervaultConsumer",(function(){return v})),r.d(t,"useEvervault",(function(){return y})),r.d(t,"withEvervault",(function(){return d}));var n=r(0),o=r.n(n),a=r(1),i=r.n(a);function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function u(e,t){return!t||"object"!==c(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function l(e){return(l=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function f(e,t){return(f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var p=o.a.createContext(void 0),h=p.Provider,v=p.Consumer;function y(){var e=o.a.useContext(p);if(!e)throw new Error("No context found for evervault");if("function"!=typeof n.useContext)throw new Error("You must use React >= 16.8 in order to use useEvervault()");return e}function d(e,t){var r=t.appId,n=t.authUrl,a=t.apiUrl,c=t.useEvervaultContext;return(function(t){function p(e){var t;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,p),t=u(this,l(p).call(this,e)),i.a.init(r,{auth:n,api:a}),i.a.checkAuth(),t.state={evervault:i.a},t}var v,y,d;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&f(e,t)}(p,t),v=p,(y=[{key:"render",value:function(){return c?o.a.createElement(h,{value:this.state.evervault},o.a.createElement(e,null)):o.a.createElement(e,{evervault:this.state.evervault})}}])&&s(v.prototype,y),d&&s(v,d),p}(o.a.Component))}},function(e,t){e.exports=class e{static getEncryptionKey(e){const t=this.b64ToBuffer(e);return window.crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])}static b64ToBuffer(e){const t=window.atob(e);for(var r=new ArrayBuffer(t.length),n=new Uint8Array(r),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}static ensureString(e){return(e=>"string"==typeof e?e:["bigint","function"].includes(typeof e)?e.toString():JSON.stringify(e))(e).trim()}static bufToStr(e){const t=new Uint8Array(e);let r,n=0,o="",a=8*n;for(;a+8<t.length;)r=t.subarray(a,a+8),o+=String.fromCharCode.apply(null,r),n++,a=8*n;return o+=String.fromCharCode.apply(null,t.subarray(a)),o}static bufferToB64(e){return window.btoa(this.bufToStr(e))}static dataToBuffer(e){return(new TextEncoder).encode(e)}static checkAccessToken(e){return JSON.parse(this.bufToStr(this.b64ToBuffer(e.split(".")[1]))).exp>Math.floor(Date.now()/1e3)}static parseEvervaultString(e){const t=e.split(":");if(t.length<4)throw new Error("String does not match expected structure");return{prefix:t[0],version:t[1],iv:t[2],browserData:t[3]}}static isEvervaultString(e){return/^enc:v\d:(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?:(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/s.test(e)}static bufferToString(e){const t=new Uint8Array(e);let r,n=0,o="",a=8*n,i=new TextDecoder("utf-8");for(;a+8<t.length;)r=t.subarray(a,a+8),o+=i.decode(r),n++,a=8*n;return o+=i.decode(t.subarray(a)),o}static buildEvervaultString(e,t){return`enc:v1:${this.bufferToB64(e)}:${this.bufferToB64(t)}`}static setUserKeysInStorage(e){const t=e.split(":");localStorage.setItem("evervault-privateKey",t[0]),localStorage.setItem("evervault-accessToken",t[1]),localStorage.setItem("evervault-refreshToken",t[2]),localStorage.setItem("evervault-haiku",JSON.parse(window.atob(t[1].split(".")[1])).haiku)}static handleRedirect(t){const r=e.getParams(),n=["redirectUrl","state","nonce"],o=Object.keys(r).filter(e=>n.includes(e)).map(e=>`${e}=${encodeURI(r[e])}`).join("&");window.location.replace(`${t}${o&&o.length>0?"?"+o:o}`)}static getParams(){let e={};return window.location.search.substr(1).split("&").forEach(t=>{const[r,n]=t.split("=");e[r]=decodeURIComponent(n)}),e}}}])})); | ||
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("react"));else if("function"==typeof define&&define.amd)define(["react"],t);else{var r="object"==typeof exports?t(require("react")):t(e.react);for(var n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(window,(function(e){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=3)}([function(t,r){t.exports=e},function(e,t,r){e.exports=r(4)()},function(e,t,r){const n=r(6);e.exports={keyStore:new class{constructor(){let e=void 0;this.encryptString=t=>{const r=n.dataToBuffer(t),o=window.crypto.getRandomValues(new Uint8Array(12));return window.crypto.subtle.encrypt({name:"AES-GCM",iv:o},e,r).then(e=>n.buildEvervaultString(o,e)).catch(e=>{throw new Error("Encryption operation failed.")})},this.decryptString=t=>{if(n.isEvervaultString(t)){const r=n.parseEvervaultString(t),o=n.b64ToBuffer(r.browserData),a=n.b64ToBuffer(r.iv);return window.crypto.subtle.decrypt({name:"AES-GCM",iv:a},e,o).then(e=>n.bufferToString(e)).catch(e=>{throw new Error(e)})}return t},this.updateKey=async t=>{if(!e){const r=await n.getEncryptionKey(t||localStorage.getItem("evervault-privateKey"));e=r}}}},urls:{auth:"https://auth.evervault.com",api:"https://api.evervault.com"},init:function(e,t){if(!e)throw new Error("No appId provided to the evervault sdk");if(this.appId=e,t){const e=/^(http){1}(s)?(:\/{2}){1}/;let r={};Object.keys(t).forEach(n=>{const o=t[n];if(e.test(o))r[n]=o;else if(o)throw new Error(`Invalid URL received in evervault sdk for ${n} url (value: ${o})`)}),Object.assign(this.urls,r)}},set:async function(e){e=await this.encrypt(e,{preserveObjectShape:!0});const t=await this.getValidAccessToken();return fetch(`${this.urls.api}/data/${this.appId}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({data:e})}).then(e=>e.json()).then(e=>{if(!e)throw new Error("Unable to save data");return e}).catch(e=>{throw new Error("Unable to save data",e)})},get:async function(e=""){const t=await this.getValidAccessToken();return await fetch(`${this.urls.api}/data/${this.appId}/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}}).then(e=>e.json()).then(e=>{if(!e)throw new Error("Unable to get data");return this.decrypt(e)}).catch(e=>{throw new Error("Unable to get data",e)})},getValidAccessToken:async function(){if(n.checkAccessToken(localStorage.getItem("evervault-accessToken")))return localStorage.getItem("evervault-accessToken");return(await this.refreshAccessToken(localStorage.getItem("evervault-accessToken"),localStorage.getItem("evervault-refreshToken"))).accessToken},encrypt:function(e,t={preserveObjectShape:!0}){const r=(e,t)=>{if(e){return(async(e,t)=>{let r=Object.assign({},e);for(let e=0;e<t.length;e++){let o=t[e];r[o]&&(r[o]=await this.keyStore.encryptString(n.ensureString(r[o])))}return r})(e,t)}};if("object"==typeof e&&e&&"Array"!==e.constructor.name&&t.preserveObjectShape){const n=t.fieldsToEncrypt||Object.keys(e);return this.keyStore.updateKey(t.privateKey).then(()=>r(e,n))}if(void 0!==e&&"symbol"!=typeof e)return this.keyStore.updateKey(t.privateKey).then(()=>this.keyStore.encryptString(n.ensureString(e)))},decrypt:function(e,t){const r=e=>(async t=>{let r=new Array(t.length);for(let o=0;o<e.length;o++)r[o]=await this.keyStore.decryptString(n.ensureString(t[o]));return r})(e),o=(e,t)=>{if(e){return(async(e,t)=>{let r=Object.assign({},e);for(let e=0;e<t.length;e++){let o=t[e];r[o]&&(r[o]=await this.keyStore.decryptString(n.ensureString(r[o])))}return r})(e,t)}};return"object"==typeof e?"Array"===e.constructor.name?this.keyStore.updateKey(t).then(()=>r(e)):this.keyStore.updateKey(t).then(()=>o(e,Object.keys(e))):void 0!==e&&"symbol"!=typeof e?this.keyStore.updateKey(t).then(()=>this.keyStore.decryptString(n.ensureString(e))):e},logout:function(e){localStorage.removeItem("evervault-privateKey"),localStorage.removeItem("evervault-accessToken"),localStorage.removeItem("evervault-refreshToken"),localStorage.removeItem("evervault-haiku"),e?window.location.replace(e):n.handleRedirect(`${this.urls.auth}/${this.appId}`)},refreshAccessToken:function(e,t){const r={accessToken:e||localStorage.getItem("evervault-accessToken"),refreshToken:t||localStorage.getItem("evervault-refreshToken")};return fetch(`${this.urls.api}/token/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}).then(e=>401===e.status?this.logout():e.json()).then(({accessToken:e,refreshToken:t})=>{if(!e)throw new Error("Unable to retrive access token");return localStorage.setItem("evervault-accessToken",e),localStorage.setItem("evervault-refreshToken",t),{accessToken:e,refreshToken:t}}).catch(e=>{throw new Error("Unable to retrieve refresh token",e)})},checkAuth:function(e){e&&this.init(e);const t=window.location.hash.substring(2);if(t&&n.areHashValuesFromAuth(t))if("pushState"in history){const{pathname:e,search:t}=window.location,r=e+(t||"");history.pushState("",document.title,r)}else window.location.hash="/";const r=localStorage.getItem("evervault-privateKey"),o=localStorage.getItem("evervault-accessToken"),a=localStorage.getItem("evervault-refreshToken"),i=Boolean(o&&a&&r);if(i||t){if(t){const{accessToken:e,refreshToken:r,haiku:o}=n.setUserKeysInStorage(t);return this.accessToken=e,this.refreshToken=r,this.haiku=o,this.keyStore.updateKey().then(()=>!0)}!i||this.accessToken||this.refreshToken||this.haiku||(this.accessToken=o,this.refreshToken=a,this.haiku=localStorage.getItem("evervault-haiku"))}else n.handleRedirect(`${this.urls.auth}/${this.appId}`);return i},auth:t=>e.exports.checkAuth(t),fetch:function(e,t){const r=(e,t,r)=>{const n={authorization:`Bearer ${this.accessToken}`},o=Object.assign(n,t.headers),a=Object.assign(t,{headers:o});return fetch(e,a).then(e=>!e.ok&&401===e.status&&r?this.logout():e)};return r(e,t).then(n=>n.ok||401!==n.status?n:this.refreshAccessToken(this.accessToken,this.refreshToken).then(({accessToken:n,refreshToken:o})=>(this.accessToken=n,this.refreshToken=o,r(e,t,!0))))}}},function(e,t,r){"use strict";r.r(t),r.d(t,"EvervaultContext",(function(){return k})),r.d(t,"EvervaultProvider",(function(){return T})),r.d(t,"EvervaultConsumer",(function(){return O})),r.d(t,"useEvervault",(function(){return E})),r.d(t,"withEvervault",(function(){return j})),r.d(t,"Decrypt",(function(){return I})),r.d(t,"withEvervaultDecrypt",(function(){return x})),r.d(t,"EvervaultForm",(function(){return P}));var n=r(0),o=r.n(n),a=r(1),i=r.n(a),c=r(2),s=r.n(c);function u(e){return(u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function l(e,t,r,n,o,a,i){try{var c=e[a](i),s=c.value}catch(e){return void r(e)}c.done?t(s):Promise.resolve(s).then(n,o)}function f(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function h(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?f(Object(r),!0).forEach((function(t){p(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):f(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function p(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function d(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if(!(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)))return;var r=[],n=!0,o=!1,a=void 0;try{for(var i,c=e[Symbol.iterator]();!(n=(i=c.next()).done)&&(r.push(i.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{n||null==c.return||c.return()}finally{if(o)throw a}}return r}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function y(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function v(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function g(e,t,r){return t&&v(e.prototype,t),r&&v(e,r),e}function b(e,t){return!t||"object"!==u(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function m(e){return(m=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function w(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&S(e,t)}function S(e,t){return(S=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var k=o.a.createContext(void 0),T=k.Provider,O=k.Consumer;function E(){var e=o.a.useContext(k);if(!e)throw new Error("No context found for evervault");if("function"!=typeof n.useContext)throw new Error("You must use React >= 16.8 in order to use useEvervault()");return e}function j(e,t){var r=t.appId,n=t.authUrl,a=t.apiUrl,i=t.useEvervaultContext;return(function(t){function c(e){var t;return y(this,c),t=b(this,m(c).call(this,e)),s.a.init(r,{auth:n,api:a}),s.a.checkAuth(),t.state={evervault:s.a},t}return w(c,t),g(c,[{key:"render",value:function(){return i?o.a.createElement(T,{value:this.state.evervault},o.a.createElement(e,null)):o.a.createElement(e,{evervault:this.state.evervault})}}]),c}(o.a.Component))}function A(e){var t=e.data,r=d(o.a.useState(void 0),2),n=r[0],a=r[1];return o.a.useEffect((function(){var e=!1;return s.a.decrypt(t).then((function(t){e||a(t)})),function(){e=!0}}),[t]),o.a.createElement(o.a.Fragment,null,n)}function I(e){var t=e.children,r=e.data;if(!Boolean(t)&&Boolean(r))return o.a.createElement(A,{data:r});if(Boolean(t)&&Boolean(r)){var n=d(o.a.useState({loading:!0,decrypted:void 0,error:void 0}),2),a=n[0],i=n[1];return o.a.useEffect((function(){var e=!1;return s.a.decrypt(r).then((function(t){e||i({loading:!1,decrypted:t,error:void 0})})).catch((function(t){e||i({loading:!1,decrypted:void 0,error:"An error occurred while decrypting your data"})})),function(){e=!0}}),[]),t(h({},a))}throw new Error("Decrypt component requires data to be provided")}function x(e,t){return function(r){function n(e){var t;return y(this,n),(t=b(this,m(n).call(this,e))).state={loading:!0,decrypted:void 0,error:void 0},t}return w(n,r),g(n,[{key:"componentDidMount",value:function(){var e=this;s.a.decrypt(t).then((function(t){e.setState({loading:!1,decrypted:t,error:void 0})})).catch((function(t){e.setState({loading:!1,decrypted:void 0,error:"An error occurred while decrypting your data"})}))}},{key:"render",value:function(){return o.a.createElement(e,this.state)}}]),n}(o.a.Component)}function P(e){var t=e.children,r=e.initialValues,n=void 0===r?{}:r,a=e.handleSubmit,i=e.fieldsToEncrypt,c=d(o.a.useState(n),2),u=c[0],f=c[1],y=function(){var e,t=(e=regeneratorRuntime.mark((function e(t){var r,n,o;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t.preventDefault(),r=i,Boolean(r)||(r=Object.keys(u)),r.length<1&&a(u),n=Object.assign({},u),o=0;case 6:if(!(o<r.length)){e.next=14;break}if(!u[r[o]]){e.next=11;break}return e.next=10,s.a.encrypt(u[r[o]]);case 10:n[r[o]]=e.sent;case 11:o++,e.next=6;break;case 14:return e.abrupt("return",a(n));case 15:case"end":return e.stop()}}),e)})),function(){var t=this,r=arguments;return new Promise((function(n,o){var a=e.apply(t,r);function i(e){l(a,n,o,i,c,"next",e)}function c(e){l(a,n,o,i,c,"throw",e)}i(void 0)}))});return function(e){return t.apply(this,arguments)}}();return o.a.createElement("form",{onSubmit:y},t({values:h({},u),handleChange:function(e){f(h({},u,p({},e.target.name,e.target.value)))}}))}I.propTypes={children:i.a.func,data:i.a.oneOfType([i.a.string,i.a.object]).isRequired},P.propTypes={handleSubmit:i.a.func.isRequired,fieldsToEncrypt:i.a.array,initialValues:i.a.object}},function(e,t,r){"use strict";var n=r(5);function o(){}function a(){}a.resetWarningCache=o,e.exports=function(){function e(e,t,r,o,a,i){if(i!==n){var c=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw c.name="Invariant Violation",c}}function t(){return e}e.isRequired=e;var r={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:a,resetWarningCache:o};return r.PropTypes=r,r}},function(e,t,r){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t){e.exports=class e{static getEncryptionKey(e){const t=this.b64ToBuffer(e);return window.crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])}static b64ToBuffer(e){const t=window.atob(e);for(var r=new ArrayBuffer(t.length),n=new Uint8Array(r),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}static ensureString(e){return(e=>"string"==typeof e?e:["bigint","function"].includes(typeof e)?e.toString():JSON.stringify(e))(e).trim()}static bufToStr(e){const t=new Uint8Array(e);let r,n=0,o="",a=8*n;for(;a+8<t.length;)r=t.subarray(a,a+8),o+=String.fromCharCode.apply(null,r),n++,a=8*n;return o+=String.fromCharCode.apply(null,t.subarray(a)),o}static bufferToB64(e){return window.btoa(this.bufToStr(e))}static dataToBuffer(e){return(new TextEncoder).encode(e)}static checkAccessToken(e){return JSON.parse(this.bufToStr(this.b64ToBuffer(e.split(".")[1]))).exp>Math.floor(Date.now()/1e3)}static parseEvervaultString(e){const t=e.split(":");if(t.length<4)throw new Error("String does not match expected structure");return{prefix:t[0],version:t[1],iv:t[2],browserData:t[3]}}static isEvervaultString(e){return/^enc:v\d:(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?:(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/s.test(e)}static bufferToString(e){const t=new Uint8Array(e);let r,n=0,o="",a=8*n,i=new TextDecoder("utf-8");for(;a+8<t.length;)r=t.subarray(a,a+8),o+=i.decode(r),n++,a=8*n;return o+=i.decode(t.subarray(a)),o}static buildEvervaultString(e,t){return`enc:v1:${this.bufferToB64(e)}:${this.bufferToB64(t)}`}static setUserKeysInStorage(e){const[t,r,n]=e.split(":");localStorage.setItem("evervault-privateKey",t),localStorage.setItem("evervault-accessToken",r),localStorage.setItem("evervault-refreshToken",n);const o=JSON.parse(window.atob(r.split(".")[1])).haiku;return localStorage.setItem("evervault-haiku",o),{haiku:o,accessToken:r,refreshToken:n}}static handleRedirect(t){const r=e.getParams(),n=["redirectUrl","state","nonce"],o=Object.keys(r).filter(e=>n.includes(e)).map(e=>`${e}=${encodeURI(r[e])}`).join("&");window.location.replace(`${t}${o&&o.length>0?"?"+o:o}`)}static getParams(){let e={};return window.location.search.substr(1).split("&").forEach(t=>{const[r,n]=t.split("=");e[r]=decodeURIComponent(n)}),e}static areHashValuesFromAuth(e){return/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=?){1}:((eyJ){1}[A-Za-z0-9-_]+\.(eyJ){1}[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+\/=]*){1}:([a-z]+-[a-z]+-[0-9]{6,8}.[a-f0-9]{8}-[a-f0-9]{3,4}-[a-f0-9]{3,4}-[a-f0-9]{3,4}-[a-f0-9]{12}){1}$/.test(e)}}}])})); |
161
index.js
@@ -0,3 +1,6 @@ | ||
/** @format */ | ||
import React, { useContext } from 'react'; | ||
import evervault from '@evervault/sdk' | ||
import PropTypes from 'prop-types'; | ||
import evervault from '@evervault/sdk'; | ||
@@ -13,4 +16,6 @@ export const EvervaultContext = React.createContext(undefined); | ||
} | ||
if (typeof useContext !== "function") { | ||
throw new Error('You must use React >= 16.8 in order to use useEvervault()'); | ||
if (typeof useContext !== 'function') { | ||
throw new Error( | ||
'You must use React >= 16.8 in order to use useEvervault()' | ||
); | ||
} | ||
@@ -20,3 +25,2 @@ return evervault; | ||
export function withEvervault(WrappedComponent, params) { | ||
@@ -46,1 +50,150 @@ const { appId, authUrl, apiUrl, useEvervaultContext } = params; | ||
} | ||
function DataDecrypt({ data }) { | ||
const [decrypted, setDecrypted] = React.useState(undefined); | ||
React.useEffect(() => { | ||
let ignore = false; | ||
evervault.decrypt(data).then((decryptedData) => { | ||
if (!ignore) { | ||
setDecrypted(decryptedData); | ||
} | ||
}); | ||
return () => { | ||
ignore = true; | ||
}; | ||
}, [data]); | ||
return <>{decrypted}</>; | ||
} | ||
export function Decrypt({ children, data }) { | ||
if (!Boolean(children) && Boolean(data)) { | ||
return <DataDecrypt data={data} />; | ||
} | ||
const [decryptState, setDecryptState] = React.useState({ | ||
loading: true, | ||
decrypted: undefined, | ||
error: undefined, | ||
}); | ||
React.useEffect(() => { | ||
let ignore = false; | ||
evervault | ||
.decrypt(data) | ||
.then((decryptedData) => { | ||
if (!ignore) { | ||
setDecryptState({ | ||
loading: false, | ||
decrypted: decryptedData, | ||
error: undefined, | ||
}); | ||
} | ||
}) | ||
.catch((err) => { | ||
if (!ignore) { | ||
setDecryptState({ | ||
loading: false, | ||
decrypted: undefined, | ||
error: 'An error occurred while decrypting your data', | ||
}); | ||
} | ||
}); | ||
return () => { | ||
ignore = true; | ||
}; | ||
}, []); | ||
return children({ ...decryptState }); | ||
} | ||
Decrypt.propTypes = { | ||
children: PropTypes.func, | ||
data: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired, | ||
}; | ||
export function withEvervaultDecrypt(WrappedComponent, data) { | ||
return class extends React.Component { | ||
constructor(props) { | ||
super(props); | ||
this.state = { | ||
loading: true, | ||
decrypted: undefined, | ||
error: undefined, | ||
}; | ||
} | ||
componentDidMount() { | ||
evervault | ||
.decrypt(data) | ||
.then((decryptedData) => { | ||
this.setState({ | ||
loading: false, | ||
decrypted: decryptedData, | ||
error: undefined, | ||
}); | ||
}) | ||
.catch((err) => { | ||
this.setState({ | ||
loading: false, | ||
decrypted: undefined, | ||
error: 'An error occurred while decrypting your data', | ||
}); | ||
}); | ||
} | ||
render() { | ||
return <WrappedComponent {...this.state} />; | ||
} | ||
}; | ||
} | ||
export function EvervaultForm({ | ||
children, | ||
initialValues = {}, | ||
handleSubmit, | ||
fieldsToEncrypt, | ||
}) { | ||
const [formState, setFormState] = React.useState(initialValues); | ||
const handleChange = (e) => { | ||
setFormState({ ...formState, [e.target.name]: e.target.value }); | ||
}; | ||
const wrappedOnSubmit = async (e) => { | ||
e.preventDefault(); | ||
let _fieldsToEncrypt = fieldsToEncrypt; | ||
if (!Boolean(_fieldsToEncrypt)) { | ||
_fieldsToEncrypt = Object.keys(formState); | ||
} | ||
if (_fieldsToEncrypt.length < 1) { | ||
handleSubmit(formState); | ||
} | ||
let submissionObject = Object.assign({}, formState); | ||
for (let i = 0; i < _fieldsToEncrypt.length; i++) { | ||
if (formState[_fieldsToEncrypt[i]]) { | ||
submissionObject[_fieldsToEncrypt[i]] = await evervault.encrypt( | ||
formState[_fieldsToEncrypt[i]] | ||
); | ||
} | ||
} | ||
return handleSubmit(submissionObject); | ||
}; | ||
return ( | ||
<form onSubmit={wrappedOnSubmit}> | ||
{children({ values: { ...formState }, handleChange })} | ||
</form> | ||
); | ||
} | ||
EvervaultForm.propTypes = { | ||
handleSubmit: PropTypes.func.isRequired, | ||
fieldsToEncrypt: PropTypes.array, | ||
initialValues: PropTypes.object, | ||
}; |
{ | ||
"name": "@evervault/react", | ||
"version": "0.0.7", | ||
"version": "0.1.7", | ||
"description": "React package for the Evervault SDK", | ||
@@ -16,3 +16,3 @@ "main": "./build/lib/index.js", | ||
"dependencies": { | ||
"@evervault/sdk": "^0.3.2", | ||
"@evervault/sdk": "^0.3.4", | ||
"prop-types": "^15.7.2" | ||
@@ -19,0 +19,0 @@ }, |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
23736
204
5
Updated@evervault/sdk@^0.3.4