virgil-sdk
Version:
Virgil Security Services SDK
2 lines (1 loc) • 38.8 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Virgil={})}(this,(function(e){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(e,t){return e(t={exports:{}},t.exports),t.exports}var n=r((function(e,r){!function(n){var i=r,o=e&&e.exports==i&&e,s="object"==typeof t&&t;s.global!==s&&s.window!==s||(n=s);var a=function(e){this.message=e};(a.prototype=new Error).name="InvalidCharacterError";var c=function(e){throw new a(e)},d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=/[\t\n\f\r ]/g,h={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&c("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,i,o=e.length%3,s="",a=-1,u=e.length-o;++a<u;)t=e.charCodeAt(a)<<16,r=e.charCodeAt(++a)<<8,n=e.charCodeAt(++a),s+=d.charAt((i=t+r+n)>>18&63)+d.charAt(i>>12&63)+d.charAt(i>>6&63)+d.charAt(63&i);return 2==o?(t=e.charCodeAt(a)<<8,r=e.charCodeAt(++a),s+=d.charAt((i=t+r)>>10)+d.charAt(i>>4&63)+d.charAt(i<<2&63)+"="):1==o&&(i=e.charCodeAt(a),s+=d.charAt(i>>2)+d.charAt(i<<4&63)+"=="),s},decode:function(e){var t=(e=String(e).replace(u,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&c("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,i=0,o="",s=-1;++s<t;)n=d.indexOf(e.charAt(s)),r=i%4?64*r+n:n,i++%4&&(o+=String.fromCharCode(255&r>>(-2*i&6)));return o},version:"1.0.0"};if(i&&!i.nodeType)if(o)o.exports=h;else for(var l in h)h.hasOwnProperty(l)&&(i[l]=h[l]);else n.base64=h}(t)}));function i(e){return n.decode(e)}function o(e){return n.encode(e)}function s(e){return e=(e=e.split("=")[0]).replace(/\+/g,"-").replace(/\//g,"_")}function a(e){switch((e=e.replace(/-/g,"+").replace(/_/g,"/")).length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("Invalid base64 string")}return e}function c(e){return s(o(e))}function d(e){return i(a(e))}function u(e){let t;return t="number"==typeof e?e:e.getTime(),Math.floor(t/1e3)}const h="identity-",l="virgil-",f="virgil-jwt;v=1";class p{constructor(e,t,r){if("string"==typeof e){const t=e,r=t.split(".");if(3!==r.length)throw new Error("Wrong JWT format");try{this.header=JSON.parse(d(r[0])),this.body=JSON.parse(d(r[1])),this.signature=a(r[2])}catch(e){throw new Error("Wrong JWT format")}this.unsignedData=r[0]+"."+r[1],this.stringRepresentation=t}else{if("object"!=typeof e||"object"!=typeof t)throw new TypeError("Invalid arguments for function Jwt. Expected a string representation of a token, or header and body as objects");this.header=e,this.body=t,this.signature=r,this.unsignedData=this.headerBase64()+"."+this.bodyBase64(),this.stringRepresentation=null==this.signature?this.unsignedData:this.unsignedData+"."+this.signatureBase64()}}static fromString(e){return new p(e)}toString(){return this.stringRepresentation}identity(){if(0!==this.body.sub.indexOf(h))throw new Error("wrong sub format");return this.body.sub.substr(h.length)}appId(){if(0!==this.body.iss.indexOf(l))throw new Error("wrong iss format");return this.body.iss.substr(l.length)}isExpired(e=new Date){const t=u(e);return this.body.exp<t}headerBase64(){return c(JSON.stringify(this.header))}bodyBase64(){return c(JSON.stringify(this.body))}signatureBase64(){return s(this.signature)}}function y(e,t){if(!e)throw new Error(t)}class g{constructor(e,t){this.contentSnapshot=e,this.signatures=t}static fromString(e){const t=i(e);let r;try{r=JSON.parse(t)}catch(e){throw new Error("The string to be parsed is in invalid format")}return g.fromJson(r)}static fromJson(e){const t=i(e.content_snapshot),r=(e.signatures||[]).map((({signer:e,signature:t,snapshot:r})=>r?{signer:e,signature:t,snapshot:i(r)}:{signer:e,signature:t}));return new g(t,r)}toJSON(){return this.toJson()}toJson(){return{content_snapshot:o(this.contentSnapshot),signatures:this.signatures.map((({signer:e,signature:t,snapshot:r})=>r?{signer:e,signature:t,snapshot:o(r)}:{signer:e,signature:t}))}}toString(){return o(JSON.stringify(this))}exportAsJson(){return this.toJson()}exportAsString(){return this.toString()}}var w,b=r((function(e,r){!function(t){e.exports=function(e){var n=e&&e.Promise||t.Promise,i=e&&e.XMLHttpRequest||t.XMLHttpRequest;return function(){var e=Object.create(t,{fetch:{value:void 0,writable:!0}});return function(t){var r=void 0!==e&&e||"undefined"!=typeof self&&self||void 0!==r&&r,o={searchParams:"URLSearchParams"in r,iterable:"Symbol"in r&&"iterator"in Symbol,blob:"FileReader"in r&&"Blob"in r&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in r,arrayBuffer:"ArrayBuffer"in r};function s(e){return e&&DataView.prototype.isPrototypeOf(e)}if(o.arrayBuffer)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function d(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function h(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return o.iterable&&(t[Symbol.iterator]=function(){return t}),t}function l(e){this.map={},e instanceof l?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function f(e){if(e.bodyUsed)return n.reject(new TypeError("Already read"));e.bodyUsed=!0}function p(e){return new n((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function y(e){var t=new FileReader,r=p(t);return t.readAsArrayBuffer(e),r}function g(e){var t=new FileReader,r=p(t);return t.readAsText(e),r}function w(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n<t.length;n++)r[n]=String.fromCharCode(t[n]);return r.join("")}function b(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:o.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:o.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():o.arrayBuffer&&o.blob&&s(e)?(this._bodyArrayBuffer=b(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||c(e))?this._bodyArrayBuffer=b(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):o.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o.blob&&(this.blob=function(){var e=f(this);if(e)return e;if(this._bodyBlob)return n.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return n.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return n.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?f(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?n.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):n.resolve(this._bodyArrayBuffer)):this.blob().then(y)}),this.text=function(){var e=f(this);if(e)return e;if(this._bodyBlob)return g(this._bodyBlob);if(this._bodyArrayBuffer)return n.resolve(w(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return n.resolve(this._bodyText)},o.formData&&(this.formData=function(){return this.text().then(T)}),this.json=function(){return this.text().then(JSON.parse)},this}l.prototype.append=function(e,t){e=d(e),t=u(t);var r=this.map[e];this.map[e]=r?r+", "+t:t},l.prototype.delete=function(e){delete this.map[d(e)]},l.prototype.get=function(e){return e=d(e),this.has(e)?this.map[e]:null},l.prototype.has=function(e){return this.map.hasOwnProperty(d(e))},l.prototype.set=function(e,t){this.map[d(e)]=u(t)},l.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},l.prototype.keys=function(){var e=[];return this.forEach((function(t,r){e.push(r)})),h(e)},l.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),h(e)},l.prototype.entries=function(){var e=[];return this.forEach((function(t,r){e.push([r,t])})),h(e)},o.iterable&&(l.prototype[Symbol.iterator]=l.prototype.entries);var v=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function S(e){var t=e.toUpperCase();return v.indexOf(t)>-1?t:e}function E(e,t){if(!(this instanceof E))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r=(t=t||{}).body;if(e instanceof E){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new l(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,r||null==e._bodyInit||(r=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new l(t.headers)),this.method=S(t.method||this.method||"GET"),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(r),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var n=/([?&])_=[^&]*/;if(n.test(this.url))this.url=this.url.replace(n,"$1_="+(new Date).getTime());else{var i=/\?/;this.url+=(i.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function T(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}})),t}function x(e){var t=new l;return e.replace(/\r?\n[\t ]+/g," ").split("\r").map((function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e})).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}})),t}function A(e,t){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"",this.headers=new l(t.headers),this.url=t.url||"",this._initBody(e)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})},m.call(E.prototype),m.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new l(this.headers),url:this.url})},A.error=function(){var e=new A(null,{status:0,statusText:""});return e.type="error",e};var C=[301,302,303,307,308];A.redirect=function(e,t){if(-1===C.indexOf(t))throw new RangeError("Invalid status code");return new A(null,{status:t,headers:{location:e}})},t.DOMException=r.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function k(e,s){return new n((function(n,a){var c=new E(e,s);if(c.signal&&c.signal.aborted)return a(new t.DOMException("Aborted","AbortError"));var d=new i;function h(){d.abort()}function f(e){try{return""===e&&r.location.href?r.location.href:e}catch(t){return e}}d.onload=function(){var e={status:d.status,statusText:d.statusText,headers:x(d.getAllResponseHeaders()||"")};e.url="responseURL"in d?d.responseURL:e.headers.get("X-Request-URL");var t="response"in d?d.response:d.responseText;setTimeout((function(){n(new A(t,e))}),0)},d.onerror=function(){setTimeout((function(){a(new TypeError("Network request failed"))}),0)},d.ontimeout=function(){setTimeout((function(){a(new TypeError("Network request failed"))}),0)},d.onabort=function(){setTimeout((function(){a(new t.DOMException("Aborted","AbortError"))}),0)},d.open(c.method,f(c.url),!0),"include"===c.credentials?d.withCredentials=!0:"omit"===c.credentials&&(d.withCredentials=!1),"responseType"in d&&(o.blob?d.responseType="blob":o.arrayBuffer&&c.headers.get("Content-Type")&&-1!==c.headers.get("Content-Type").indexOf("application/octet-stream")&&(d.responseType="arraybuffer")),!s||"object"!=typeof s.headers||s.headers instanceof l?c.headers.forEach((function(e,t){d.setRequestHeader(t,e)})):Object.getOwnPropertyNames(s.headers).forEach((function(e){d.setRequestHeader(e,u(s.headers[e]))})),c.signal&&(c.signal.addEventListener("abort",h),d.onreadystatechange=function(){4===d.readyState&&c.signal.removeEventListener("abort",h)}),d.send(void 0===c._bodyInit?null:c._bodyInit)}))}k.polyfill=!0,r.fetch||(r.fetch=k,r.Headers=l,r.Request=E,r.Response=A),t.Headers=l,t.Request=E,t.Response=A,t.fetch=k,Object.defineProperty(t,"__esModule",{value:!0})}(r),{fetch:e.fetch,Headers:e.Headers,Request:e.Request,Response:e.Response,DOMException:e.DOMException}}()}}("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:t)})),m=(w=b)&&w.__esModule&&Object.prototype.hasOwnProperty.call(w,"default")?w.default:w;const{fetch:v,Request:S,Response:E,Headers:T}=m(),x=[{name:"Windows Phone",test:[/windows phone/i]},{test:[/windows/i],name:"Windows"},{test:[/macintosh/i],name:"macOS"},{test:[/(ipod|iphone|ipad)/i],name:"iOS"},{test:[/android/i],name:"Android"},{test:[/linux/i],name:"Linux"},{test:[/CrOS/],name:"Chrome OS"},{test:[/PlayStation 4/],name:"PlayStation 4"}],A=[{test:[/googlebot/i],name:"Googlebot"},{test:[/opera/i,/opr\/|opios/i],name:"Opera"},{test:[/msie|trident/i],name:"Internet Explorer"},{test:[/\sedg/i],name:"Microsoft Edge"},{test:[/firefox|iceweasel|fxios/i],name:"Firefox"},{test:[/chromium/i],name:"Chromium"},{test:[/chrome|crios|crmo/i],name:"Chrome"},{test:[/android/i],name:"Android Browser"},{test:[/playstation 4/i],name:"PlayStation 4"},{test:[/safari|applewebkit/i],name:"Safari"}];class C{constructor(e,t,r){this.isIonic=()=>"undefined"!=typeof window&&!!("cordova"in window||"phonegap"in window||"PhoneGap"in window)&&/android|ios|iphone|ipod|ipad|iemobile/i.test(this.userAgent),this.userAgent=r||this.getUserAgent(),this.value=`${e};js;${this.getHeaderValue()};${t}`}getUserAgent(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}getOsName(){const e=x.find((e=>e.test.some((e=>e.test(this.userAgent)))));return e?e.name:"other"}getBrowser(){const e=A.find((e=>e.test.some((e=>e.test(this.userAgent)))));return e?e.name:"other"}isReactNative(){return"object"==typeof navigator&&"ReactNative"===navigator.product}getHeaderValue(){try{return this.isReactNative()?"ReactNative":this.isIonic()?`Ionic/${this.getOsName()}`:`${this.getBrowser()}/${this.getOsName()}`}catch(e){return"Unknown"}}}class k{constructor(e,t){this.prefix=e,t||(t={product:"sdk",version:"6.2.0"}),this.virgilAgentValue=new C(t.product,t.version).value}get(e,t){const r=this.createHeaders(t);return this.send(e,"GET",{headers:r})}post(e,t,r={}){const n=this.createHeaders(t);return n.set("Content-Type","application/json"),this.send(e,"POST",{headers:n,body:JSON.stringify(r)})}send(e,t,r){return v(this.prefix+e,{method:t,...r})}createHeaders(e){const t=new T;return t.set("Authorization",`Virgil ${e}`),t.set("Virgil-Agent",this.virgilAgentValue),t}}class P extends Error{constructor(e,t="VirgilError",r=P){super(e),Object.setPrototypeOf(this,r.prototype),this.name=t}}var O;!function(e){e[e.AccessTokenExpired=20304]="AccessTokenExpired",e[e.Unknown=0]="Unknown"}(O||(O={}));class I extends P{constructor(e,t,r){super(e,"VirgilHttpError",I),this.httpStatus=t,this.errorCode=r}}async function _(e){if(e.status>=400&&e.status<500){const t=await e.json();return new I(t.message,e.status,t.code)}return new I(e.statusText,e.status,0)}class D{constructor(e,t){this.connection="string"==typeof e?new k(e,t):e||new k("https://api.virgilsecurity.com",t)}async searchCards(e,t){const r=await this.connection.post("/card/v5/actions/search",t,{identities:e});if(!r.ok)throw await _(r);const n=await r.json();return null===n?[]:n.map(g.fromJson)}async getCard(e,t){if(!e)throw new TypeError("`cardId` should not be empty");if(!t)throw new TypeError("`accessToken` should not be empty");const r=await this.connection.get((e=>`/card/v5/${e}`)(e),t);if(!r.ok)throw await _(r);const n="true"===r.headers.get("X-Virgil-Is-Superseeded"),i=await r.json();return{cardRaw:g.fromJson(i),isOutdated:n}}async publishCard(e,t){if(!e)throw new TypeError("`model` should not be empty");if(!t)throw new TypeError("`accessToken` should not be empty");const r=await this.connection.post("/card/v5",t,e);if(!r.ok)throw await _(r);const n=await r.json();return g.fromJson(n)}async revokeCard(e,t){if(!e)throw new TypeError("`cardId` should not be empty");if(!t)throw new TypeError("`accessToken` should not be empty");const r=await this.connection.post((e=>`/card/v5/actions/revoke/${e}`)(e),t);if(!r.ok)throw await _(r)}}const j="self";class K{constructor(e){this.crypto=e}sign(e){const{model:t,signerPrivateKey:r,signer:n,extraSnapshot:i}=this.prepareParams(e),o=null!=i?t.contentSnapshot+i:t.contentSnapshot,s=this.crypto.generateSignature({value:o,encoding:"utf8"},r);t.signatures.push({signer:n,signature:s.toString("base64"),snapshot:i})}prepareParams({model:e,signerPrivateKey:t,extraFields:r,signer:n}){let i;n=n||j,null!=r&&(i=JSON.stringify(r));const o={model:e,signerPrivateKey:t,signer:n,extraSnapshot:i};return this.validate(o),o}validate({model:e,signerPrivateKey:t,signer:r}){if(null==e)throw new Error("Model is empty");if(null==t)throw new Error("`signerPrivateKey` property is mandatory");if(null!=e.signatures&&e.signatures.some((e=>e.signer==r)))throw new Error("The model already has this signature.")}}function B(e,t,r=!1){const n=JSON.parse(t.contentSnapshot),i=t.signatures.map(J);return{id:R(e,t.contentSnapshot),publicKey:e.importPublicKey({value:n.public_key,encoding:"base64"}),contentSnapshot:t.contentSnapshot,identity:n.identity,version:n.version,createdAt:new Date(1e3*n.created_at),previousCardId:n.previous_card_id,signatures:i,isOutdated:r}}function R(e,t){return e.generateSha512({value:t,encoding:"utf8"}).slice(0,32).toString("hex")}function J({snapshot:e,signature:t,signer:r}){return{signer:r,signature:t,snapshot:e,extraFields:N(e)}}function N(e){if(e)try{return JSON.parse(e)}catch(e){}return{}}class U extends P{constructor(e){super(e,"CardVerificationError",U)}}const V="cards",F={getToken:()=>{throw new Error("Please set `CardManager.accessTokenProvider` to be able to make requests.")}},q=e=>({...e,service:V});const M={verifySelfSignature:!0,verifyVirgilSignature:!0,whitelists:[]};var L=r((function(e,t){!function(e){var t,r,n,i=String.fromCharCode;function o(e){for(var t,r,n=[],i=0,o=e.length;i<o;)(t=e.charCodeAt(i++))>=55296&&t<=56319&&i<o?56320==(64512&(r=e.charCodeAt(i++)))?n.push(((1023&t)<<10)+(1023&r)+65536):(n.push(t),i--):n.push(t);return n}function s(e){if(e>=55296&&e<=57343)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value")}function a(e,t){return i(e>>t&63|128)}function c(e){if(0==(4294967168&e))return i(e);var t="";return 0==(4294965248&e)?t=i(e>>6&31|192):0==(4294901760&e)?(s(e),t=i(e>>12&15|224),t+=a(e,6)):0==(4292870144&e)&&(t=i(e>>18&7|240),t+=a(e,12),t+=a(e,6)),t+=i(63&e|128)}function d(){if(n>=r)throw Error("Invalid byte index");var e=255&t[n];if(n++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function u(){var e,i;if(n>r)throw Error("Invalid byte index");if(n==r)return!1;if(e=255&t[n],n++,0==(128&e))return e;if(192==(224&e)){if((i=(31&e)<<6|d())>=128)return i;throw Error("Invalid continuation byte")}if(224==(240&e)){if((i=(15&e)<<12|d()<<6|d())>=2048)return s(i),i;throw Error("Invalid continuation byte")}if(240==(248&e)&&(i=(7&e)<<18|d()<<12|d()<<6|d())>=65536&&i<=1114111)return i;throw Error("Invalid UTF-8 detected")}e.version="3.0.0",e.encode=function(e){for(var t=o(e),r=t.length,n=-1,i="";++n<r;)i+=c(t[n]);return i},e.decode=function(e){t=o(e),r=t.length,n=0;for(var s,a=[];!1!==(s=u());)a.push(s);return function(e){for(var t,r=e.length,n=-1,o="";++n<r;)(t=e[n])>65535&&(o+=i((t-=65536)>>>10&1023|55296),t=56320|1023&t),o+=i(t);return o}(a)}}(t)}));class H extends P{constructor(e){super(`Storage entry ${e?"with key "+name:"with the given key"}already exists`,"StorageEntryAlreadyExistsError",H)}}const $="readonly",G="readwrite",W={};class z{constructor(e){if(this._initStorage=()=>{const e={db:null,name:this._defaultConfig.name,storeName:this._defaultConfig.storeName,version:this._defaultConfig.version};let t=W[e.name];return t||(t={db:null,dbReady:null,deferredOperations:[]},W[e.name]=t),Promise.resolve().then((()=>(e.db=t.db,Z(e)))).then((t=>(e.db=t,ee(e,this._defaultConfig.version)?Q(e):t))).then((r=>{e.db=t.db=r,this._dbInfo=e}))},this.ready=()=>this._ready.then((()=>{const e=W[this._dbInfo.name];if(e&&e.dbReady)return e.dbReady})),!function(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange}catch(e){return!1}}())throw new Error("Cannot use IndexedDbStorageAdapter. indexedDb is not supported");this._defaultConfig={name:e.name,version:1,storeName:"keyvaluepairs"},this._ready=this._initStorage()}store(e,t){return e=ne(e),new Promise(((r,n)=>{this.ready().then((()=>{re(this._dbInfo,G,((i,o)=>{if(i)return n(i);try{const i=o.objectStore(this._dbInfo.storeName).add(t,e);o.oncomplete=()=>{r()},o.onabort=o.onerror=()=>{let t=i.error?i.error:i.transaction.error;t&&"ConstraintError"===t.name&&n(new H(e)),n(t)}}catch(e){n(e)}}))})).catch(n)}))}load(e){return e=ne(e),new Promise(((t,r)=>{this.ready().then((()=>{re(this._dbInfo,$,((n,i)=>{if(n)return r(n);try{const n=i.objectStore(this._dbInfo.storeName).get(e);n.onsuccess=function(){if(null==n.result)return t(null);t(ie(n.result))},n.onerror=function(){r(n.error)}}catch(e){r(e)}}))})).catch(r)}))}exists(e){return e=ne(e),new Promise(((t,r)=>{this.ready().then((()=>{re(this._dbInfo,$,((n,i)=>{if(n)return r(n);try{const n=i.objectStore(this._dbInfo.storeName).openCursor(e);n.onsuccess=()=>{const e=n.result;t(null!==e)},n.onerror=()=>{r(n.error)}}catch(e){r(e)}}))})).catch(r)}))}remove(e){return e=ne(e),new Promise(((t,r)=>{this.ready().then((()=>{re(this._dbInfo,G,((n,i)=>{if(n)return r(n);try{const n=i.objectStore(this._dbInfo.storeName),o=n.count(e);let s;o.onsuccess=()=>{if(0===o.result)return t(!1);s=n.delete(e),s.onsuccess=()=>t(!0)},i.onabort=i.onerror=()=>{const e=s||o,t=e.error?e.error:e.transaction.error;r(t)}}catch(e){r(e)}}))})).catch(r)}))}update(e,t){return e=ne(e),new Promise(((r,n)=>{this.ready().then((()=>{re(this._dbInfo,G,((i,o)=>{if(i)return n(i);try{const i=o.objectStore(this._dbInfo.storeName).put(t,e);i.onsuccess=()=>{r()},i.onerror=()=>{n(i.error)}}catch(e){n(e)}}))})).catch(n)}))}clear(){return new Promise(((e,t)=>{this.ready().then((()=>{re(this._dbInfo,G,((r,n)=>{if(r)return t(r);try{const r=n.objectStore(this._dbInfo.storeName).clear();n.oncomplete=()=>e(),n.onabort=n.onerror=()=>{const e=r.error?r.error:r.transaction.error;t(e)}}catch(e){t(e)}}))})).catch(t)}))}list(){return new Promise(((e,t)=>{this.ready().then((()=>{re(this._dbInfo,$,((r,n)=>{if(r)return t(r);try{const r=n.objectStore(this._dbInfo.storeName).openCursor(),i=[];r.onsuccess=()=>{const t=r.result;t?(i.push(ie(t.value)),t.continue()):e(i)},r.onerror=()=>{t(r.error)}}catch(e){t(e)}}))})).catch(t)}))}}function X(e){const t=W[e.name],r={};r.promise=new Promise(((e,t)=>{r.resolve=e,r.reject=t})),t.deferredOperations.push(r),t.dbReady?t.dbReady=t.dbReady.then((()=>r.promise)):t.dbReady=r.promise}function Y(e,t){return new Promise((function(r,n){if(W[e.name]=W[e.name]||{db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return r(e.db);X(e),e.db.close()}const i=[e.name];t&&i.push(String(e.version));const o=indexedDB.open.apply(indexedDB,i);t&&(o.onupgradeneeded=t=>{const r=o.result;try{r.createObjectStore(e.storeName)}catch(r){if("ConstraintError"!==r.name)throw r;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),o.onerror=e=>{e.preventDefault(),n(o.error)},o.onsuccess=()=>{r(o.result),function(e){const t=W[e.name].deferredOperations.pop();if(t)t.resolve(),t.promise}(e)}}))}function Z(e){return Y(e,!1)}function Q(e){return Y(e,!0)}function ee(e,t){if(!e.db)return!0;const r=!e.db.objectStoreNames.contains(e.storeName),n=e.version<e.db.version,i=e.version>e.db.version;if(n&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),i||r){if(r){const t=e.db.version+1;t>e.version&&(e.version=t)}return!0}return!1}function te(e){X(e);const t=W[e.name];return e.db=null,Z(e).then((t=>(e.db=t,ee(e)?Q(e):t))).then((r=>{e.db=t.db=r})).catch((t=>{throw function(e,t){const r=W[e.name].deferredOperations.pop();if(r)r.reject(t),r.promise}(e,t),t}))}function re(e,t,r,n){void 0===n&&(n=1);try{const n=e.db.transaction(e.storeName,t);r(null,n)}catch(i){n>0&&(!e.db||"InvalidStateError"===i.name||"NotFoundError"===i.name)&&Promise.resolve().then((()=>{if(!e.db||"NotFoundError"===i.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),Q(e)})).then((()=>te(e).then((function(){re(e,t,r,n-1)})))).catch(r),r(i)}}function ne(e){return"string"!=typeof e&&(console.warn(`${e} used as a key, but it is not a string.`),e=String(e)),e}function ie(e){if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return L.decode(String.fromCharCode.apply(null,t))}if("string"==typeof e)return e;throw new TypeError("Unknown value format")}class oe extends P{constructor(e="Private key with same name already exists"){super(e,"PrivateKeyExistsError",oe)}}const se={dir:".virgil_keys",name:"VirgilKeys"};function ae(e){if(!e)throw new TypeError("Argument `name` is required.")}class ce extends P{constructor(e="Loaded key entry was in invalid format."){super(e,"InvalidKeyEntryError",ce)}}class de extends P{constructor(e){super(`Key entry ${e?"named "+e:"with same name"}already exists`,"KeyEntryAlreadyExistsError",de)}}class ue extends P{constructor(e){super(`Key entry ${e?"named "+e:"with the given name"} does not exist.`,"KeyEntryDoesNotExistError",ue)}}const he={dir:".virgil_key_entries",name:"VirgilKeyEntries"};class le{constructor(e={}){this.adapter=function(e){if("string"==typeof e)return new z({dir:e,name:e});const{adapter:t,...r}=e;if(null!=t)return t;return new z({...he,...r})}(e)}exists(e){return ge(e),this.adapter.exists(e)}load(e){return ge(e),this.adapter.load(e).then((e=>null==e?null:pe(e)))}remove(e){return ge(e),this.adapter.remove(e)}save({name:e,value:t,meta:r}){we(e),be(t);const n={name:e,value:t,meta:r,creationDate:new Date,modificationDate:new Date};return this.adapter.store(e,fe(n)).then((()=>n)).catch((t=>{if(t&&"StorageEntryAlreadyExistsError"===t.name)throw new de(e);throw t}))}list(){return this.adapter.list().then((e=>e.map((e=>pe(e)))))}update({name:e,value:t,meta:r}){if(we(e),!t&&!r)throw new TypeError("Invalid argument. Either `value` or `meta` property is required.");return this.adapter.load(e).then((n=>{if(null===n)throw new ue(e);const i=pe(n),o=Object.assign(i,{value:t||i.value,meta:r||i.meta,modificationDate:new Date});return this.adapter.update(e,fe(o)).then((()=>o))}))}clear(){return this.adapter.clear()}}function fe(e){return JSON.stringify(e)}function pe(e){try{return JSON.parse(e,((e,t)=>"creationDate"===e||"modificationDate"===e?new Date(t):t))}catch(e){throw new ce}}const ye=e=>t=>{if(!t)throw new TypeError(`Invalid argument. Property ${e} is required`)},ge=(e=>t=>{if(!t)throw new TypeError(`Argument '${e}' is required.`)})("name"),we=ye("name"),be=ye("value");e.CachingJwtProvider=class{constructor(e,t){if("function"!=typeof e)throw new TypeError("`renewJwtFn` must be a function");if(t){let e;if("string"==typeof t)e=p.fromString(t);else{if(!(t instanceof p))throw new Error('Expected "initialToken" to be a string or an instance of Jwt, got '+typeof t);e=t}this.cachedJwt=e}this.getJwt=t=>{return this.cachedJwt&&!this.cachedJwt.isExpired((r=new Date,n=5,"number"==typeof r?new Date(r+1e3*n):new Date(r.getTime()+1e3*n)))?Promise.resolve(this.cachedJwt):(this.jwtPromise||(this.jwtPromise=Promise.resolve(e(t)).then((e=>{const t="string"==typeof e?p.fromString(e):e;return this.cachedJwt=t,this.jwtPromise=void 0,t})).catch((e=>{throw this.jwtPromise=void 0,e}))),this.jwtPromise);var r,n}}getToken(e){return this.getJwt(e)}},e.CallbackJwtProvider=class{constructor(e){if("function"!=typeof e)throw new TypeError("`getJwtFn` must be a function");this.getJwt=t=>Promise.resolve(e(t)).then((e=>"string"==typeof e?p.fromString(e):e))}getToken(e){return this.getJwt(e)}},e.CardManager=class{constructor(e){this.crypto=e.cardCrypto,this.client=new D(e.apiUrl,e.productInfo),this.modelSigner=new K(e.cardCrypto),this.signCallback=e.signCallback,this.retryOnUnauthorized=e.retryOnUnauthorized,this.cardVerifier=e.cardVerifier,this.accessTokenProvider=e.accessTokenProvider||F}generateRawCard(e){const t=function(e,t){const{identity:r,publicKey:n,previousCardId:i}=t,o={identity:r,previous_card_id:i,created_at:u(new Date),version:"5.0",public_key:e.exportPublicKey(n).toString("base64")};return new g(JSON.stringify(o),[])}(this.crypto,e);return this.modelSigner.sign({model:t,signerPrivateKey:e.privateKey,signer:j,extraFields:e.extraFields}),t}async publishCard(e){!function(e,t=!1){y(null!=e,"Card parameters must be provided"),y(null!=e.privateKey,"Card's private key is required"),y(null!=e.publicKey,"Card's public key is required"),t&&y("string"==typeof e.identity&&""!==e.identity,"Card's identity is required")}(e);const t={service:V,identity:e.identity,operation:"publish"},r=await this.accessTokenProvider.getToken(t),n=this.generateRawCard(Object.assign({},e,{identity:r.identity()}));return await this.publishRawSignedModel(n,t,r)}async publishRawCard(e){y(null!=e&&null!=e.contentSnapshot,"`rawCard` should not be empty");const t=JSON.parse(e.contentSnapshot),r=q({identity:t.identity,operation:"publish"}),n=await this.accessTokenProvider.getToken(r);return this.publishRawSignedModel(e,r,n)}async getCard(e){const t=q({operation:"get"}),r=await this.accessTokenProvider.getToken(t),n=await this.tryDo(t,r,(async t=>await this.client.getCard(e,t.toString()))),i=B(this.crypto,n.cardRaw,n.isOutdated);if(i.id!==e)throw new U("Received invalid card");return this.validateCards([i]),i}async searchCards(e){if(!e)throw new TypeError("Argument `identities` is required");const t=Array.isArray(e)?e:[e];if(0===t.length)throw new TypeError("Identities array must not be empty");const r=q({operation:"search"}),n=await this.accessTokenProvider.getToken(r),i=(await this.tryDo(r,n,(async e=>await this.client.searchCards(t,e.toString())))).map((e=>B(this.crypto,e,!1))),o=new Set(t);if(i.some((e=>!o.has(e.identity))))throw new U("Received invalid cards");return this.validateCards(i),function(e){const t=Object.create(null);for(const r of e)t[r.id]=r;for(const r of e)null!=r.previousCardId&&null!=t[r.previousCardId]&&(t[r.previousCardId].isOutdated=!0,r.previousCard=t[r.previousCardId],delete t[r.previousCardId]);return Object.keys(t).map((e=>t[e]))}(i)}async revokeCard(e){if(!e)throw new TypeError("Argument `cardId` is required");const t=q({operation:"revoke"}),r=await this.accessTokenProvider.getToken(t);await this.tryDo(t,r,(async t=>await this.client.revokeCard(e,t.toString())))}importCard(e){const t=B(this.crypto,e);return this.validateCards([t]),t}importCardFromString(e){return y(Boolean(e),"`str` should not be empty"),this.importCard(g.fromString(e))}importCardFromJson(e){return y(Boolean(e),"`json` should not be empty"),this.importCard(g.fromJson(e))}exportCard(e){return function(e){return new g(e.contentSnapshot,e.signatures.slice())}(e)}exportCardAsString(e){return this.exportCard(e).toString()}exportCardAsJson(e){return this.exportCard(e).toJson()}async publishRawSignedModel(e,t,r){null!=this.signCallback&&(e=await this.signCallback(e));const n=await this.tryDo(t,r,(async t=>await this.client.publishCard(e,t.toString())));if(e.contentSnapshot!==n.contentSnapshot)throw new U("Received invalid card");const i=B(this.crypto,n);return this.validateCards([i]),i}async tryDo(e,t,r){try{return await r(t)}catch(n){if(n instanceof I&&401===n.httpStatus&&n.errorCode===O.AccessTokenExpired&&this.retryOnUnauthorized)return t=await this.accessTokenProvider.getToken(q({identity:e.identity,operation:e.operation,forceReload:!0})),await r(t);throw n}}validateCards(e){if(null!=this.cardVerifier)for(const t of e)if(!this.cardVerifier.verifyCard(t))throw new U("Validation errors have been detected")}},e.ConstAccessTokenProvider=class{constructor(e){if(this.accessToken=e,null==e)throw new TypeError("`accessToken` is required")}getToken(e){return Promise.resolve(this.accessToken)}},e.DefaultStorageAdapter=z,e.GeneratorJwtProvider=class{constructor(e,t,r){if(this.jwtGenerator=e,this.additionalData=t,this.defaultIdentity=r,null==e)throw new TypeError("`jwtGenerator` is required")}getToken(e){return Promise.resolve().then((()=>this.jwtGenerator.generateToken(e.identity||this.defaultIdentity||"",this.additionalData)))}},e.InvalidKeyEntryError=ce,e.Jwt=p,e.JwtGenerator=class{constructor(e){!function(e){const t=e=>`Invalid JwtGenerator options. \`${e}\` is required`;y(null!=e,"JwtGenerator options must be provided"),y(null!=e.apiKey,t("apiKey")),y(null!=e.apiKeyId,t("apiKeyId")),y(null!=e.appId,t("appId")),y(null!=e.accessTokenSigner,t("accessTokenSigner"))}(e),this.appId=e.appId,this.apiKey=e.apiKey,this.apiKeyId=e.apiKeyId,this.accessTokenSigner=e.accessTokenSigner,this.millisecondsToLive=void 0!==e.millisecondsToLive?Number(e.millisecondsToLive):12e5}generateToken(e,t){if(!e)throw new TypeError("Illegal arguments for function `generateToken`. Argument `identity` is required.");const r=u(new Date),n=u((new Date).getTime()+this.millisecondsToLive),i={iss:l+this.appId,sub:h+e,iat:r,exp:n,ada:t},o={alg:this.accessTokenSigner.getAlgorithm(),kid:this.apiKeyId,typ:"JWT",cty:f},s=new p(o,i),a=this.accessTokenSigner.generateTokenSignature({value:s.unsignedData,encoding:"utf8"},this.apiKey);return new p(o,i,a.toString("base64"))}},e.JwtVerifier=class{constructor(e){!function(e){const t=e=>`Invalid JwtVerifier options. \`${e}\` is required`;y(null!=e,"JwtVerifier options must be provided"),y(null!=e.apiPublicKey,t("apiPublicKey")),y(null!=e.apiKeyId,t("apiKeyId")),y(null!=e.accessTokenSigner,t("accessTokenSigner"))}(e),this.accessTokenSigner=e.accessTokenSigner,this.apiPublicKey=e.apiPublicKey,this.apiKeyId=e.apiKeyId}verifyToken(e){if(null==e)throw new Error("Token is empty");return!!this.allFieldsAreCorrect(e)&&this.accessTokenSigner.verifyTokenSignature({value:e.unsignedData,encoding:"utf8"},{value:e.signature,encoding:"base64"},this.apiPublicKey)}allFieldsAreCorrect(e){return e.header.kid==this.apiKeyId&&e.header.alg==this.accessTokenSigner.getAlgorithm()&&e.header.cty==f&&"JWT"==e.header.typ}},e.KeyEntryAlreadyExistsError=de,e.KeyEntryDoesNotExistError=ue,e.KeyEntryStorage=le,e.KeyStorage=class{constructor(e={}){console.log("Warning! `KeyStorage` is deprecated. Use `PrivateKeyStorage` instead."),this.adapter=function(e){if("string"==typeof e)return new z({dir:e,name:e});const{adapter:t,...r}=e;if(null!=t)return t;return new z({...se,...r})}(e)}exists(e){return ae(e),this.adapter.exists(e)}load(e){return ae(e),this.adapter.load(e)}remove(e){return ae(e),this.adapter.remove(e)}save(e,t){return ae(e),this.adapter.store(e,t).catch((e=>e&&"EEXIST"===e.code?Promise.reject(new oe):Promise.reject(e)))}},e.ModelSigner=K,e.PrivateKeyStorage=class{constructor(e,t=new le){this.privateKeyExporter=e,this.keyEntryStorage=t}async store(e,t,r){const n=this.privateKeyExporter.exportPrivateKey(t);try{await this.keyEntryStorage.save({name:e,value:n.toString("base64"),meta:r})}catch(t){if(t&&"KeyEntryAlreadyExistsError"===t.name)throw new oe(`Private key with the name ${e} already exists.`);throw t}}async load(e){const t=await this.keyEntryStorage.load(e);if(null===t)return null;return{privateKey:this.privateKeyExporter.importPrivateKey(t.value),meta:t.meta}}async delete(e){await this.keyEntryStorage.remove(e)}},e.RawSignedModel=g,e.StorageEntryAlreadyExistsError=H,e.VirgilAgent=C,e.VirgilCardVerifier=class{constructor(e,t){this.crypto=e;const r={...M,...t||{}};this.verifySelfSignature=r.verifySelfSignature,this.verifyVirgilSignature=r.verifyVirgilSignature,this.whitelists=r.whitelists,this.virgilCardsPublicKey=e.importPublicKey({value:"MCowBQYDK2VwAyEAljOYGANYiVq1WbvVvoYIKtvZi2ji9bAhxyu6iV/LF8M=",encoding:"base64"})}verifyCard(e){if(this.selfValidationFailed(e))return!1;if(this.virgilValidationFailed(e))return!1;if(!this.whitelists||0===this.whitelists.length)return!0;const t=e.signatures.map((e=>e.signer));for(const r of this.whitelists){if(null==r||0===r.length)return!1;const n=r.filter((e=>-1!==t.indexOf(e.signer)));if(0===n.length)return!1;if(!n.some((t=>this.validateSignerSignature(e,this.getPublicKey(t.publicKeyBase64),t.signer))))return!1}return!0}selfValidationFailed(e){return this.verifySelfSignature&&!this.validateSignerSignature(e,e.publicKey,j)}virgilValidationFailed(e){return this.verifyVirgilSignature&&!this.validateSignerSignature(e,this.virgilCardsPublicKey,"virgil")}getPublicKey(e){return this.crypto.importPublicKey({value:e,encoding:"base64"})}validateSignerSignature(e,t,r){const n=e.signatures.find((e=>e.signer===r));if(null==n)return!1;const i=null==n.snapshot?e.contentSnapshot:e.contentSnapshot+n.snapshot;return this.crypto.verifySignature({value:i,encoding:"utf8"},{value:n.signature,encoding:"base64"},t)}}}));