UNPKG

@trustcomponent/trustcaptcha-frontend

Version:

TrustCaptcha – Privacy-first CAPTCHA solution. GDPR-compliant, bot protection made in Europe.

1 lines 74.6 kB
import{h as e,r as t,c as i,H as r,g as n}from"./p-a062566d.js";class s{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,n,s,a,o){const c=`${e.trustcaptchaApi}/verifications/${t}/challenges`;const h={startSolvingTimestamp:i,solvedTimestamp:r,tasks:n,honeypotField:s,userEvents:a};return await this.post(c,h,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 n=new Worker(this.objectUrl);this.workers.push(n);n.postMessage({task:e,difficulty:t});n.onmessage=e=>{if(this.isReset){r(new Error("WorkerPool has been reset"))}else{i(e.data)}this.activeTasks--;this.workers.splice(this.workers.indexOf(n),1);n.terminate();this.processQueue()};n.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(n),1);n.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 h="2.0.1";class l{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:h,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,hideBranding:this.box.config.hideBranding,customPrivacy:this.box.config.privacyUrl!==undefined,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 n=await this.hashData(r);Object.assign(t,{mc:n});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 n=t.getParameter(i.UNMASKED_RENDERER_WEBGL);return r+"|"+n}getAudioFingerprint(){return new Promise(((e,t)=>{try{const t=new(window.AudioContext||window.webkitAudioContext);const i=t.createOscillator();const r=t.createAnalyser();const n=t.createGain();const s=t.createScriptProcessor(4096,1,1);let a="";s.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(s);s.connect(n);n.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 n=r.getContext("2d");const s={};e.forEach((e=>{n.font=`${i} ${e}`;s[e]=n.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`;n.font=`${i} ${r}`;const o=n.measureText(t).width;if(o!==s["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 l(this.captchaBox).collectInformation().then((e=>{s.verifyUser(this.captchaBox.config,e,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 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;s.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 n=["keydown","keyup"];const s=["isTrusted","timeStamp","type","altKey","bubbles","cancelBubble","cancelable","composed","ctrlKey","defaultPrevented","detail","eventPhase","isComposing","location","metaKey","repeat","returnValue","shiftKey"];n.forEach((e=>{this.eventProperties[e]=s}));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 h=["isTrusted","timeStamp","type","bubbles","cancelBubble","cancelable","composed","defaultPrevented","eventPhase","returnValue"];c.forEach((e=>{this.eventProperties[e]=h}));const l=["copy","paste"];const u=["isTrusted","timeStamp","type","bubbles","cancelBubble","cancelable","composed","defaultPrevented","eventPhase","returnValue","clipboardData"];l.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)))}));n.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)))}));l.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 n=this;if(!i){e.apply(n,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>=2500){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 m{constructor(e,t){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}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.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 g(e,t){return{language:e,boxStart:t[0],boxInProgress:t[1],boxCompleted:t[2],endPrivacyPolicy:t[3],ariaLabelStart:t[4]||k["en"][4],ariaLabelRunning:t[5]||k["en"][5],ariaLabelDone:t[6]||k["en"][6],srRunning:t[7]||k["en"][7],srDone:t[8]||k["en"][8],srFailed:t[9]||k["en"][9],srTrustcaptcha:t[10]||k["en"][10],srPrivacy:t[11]||k["en"][11]}}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 n=k[r]||k["en"];const s=g(r,n);const a=i.find((e=>e.language===r));if(a){return v(s,a)}return s}const k={ar:["ابدأ التحقق","التحقق جارٍ","أنا إنسان!","سياسة الخصوصية","اضغط الزر حتى يصبح أخضر تماماً","الآن اترك الزر","ناجح","تم تحرير الزر مبكرًا جدًا أو متأخرًا جدًا","استمر في الضغط"],be:["Пачаць праверку","Праверка працягваецца","Я чалавек!","Палітыка прыватнасці"],bg:["Старт на проверката","Проверката е в ход","Аз съм човек!","Защита на данни"],bs:["Započni verifikaciju","Verifikacija je u toku","Ja sam čovjek!","Privatnost"],ca:["Comença la verificació","Verificació en curs","Sóc humà!","Privacitat"],cs:["Začít kontrolu","Kontrola probíhá","Jsem člověk!","Soukromí"],da:["Start kontrol","Kontrol i gang","Jeg er et menneske!","Privatliv"],de:["Überprüfung starten","Überprüfung läuft","Ich bin ein Mensch!","Datenschutz","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","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 curso","¡Soy humano!","Privacidad","CAPTCHA no iniciado; haga clic aquí para iniciar el CAPTCHA","CAPTCHA en curso","CAPTCHA completado","Verificación CAPTCHA iniciada","Verificación CAPTCHA completada con éxito","El CAPTCHA ha fallado debido a un error técnico. Por favor, póngase en contacto con el soporte.","Ir al sitio web de Trustcaptcha","Ir a la política de privacidad"],et:["Alusta kontrollimist","Kontroll on käimas.","Ma olen inimene!","Privaatsus"],fi:["Aloita tarkistus","Tarkistus käynnissä","Olen ihminen!","Yksityisyys"],fr:["Démarrer la vérification","Vérification en cours","Je suis un humain !","Confidentialité","CAPTCHA non démarré ; cliquez ici pour lancer le CAPTCHA","CAPTCHA en cours d’exécution","CAPTCHA terminé","Vérification CAPTCHA lancée","Vérification CAPTCHA réussie","Le CAPTCHA a échoué en raison d’une erreur technique. Veuillez contacter le support.","Aller sur le site Trustcaptcha","Aller à la politique de confidentialité"],hi:["सत्यापन प्रारंभ करें","सत्यापन प्रगति पर है","मैं एक इंसान हूँ!","गोपनीयता"],hr:["Pokreni provjeru","Provjera je u tijeku","Ja sam čovjek!","Privatnost"],hu:["Indítsa el az ellenőrzést","Ellenőrzés folyamatban","Ember vagyok!","Adatvédelem"],it:["Avvia verifica","Verifica in corso","Sono umano!","Privacy","CAPTCHA non avviato; fai clic qui per avviare il CAPTCHA","CAPTCHA in esecuzione","CAPTCHA completato","Verifica CAPTCHA avviata","Verifica CAPTCHA completata con successo","Il CAPTCHA non è riuscito a causa di un errore tecnico. Contatta il supporto.","Vai al sito Trustcaptcha","Vai all'informativa sulla privacy"],ko:["인증 시작","인증 진행 중","나는 사람입니다!","개인 정보 보호"],lb:["Verifikatioun starten","Verifikatioun am Gaang","Ech sinn e Mënsch!","Dateschutz","CAPTCHA net gestart; klick hei fir de CAPTCHA ze starten","CAPTCHA leeft","CAPTCHA ofgeschloss","CAPTCHA-Verifikatioun ugefaang","CAPTCHA-Verifikatioun erfollegräich ofgeschloss","De CAPTCHA ass wéinst engem technesche Feeler fehlgeschloen. Kontaktéiert de Support.","Trustcaptcha besichen","Dateschutzerklärung besichen"],lt:["Pradėti patikrą","Patikra vyksta","Aš esu žmogus!","Privatumas"],lv:["Sākt pārbaudi","Pārbaude notiek","Es esmu cilvēks!","Privātums"],mk:["Започнете верификација","Верификацијата е во тек","Јас сум човек!","Приватност"],nl:["Verificatie starten","Verificatie bezig","Ik ben een mens!","Privacy","CAPTCHA niet gestart, klik hier om de CAPTCHA te starten","CAPTCHA in uitvoering","CAPTCHA voltooid","CAPTCHA-verificatie gestart","CAPTCHA-verificatie succesvol voltooid","De CAPTCHA is mislukt door een technische fout. Neem contact op met de support.","Ga naar de Trustcaptcha-website","Ga naar het privacybeleid"],no:["Start verifisering","Verifisering pågår","Jeg er et menneske!","Personvern"],pl:["Rozpocznij weryfikację","Weryfikacja trwa","Jestem człowiekiem!","Prywatność"],pt:["Iniciar verificação","Verificação em progresso","Sou humano!","Privacidade"],ro:["Începeți verificarea","Verificarea este în desfășurare","Sunt om!","Confidențialitate"],ru:["Начать проверку","Проверка выполняется","Я человек!","Политика конфиденциальности"],sk:["Začať kontrolu","Kontrola prebieha","Som človek!","Súkromie"],sl:["Začetek preverjanja","Preverjanje poteka","Sem človek!","Zasebnost"],sq:["Filloni verifikimin","Verifikimi në vazhdim","Unë jam një njeri!","Privatësia"],sr:["Započni verifikaciju","Verifikacija u toku","Ja sam čovek!","Privatnost"],sv:["Starta kontroll","Kontroll pågår","Jag är en människa!","Sekretess"],tr:["Doğrulamayı başlat","Doğrulama devam ediyor","Ben bir insanım!","Gizlilik"],uk:["Почати перевірку","Виконується перевірка","Я людина!","Конфіденційність"],zh:["开始验证","验证进行中","我是人类!","隐私"]};const A=crypto;const S=e=>e instanceof CryptoKey;const E=new TextEncoder;const x=new TextDecoder;function C(...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 P=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 T=e=>{let t=e;if(t instanceof Uint8Array){t=x.decode(t)}t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return P(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class _ extends Error{constructor(e,t){super(e,t);this.code="ERR_JOSE_GENERIC";this.name=this.constructor.name;Error.captureStackTrace?.(this,this.constructor)}}_.code="ERR_JOSE_GENERIC";class R extends _{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 _{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 H extends _{constructor(){super(...arguments);this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}H.code="ERR_JOSE_ALG_NOT_ALLOWED";class D extends _{constructor(){super(...arguments);this.code="ERR_JOSE_NOT_SUPPORTED"}}D.code="ERR_JOSE_NOT_SUPPORTED";class K extends _{constructor(e="decryption operation failed",t){super(e,t);this.code="ERR_JWE_DECRYPTION_FAILED"}}K.code="ERR_JWE_DECRYPTION_FAILED";class O extends _{constructor(){super(...arguments);this.code="ERR_JWE_INVALID"}}O.code="ERR_JWE_INVALID";class N extends _{constructor(){super(...arguments);this.code="ERR_JWS_INVALID"}}N.code="ERR_JWS_INVALID";class W extends _{constructor(){super(...arguments);this.code="ERR_JWT_INVALID"}}W.code="ERR_JWT_INVALID";class J extends _{constructor(){super(...arguments);this.code="ERR_JWK_INVALID"}}J.code="ERR_JWK_INVALID";class L extends _{constructor(){super(...arguments);this.code="ERR_JWKS_INVALID"}}L.code="ERR_JWKS_INVALID";class U extends _{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t);this.code="ERR_JWKS_NO_MATCHING_KEY"}}U.code="ERR_JWKS_NO_MATCHING_KEY";class j extends _{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t);this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}j.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class $ extends _{constructor(e="request timed out",t){super(e,t);this.code="ERR_JWKS_TIMEOUT"}}$.code="ERR_JWKS_TIMEOUT";class M extends _{constructor(e="signature verification failed",t){super(e,t);this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}M.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function z(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function V(e,t){return e.name===t}function B(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(!V(e.algorithm,"HMAC"))throw z("HMAC");const i=parseInt(t.slice(2),10);const r=B(e.algorithm.hash);if(r!==i)throw z(`SHA-${i}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!V(e.algorithm,"RSASSA-PKCS1-v1_5"))throw z("RSASSA-PKCS1-v1_5");const i=parseInt(t.slice(2),10);const r=B(e.algorithm.hash);if(r!==i)throw z(`SHA-${i}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!V(e.algorithm,"RSA-PSS"))throw z("RSA-PSS");const i=parseInt(t.slice(2),10);const r=B(e.algorithm.hash);if(r!==i)throw z(`SHA-${i}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448"){throw z("Ed25519 or Ed448")}break}case"Ed25519":{if(!V(e.algorithm,"Ed25519"))throw z("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!V(e.algorithm,"ECDSA"))throw z("ECDSA");const i=F(t);const r=e.algorithm.namedCurve;if(r!==i)throw z(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(S(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 ne(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 se=(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 ne(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 he(e){return ae(e)&&e.kty==="oct"&&typeof e.k==="string"}function le(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 D('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 D('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 D('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new D('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}=le(e);const r=[t,e.ext??false,e.key_ops??i];const n={...e};delete n.alg;delete n.use;return A.subtle.importKey("jwk",n,...r)};const de=ue;const fe=e=>T(e);let pe;let we;const be=e=>e?.[Symbol.toStringTag]==="KeyObject";const me=async(e,t,i,r,n=false)=>{let s=e.get(t);if(s?.[r]){return s[r]}const a=await de({...i,alg:r});if(n)Object.freeze(t);if(!s){e.set(t,{[r]:a})}else{s[r]=a}return a};const ge=(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 me(we,e,i,t)}if(ae(e)){if(e.k)return T(e.k);we||(we=new WeakMap);const i=me(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 me(pe,e,i,t)}if(ae(e)){if(e.k)return T(e.k);pe||(pe=new WeakMap);const i=me(pe,e,e,t,true);return i}return e};const ye={normalizePublicKey:ge,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 n=e.subarray(r,r+t.length);if(n.length!==t.length)return false;return n.every(((e,i)=>e===t[i]))||ke(e,t,r+1)};const Ae=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 D("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}};const Se=async(e,t,i,r,n)=>{let s;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":s={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`};a=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":s={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":s={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`};a=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"};a=c?["verify"]:["sign"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"};a=c?["verify"]:["sign"];break;case"ES512":s={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=Ae(o);s=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e};a=c?[]:["deriveBits"];break}case"Ed25519":s={name:"Ed25519"};a=c?["verify"]:["sign"];break;case"EdDSA":s={name:Ae(o)};a=c?["verify"]:["sign"];break;default:throw new D('Invalid or unsupported "alg" (Algorithm) value')}return A.subtle.importKey(t,o,s,n?.extractable??false,a)};const Ee=(e,t,i)=>Se(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,i);async function xe(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 Ce(e,t){if(!ne(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 T(e.k);case"RSA":if("oth"in e&&e.oth!==undefined){throw new D('RSA JWK "oth" (Other Primes Info) Parameter value is not supported')}case"EC":case"OKP":return de({...e,alg:t});default:throw new D('Unsupported "kty" (Key Type) Parameter value')}}const Pe=e=>e?.[Symbol.toStringTag];const Te=(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 _e=(e,t,i,r)=>{if(t instanceof Uint8Array)return;if(r&&ae(t)){if(he(t)&&Te(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(`${Pe(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)&&Te(e,t,i))return;throw new TypeError(`JSON Web Key for this operation be a private JWK`);case"verify":if(ce(t)&&Te(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(`${Pe(t)} instances for asymmetric algorithms must not be of type "secret"`)}if(i==="sign"&&t.type==="public"){throw new TypeError(`${Pe(t)} instances for asymmetric algorithm signing must be of type "private"`)}if(i==="decrypt"&&t.type==="public"){throw new TypeError(`${Pe(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.algorithm&&i==="verify"&&t.type==="private"){throw new TypeError(`${Pe(t)} instances for asymmetric algorithm verifying must be of type "public"`)}if(t.algorithm&&i==="encrypt"&&t.type==="private"){throw new TypeError(`${Pe(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Ie(e,t,i,r){const n=t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t);if(n){_e(t,i,r,e)}else{Re(t,i,r,e)}}Ie.bind(undefined,false);const He=Ie.bind(undefined,true);function De(e,t,i,r,n){if(n.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 s;if(i!==undefined){s=new Map([...Object.entries(i),...t.entries()])}else{s=t}for(const t of r.crit){if(!s.has(t)){throw new D(`Extension Header Parameter "${t}" is not recognized`)}if(n[t]===undefined){throw new e(`Extension Header Parameter "${t}" is missing`)}if(s.get(t)&&r[t]===undefined){throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}}return new Set(r.crit)}const Ke=(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 Oe=Ke;function Ne(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 D(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function We(e,t,i){if(i==="sign"){t=await ye.normalizePrivateKey(t,e)}if(i==="verify"){t=await ye.normalizePublicKey(t,e)}if(S(t)){Y(t,e,i);return t}if(t instanceof Uint8Array){if(!e.startsWith("HS")){throw new TypeError(q(t,...ee))}return A.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},false,[i])}throw new TypeError(q(t,...ee,"Uint8Array","JSON Web Key"))}const Je=async(e,t,i,r)=>{const n=await We(e,t,"verify");se(e,n);const s=Ne(e,n.algorithm);try{return await A.subtle.verify(s,n,i,r)}catch{return false}};const Le=Je;async function Ue(e,t,i){if(!ne(e)){throw new N("Flattened JWS must be an object")}if(e.protected===undefined&&e.header===undefined){throw new N('Flattened JWS must have either of the "protected" or "header" members')}if(e.protected!==undefined&&typeof e.protected!=="string"){throw new N("JWS Protected Header incorrect type")}if(e.payload===undefined){throw new N("JWS Payload missing")}if(typeof e.signature!=="string"){throw new N("JWS Signature missing or incorrect type")}if(e.header!==undefined&&!ne(e.header)){throw new N("JWS Unprotected Header incorrect type")}let r={};if(e.protected){try{const t=T(e.protected);r=JSON.parse(x.decode(t))}catch{throw new N("JWS Protected Header is invalid")}}if(!ie(r,e.header)){throw new N("JWS Protected and JWS Unprotected Header Parameter names must be disjoint")}const n={...r,...e.header};const s=De(N,new Map([["b64",true]]),i?.crit,r,n);let a=true;if(s.has("b64")){a=r.b64;if(typeof a!=="boolean"){throw new N('The "b64" (base64url-encode payload) Header Parameter must be a boolean')}}const{alg:o}=n;if(typeof o!=="string"||!o){throw new N('JWS "alg" (Algorithm) Header Parameter missing or invalid')}const c=i&&Oe("algorithms",i.algorithms);if(c&&!c.has(o)){throw new H('"alg" (Algorithm) Header Parameter value not allowed')}if(a){if(typeof e.payload!=="string"){throw new N("JWS Payload must be a string")}}else if(typeof e.payload!=="string"&&!(e.payload instanceof Uint8Array)){throw new N("JWS Payload must be a string or an Uint8Array instance")}let h=false;if(typeof t==="function"){t=await t(r,e);h=true;He(o,t,"verify");if(ae(t)){t=await Ce(t,o)}}else{He(o,t,"verify")}const l=C(E.encode(e.protected??""),E.encode("."),typeof e.payload==="string"?E.encode(e.payload):e.payload);let u;try{u=T(e.signature)}catch{throw new N("Failed to base64url decode the signature")}const d=await Le(o,t,u,l);if(!d){throw new M}let f;if(a){try{f=T(e.payload)}catch{throw new N("Failed to base64url decode the payload")}}else if(typeof e.payload==="string"){f=E.encode(e.payload)}else{f=e.payload}const p={payload:f};if(e.protected!==undefined){p.protectedHeader=r}if(e.header!==undefined){p.unprotectedHeader=e.header}if(h){return{...p,key:t}}return p}async function je(e,t,i){if(e instanceof Uint8Array){e=x.decode(e)}if(typeof e!=="string"){throw new N("Compact JWS must be a string or Uint8Array")}const{0:r,1:n,2:s,length:a}=e.split(".");if(a!==3){throw new N("Invalid Compact JWS")}const o=await Ue({payload:n,protected:r,signature:s},t,i);const c={payload:o.payload,protectedHeader:o.protectedHeader};if(typeof t==="function"){return{...c,key:o.key}}return c}const $e=e=>Math.floor(e.getTime()/1e3);const Me=60;const ze=Me*60;const Ve=ze*24;const Be=Ve*7;const Fe=Ve*365.25;const Ge=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;const Ye=e=>{const t=Ge.exec(e);if(!t||t[4]&&t[1]){throw new TypeError("Invalid time period format")}const i=parseFloat(t[2]);const r=t[3].toLowerCase();let n;switch(r){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(i);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(i*Me);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(i*ze);break;case"day":case"days":case"d":n=Math.round(i*Ve);break;case"week":case"weeks":case"w":n=Math.round(i*Be);break;default:n=Math.round(i*Fe);break}if(t[1]==="-"||t[4]==="ago"){return-n}return n};const Xe=e=>e.toLowerCase().replace(/^application\//,"");const qe=(e,t)=>{if(typeof e==="string"){return t.includes(e)}if(Array.isArray(e)){return t.some(Set.prototype.has.bind(new Set(e)))}return false};const Ze=(e,t,i={})=>{let r;try{r=JSON.parse(x.decode(t))}catch{}if(!ne(r)){throw new W("JWT Claims Set must be a top-level JSON object")}const{typ:n}=i;if(n&&(typeof e.typ!=="string"||Xe(e.typ)!==Xe(n))){throw new R('unexpected "typ" JWT header value',r,"typ","check_failed")}const{requiredClaims:s=[],issuer:a,subject:o,audience:c,maxTokenAge:h}=i;const l=[...s];if(h!==undefined)l.push("iat");if(c!==undefined)l.push("aud");if(o!==undefined)l.push("sub");if(a!==undefined)l.push("iss");for(cons