UNPKG

@trustcaptcha/trustcaptcha-frontend

Version:

Frondend library for trustcaptcha

1 lines 88.3 kB
import{h as e,r as t,c as i,H as r,g as s}from"./p-a062566d.js";class n{static async verifyUser(e,t,i){const r=`${e.trustcaptchaApi}/verifications?siteKey=${e.sitekey}`;return await this.post(r,t,i)}static async sendSolutions(e,t,i,r,s,n,a,o){const c=`${e.trustcaptchaApi}/verifications/${t}/challenges`;const l={startSolvingTimestamp:i,solvedTimestamp:r,tasks:s,honeypotField:n,userEvents:a};return await this.post(c,l,o)}static async post(e="",t={},i){return await fetch(e,{method:"POST",mode:"cors",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json"},redirect:"follow",referrerPolicy:"no-referrer",body:JSON.stringify(t),signal:i})}}const a=`\nvar __awaiter=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(a,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function u(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,u)}c((r=r.apply(e,t||[])).next())}))},__generator=this&&this.__generator||function(e,t){var n,r,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(u){return function(c){return function(u){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,u[0]&&(i=0)),i;)try{if(n=1,r&&(a=2&u[0]?r.return:u[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,u[1])).done)return a;switch(r=0,a&&(u=[2&u[0],a.value]),u[0]){case 0:case 1:a=u;break;case 4:return i.label++,{value:u[1],done:!1};case 5:i.label++,r=u[1],u=[0];continue;case 7:u=i.ops.pop(),i.trys.pop();continue;default:if(!(a=i.trys,(a=a.length>0&&a[a.length-1])||6!==u[0]&&2!==u[0])){i=0;continue}if(3===u[0]&&(!a||u[1]>a[0]&&u[1]<a[3])){i.label=u[1];break}if(6===u[0]&&i.label<a[1]){i.label=a[1],a=u;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(u);break}a[2]&&i.ops.pop(),i.trys.pop();continue}u=t.call(e,i)}catch(e){u=[6,e],r=0}finally{n=a=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([u,c])}}},_this=this;function base64ToArrayBuffer(e){for(var t=self.atob(e),n=t.length,r=new Uint8Array(n),a=0;a<n;a++)r[a]=t.charCodeAt(a);return r.buffer}function appendBuffer(e,t){var n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}function countLeadingZeroBits(e){var t=new Uint8Array(e),n=t.findIndex((function(e){return 0!==e}));return-1===n?8*t.length:8*n+(Math.clz32(t[n])-24)}function executePowTask(e,t){return __awaiter(this,void 0,void 0,(function(){var n,r,a,o;return __generator(this,(function(i){switch(i.label){case 0:n=base64ToArrayBuffer(e.input),r=0,i.label=1;case 1:return a="tcn".concat(r),o=appendBuffer(n,(new TextEncoder).encode(a).buffer),[4,crypto.subtle.digest("SHA-256",o)];case 2:return countLeadingZeroBits(i.sent())===t?[2,{number:e.number,nonce:a}]:(r++,[3,1]);case 3:return[2]}}))}))}self.addEventListener("message",(function(e){return __awaiter(_this,void 0,void 0,(function(){var t,n,r,a;return __generator(this,(function(o){switch(o.label){case 0:return t=e.data,n=t.task,r=t.difficulty,a=postMessage,[4,executePowTask(n,r)];case 1:return a.apply(void 0,[o.sent()]),[2]}}))}))}));\n`;class o{constructor(){this.queue=[];this.activeTasks=0;this.workers=[];this.isReset=false;const e=new Blob([a],{type:"application/javascript"});this.objectUrl=URL.createObjectURL(e);this.maxWorkers=Math.min(Math.max(4,navigator.hardwareConcurrency||4),10)}enqueue(e,t){return new Promise(((i,r)=>{if(this.isReset){r(new Error("WorkerPool has been reset"));return}this.queue.push({task:e,difficulty:t,resolve:i,reject:r});this.processQueue()}))}processQueue(){if(this.queue.length===0||this.activeTasks>=this.maxWorkers||this.isReset){return}const{task:e,difficulty:t,resolve:i,reject:r}=this.queue.shift();this.activeTasks++;const s=new Worker(this.objectUrl);this.workers.push(s);s.postMessage({task:e,difficulty:t});s.onmessage=e=>{if(this.isReset){r(new Error("WorkerPool has been reset"))}else{i(e.data)}this.activeTasks--;this.workers.splice(this.workers.indexOf(s),1);s.terminate();this.processQueue()};s.onerror=()=>{if(!this.isReset){r(new Error("Worker error"))}else{r(new Error("WorkerPool has been reset"))}this.activeTasks--;this.workers.splice(this.workers.indexOf(s),1);s.terminate();this.processQueue()}}reset(){this.isReset=true;for(const e of this.workers){e.terminate()}this.workers=[];this.queue=[]}}class c{constructor(){this.workerPool=new o}async solveTasks(e){const t=e.challenge.tasks.map((t=>this.workerPool.enqueue(t,e.challenge.difficulty)));return Promise.all(t)}reset(){this.workerPool.reset()}}const l="1.8.4";class h{constructor(e){this.box=e}async collectInformation(){const e=await this.collectProperties(this.box.config.mode==="minimal"?this.minimalPropertiesToCollect():this.standardPropertiesToCollect());let t=[];if(this.box.config.mode==="standard"){t=this.box.eventTracker.getEventsAndResetArray()}return{custom:{boxCreationTimestamp:this.box.boxCreationTimestamp,startSolvingTimestamp:new Date,timezone:this.getTimezone(),honeypotField:this.box.honeypotField.value,framework:this.safeGet((()=>this.detectFrontendFramework())),version:l,bypassToken:this.box.config.bypassToken,mode:this.getMode(),boxSettings:{language:this.box.config.language,currentLanguage:this.box.config.translation.language,theme:this.box.config.theme,currentTheme:this.box.config.currentTheme,autostart:this.box.config.autostart,mode:this.box.config.mode,slider:this.box.config.slider,hideBranding:this.box.config.hideBranding,hidePrivacy:this.box.config.hidePrivacy,customPrivacy:!this.box.config.privacyUrl.includes("https://www.trustcaptcha.com/"),invisible:this.box.config.invisible}},browserInformation:e,userEvents:t}}getTimezone(){var e;const t=(e=window.Intl)===null||e===void 0?void 0:e.DateTimeFormat;if(t){const e=(new t).resolvedOptions().timeZone;if(e){return e}}const i=-this.getTimezoneOffset();return`UTC${i>=0?"+":""}${Math.abs(i)}`}getTimezoneOffset(){const e=(new Date).getFullYear();return Math.max(this.toFloat(new Date(e,0,1).getTimezoneOffset()),this.toFloat(new Date(e,6,1).getTimezoneOffset()))}toFloat(e){return parseFloat(e)}getMode(){return this.box.config.mode==="minimal"?"MINIMAL_DATA":"STANDARD"}minimalPropertiesToCollect(){return["devicePixelRatio","navigator.connection.downlink","navigator.connection.effectiveType","navigator.connection.rtt","navigator.connection.saveData","location.href","navigator.cookieEnabled","navigator.deviceMemory","navigator.doNotTrack","navigator.hardwareConcurrency","navigator.language","navigator.languages","navigator.userAgent","origin"]}standardPropertiesToCollect(){return["navigator.connection.downlink","navigator.connection.effectiveType","navigator.connection.rtt","navigator.connection.saveData","navigator.connection.type","devicePixelRatio","history.length","innerHeight","innerWidth","length","location.href","locationbar.visible","menubar.visible","navigator.cookieEnabled","navigator.deviceMemory","navigator.doNotTrack","navigator.hardwareConcurrency","navigator.language","navigator.languages","navigator.maxTouchPoints","navigator.pdfViewerEnabled","navigator.platform","navigator.userAgent","navigator.webdriver","navigator.vendor","origin","performance.navigation.type","performance.navigation.redirectCount","performance.now()","outerHeight","outerWidth","personalbar.visible","screen.availHeight","screen.availWidth","screen.colorDepth","screen.height","screen.orientation.angle","screen.orientation.type","screen.pixelDepth","screen.width","screenLeft","screenTop","screenX","screenY","scrollbars.visible"]}async collectProperties(e){const t={};for(const i of e){const e="window."+i;const r=e.replace(/\./g,"-");t[r]=this.safeGet((()=>this.getValueAtPath(e)))}Object.assign(t,{"dom-automationNote":this.safeGet((()=>this.getAutomationNote())),"dom-webGlSupport":this.safeGet((()=>this.isWebGLSupported())),"dom-canvasSupport":this.safeGet((()=>this.isCanvasSupported())),cookies:document.cookie.split("; ").map((e=>e.split("=")[0])),plugins:Array.from(navigator.plugins).map((e=>e.name)).join(","),"fp-audio":await this.hashData(await this.getAudioFingerprint()),"fp-canvas":await this.hashData(this.getCanvasFingerprint()),"fp-webgl":await this.hashData(this.getWebGLFingerprint()),"fp-navigator":await this.hashData(this.getNavigatorFingerprint()),"fp-fonts":await this.hashData(this.getFontsFingerprint()),"fp-screen":await this.hashData(this.getScreenFingerprint())});const i=Object.keys(t).sort();const r=i.map((e=>{const i=Array.isArray(t[e])?`[${t[e].join(", ")}]`:t[e];return`${e}=${i}`})).join(", ");const s=await this.hashData(r);Object.assign(t,{mc:s});return t}getValueAtPath(e){const t=e.split(".");let i=window;for(const e of t.slice(1)){if(!i){return null}const t=e.match(/^(\w+)\(\)$/);if(t){const e=t[1];try{i=i[e]()}catch(e){return null}}else{i=i[e]}}return i}safeGet(e){try{const t=e();if(t===undefined){return null}return t}catch(e){return null}}getAutomationNote(){const e=["__webdriver_evaluate","__selenium_evaluate","__webdriver_script_function","__webdriver_script_func","__webdriver_script_fn","__fxdriver_evaluate","__driver_unwrapped","__webdriver_unwrapped","__driver_evaluate","__selenium_unwrapped","__fxdriver_unwrapped"];const t=["_phantom","__nightmare","_selenium","callPhantom","callSelenium","_Selenium_IDE_Recorder"];for(const e of t){if(window[e]){return true}}for(const t of e){if(window.document[t]){return true}}for(const e in window.document){if(e.match(/\$[a-z]dc_/)&&window.document[e]["cache_"]){return true}}if(window["external"]&&window["external"].toString()&&window["external"].toString().indexOf("Sequentum")!==-1){return true}if(window.document.documentElement.getAttribute("selenium"))return true;if(window.document.documentElement.getAttribute("webdriver"))return true;if(window.document.documentElement.getAttribute("driver"))return true;return false}isCanvasSupported(){const e=document.createElement("canvas");return!!(e.getContext&&e.getContext("2d"))}isWebGLSupported(){try{const e=document.createElement("canvas");return!!(window.WebGLRenderingContext&&(e.getContext("webgl")||e.getContext("experimental-webgl")))}catch(e){return false}}detectFrontendFramework(){if(this.box.config.framework){return this.box.config.framework}try{if(!!document.querySelector("[data-reactroot], [data-reactid]")){return"react"}if(!!document.querySelector("[ng-version]")){return"angular"}if(!!document.querySelector("[data-vue]")){return"vue"}return"other"}catch(e){return"other"}}getCanvasFingerprint(){const e=document.createElement("canvas");const t=e.getContext("2d");t.textBaseline="top";t.font="14px Arial";t.fillText("Browser Fingerprint",2,2);return e.toDataURL()}getWebGLFingerprint(){const e=document.createElement("canvas");const t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return null;const i=t.getExtension("WEBGL_debug_renderer_info");const r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);const s=t.getParameter(i.UNMASKED_RENDERER_WEBGL);return r+"|"+s}getAudioFingerprint(){return new Promise(((e,t)=>{try{const t=new(window.AudioContext||window.webkitAudioContext);const i=t.createOscillator();const r=t.createAnalyser();const s=t.createGain();const n=t.createScriptProcessor(4096,1,1);let a="";n.onaudioprocess=function(){const i=new Uint8Array(r.frequencyBinCount);r.getByteFrequencyData(i);a=i.join("");t.close();e(a)};i.type="triangle";i.connect(r);r.connect(n);n.connect(s);s.connect(t.destination);i.start(0);setTimeout((()=>{if(!a){t.close();e("")}}),500)}catch(e){t(e)}}))}getNavigatorFingerprint(){return`${this.safeGet((()=>navigator.cookieEnabled))}|${this.safeGet((()=>navigator.doNotTrack))}|${this.safeGet((()=>navigator.pdfViewerEnabled))}|${this.safeGet((()=>navigator.platform))}|${this.safeGet((()=>navigator.vendor))}`}getScreenFingerprint(){return`${this.safeGet((()=>window.screen.width))}x${this.safeGet((()=>window.screen.height))}x${this.safeGet((()=>window.screen.colorDepth))}x${this.safeGet((()=>window.screen.pixelDepth))}x${this.safeGet((()=>window.screen.orientation.type))}`}getFontsFingerprint(){const e=["monospace","sans-serif","serif"];const t="mmmmmmmmmmlli";const i="72px";const r=document.createElement("canvas");const s=r.getContext("2d");const n={};e.forEach((e=>{s.font=`${i} ${e}`;n[e]=s.measureText(t).width}));const a=[];const o=["Arial","Verdana","Times New Roman","Courier New","Comic Sans MS","Georgia","Impact","Trebuchet MS","Palatino","Tahoma","Helvetica","Geneva","Menlo","Monaco","Didot","Gill Sans","Segoe UI","Candara","Consolas","Franklin Gothic Medium","Book Antiqua","Roboto","Open Sans","Lato","Oswald","Montserrat","Futura","Garamond","Baskerville","Optima","Lucida Bright","Century Gothic","Arial Unicode MS","SimSun","MS Mincho","Batang","Gulim"];o.forEach((e=>{const r=`${e}, monospace`;s.font=`${i} ${r}`;const o=s.measureText(t).width;if(o!==n["monospace"]){a.push(e)}}));return a.join(",")}async hashData(e){const t=new TextEncoder;const i=t.encode(e);const r=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(r)).map((e=>e.toString(16).padStart(2,"0"))).join("")}}var u;(function(e){e[e["UNKNOWN_ERROR"]=0]="UNKNOWN_ERROR";e[e["NO_FORM_FOUND"]=1]="NO_FORM_FOUND";e[e["COMMUNICATION_FAILURE"]=2]="COMMUNICATION_FAILURE";e[e["SITE_KEY_NOT_VALID"]=3]="SITE_KEY_NOT_VALID";e[e["MODES_NOT_MATCHING"]=4]="MODES_NOT_MATCHING";e[e["CAPTCHA_NOT_ACCESSIBLE"]=5]="CAPTCHA_NOT_ACCESSIBLE";e[e["POW_FAILURE"]=6]="POW_FAILURE";e[e["PAYMENT_REQUIRED"]=7]="PAYMENT_REQUIRED";e[e["LOCKED"]=8]="LOCKED";e[e["LICENSE_INVALID"]=9]="LICENSE_INVALID";e[e["OPTION_NOT_AVAILABLE"]=10]="OPTION_NOT_AVAILABLE";e[e["NO_SITE_KEY_SPECIFIED"]=11]="NO_SITE_KEY_SPECIFIED"})(u||(u={}));class d{constructor(e,t){this.errorCode=u[e];this.message=t}}class f{constructor(e,t,i){this.isReset=false;this.captchaBox=e;this.successCallback=t;this.failureCallback=i;this.abortController=new AbortController;this.powSolver=new c}verify(){new h(this.captchaBox).collectInformation().then((e=>{n.verifyUser(this.captchaBox.config,e,this.abortController.signal).then((e=>{if(this.isReset)return;switch(e.status){case 200:if(this.captchaBox.config.slider!=="disabled"){this.captchaBox.captchaSlider.startSlider()}e.json().then((e=>{this.solveChallenges(e)}));break;case 201:e.json().then((e=>this.successCallback(e.verificationToken)));break;case 402:this.failureCallback(new d(u.PAYMENT_REQUIRED,"Limit of requests has been reached. Please contact support."));break;case 403:this.failureCallback(new d(u.CAPTCHA_NOT_ACCESSIBLE,`The captcha is not accessible from '${location.hostname}'.`));break;case 404:this.failureCallback(new d(u.SITE_KEY_NOT_VALID,`No captcha found with siteKey ${this.captchaBox.config.sitekey}.`));break;case 422:this.failureCallback(new d(u.MODES_NOT_MATCHING,`Captcha mode '${this.captchaBox.config.mode}' not compatible with the captcha mode set in the settings.`));break;case 423:this.failureCallback(new d(u.LOCKED,"Captcha blocked. Please contact the support."));break;default:this.failureCallback(new d(u.UNKNOWN_ERROR,"Unknown error."));break}})).catch((e=>{if(this.isReset)return;if(e.name==="AbortError");else{this.failureCallback(new d(u.COMMUNICATION_FAILURE,"Server not reachable. Check your internet connection and try again."))}}))}))}async solveChallenges(e){if(this.isReset)return;const t=(new Date).toISOString();const i=await this.powSolver.solveTasks(e);const r=(new Date).toISOString();if(this.isReset)return;n.sendSolutions(this.captchaBox.config,e.challenge.verificationId,t,r,i,this.captchaBox.honeypotField.value,this.captchaBox.eventTracker.getEventsAndResetArray(),this.abortController.signal).then((e=>{if(this.isReset)return;switch(e.status){case 200:e.json().then((e=>{this.solveChallenges(e)}));break;case 201:e.json().then((e=>this.successCallback(e.verificationToken)));break;case 404:this.failureCallback(new d(u.SITE_KEY_NOT_VALID,`No captcha found with siteKey ${this.captchaBox.config.sitekey}.`));break;case 409:this.failureCallback(new d(u.POW_FAILURE,"The solution of the bot verification tasks failed."));break;default:this.failureCallback(new d(u.UNKNOWN_ERROR,"Unknown error."));break}})).catch((e=>{if(this.isReset)return;if(e.name==="AbortError");else{this.failureCallback(new d(u.COMMUNICATION_FAILURE,"Failed to communicate with the captcha backend services."))}}))}reset(){this.isReset=true;this.abortController.abort();this.powSolver.reset()}}var p;(function(e){e[e["START"]=0]="START";e[e["RUNNING"]=1]="RUNNING";e[e["DONE"]=2]="DONE";e[e["FAILED"]=3]="FAILED"})(p||(p={}));class w{constructor(){this.userEvents=[];this.active=true;this.eventProperties={};const e=["click","mousedown","mouseup","mousemove"];const t=["isTrusted","timeStamp","type","altKey","bubbles","button","buttons","cancelBubble","cancelable","clientX","clientY","composed","ctrlKey","defaultPrevented","detail","eventPhase","layerX","layerY","metaKey","movementX","movementY","offsetX","offsetY","pageX","pageY","returnValue","screenX","screenY","shiftKey","which","x","y"];e.forEach((e=>{this.eventProperties[e]=t}));const i=["touchstart","touchend","touchmove","touchcancel"];const r=["isTrusted","timeStamp","type","altKey","bubbles","cancelBubble","cancelable","changedTouches","composed","ctrlKey","defaultPrevented","detail","eventPhase","metaKey","returnValue","shiftKey","targetTouches","touches"];i.forEach((e=>{this.eventProperties[e]=r}));const s=["keydown","keyup"];const n=["isTrusted","timeStamp","type","altKey","bubbles","cancelBubble","cancelable","composed","ctrlKey","defaultPrevented","detail","eventPhase","isComposing","location","metaKey","repeat","returnValue","shiftKey"];s.forEach((e=>{this.eventProperties[e]=n}));const a=["resize"];const o=["isTrusted","timeStamp","type","bubbles","cancelBubble","cancelable","composed","eventPhase","returnValue"];a.forEach((e=>{this.eventProperties[e]=o}));const c=["focus","blur"];const l=["isTrusted","timeStamp","type","bubbles","cancelBubble","cancelable","composed","defaultPrevented","eventPhase","returnValue"];c.forEach((e=>{this.eventProperties[e]=l}));const h=["copy","paste"];const u=["isTrusted","timeStamp","type","bubbles","cancelBubble","cancelable","composed","defaultPrevented","eventPhase","returnValue","clipboardData"];h.forEach((e=>{this.eventProperties[e]=u}));const d=["scroll"];const f=["isTrusted","timeStamp","type","bubbles","cancelBubble","cancelable","composed","defaultPrevented","eventPhase","returnValue"];d.forEach((e=>{this.eventProperties[e]=f}));e.forEach((e=>{if(e==="mousemove"){document.addEventListener(e,this.throttle((e=>this.saveEvent(e)),1))}else{document.addEventListener(e,(e=>this.saveEvent(e)))}}));i.forEach((e=>{document.addEventListener(e,(e=>this.saveEvent(e)))}));s.forEach((e=>{document.addEventListener(e,(e=>this.saveEvent(e)))}));a.forEach((e=>{window.addEventListener(e,(e=>this.saveEvent(e)))}));d.forEach((e=>{window.addEventListener(e,(e=>this.saveEvent(e)))}));h.forEach((e=>{document.addEventListener(e,(e=>this.saveEvent(e)))}));const p=["a[href]","area[href]","button","details",'input:not([type="hidden"]):not([type="radio"]):not([type="checkbox"]):not([disabled])',"iframe","object","select:not([disabled])","textarea:not([disabled])","summary","[contenteditable]"];p.forEach((e=>{const t=document.querySelectorAll(e);t.forEach((e=>{c.forEach((t=>{e.addEventListener(t,(e=>this.saveEvent(e)))}))}))}))}throttle(e,t){let i;return function(){const r=arguments;const s=this;if(!i){e.apply(s,r);i=true;setTimeout((()=>i=false),t)}}}getEventsAndResetArray(){const e=this.userEvents;this.userEvents=[];return e}saveEvent(e){if(!this.active){return}if(this.userEvents.length>=25e3){this.userEvents.shift()}const t=e.type;if(this.eventProperties.hasOwnProperty(t)){const i=this.eventProperties[t];const r=this.pickProperties(e,i);this.userEvents.push(r)}else{console.log("Unhandled event type:",t)}}pickProperties(e,t){const i={};t.forEach((t=>{try{let r=e[t];if(t==="clipboardData"){r={files:r.files.length,items:r.items.length,types:r.types.length}}else if(t==="changedTouches"||t==="targetTouches"||t==="touches"){r=this.mapTouchList(r)}if(typeof r!=="function"){i[t]=r}}catch(e){}}));return i}mapTouchList(e){const t=[];for(let i=0;i<e.length;i++){const r=e[i];t.push({clientX:r.clientX,clientY:r.clientY,force:r.force,identifier:r.identifier,pageX:r.pageX,pageY:r.pageY,radiusX:r.radiusX,radiusY:r.radiusY,rotationAngle:r.rotationAngle,screenX:r.screenX,screenY:r.screenY})}return t}stop(){this.active=false}reset(){this.userEvents=[];this.active=true}}class b{constructor(){this.listeners={}}on(e,t){if(!this.listeners[e]){this.listeners[e]=[]}this.listeners[e].push(t)}emit(e,...t){if(!this.listeners[e])return;const i=[...this.listeners[e]];for(const e of i){e(...t)}}}class g{constructor(e,t,i){this.statusChangedEvent=new b;this.captchaFinishEvent=new b;this.status=p.START;this.boxCreationTimestamp=new Date;this.eventTracker=new w;this.verificationToken=null;this.apiManager=null;this.config=e;this.htmlElement=t;this.captchaSlider=i}setup(){this.formElement=this.htmlElement.closest("form");if(this.formElement!=null){this.honeypotField=this.createHoneypotField();this.verificationTokenField=this.createVerificationTokenField();this.registerElementFocusListeners()}else{this.setErrorStatus(new d(u.NO_FORM_FOUND,"No parent form element found."))}}createHoneypotField(){const e=document.createElement("input");e.setAttribute("type","text");e.setAttribute("name",this.generateHoneypotName());e.setAttribute("style","display:none");e.setAttribute("tabindex","-1");this.formElement.appendChild(e);return e}generateHoneypotName(){const e=["userDetail","confirmAction","userData","verifyContact","sessionInfo","profileUpdate","accountVerify","securityCheck","membershipInfo","customerPreference","siteFeedback","userExperience","navigationData","serviceUsage","interactionTrack","clientDetail","transactionVerify","operationStatus","activityLog","registrationData","processCheck","confirmationStatus","userContribution","accessValidation","engagementLevel","validationCode","preferenceSetting","userEngage","activityConfirm","serviceInteraction"];const t=Math.floor(Math.random()*e.length);const i=Math.floor(Math.random()*1e3);return e[t]+i}createVerificationTokenField(){const e=document.createElement("input");e.setAttribute("type","text");e.setAttribute("name",this.config.tokenFieldName);e.setAttribute("style","display:none");e.setAttribute("tabindex","-1");return e}registerElementFocusListeners(){this.formElement.addEventListener("keydown",(e=>{if(e instanceof KeyboardEvent){this.autostartVerification()}}));this.formElement.querySelectorAll('input:not([data-autostart="false"]), select:not([data-autostart="false"]), textarea:not([data-autostart="false"])').forEach((e=>{e.addEventListener("focusin",(()=>{this.autostartVerification()}))}))}autostartVerification(){if(this.config.autostart){this.startVerification()}}startVerification(){if(this.status!==p.START){return}this.switchStatus(p.RUNNING);this.apiManager=new f(this,(e=>{this.eventTracker.stop();this.finishVerification(e);this.apiManager=null}),(e=>{this.eventTracker.stop();this.setErrorStatus(e);this.apiManager=null}));this.apiManager.verify()}finishVerification(e){const t=JSON.stringify(e);const i=btoa(t);this.verificationToken=i;this.verificationTokenField.setAttribute("value",i);this.formElement.appendChild(this.verificationTokenField);this.handleCaptchaSolved()}handleCaptchaSolved(){if(this.verificationToken&&(this.config.slider==="disabled"||this.captchaSlider.status==="init"||this.captchaSlider.status==="success")){this.captchaFinishEvent.emit("captchaSolved",this.verificationToken);this.switchStatus(p.DONE)}}switchStatus(e){this.status=e;this.statusChangedEvent.emit("statusChanged",e)}setErrorStatus(e){this.switchStatus(p.FAILED);this.captchaFinishEvent.emit("captchaFailed",e)}reset(){if(this.apiManager){this.apiManager.reset();this.apiManager=null}this.honeypotField.removeAttribute("value");this.verificationToken=null;this.verificationTokenField.removeAttribute("value");if(this.verificationTokenField&&this.formElement.contains(this.verificationTokenField)){this.formElement.removeChild(this.verificationTokenField)}this.eventTracker.reset();this.switchStatus(p.START);this.captchaFinishEvent.emit("captchaReset")}setNewConfig(e){this.config=e}}function m(e,t){return{language:e,boxStart:t[0],boxInProgress:t[1],boxCompleted:t[2],endPrivacyPolicy:t[3],sliderRunning:t[4],sliderRelease:t[5],sliderSuccess:t[6],sliderError:t[7],sliderHold:t[8],ariaLabelStart:t[9]||k["en"][9],ariaLabelRunning:t[10]||k["en"][10],ariaLabelDone:t[11]||k["en"][11],srRunning:t[12]||k["en"][12],srDone:t[13]||k["en"][13],srFailed:t[14]||k["en"][14],srTrustcaptcha:t[15]||k["en"][15],srPrivacy:t[16]||k["en"][16]}}function v(e,t){return Object.assign(Object.assign({},e),t)}function y(e="auto",t=""){let i=[];if(t&&t!=""){try{i=JSON.parse(t).filter((e=>e.language&&e.language!==""))}catch(e){}}let r=e;if(e==="auto"){const e=document.documentElement.lang.trim().toLowerCase().substring(0,2);if(e&&k[e]){r=e}else if(e&&i.find((t=>t.language===e))){r=e}else{r="en"}}const s=k[r]||k["en"];const n=m(r,s);const a=i.find((e=>e.language===r));if(a){return v(n,a)}return n}const k={ar:["ابدأ التحقق","التحقق جارٍ","أنا إنسان!","سياسة الخصوصية","اضغط الزر حتى يصبح أخضر تماماً","الآن اترك الزر","ناجح","تم تحرير الزر مبكرًا جدًا أو متأخرًا جدًا","استمر في الضغط"],be:["Пачаць праверку","Праверка працягваецца","Я чалавек!","Палітыка прыватнасці","Націсніце кнопку, пакуль яна не стане цалкам зялёнай","Цяпер адпусціце","Паспяхова","Адпушчаны занадта рана або занадта позна","Трымайце націснутым"],bg:["Старт на проверката","Проверката е в ход","Аз съм човек!","Защита на данни","Натиснете бутона, докато не стане напълно зелен","освободете бутона сега","успешно завършен","Освободено твърде рано или твърде късно","Дръжте натиснато"],bs:["Započni verifikaciju","Verifikacija je u toku","Ja sam čovjek!","Privatnost","Pritisnite dugme dok ne postane potpuno zeleno","Sada otpustite","Uspješno","Otpušteno prerano ili prekasno","Držite pritisnuto"],ca:["Comença la verificació","Verificació en curs","Sóc humà!","Privacitat","Prem el botó fins que es torni completament verd","Ara solta el botó","Exitós","Alliberat massa aviat o massa tard","Mantingues pressionat"],cs:["Začít kontrolu","Kontrola probíhá","Jsem člověk!","Soukromí","Stiskněte tlačítko, dokud nebude úplně zelené","Teď uvolněte","Úspěšné","Uvolněno příliš brzy nebo příliš pozdě","Držte stisknuté"],da:["Start kontrol","Kontrol i gang","Jeg er et menneske!","Privatliv","Tryk på knappen, indtil den bliver helt grøn","Slip nu","Succesfuldt","Sluppet for tidligt eller for sent","Hold knappen nede"],de:["Überprüfung starten","Überprüfung läuft","Ich bin ein Mensch!","Datenschutz","Knopf drücken, bis er vollständig grün ist","Jetzt loslassen","Erfolgreich","Zu früh oder zu spät losgelassen","Gedrückt halten","CAPTCHA nicht gestartet, klicken Sie hier, um das CAPTCHA zu starten","CAPTCHA läuft","CAPTCHA abgeschlossen","CAPTCHA-Prüfung gestartet","CAPTCHA-Prüfung erfolgreich abgeschlossen","CAPTCHA ist aufgrund eines technischen Fehlers fehlgeschlagen. Bitte wenden Sie sich an den Support.","Zur Trustcaptcha-Website gehen","Zur Datenschutzerklärung gehen"],el:["Έναρξη ελέγχου","Ο έλεγχος βρίσκεται σε εξέλιξη","Είμαι άνθρωπος!","Απόρρητο","Πατήστε το κουμπί μέχρι να γίνει εντελώς πράσινο","Αφήστε τώρα","Επιτυχία","Απελευθερώθηκε πολύ νωρίς ή πολύ αργά","Κρατήστε πατημένο"],en:["Start verification","Verification in progress","I am a human!","Privacy","Press the button until it turns completely green","Now release","Success","Released too early or too late","Keep holding","CAPTCHA not started, click here to start the CAPTCHA","CAPTCHA in process","CAPTCHA completed","CAPTCHA verification started","CAPTCHA verification successfully completed","CAPTCHA has failed due to a technical error. Please contact the support.","Go to the Trustcaptcha website","Go to the privacy policy"],es:["Iniciar verificación","Verificación en progreso","¡Soy humano!","Privacidad","Presiona el botón hasta que se vuelva completamente verde","Ahora suelta","Éxito","Liberado demasiado pronto o demasiado tarde","Mantén presionado"],et:["Alusta kontrollimist","Kontroll on käimas.","Ma olen inimene!","Privaatsus","Vajuta nuppu, kuni see muutub täielikult roheliseks","Nüüd lase","Edukas","Vabastatud liiga vara või liiga hilja","Hoia all vajutatud"],fi:["Aloita tarkistus","Tarkistus käynnissä","Olen ihminen!","Yksityisyys","Paina nappia, kunnes se muuttuu täysin vihreäksi","Vapauta nyt","Onnistunut","Vapautit painikkeen liian aikaisin tai liian myöhään","Pidä pohjassa"],fr:["Démarrer la vérification","Vérification en cours","Je suis un humain!","Confidentialité","Appuyez sur le bouton jusqu'à ce qu'il devienne complètement vert","Relâchez maintenant","Succès","Relâché trop tôt ou trop tard","Maintenez enfoncé"],hi:["सत्यापन प्रारंभ करें","सत्यापन प्रगति पर है","मैं एक इंसान हूँ!","गोपनीयता","जब तक बटन पूरी तरह से हरा न हो जाए, बटन दबाएं","अब छोड़ें","सफल","बहुत जल्दी या बहुत देर से छोड़ा गया","दबाए रखें"],hr:["Pokreni provjeru","Provjera je u tijeku","Ja sam čovjek!","Privatnost","Pritisnite gumb dok ne postane potpuno zelen","Sada otpustite","Uspješno","Otpušteno prerano ili prekasno","Držite pritisnuto"],hu:["Indítsa el az ellenőrzést","Ellenőrzés folyamatban","Ember vagyok!","Adatvédelem","Nyomja meg a gombot, amíg teljesen zöld nem lesz","Most engedje el","Sikeres","Túl korán vagy túl későn engedte el a gombot","Tartsa nyomva"],it:["Avvia controllo","Controllo in corso","Sono un umano!","Privacy","Premi il pulsante finché non diventa completamente verde","Rilascia ora","Successo","Rilasciato troppo presto o troppo tardi","Tieni premuto"],ko:["인증 시작","인증 진행 중","나는 사람입니다!","개인 정보 보호","버튼이 완전히 초록색이 될 때까지 누르세요","지금 놓으세요","성공","너무 일찍 또는 너무 늦게 놓았습니다","누른 상태를 유지하세요"],lb:["Start Verifizéierung","Kontroll am Gaang","Ech sinn e Mënsch!","Dateschutz","Dréck de Knäppchen bis et komplett gréng gëtt","Elo lassloossen","Erfollegräich","Ze laang oder ze kuerz gehal","Gedrückt halen"],lt:["Pradėti patikrą","Patikra vyksta","Aš esu žmogus!","Privatumas","Spauskite mygtuką, kol jis taps visiškai žalias","Dabar atleiskite","Sėkmingai","Atleista per anksti arba per vėlai","Laikykite paspaudę"],lv:["Sākt pārbaudi","Pārbaude notiek","Es esmu cilvēks!","Privātums","Nospiediet pogu, līdz tā kļūst pilnībā zaļa","Tagad atlaidiet","Veiksmīgi","Atlaists pārāk agri vai pārāk vēlu","Turiet nospiestu"],mk:["Започнете верификација","Верификацијата е во тек","Јас сум човек!","Приватност","Притиснете го копчето додека не стане целосно зелено","Сега отпуштете","Успешно","Отпуштено прерано или предоцна","Држете го притиснато"],nl:["Verificatie starten","Verificatie bezig","Ik ben een mens!","Privacy","Druk op de knop totdat hij volledig groen wordt","Laat nu los","Succesvol","Te vroeg of te laat losgelaten","Ingedrukt houden"],no:["Start verifisering","Verifisering pågår","Jeg er et menneske!","Personvern","Trykk på knappen til den blir helt grønn","Slipp nå","Vellykket","Sluppet for tidlig eller for sent","Hold knappen nede"],pl:["Rozpocznij weryfikację","Weryfikacja trwa","Jestem człowiekiem!","Prywatność","Naciśnij przycisk, aż stanie się całkowicie zielony","Teraz puść","Sukces","Puścił za wcześnie lub za późno","Przytrzymaj wciśnięty"],pt:["Iniciar verificação","Verificação em progresso","Sou humano!","Privacidade","Pressione o botão até que fique completamente verde","Agora solte","Bem-sucedido","Soltou o botão cedo demais ou tarde demais","Mantenha pressionado"],ro:["Începeți verificarea","Verificarea este în desfășurare","Sunt om!","Confidențialitate","Apăsați butonul până devine complet verde","Acum eliberați","Reușit","Eliberat prea devreme sau prea târziu","Țineți apăsat"],ru:["Начать проверку","Проверка выполняется","Я человек!","Политика конфиденциальности","Нажмите кнопку, пока она не станет полностью зеленой","Теперь отпустите","Успешно","Отпущено слишком рано или слишком поздно","Держите нажатым"],sk:["Začať kontrolu","Kontrola prebieha","Som človek!","Súkromie","Stlačte tlačidlo, kým sa úplne nezelená","Teraz uvoľnite","Úspešné","Uvoľnené príliš skoro alebo príliš neskoro","Držte stlačené"],sl:["Začetek preverjanja","Preverjanje poteka","Sem človek!","Zasebnost","Pritisnite gumb, dokler ne postane popolnoma zelen","Zdaj sprosti","Uspešno","Gumb je bil sproščen prezgodaj ali prepozno","Držite pritisnjeno"],sq:["Filloni verifikimin","Verifikimi në vazhdim","Unë jam një njeri!","Privatësia","Shtypni butonin derisa të bëhet plotësisht jeshile","Tani lëshoni","E suksesshme","Lëshuar shumë herët ose shumë vonë","Mbajeni të shtypur"],sr:["Započni verifikaciju","Verifikacija u toku","Ja sam čovek!","Privatnost","Pritisnite dugme dok ne postane potpuno zeleno","Sada otpustite","Uspešno","Otpušteno prerano ili prekasno","Držite pritisnuto"],sv:["Starta kontroll","Kontroll pågår","Jag är en människa!","Sekretess","Tryck på knappen tills den blir helt grön","Släpp nu","Framgångsrik","Släppt för tidigt eller för sent","Håll knappen intryckt"],tr:["Doğrulamayı başlat","Doğrulama devam ediyor","Ben bir insanım!","Gizlilik","Düğmeye tamamen yeşil olana kadar basın","Şimdi bırakın","Başarılı","Çok erken veya çok geç bırakıldı","Basılı tutun"],uk:["Почати перевірку","Виконується перевірка","Я людина!","Конфіденційність","Натисніть кнопку, доки вона не стане повністю зеленою","Тепер відпустіть","Успішно","Відпущено занадто рано або занадто пізно","Тримайте натиснутим"],zh:["开始验证","验证进行中","我是人类!","隐私","按住按钮直到它完全变绿","现在松开","成功","过早或过晚松开","请勿松开"]};const S=crypto;const x=e=>e instanceof CryptoKey;const E=new TextEncoder;const A=new TextDecoder;function P(...e){const t=e.reduce(((e,{length:t})=>e+t),0);const i=new Uint8Array(t);let r=0;for(const t of e){i.set(t,r);r+=t.length}return i}const T=e=>{const t=atob(e);const i=new Uint8Array(t.length);for(let e=0;e<t.length;e++){i[e]=t.charCodeAt(e)}return i};const _=e=>{let t=e;if(t instanceof Uint8Array){t=A.decode(t)}t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return T(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class C extends Error{constructor(e,t){super(e,t);this.code="ERR_JOSE_GENERIC";this.name=this.constructor.name;Error.captureStackTrace?.(this,this.constructor)}}C.code="ERR_JOSE_GENERIC";class R extends C{constructor(e,t,i="unspecified",r="unspecified"){super(e,{cause:{claim:i,reason:r,payload:t}});this.code="ERR_JWT_CLAIM_VALIDATION_FAILED";this.claim=i;this.reason=r;this.payload=t}}R.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class I extends C{constructor(e,t,i="unspecified",r="unspecified"){super(e,{cause:{claim:i,reason:r,payload:t}});this.code="ERR_JWT_EXPIRED";this.claim=i;this.reason=r;this.payload=t}}I.code="ERR_JWT_EXPIRED";class D extends C{constructor(){super(...arguments);this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}D.code="ERR_JOSE_ALG_NOT_ALLOWED";class K extends C{constructor(){super(...arguments);this.code="ERR_JOSE_NOT_SUPPORTED"}}K.code="ERR_JOSE_NOT_SUPPORTED";class O extends C{constructor(e="decryption operation failed",t){super(e,t);this.code="ERR_JWE_DECRYPTION_FAILED"}}O.code="ERR_JWE_DECRYPTION_FAILED";class j extends C{constructor(){super(...arguments);this.code="ERR_JWE_INVALID"}}j.code="ERR_JWE_INVALID";class z extends C{constructor(){super(...arguments);this.code="ERR_JWS_INVALID"}}z.code="ERR_JWS_INVALID";class N extends C{constructor(){super(...arguments);this.code="ERR_JWT_INVALID"}}N.code="ERR_JWT_INVALID";class H extends C{constructor(){super(...arguments);this.code="ERR_JWK_INVALID"}}H.code="ERR_JWK_INVALID";class M extends C{constructor(){super(...arguments);this.code="ERR_JWKS_INVALID"}}M.code="ERR_JWKS_INVALID";class W extends C{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t);this.code="ERR_JWKS_NO_MATCHING_KEY"}}W.code="ERR_JWKS_NO_MATCHING_KEY";class L extends C{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t);this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}L.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class J extends C{constructor(e="request timed out",t){super(e,t);this.code="ERR_JWKS_TIMEOUT"}}J.code="ERR_JWKS_TIMEOUT";class U extends C{constructor(e="signature verification failed",t){super(e,t);this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}U.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function B(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function $(e,t){return e.name===t}function V(e){return parseInt(e.name.slice(4),10)}function F(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function G(e,t){if(t.length&&!t.some((t=>e.usages.includes(t)))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const i=t.pop();e+=`one of ${t.join(", ")}, or ${i}.`}else if(t.length===2){e+=`one of ${t[0]} or ${t[1]}.`}else{e+=`${t[0]}.`}throw new TypeError(e)}}function Y(e,t,...i){switch(t){case"HS256":case"HS384":case"HS512":{if(!$(e.algorithm,"HMAC"))throw B("HMAC");const i=parseInt(t.slice(2),10);const r=V(e.algorithm.hash);if(r!==i)throw B(`SHA-${i}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!$(e.algorithm,"RSASSA-PKCS1-v1_5"))throw B("RSASSA-PKCS1-v1_5");const i=parseInt(t.slice(2),10);const r=V(e.algorithm.hash);if(r!==i)throw B(`SHA-${i}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!$(e.algorithm,"RSA-PSS"))throw B("RSA-PSS");const i=parseInt(t.slice(2),10);const r=V(e.algorithm.hash);if(r!==i)throw B(`SHA-${i}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448"){throw B("Ed25519 or Ed448")}break}case"Ed25519":{if(!$(e.algorithm,"Ed25519"))throw B("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!$(e.algorithm,"ECDSA"))throw B("ECDSA");const i=F(t);const r=e.algorithm.namedCurve;if(r!==i)throw B(i,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}G(e,i)}function X(e,t,...i){i=i.filter(Boolean);if(i.length>2){const t=i.pop();e+=`one of type ${i.join(", ")}, or ${t}.`}else if(i.length===2){e+=`one of type ${i[0]} or ${i[1]}.`}else{e+=`of type ${i[0]}.`}if(t==null){e+=` Received ${t}`}else if(typeof t==="function"&&t.name){e+=` Received function ${t.name}`}else if(typeof t==="object"&&t!=null){if(t.constructor?.name){e+=` Received an instance of ${t.constructor.name}`}}return e}const q=(e,...t)=>X("Key must be ",e,...t);function Z(e,t,...i){return X(`Key for the ${e} algorithm must be `,t,...i)}const Q=e=>{if(x(e)){return true}return e?.[Symbol.toStringTag]==="KeyObject"};const ee=["CryptoKey"];const te=(...e)=>{const t=e.filter(Boolean);if(t.length===0||t.length===1){return true}let i;for(const e of t){const t=Object.keys(e);if(!i||i.size===0){i=new Set(t);continue}for(const e of t){if(i.has(e)){return false}i.add(e)}}return true};const ie=te;function re(e){return typeof e==="object"&&e!==null}function se(e){if(!re(e)||Object.prototype.toString.call(e)!=="[object Object]"){return false}if(Object.getPrototypeOf(e)===null){return true}let t=e;while(Object.getPrototypeOf(t)!==null){t=Object.getPrototypeOf(t)}return Object.getPrototypeOf(e)===t}const ne=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:i}=t.algorithm;if(typeof i!=="number"||i<2048){throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}};function ae(e){return se(e)&&typeof e.kty==="string"}function oe(e){return e.kty!=="oct"&&typeof e.d==="string"}function ce(e){return e.kty!=="oct"&&typeof e.d==="undefined"}function le(e){return ae(e)&&e.kty==="oct"&&typeof e.k==="string"}function he(e){let t;let i;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`};i=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`};i=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`};i=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new K('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"};i=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"};i=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"};i=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv};i=e.d?["deriveBits"]:[];break;default:throw new K('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"Ed25519":t={name:"Ed25519"};i=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv};i=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv};i=e.d?["deriveBits"]:[];break;default:throw new K('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new K('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:i}}const ue=async e=>{if(!e.alg){throw new TypeError('"alg" argument is required when "jwk.alg" is not present')}const{algorithm:t,keyUsages:i}=he(e);const r=[t,e.ext??false,e.key_ops??i];const s={...e};delete s.alg;delete s.use;return S.subtle.importKey("jwk",s,...r)};const de=ue;const fe=e=>_(e);let pe;let we;const be=e=>e?.[Symbol.toStringTag]==="KeyObject";const ge=async(e,t,i,r,s=false)=>{let n=e.get(t);if(n?.[r]){return n[r]}const a=await de({...i,alg:r});if(s)Object.freeze(t);if(!n){e.set(t,{[r]:a})}else{n[r]=a}return a};const me=(e,t)=>{if(be(e)){let i=e.export({format:"jwk"});delete i.d;delete i.dp;delete i.dq;delete i.p;delete i.q;delete i.qi;if(i.k){return fe(i.k)}we||(we=new WeakMap);return ge(we,e,i,t)}if(ae(e)){if(e.k)return _(e.k);we||(we=new WeakMap);const i=ge(we,e,e,t,true);return i}return e};const ve=(e,t)=>{if(be(e)){let i=e.export({format:"jwk"});if(i.k){return fe(i.k)}pe||(pe=new WeakMap);return ge(pe,e,i,t)}if(ae(e)){if(e.k)return _(e.k);pe||(pe=new WeakMap);const i=ge(pe,e,e,t,true);return i}return e};const ye={normalizePublicKey:me,normalizePrivateKey:ve};const ke=(e,t,i=0)=>{if(i===0){t.unshift(t.length);t.unshift(6)}const r=e.indexOf(t[0],i);if(r===-1)return false;const s=e.subarray(r,r+t.length);if(s.length!==t.length)return false;return s.every(((e,i)=>e===t[i]))||ke(e,t,r+1)};const Se=e=>{switch(true){case ke(e,[42,134,72,206,61,3,1,7]):return"P-256";case ke(e,[43,129,4,0,34]):return"P-384";case ke(e,[43,129,4,0,35]):return"P-521";case ke(e,[43,101,110]):return"X25519";case ke(e,[43,101,111]):return"X448";case ke(e,[43,101,112]):return"Ed25519";case ke(e,[43,101,113]):return"Ed448";default:throw new K("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}};const xe=async(e,t,i,r,s)=>{let n;let a;const o=new Uint8Array(atob(i.replace(e,"")).split("").map((e=>e.charCodeAt(0))));const c=t==="spki";switch(r){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`};a=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`};a=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`};a=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"};a=c?["verify"]:["sign"];break;case"ES384":n={name:"ECDSA",namedCurve:"P-384"};a=c?["verify"]:["sign"];break;case"ES512":n={name:"ECDSA",namedCurve:"P-521"};a=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=Se(o);n=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e};a=c?[]:["deriveBits"];break}case"Ed25519":n={name:"Ed25519"};a=c?["verify"]:["sign"];break;case"EdDSA":n={name:Se(o)};a=c?["verify"]:["sign"];break;default:throw new K('Invalid or unsupported "alg" (Algorithm) value')}return S.subtle.importKey(t,o,n,s?.extractable??false,a)};const Ee=(e,t,i)=>xe(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,i);async function Ae(e,t,i){if(typeof e!=="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0){throw new TypeError('"spki" must be SPKI formatted string')}return Ee(e,t,i)}async function Pe(e,t){if(!se(e)){throw new TypeError("JWK must be an object")}t||(t=e.alg);switch(e.kty){case"oct":if(typeof e.k!=="string"||!e.k){throw new TypeError('missing "k" (Key Value) Parameter value')}return _(e.k);case"RSA":if("oth"in e&&e.oth!==undefined){throw new K('RSA JWK "oth" (Other Primes Info) Parameter value is not supported')}case"EC":case"OKP":return de({...e,alg:t});default:throw new K('Unsupported "kty" (Key Type) Parameter value')}}const Te=e=>e?.[Symbol.toStringTag];const _e=(e,t,i)=>{if(t.use!==undefined&&t.use!=="sig"){throw new TypeError("Invalid key for this operation, when present its use must be sig")}if(t.key_ops!==undefined&&t.key_ops.includes?.(i)!==true){throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${i}`)}if(t.alg!==undefined&&t.alg!==e){throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`)}return true};const Ce=(e,t,i,r)=>{if(t instanceof Uint8Array)return;if(r&&ae(t)){if(le(t)&&_e(e,t,i))return;throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!Q(t)){throw new TypeError(Z(e,t,...ee,"Uint8Array",r?"JSON Web Key":null))}if(t.type!=="secret"){throw new TypeError(`${Te(t)} instances for symmetric algorithms must be of type "secret"`)}};const Re=(e,t,i,r)=>{if(r&&ae(t)){switch(i){case"sign":if(oe(t)&&_e(e,t,i))return;throw new TypeError(`JSON Web Key for this operation be a private JWK`);case"verify":if(ce(t)&&_e(e,t,i))return;throw new TypeError(`JSON Web Key for this operation be a public JWK`)}}if(!Q(t)){throw new TypeError(Z(e,t,...ee,r?"JSON Web Key":null))}if(t.type==="secret"){throw new TypeError(`${Te(t)} instances for asymmetric algorithms must not be of type "secret"`)}if(i==="sign"&&t.type==="public"){throw new TypeError(`${Te(t)} instances for asymmetric algorithm signing must be of type "private"`)}if(i==="decrypt"&&t.type==="public"){throw new TypeError(`${Te(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.algorithm&&i==="verify"&&t.type==="private"){throw new TypeError(`${Te(t)} instances for asymmetric algorithm verifying must be of type "public"`)}if(t.algorithm&&i==="encrypt"&&t.type==="private"){throw new TypeError(`${Te(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Ie(e,t,i,r){const s=t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t);if(s){Ce(t,i,r,e)}else{Re(t,i,r,e)}}Ie.bind(undefined,false);const De=Ie.bind(undefined,true);function Ke(e,t,i,r,s){if(s.crit!==undefined&&r?.crit===undefined){throw new e('"crit" (Critical) Header Parameter MUST be integrity protected')}if(!r||r.crit===undefined){return new Set}if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some((e=>typeof e!=="string"||e.length===0))){throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present')}let n;if(i!==undefined){n=new Map([...Object.entries(i),...t.entries()])}else{n=t}for(const t of r.crit){if(!n.has(t)){throw new K(`Extension Header Parameter "${t}" is not recognized`)}if(s[t]===undefined){throw new e(`Extension Header Parameter "${t}" is missing`)}if(n.get(t)&&r[t]===undefined){throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}}return new Set(r.crit)}const Oe=(e,t)=>{if(t!==undefined&&(!Array.isArray(t)||t.some((e=>typeof e!=="string")))){throw new TypeError(`"${e}" option must be an array of strings`)}if(!t){return undefined}return new Set(t)};const je=Oe;function ze(e,t){const i=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:i,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:i,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:i,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:i,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new K(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ne(e,t,i){if(i==="sign"){t=await ye.normalizePrivateKey(t,e)}if(i==="verify"){t=await ye.normalizePublicKey(t,e)}if(x(t)){Y(t,e,i);return t}if(t instanceof Uint8Array){if(!e.startsWith("HS")){throw new TypeError(q(t,...ee))}return S.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},false,[i])}throw new TypeError(q(t,...ee,"Uint8Array","JSON Web Key"))}const He=async(e,t,i,r)=>{const s=await Ne(e,t,"verify");ne(e,s);const n=ze(e,s.algorithm);try{return await S.subtle.verify(n,s,i,r)}catch{return false}};const Me=He;async function We(e,t,i){if(!se(e)){throw new z("Flattened JWS must be an object")}if(e.protected===undefined&&e.header===undefined){throw new z('Flattened JWS must have either of the "protected" or "header" members')}if(e.protected!==undefined&&typeof e.protected!=="string"){throw new z("JWS Protected Header incorrect type")}if(e.payload===undefined){throw new z("JWS Payload missing")}if(typeof e.signature!=="string"){throw new z("JWS Signature missing or incorrect type")}if(e.header!==undefined&&!se(e.header)){throw new z("JWS Unprotected Header incorrect type")}let r={};if(e.protected){try{const t=_(e.protec