@loginid/websdk3 3.0.8-next.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var W=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var we=Object.prototype.hasOwnProperty;var ue=(t,e)=>{for(var r in e)W(t,r,{get:e[r],enumerable:!0})},Be=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ve(e))!we.call(t,o)&&o!==r&&W(t,o,{get:()=>e[o],enumerable:!(s=Se(e,o))||s.enumerable});return t};var De=t=>Be(W({},"__esModule",{value:!0}),t);var Ye={};ue(Ye,{AbortError:()=>L,ApiError:()=>m,LoginIDAPI:()=>ee,LoginIDWebSDK:()=>ae,PasskeyError:()=>c,WebAuthnHelper:()=>_,canCreatePasskey:()=>Ce,createPasskeyCredential:()=>k,default:()=>Ge,doesDeviceSupportPasskeys:()=>Z,getPasskeyCredential:()=>E,isConditionalUIAvailable:()=>be,isPlatformAuthenticatorAvailable:()=>X});module.exports=De(Ye);var z=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,r=this.config.baseUrl.match(e);if(r)return r[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},N=z;var Ne=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Ue=t=>{if(!t)return t;let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<t.length;){let i=t.charCodeAt(s++),a=t.charCodeAt(s++),u=t.charCodeAt(s++),p=i<<16|a<<8|u;r.push(e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63])}let o=r.join(""),n=t.length%3;return n?o.slice(0,n-3)+"===".slice(n||3):o},Fe=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let a=0;a<64;a++)r[e.charAt(a)]=a;let o=0,n=0,i="";for(let a of t){let u=r[a];if(u!==void 0)for(o=(o<<6)+u,n+=6;n>=8;)i+=s(o>>(n-=8)&255)}return i},l=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=Ue(e);return Ne(s)},R=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=Fe(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},pe=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),le=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},S=t=>{try{let r=t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(window.atob(r).split("").map(o=>"%"+("00"+o.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(s)}catch(e){console.error(e)}},ce=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},de=t=>{document.cookie=t},me=t=>{document.cookie=`${t}=; expires=${new Date}`};var j=class{config;constructor(e){this.config=new N(e)}getToken(e){if(e.authzToken)return e.authzToken;{let r=this.getJwtCookie();return r||""}}getSessionInfo(){if(!this.isLoggedIn())return null;let e=S(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=S(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;de(o)}getJwtCookie(){return ce(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}logout(){me(this.getJwtCookieName())}},ye=j;var b=class{constructor(e){this.config=e}};var m=class extends Error{url;status;statusText;body;request;constructor(e,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=e}};var v=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},C=class{#t;#r;#e;#o;#n;#i;#s;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#o=[],this.#n=new Promise((r,s)=>{this.#i=r,this.#s=s;let o=a=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(a))},n=a=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#s&&this.#s(a))},i=a=>{this.#t||this.#r||this.#e||this.#o.push(a)};return Object.defineProperty(i,"isResolved",{get:()=>this.#t}),Object.defineProperty(i,"isRejected",{get:()=>this.#r}),Object.defineProperty(i,"isCancelled",{get:()=>this.#e}),e(o,n,i)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,r){return this.#n.then(e,r)}catch(e){return this.#n.catch(e)}finally(e){return this.#n.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#o.length)try{for(let e of this.#o)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#o.length=0,this.#s&&this.#s(new v("Request aborted"))}}get isCancelled(){return this.#e}};var M=t=>t!=null,w=t=>typeof t=="string",V=t=>w(t)&&t!=="",J=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),fe=t=>t instanceof FormData,Le=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Ke=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{M(n)&&(Array.isArray(n)?n.forEach(i=>{s(o,i)}):typeof n=="object"?Object.entries(n).forEach(([i,a])=>{s(`${o}[${i}]`,a)}):r(o,n))};return Object.entries(t).forEach(([o,n])=>{s(o,n)}),e.length>0?`?${e.join("&")}`:""},He=(t,e)=>{let r=t.ENCODE_PATH||encodeURI,s=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(n,i)=>e.path?.hasOwnProperty(i)?r(String(e.path[i])):n),o=`${t.BASE}${s}`;return e.query?`${o}${Ke(e.query)}`:o},_e=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{w(o)||J(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>M(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},U=async(t,e)=>typeof e=="function"?e(t):e,We=async(t,e)=>{let[r,s,o,n]=await Promise.all([U(e,t.TOKEN),U(e,t.USERNAME),U(e,t.PASSWORD),U(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>M(u)).reduce((a,[u,p])=>({...a,[u]:String(p)}),{});if(V(r)&&(i.Authorization=`Bearer ${r}`),V(s)&&V(o)){let a=Le(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:J(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":w(e.body)?i["Content-Type"]="text/plain":fe(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},ze=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):w(t.body)||J(t.body)||fe(t.body)?t.body:JSON.stringify(t.body)},je=async(t,e,r,s,o,n,i)=>{let a=new AbortController,u={headers:n,body:s??o,method:e.method,signal:a.signal};return t.WITH_CREDENTIALS&&(u.credentials=t.CREDENTIALS),i(()=>a.abort()),await fetch(r,u)},Ve=(t,e)=>{if(e){let r=t.headers.get(e);if(w(r))return r}},Me=async t=>{if(t.status!==204)try{let e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(o=>e.toLowerCase().startsWith(o))?await t.json():await t.text()}catch(e){console.error(e)}},Je=(t,e)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(s)throw new m(t,e,s);if(!e.ok){let o=e.status??"unknown",n=e.statusText??"unknown",i=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})();throw new m(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},he=(t,e)=>new C(async(r,s,o)=>{try{let n=He(t,e),i=_e(e),a=ze(e),u=await We(t,e);if(!o.isCancelled){let p=await je(t,e,n,a,i,u,o),d=await Me(p),g=Ve(p,e.responseHeader),D={url:n,ok:p.ok,status:p.status,statusText:p.statusText,body:g??d};Je(e,D),r(D.body)}}catch(n){s(n)}});var F=class extends b{constructor(e){super(e)}request(e){return he(this.config,e)}};var A=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":r},body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var P=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:r}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:r,authorization:s}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:s},body:r,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:r}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:r},errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var q=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:r,authorization:s}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":r,Authorization:s},body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}};var O=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var I=class{auth;passkeys;reg;tx;request;constructor(e,r=F){this.request=new r({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new A(this.request),this.passkeys=new P(this.request),this.reg=new q(this.request),this.tx=new O(this.request)}};var $=class{config;service;session;constructor(e){this.config=new N(e),this.service=new I({BASE:e.baseUrl}),this.session=new ye(e)}},y=$;var G=class extends Error{constructor(e){super(e),this.name="AbortError"}},L=G;var Y=class t{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let e=new L("Cancelling current WebAuthn request");t.abortController.abort(e)};static renewWebAuthnAbortController=()=>{t.abortWebAuthnRequest();let e=new AbortController;t.abortController=e};static assignWebAuthnAbortController=e=>{t.abortWebAuthnRequest(),t.abortController=e}},h=Y;var f=(t,e,r)=>({...r,authzToken:e||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||t,callbacks:r.callbacks||{}}),ge=(t,e)=>({...f(t,"",e),txType:e.txType||"raw",nonce:e.nonce||pe()}),T=(t,e=!0,r=!1)=>({token:t,isAuthenticated:e,isFallback:r});var Q=class extends y{constructor(e){super(e)}async validateOtp(e,r,s={}){let o=f(e,"",s),n={authCode:r,user:{username:e,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:n}),a=T(i.jwtAccess);return h.renewWebAuthnAbortController(),this.session.setJwtCookie(a.token),a}async requestAndSendOtp(e,r="email",s={}){let o=f(e,"",s),n={user:{username:e,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:n});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:n});break;default:throw new Error("Invalid message method")}}},K=Q;var Re=require("ua-parser-js"),B=t=>{let e={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return t&&(e.deviceId=t),e},$e=(t,e)=>{let r=t.split(".").map(Number),s=e.split(".").map(Number),o=Math.max(r.length,s.length);for(let n=0;n<o;n++){let i=n<r.length?r[n]:0,a=n<s.length?s[n]:0;if(i<a)return-1;if(i>a)return 1}return 0};async function X(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function be(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function Z(){let t=new Re.UAParser(window.navigator.userAgent).getResult(),e={solution:"",deviceSupported:!1};if(!window.PublicKeyCredential)return e.solution="Your browser seems to be outdated. Please upgrade to the latest version.",e;if(!await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable())switch(t.os.name){case"Mac OS":{let s=t.browser.version||"";return t.browser.name==="Firefox"&&$e(s,"122.0")<0?(e.solution="Please update your Firefox browser to the latest version.",e):(e.solution="Enable Touch ID on your device.",e)}case"iOS":return e.solution="Enable Face ID or Touch ID on your device.",e;case"Windows":return e.solution="Enable Windows Hello on your device. See here: https://support.microsoft.com/en-us/windows/learn-about-windows-hello-and-set-it-up-dae28983-8242-bb2a-d3d1-87c9d265a5f0.",e;case"Android":return t.browser.name==="Firefox"?(e.solution="Passkeys may not be supported on your Firefox browser. Please switch to a Chromium browser.",e):(e.solution="Enable device unlock via fingerprint, PIN, or facial recognition on your device.",e);default:return e.solution="Enable device unlock features such as fingerprint, PIN, or facial recognition.",e}return e.deviceSupported=!0,e}async function Ce(){let t=await X(),e=await Z();return t&&e.deviceSupported}var ee={};ue(ee,{ApiError:()=>m,AuthService:()=>A,BaseHttpRequest:()=>b,CancelError:()=>v,CancelablePromise:()=>C,LoginIDService:()=>I,OpenAPI:()=>Ae,PasskeysService:()=>P,RegService:()=>q,TxService:()=>O});var Ae={BASE:"https://api.loginid.io/fido2/v2",VERSION:"2.0",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};var te=class extends y{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let r=f("","",{}),s={app:{id:this.config.getAppId()},deviceInfo:B(),user:{username:"",usernameType:r.usernameType}};await this.service.auth.authAuthInit({requestBody:s})}catch(r){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",r instanceof m&&(e.code=r.body.msgCode||"unknown_error",e.message=r.body.msg||r.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){this.session.logout()}},Pe=te;var qe=t=>`LoginID_${t}_device-id`,x=class{static persistDeviceId(e,r){r&&localStorage.setItem(qe(e),r)}static getDeviceId(e){return localStorage.getItem(qe(e))||""}};var Oe=t=>[...t.crossAuthMethods,...t.fallbackMethods];var re=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},c=re;var oe=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},se=oe;var Ie=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new c("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new c("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new c("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new c("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new c("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",t);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new c(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new c("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},Te=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new c("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new c("Passkey authentication has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new c(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new c("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},nr=new se("User needs to be logged in to perform this operation."),xe=new se("No login options available.");var k=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:R(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:R(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:R(t.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Ie(o,s):o}},E=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:R(o.id),transports:o.transports,type:o.type};r.push(n)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortController&&{signal:e.abortController.signal},publicKey:{allowCredentials:r,challenge:R(t.challenge),extensions:t.extensions,rpId:t.rpId,timeout:t.timeout,userVerification:t.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Te(o,s):o}};var ne=class extends K{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;h.renewWebAuthnAbortController();let o=await k(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}async createPasskey(e,r="",s={}){let o=this.config.getAppId(),n=x.getDeviceId(o),i=B(n),a=f(e,r,s);a.authzToken=this.session.getToken(a),a.authzToken&&S(a.authzToken).username!==e&&(a.authzToken="");let u={app:{id:o},deviceInfo:i,user:{username:e,usernameType:a.usernameType,displayName:a.displayName}},p=await this.service.reg.regRegInit({requestBody:u,...a.authzToken&&{authorization:a.authzToken}}),d=await this.createNavigatorCredential(p),g=await this.service.reg.regRegComplete({requestBody:d}),D=T(g.jwtAccess);return this.session.setJwtCookie(g.jwtAccess),x.persistDeviceId(o,n||g.deviceId),D}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortController?h.assignWebAuthnAbortController(r.abortController):(h.renewWebAuthnAbortController(),r.abortController=h.abortController);let n=await E(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=this.config.getAppId(),o=B(x.getDeviceId(s)),n=f(e,"",r),i={app:{id:s},deviceInfo:o,user:{username:e,usernameType:n.usernameType}},a=await this.service.auth.authAuthInit({requestBody:i});switch(a.action){case"proceed":{let u=await this.getNavigatorCredential(a,r),p=await this.service.auth.authAuthComplete({requestBody:u}),d=T(p.jwtAccess);return this.session.setJwtCookie(d.token),n?.callbacks?.onSuccess&&await n.callbacks.onSuccess(d),d}case"crossAuth":case"fallback":{if(n?.callbacks?.onFallback){let u=Oe(a);await n.callbacks.onFallback(e,u)}return T("",!1,!0)}default:throw xe}}async authenticateWithPasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async requestOtp(e,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(e,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(e,r,s={}){let o=ge(e,s),n={username:e,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:a}=await this.service.tx.txTxInit({requestBody:n}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:a},{assertionResult:p}=await this.getNavigatorCredential(u),d={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:a,signature:p.signature};return await this.service.tx.txTxComplete({requestBody:d})}},ke=ne;var ie=class extends y{constructor(e){super(e)}async listPasskeys(e={}){let r=this.session.getToken(e);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(e,r,s={}){let o=this.session.getToken(s),n={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:e,requestBody:n})}async deletePasskey(e,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e})}},Ee=ie;var H=class extends y{constructor(e){super(e)}};le(H,[y,ke,K,Ee,Pe]);var ae=H;var _=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await E(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await k(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}};var Ge=ae;0&&(module.exports={AbortError,ApiError,LoginIDAPI,LoginIDWebSDK,PasskeyError,WebAuthnHelper,canCreatePasskey,createPasskeyCredential,doesDeviceSupportPasskeys,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
1
+ "use strict";var M=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var ze=Object.prototype.hasOwnProperty;var fe=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})},Ve=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Je(e))!ze.call(t,o)&&o!==r&&M(t,o,{get:()=>e[o],enumerable:!(s=je(e,o))||s.enumerable});return t};var Me=t=>Ve(M({},"__esModule",{value:!0}),t);var ct={};fe(ct,{AbortError:()=>H,ApiError:()=>y,LoginIDAPI:()=>se,LoginIDWebSDK:()=>he,PasskeyError:()=>d,WebAuthnHelper:()=>z,createPasskeyCredential:()=>S,default:()=>lt,getPasskeyCredential:()=>w,isConditionalUIAvailable:()=>Se,isPlatformAuthenticatorAvailable:()=>Ee});module.exports=Me(ct);var $=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,r=this.config.baseUrl.match(e);if(r)return r[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},K=$;var U=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),L=t=>{if(!t)return t;let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<t.length;){let i=t.charCodeAt(s++),a=t.charCodeAt(s++),u=t.charCodeAt(s++),p=i<<16|a<<8|u;r.push(e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63])}let o=r.join(""),n=t.length%3;return n?o.slice(0,n-3)+"===".slice(n||3):o},$e=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let a=0;a<64;a++)r[e.charAt(a)]=a;let o=0,n=0,i="";for(let a of t){let u=r[a];if(u!==void 0)for(o=(o<<6)+u,n+=6;n>=8;)i+=s(o>>(n-=8)&255)}return i},l=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=L(e);return U(s)},A=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=$e(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},ge=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),Re=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},B=t=>{try{let r=t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(window.atob(r).split("").map(o=>"%"+("00"+o.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(s)}catch(e){console.error(e)}},be=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},Ce=t=>{document.cookie=t},Ae=t=>{document.cookie=`${t}=; expires=${new Date}`},Pe=(t=25)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<t;s++)r+=e.charAt(Math.floor(Math.random()*e.length));return r},Ie=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),G=async t=>await window.crypto.subtle.exportKey("jwk",t.publicKey),Te=async(t,e)=>{let s=new TextEncoder().encode(e),o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,s);return l(o)};var Y=class{config;constructor(e){this.config=new K(e)}getToken(e){if(e.authzToken)return e.authzToken;{let r=this.getJwtCookie();return r||""}}getSessionInfo(){if(!this.isLoggedIn())return null;let e=B(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=B(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;Ce(o)}getJwtCookie(){return be(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}logout(){Ae(this.getJwtCookieName())}},Oe=Y;var P=class{constructor(e){this.config=e}};var y=class extends Error{url;status;statusText;body;request;constructor(e,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=e}};var v=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},I=class{#t;#r;#e;#o;#n;#i;#s;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#o=[],this.#n=new Promise((r,s)=>{this.#i=r,this.#s=s;let o=a=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(a))},n=a=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#s&&this.#s(a))},i=a=>{this.#t||this.#r||this.#e||this.#o.push(a)};return Object.defineProperty(i,"isResolved",{get:()=>this.#t}),Object.defineProperty(i,"isRejected",{get:()=>this.#r}),Object.defineProperty(i,"isCancelled",{get:()=>this.#e}),e(o,n,i)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,r){return this.#n.then(e,r)}catch(e){return this.#n.catch(e)}finally(e){return this.#n.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#o.length)try{for(let e of this.#o)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#o.length=0,this.#s&&this.#s(new v("Request aborted"))}}get isCancelled(){return this.#e}};var X=t=>t!=null,D=t=>typeof t=="string",Q=t=>D(t)&&t!=="",Z=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),qe=t=>t instanceof FormData,Ge=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Ye=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{X(n)&&(Array.isArray(n)?n.forEach(i=>{s(o,i)}):typeof n=="object"?Object.entries(n).forEach(([i,a])=>{s(`${o}[${i}]`,a)}):r(o,n))};return Object.entries(t).forEach(([o,n])=>{s(o,n)}),e.length>0?`?${e.join("&")}`:""},Qe=(t,e)=>{let r=t.ENCODE_PATH||encodeURI,s=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(n,i)=>e.path?.hasOwnProperty(i)?r(String(e.path[i])):n),o=`${t.BASE}${s}`;return e.query?`${o}${Ye(e.query)}`:o},Xe=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{D(o)||Z(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>X(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},W=async(t,e)=>typeof e=="function"?e(t):e,Ze=async(t,e)=>{let[r,s,o,n]=await Promise.all([W(e,t.TOKEN),W(e,t.USERNAME),W(e,t.PASSWORD),W(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>X(u)).reduce((a,[u,p])=>({...a,[u]:String(p)}),{});if(Q(r)&&(i.Authorization=`Bearer ${r}`),Q(s)&&Q(o)){let a=Ge(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:Z(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":D(e.body)?i["Content-Type"]="text/plain":qe(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},et=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):D(t.body)||Z(t.body)||qe(t.body)?t.body:JSON.stringify(t.body)},tt=async(t,e,r,s,o,n,i)=>{let a=new AbortController,u={headers:n,body:s??o,method:e.method,signal:a.signal};return t.WITH_CREDENTIALS&&(u.credentials=t.CREDENTIALS),i(()=>a.abort()),await fetch(r,u)},rt=(t,e)=>{if(e){let r=t.headers.get(e);if(D(r))return r}},ot=async t=>{if(t.status!==204)try{let e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(o=>e.toLowerCase().startsWith(o))?await t.json():await t.text()}catch(e){console.error(e)}},st=(t,e)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(s)throw new y(t,e,s);if(!e.ok){let o=e.status??"unknown",n=e.statusText??"unknown",i=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})();throw new y(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},xe=(t,e)=>new I(async(r,s,o)=>{try{let n=Qe(t,e),i=Xe(e),a=et(e),u=await Ze(t,e);if(!o.isCancelled){let p=await tt(t,e,n,a,i,u,o),c=await ot(p),m=rt(p,e.responseHeader),g={url:n,ok:p.ok,status:p.status,statusText:p.statusText,body:m??c};st(e,g),r(g.body)}}catch(n){s(n)}});var F=class extends P{constructor(e){super(e)}request(e){return xe(this.config,e)}};var T=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}};var O=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:r}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:r,authorization:s}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:s},body:r,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:r}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:r},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}};var q=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:r,authorization:s}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":r,Authorization:s},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}};var x=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}};var k=class{auth;passkeys;reg;tx;request;constructor(e,r=F){this.request=new r({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new T(this.request),this.passkeys=new O(this.request),this.reg=new q(this.request),this.tx=new x(this.request)}};var ee=class{config;service;session;constructor(e){this.config=new K(e),this.service=new k({BASE:e.baseUrl}),this.session=new Oe(e)}},h=ee;var te=class extends Error{constructor(e){super(e),this.name="AbortError"}},H=te;var re=class t{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let e=new H("Cancelling current WebAuthn request");t.abortController.abort(e)};static renewWebAuthnAbortController=()=>{t.abortWebAuthnRequest();let e=new AbortController;t.abortController=e};static assignWebAuthnAbortController=e=>{t.abortWebAuthnRequest(),t.abortController=e}},b=re;var f=(t,e,r)=>({...r,authzToken:e||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||t,callbacks:r.callbacks||{}}),ke=(t,e)=>({...f(t,"",e),txType:e.txType||"raw",nonce:e.nonce||ge()}),E=(t,e=!0,r=!1)=>({userId:t.userId,token:t.jwtAccess,passkeyId:t.passkeyId,isAuthenticated:e,isFallback:r});var oe=class extends h{constructor(e){super(e)}async validateOtp(e,r,s={}){let o=f(e,"",s),n={authCode:r,user:{username:e,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:n}),a=E(i);return b.renewWebAuthnAbortController(),this.session.setJwtCookie(a.token),a}async requestAndSendOtp(e,r="email",s={}){let o=f(e,"",s),n={user:{username:e,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:n});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:n});break;default:throw new Error("Invalid message method")}}},j=oe;var _=t=>{let e={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return t&&(e.deviceId=t),e};async function Ee(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Se(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}var se={};fe(se,{ApiError:()=>y,AuthService:()=>T,BaseHttpRequest:()=>P,CancelError:()=>v,CancelablePromise:()=>I,LoginIDService:()=>k,OpenAPI:()=>we,PasskeysService:()=>O,RegService:()=>q,TxService:()=>x});var we={BASE:"https://api.loginid.io/fido2/v2",VERSION:"2.0",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};var ne=class extends h{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let r=f("","",{}),s={app:{id:this.config.getAppId()},deviceInfo:_(),user:{username:"",usernameType:r.usernameType}};await this.service.auth.authAuthInit({requestBody:s})}catch(r){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",r instanceof y&&(e.code=r.body.msgCode||"unknown_error",e.message=r.body.msg||r.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){this.session.logout()}},Be=ne;var ve=t=>[...t.crossAuthMethods,...t.fallbackMethods];var ie=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=ie;var ae=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},ue=ae;var De=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new d("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new d("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new d("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new d("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new d("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",t);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new d(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new d("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},_e=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new d("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new d("Passkey authentication has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new d(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new d("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},br=new ue("User needs to be logged in to perform this operation."),Ne=new ue("No login options available.");var Ke=t=>`LoginID_${t}_device-id`,C=class{static persistDeviceId(e,r){r&&localStorage.setItem(Ke(e),r)}static getDeviceId(e){return localStorage.getItem(Ke(e))||""}};var S=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:A(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:A(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:A(t.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?De(o,s):o}},w=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:A(o.id),transports:o.transports,type:o.type};r.push(n)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortController&&{signal:e.abortController.signal},publicKey:{allowCredentials:r,challenge:A(t.challenge),extensions:t.extensions,rpId:t.rpId,timeout:t.timeout,userVerification:t.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?_e(o,s):o}};var pe=class extends Error{code;constructor(e,r){super(e),this.name="StorageError",this.code=r}},R=pe;var le=class{dbName;dbVersion;storeKey;indexes;constructor(e,r,s,o=[]){this.dbName=e,this.dbVersion=r,this.storeKey=s,this.indexes=o}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let r=e.result;if(!r.objectStoreNames.contains(this.storeKey)){let s=r.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:o,keyPath:n,options:i})=>s.createIndex(o,n,i))}},e}async getByIndex(e,r){return new Promise((s,o)=>{let n=this.openDb();n.onsuccess=()=>{let c=n.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(r);c.onsuccess=()=>{let m=c.result;m?s(m):o(new R(`No record found for ${r} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},c.onerror=()=>o(new R(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},n.onerror=()=>o(new R("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let u=o.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);u.onsuccess=()=>r(),u.onerror=()=>s(new R("Failed to save record.","ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new R("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},Ue=le;var ce=(t,e,r)=>(r||(r=Pe()),{id:r,username:e,aud:t}),de=async(t,e,r)=>{let o=U(L(JSON.stringify({alg:"ES256",jwk:e}))),n=U(L(JSON.stringify(t))),i=`${o}.${n}`,a=await Te(r,i);return`${i}.${a}`};var nt=1,it="app_id_idx",at="username_idx",ut="loginid-trust-store",pt="LoginID_trust-id",Le="app_id_username_idx",N=class extends Ue{appId;constructor(e){super(ut,nt,pt,[{name:at,keyPath:["username"]},{name:it,keyPath:["appId"]},{name:Le,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let r=await Ie(),s=await G(r),o=ce(this.appId,e),n=await de(o,s,r.privateKey);return await this.putRecord({id:o.id,appId:this.appId,username:e,keyPair:r}),n}async signWithTrustId(e){let r=await this.getByIndex(Le,[this.appId,e]),s=await G(r.keyPair),o=ce(this.appId,e,r.id);return await de(o,s,r.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(r){return r instanceof R&&r.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+r),"")}}};var me=class extends j{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;b.renewWebAuthnAbortController();let o=await S(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}async createPasskey(e,r="",s={}){let o=this.config.getAppId(),n=C.getDeviceId(o),i=_(n),a=new N(o),u=f(e,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&B(u.authzToken).username!==e&&(u.authzToken="");let p=await a.setOrSignWithTrustId(e),c={app:{id:o},deviceInfo:i,user:{username:e,usernameType:u.usernameType,displayName:u.displayName},...p&&{trustInfo:p}},m=await this.service.reg.regRegInit({requestBody:c,...u.authzToken&&{authorization:u.authzToken}}),g=await this.createNavigatorCredential(m),V=await this.service.reg.regRegComplete({requestBody:g}),He=E(V);return this.session.setJwtCookie(V.jwtAccess),C.persistDeviceId(o,n||V.deviceId),He}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortController?b.assignWebAuthnAbortController(r.abortController):(b.renewWebAuthnAbortController(),r.abortController=b.abortController);let n=await w(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=this.config.getAppId(),o=_(C.getDeviceId(s)),n=new N(s),i=f(e,"",r),a=await n.setOrSignWithTrustId(r.autoFill?"":e),u={app:{id:s},deviceInfo:o,user:{username:e,usernameType:i.usernameType},...a&&{trustInfo:a}},p=await this.service.auth.authAuthInit({requestBody:u});switch(p.action){case"proceed":{let c=await this.getNavigatorCredential(p,r),m=await this.service.auth.authAuthComplete({requestBody:c}),g=E(m);return this.session.setJwtCookie(g.token),C.persistDeviceId(s,m.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g}case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let m=ve(p);await i.callbacks.onFallback(e,m)}return E({userId:"",jwtAccess:""},!1,!0)}default:throw Ne}}async authenticateWithPasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async requestOtp(e,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(e,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(e,r,s={}){let o=ke(e,s),n={username:e,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:a}=await this.service.tx.txTxInit({requestBody:n}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:a},{assertionResult:p}=await this.getNavigatorCredential(u),c={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:a,signature:p.signature};return await this.service.tx.txTxComplete({requestBody:c})}},We=me;var ye=class extends h{constructor(e){super(e)}async listPasskeys(e={}){let r=this.session.getToken(e);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(e,r,s={}){let o=this.session.getToken(s),n={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:e,requestBody:n})}async deletePasskey(e,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e})}},Fe=ye;var J=class extends h{constructor(e){super(e)}};Re(J,[h,We,j,Fe,Be]);var he=J;var z=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await w(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await S(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}};var lt=he;0&&(module.exports={AbortError,ApiError,LoginIDAPI,LoginIDWebSDK,PasskeyError,WebAuthnHelper,createPasskeyCredential,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -270,15 +270,12 @@ type DeviceInfo = {
270
270
  * Screen width in pixels
271
271
  */
272
272
  screenWidth?: number;
273
- /**
274
- * A trust identifier
275
- */
276
- trustId?: string;
277
273
  };
278
274
 
279
275
  type AuthInitRequestBody = {
280
276
  app: Application;
281
277
  deviceInfo: DeviceInfo;
278
+ trustInfo?: string;
282
279
  user?: UserLogin;
283
280
  };
284
281
 
@@ -671,6 +668,7 @@ type RegInitRequestBody = {
671
668
  app: Application;
672
669
  deviceInfo: DeviceInfo;
673
670
  passkeyOptions?: PasskeyOptions$1;
671
+ trustInfo?: string;
674
672
  user?: User;
675
673
  };
676
674
 
@@ -826,34 +824,18 @@ declare class ApiError extends Error {
826
824
  constructor(request: ApiRequestOptions, response: ApiResult, message: string);
827
825
  }
828
826
 
829
- type BadRequestError = {
827
+ type AppError = {
830
828
  msg: string;
831
- msgCode: string;
832
- };
833
-
834
- type ForbiddenError = {
835
- msg: string;
836
- msgCode: string;
837
- };
838
-
839
- type InternalServerError = {
840
- msg: string;
841
- msgCode: string;
842
- };
843
-
844
- type NotFoundError = {
845
- msg: string;
846
- msgCode: string;
847
- };
848
-
849
- type UnauthorizedError = {
850
- msg: string;
851
- msgCode: string;
829
+ /**
830
+ * Message code
831
+ */
832
+ msgCode: 'bad_request' | 'unauthorized' | 'forbidden' | 'not_found' | 'internal_error';
852
833
  };
853
834
 
854
835
  type index_Aaguid = Aaguid;
855
836
  type index_ApiError = ApiError;
856
837
  declare const index_ApiError: typeof ApiError;
838
+ type index_AppError = AppError;
857
839
  type index_Application = Application;
858
840
  type index_AuthCode = AuthCode;
859
841
  type index_AuthCodeRequestSMSRequestBody = AuthCodeRequestSMSRequestBody;
@@ -865,7 +847,6 @@ type index_AuthService = AuthService;
865
847
  declare const index_AuthService: typeof AuthService;
866
848
  type index_AuthenticatorAssertionResponse = AuthenticatorAssertionResponse;
867
849
  type index_AuthenticatorSelectionCriteria = AuthenticatorSelectionCriteria;
868
- type index_BadRequestError = BadRequestError;
869
850
  type index_BaseHttpRequest = BaseHttpRequest;
870
851
  declare const index_BaseHttpRequest: typeof BaseHttpRequest;
871
852
  type index_CancelError = CancelError;
@@ -874,12 +855,9 @@ type index_CancelablePromise<T> = CancelablePromise<T>;
874
855
  declare const index_CancelablePromise: typeof CancelablePromise;
875
856
  type index_CreationResult = CreationResult;
876
857
  type index_DeviceInfo = DeviceInfo;
877
- type index_ForbiddenError = ForbiddenError;
878
- type index_InternalServerError = InternalServerError;
879
858
  type index_JWT = JWT;
880
859
  type index_LoginIDService = LoginIDService;
881
860
  declare const index_LoginIDService: typeof LoginIDService;
882
- type index_NotFoundError = NotFoundError;
883
861
  declare const index_OpenAPI: typeof OpenAPI;
884
862
  type index_OpenAPIConfig = OpenAPIConfig;
885
863
  type index_Passkey = Passkey;
@@ -904,11 +882,10 @@ type index_TxInit = TxInit;
904
882
  type index_TxInitRequestBody = TxInitRequestBody;
905
883
  type index_TxService = TxService;
906
884
  declare const index_TxService: typeof TxService;
907
- type index_UnauthorizedError = UnauthorizedError;
908
885
  type index_User = User;
909
886
  type index_UserLogin = UserLogin;
910
887
  declare namespace index {
911
- export { type index_Aaguid as Aaguid, index_ApiError as ApiError, type index_Application as Application, type index_AuthCode as AuthCode, type index_AuthCodeRequestSMSRequestBody as AuthCodeRequestSMSRequestBody, type index_AuthCodeVerifyRequestBody as AuthCodeVerifyRequestBody, type index_AuthCompleteRequestBody as AuthCompleteRequestBody, type index_AuthInit as AuthInit, type index_AuthInitRequestBody as AuthInitRequestBody, index_AuthService as AuthService, type index_AuthenticatorAssertionResponse as AuthenticatorAssertionResponse, type index_AuthenticatorSelectionCriteria as AuthenticatorSelectionCriteria, type index_BadRequestError as BadRequestError, index_BaseHttpRequest as BaseHttpRequest, index_CancelError as CancelError, index_CancelablePromise as CancelablePromise, type index_CreationResult as CreationResult, type index_DeviceInfo as DeviceInfo, type index_ForbiddenError as ForbiddenError, type index_InternalServerError as InternalServerError, type index_JWT as JWT, index_LoginIDService as LoginIDService, type index_NotFoundError as NotFoundError, index_OpenAPI as OpenAPI, type index_OpenAPIConfig as OpenAPIConfig, type index_Passkey as Passkey, type index_PasskeyCollection as PasskeyCollection, type PasskeyOptions$1 as PasskeyOptions, type index_PasskeyRenameRequestBody as PasskeyRenameRequestBody, index_PasskeysService as PasskeysService, type index_PubKeyCredentialDescriptor as PubKeyCredentialDescriptor, type index_PublicKeyCredentialCreationOptions as PublicKeyCredentialCreationOptions, type index_PublicKeyCredentialParameters as PublicKeyCredentialParameters, type index_PublicKeyCredentialRequestOptions as PublicKeyCredentialRequestOptions, type index_PublicKeyCredentialRpEntity as PublicKeyCredentialRpEntity, type index_PublicKeyCredentialUserEntity as PublicKeyCredentialUserEntity, type index_RegCompleteRequestBody as RegCompleteRequestBody, type index_RegInit as RegInit, type index_RegInitRequestBody as RegInitRequestBody, index_RegService as RegService, type index_TxComplete as TxComplete, type index_TxCompleteRequestBody as TxCompleteRequestBody, type index_TxInit as TxInit, type index_TxInitRequestBody as TxInitRequestBody, index_TxService as TxService, type index_UnauthorizedError as UnauthorizedError, type index_User as User, type index_UserLogin as UserLogin };
888
+ export { type index_Aaguid as Aaguid, index_ApiError as ApiError, type index_AppError as AppError, type index_Application as Application, type index_AuthCode as AuthCode, type index_AuthCodeRequestSMSRequestBody as AuthCodeRequestSMSRequestBody, type index_AuthCodeVerifyRequestBody as AuthCodeVerifyRequestBody, type index_AuthCompleteRequestBody as AuthCompleteRequestBody, type index_AuthInit as AuthInit, type index_AuthInitRequestBody as AuthInitRequestBody, index_AuthService as AuthService, type index_AuthenticatorAssertionResponse as AuthenticatorAssertionResponse, type index_AuthenticatorSelectionCriteria as AuthenticatorSelectionCriteria, index_BaseHttpRequest as BaseHttpRequest, index_CancelError as CancelError, index_CancelablePromise as CancelablePromise, type index_CreationResult as CreationResult, type index_DeviceInfo as DeviceInfo, type index_JWT as JWT, index_LoginIDService as LoginIDService, index_OpenAPI as OpenAPI, type index_OpenAPIConfig as OpenAPIConfig, type index_Passkey as Passkey, type index_PasskeyCollection as PasskeyCollection, type PasskeyOptions$1 as PasskeyOptions, type index_PasskeyRenameRequestBody as PasskeyRenameRequestBody, index_PasskeysService as PasskeysService, type index_PubKeyCredentialDescriptor as PubKeyCredentialDescriptor, type index_PublicKeyCredentialCreationOptions as PublicKeyCredentialCreationOptions, type index_PublicKeyCredentialParameters as PublicKeyCredentialParameters, type index_PublicKeyCredentialRequestOptions as PublicKeyCredentialRequestOptions, type index_PublicKeyCredentialRpEntity as PublicKeyCredentialRpEntity, type index_PublicKeyCredentialUserEntity as PublicKeyCredentialUserEntity, type index_RegCompleteRequestBody as RegCompleteRequestBody, type index_RegInit as RegInit, type index_RegInitRequestBody as RegInitRequestBody, index_RegService as RegService, type index_TxComplete as TxComplete, type index_TxCompleteRequestBody as TxCompleteRequestBody, type index_TxInit as TxInit, type index_TxInitRequestBody as TxInitRequestBody, index_TxService as TxService, type index_User as User, type index_UserLogin as UserLogin };
912
889
  }
913
890
 
914
891
  type Complete<T> = {
@@ -1062,6 +1039,14 @@ interface AuthResult {
1062
1039
  * A short-lived authorization token is returned, allowing access to protected resources for the given user such as listing, renaming or deleting passkeys.
1063
1040
  */
1064
1041
  token: string;
1042
+ /**
1043
+ * The unique identifier of the authenticated user.
1044
+ */
1045
+ userId: string;
1046
+ /**
1047
+ * The identifier for the passkey used in authentication, if applicable.
1048
+ */
1049
+ passkeyId?: string;
1065
1050
  /**
1066
1051
  * An identifier for the device used in the authentication process. This property helps determine if supported authentications can be proceeded,
1067
1052
  * allowing future authentications to identify the device correctly.
@@ -1112,6 +1097,40 @@ interface VerifyConfigResult {
1112
1097
  */
1113
1098
  code?: string;
1114
1099
  }
1100
+ /**
1101
+ * Represents the claims included in a TrustID token.
1102
+ */
1103
+ interface TrustIDClaims {
1104
+ /**
1105
+ * Unique identifier for the Trust ID.
1106
+ */
1107
+ id: string;
1108
+ /**
1109
+ * Username associated with the token owner.
1110
+ */
1111
+ username: string;
1112
+ /**
1113
+ * Audience for which the token is intended. This is the app ID.
1114
+ */
1115
+ aud: string;
1116
+ }
1117
+ /**
1118
+ * Represents a stored Trust ID record in the trust store database.
1119
+ */
1120
+ interface TrustIDRecord {
1121
+ /**
1122
+ * Unique identifier for the Trust ID, derived from the TrustID token.
1123
+ */
1124
+ id: string;
1125
+ /**
1126
+ * Username associated with the Trust ID.
1127
+ */
1128
+ username: string;
1129
+ /**
1130
+ * Cryptographic key pair used for signing and verification.
1131
+ */
1132
+ keyPair: CryptoKeyPair;
1133
+ }
1115
1134
 
1116
1135
  declare class SessionManager {
1117
1136
  /**
@@ -1904,21 +1923,5 @@ declare function isPlatformAuthenticatorAvailable(): Promise<boolean>;
1904
1923
  * Checks if conditional UI is available
1905
1924
  * */
1906
1925
  declare function isConditionalUIAvailable(): Promise<boolean>;
1907
- interface DoesDeviceSupportPasskeysResponse {
1908
- solution: string;
1909
- deviceSupported: boolean;
1910
- }
1911
- /**
1912
- * Attempts to provide a solution for missing platform authenticator
1913
- */
1914
- declare function doesDeviceSupportPasskeys(): Promise<DoesDeviceSupportPasskeysResponse>;
1915
- /**
1916
- * Determines whether a passkey can be created on the current device.
1917
- *
1918
- * @returns {Promise<boolean>} A promise that resolves to a boolean indicating whether a passkey can be created.
1919
- * - `true`: The device supports passkeys and a platform authenticator is available.
1920
- * - `false`: Either the device does not support passkeys or a platform authenticator is not available.
1921
- */
1922
- declare function canCreatePasskey(): Promise<boolean>;
1923
1926
 
1924
- export { AbortError, type AllOptions, ApiError, type AuthResult, type AuthenticateWithPasskeyAutofillOptions, type AuthenticateWithPasskeysOptions, type Callbacks, type Complete, type ConfirmTransactionOptions, type CreatePasskeyOptions, type DeletePasskeyOptions, type DeviceInfoRequestBody, type DoesDeviceSupportPasskeysResponse, type FallbackCallback, type FallbackOptions, type ListPasskeysOptions, index as LoginIDAPI, type LoginIDConfig, LoginIDWebSDK, type Message, type Otp, type Passkey, type PasskeyCollection, PasskeyError, type PasskeyManagementOptions, type PasskeyOptions, type RenamePasskeyOptions, type RequestAndSendOtpOptions, type RequestOtpOptions, type SessionInfo, type SuccessCallback, type Transports, type UsernameType, type ValidateOtpOptions, type VerifyConfigResult, WebAuthnHelper, canCreatePasskey, createPasskeyCredential, LoginIDWebSDK as default, doesDeviceSupportPasskeys, getPasskeyCredential, isConditionalUIAvailable, isPlatformAuthenticatorAvailable };
1927
+ export { AbortError, type AllOptions, ApiError, type AuthResult, type AuthenticateWithPasskeyAutofillOptions, type AuthenticateWithPasskeysOptions, type Callbacks, type Complete, type ConfirmTransactionOptions, type CreatePasskeyOptions, type DeletePasskeyOptions, type DeviceInfoRequestBody, type FallbackCallback, type FallbackOptions, type ListPasskeysOptions, index as LoginIDAPI, type LoginIDConfig, LoginIDWebSDK, type Message, type Otp, type Passkey, type PasskeyCollection, PasskeyError, type PasskeyManagementOptions, type PasskeyOptions, type RenamePasskeyOptions, type RequestAndSendOtpOptions, type RequestOtpOptions, type SessionInfo, type SuccessCallback, type Transports, type TrustIDClaims, type TrustIDRecord, type UsernameType, type ValidateOtpOptions, type VerifyConfigResult, WebAuthnHelper, createPasskeyCredential, LoginIDWebSDK as default, getPasskeyCredential, isConditionalUIAvailable, isPlatformAuthenticatorAvailable };
package/dist/index.d.ts CHANGED
@@ -270,15 +270,12 @@ type DeviceInfo = {
270
270
  * Screen width in pixels
271
271
  */
272
272
  screenWidth?: number;
273
- /**
274
- * A trust identifier
275
- */
276
- trustId?: string;
277
273
  };
278
274
 
279
275
  type AuthInitRequestBody = {
280
276
  app: Application;
281
277
  deviceInfo: DeviceInfo;
278
+ trustInfo?: string;
282
279
  user?: UserLogin;
283
280
  };
284
281
 
@@ -671,6 +668,7 @@ type RegInitRequestBody = {
671
668
  app: Application;
672
669
  deviceInfo: DeviceInfo;
673
670
  passkeyOptions?: PasskeyOptions$1;
671
+ trustInfo?: string;
674
672
  user?: User;
675
673
  };
676
674
 
@@ -826,34 +824,18 @@ declare class ApiError extends Error {
826
824
  constructor(request: ApiRequestOptions, response: ApiResult, message: string);
827
825
  }
828
826
 
829
- type BadRequestError = {
827
+ type AppError = {
830
828
  msg: string;
831
- msgCode: string;
832
- };
833
-
834
- type ForbiddenError = {
835
- msg: string;
836
- msgCode: string;
837
- };
838
-
839
- type InternalServerError = {
840
- msg: string;
841
- msgCode: string;
842
- };
843
-
844
- type NotFoundError = {
845
- msg: string;
846
- msgCode: string;
847
- };
848
-
849
- type UnauthorizedError = {
850
- msg: string;
851
- msgCode: string;
829
+ /**
830
+ * Message code
831
+ */
832
+ msgCode: 'bad_request' | 'unauthorized' | 'forbidden' | 'not_found' | 'internal_error';
852
833
  };
853
834
 
854
835
  type index_Aaguid = Aaguid;
855
836
  type index_ApiError = ApiError;
856
837
  declare const index_ApiError: typeof ApiError;
838
+ type index_AppError = AppError;
857
839
  type index_Application = Application;
858
840
  type index_AuthCode = AuthCode;
859
841
  type index_AuthCodeRequestSMSRequestBody = AuthCodeRequestSMSRequestBody;
@@ -865,7 +847,6 @@ type index_AuthService = AuthService;
865
847
  declare const index_AuthService: typeof AuthService;
866
848
  type index_AuthenticatorAssertionResponse = AuthenticatorAssertionResponse;
867
849
  type index_AuthenticatorSelectionCriteria = AuthenticatorSelectionCriteria;
868
- type index_BadRequestError = BadRequestError;
869
850
  type index_BaseHttpRequest = BaseHttpRequest;
870
851
  declare const index_BaseHttpRequest: typeof BaseHttpRequest;
871
852
  type index_CancelError = CancelError;
@@ -874,12 +855,9 @@ type index_CancelablePromise<T> = CancelablePromise<T>;
874
855
  declare const index_CancelablePromise: typeof CancelablePromise;
875
856
  type index_CreationResult = CreationResult;
876
857
  type index_DeviceInfo = DeviceInfo;
877
- type index_ForbiddenError = ForbiddenError;
878
- type index_InternalServerError = InternalServerError;
879
858
  type index_JWT = JWT;
880
859
  type index_LoginIDService = LoginIDService;
881
860
  declare const index_LoginIDService: typeof LoginIDService;
882
- type index_NotFoundError = NotFoundError;
883
861
  declare const index_OpenAPI: typeof OpenAPI;
884
862
  type index_OpenAPIConfig = OpenAPIConfig;
885
863
  type index_Passkey = Passkey;
@@ -904,11 +882,10 @@ type index_TxInit = TxInit;
904
882
  type index_TxInitRequestBody = TxInitRequestBody;
905
883
  type index_TxService = TxService;
906
884
  declare const index_TxService: typeof TxService;
907
- type index_UnauthorizedError = UnauthorizedError;
908
885
  type index_User = User;
909
886
  type index_UserLogin = UserLogin;
910
887
  declare namespace index {
911
- export { type index_Aaguid as Aaguid, index_ApiError as ApiError, type index_Application as Application, type index_AuthCode as AuthCode, type index_AuthCodeRequestSMSRequestBody as AuthCodeRequestSMSRequestBody, type index_AuthCodeVerifyRequestBody as AuthCodeVerifyRequestBody, type index_AuthCompleteRequestBody as AuthCompleteRequestBody, type index_AuthInit as AuthInit, type index_AuthInitRequestBody as AuthInitRequestBody, index_AuthService as AuthService, type index_AuthenticatorAssertionResponse as AuthenticatorAssertionResponse, type index_AuthenticatorSelectionCriteria as AuthenticatorSelectionCriteria, type index_BadRequestError as BadRequestError, index_BaseHttpRequest as BaseHttpRequest, index_CancelError as CancelError, index_CancelablePromise as CancelablePromise, type index_CreationResult as CreationResult, type index_DeviceInfo as DeviceInfo, type index_ForbiddenError as ForbiddenError, type index_InternalServerError as InternalServerError, type index_JWT as JWT, index_LoginIDService as LoginIDService, type index_NotFoundError as NotFoundError, index_OpenAPI as OpenAPI, type index_OpenAPIConfig as OpenAPIConfig, type index_Passkey as Passkey, type index_PasskeyCollection as PasskeyCollection, type PasskeyOptions$1 as PasskeyOptions, type index_PasskeyRenameRequestBody as PasskeyRenameRequestBody, index_PasskeysService as PasskeysService, type index_PubKeyCredentialDescriptor as PubKeyCredentialDescriptor, type index_PublicKeyCredentialCreationOptions as PublicKeyCredentialCreationOptions, type index_PublicKeyCredentialParameters as PublicKeyCredentialParameters, type index_PublicKeyCredentialRequestOptions as PublicKeyCredentialRequestOptions, type index_PublicKeyCredentialRpEntity as PublicKeyCredentialRpEntity, type index_PublicKeyCredentialUserEntity as PublicKeyCredentialUserEntity, type index_RegCompleteRequestBody as RegCompleteRequestBody, type index_RegInit as RegInit, type index_RegInitRequestBody as RegInitRequestBody, index_RegService as RegService, type index_TxComplete as TxComplete, type index_TxCompleteRequestBody as TxCompleteRequestBody, type index_TxInit as TxInit, type index_TxInitRequestBody as TxInitRequestBody, index_TxService as TxService, type index_UnauthorizedError as UnauthorizedError, type index_User as User, type index_UserLogin as UserLogin };
888
+ export { type index_Aaguid as Aaguid, index_ApiError as ApiError, type index_AppError as AppError, type index_Application as Application, type index_AuthCode as AuthCode, type index_AuthCodeRequestSMSRequestBody as AuthCodeRequestSMSRequestBody, type index_AuthCodeVerifyRequestBody as AuthCodeVerifyRequestBody, type index_AuthCompleteRequestBody as AuthCompleteRequestBody, type index_AuthInit as AuthInit, type index_AuthInitRequestBody as AuthInitRequestBody, index_AuthService as AuthService, type index_AuthenticatorAssertionResponse as AuthenticatorAssertionResponse, type index_AuthenticatorSelectionCriteria as AuthenticatorSelectionCriteria, index_BaseHttpRequest as BaseHttpRequest, index_CancelError as CancelError, index_CancelablePromise as CancelablePromise, type index_CreationResult as CreationResult, type index_DeviceInfo as DeviceInfo, type index_JWT as JWT, index_LoginIDService as LoginIDService, index_OpenAPI as OpenAPI, type index_OpenAPIConfig as OpenAPIConfig, type index_Passkey as Passkey, type index_PasskeyCollection as PasskeyCollection, type PasskeyOptions$1 as PasskeyOptions, type index_PasskeyRenameRequestBody as PasskeyRenameRequestBody, index_PasskeysService as PasskeysService, type index_PubKeyCredentialDescriptor as PubKeyCredentialDescriptor, type index_PublicKeyCredentialCreationOptions as PublicKeyCredentialCreationOptions, type index_PublicKeyCredentialParameters as PublicKeyCredentialParameters, type index_PublicKeyCredentialRequestOptions as PublicKeyCredentialRequestOptions, type index_PublicKeyCredentialRpEntity as PublicKeyCredentialRpEntity, type index_PublicKeyCredentialUserEntity as PublicKeyCredentialUserEntity, type index_RegCompleteRequestBody as RegCompleteRequestBody, type index_RegInit as RegInit, type index_RegInitRequestBody as RegInitRequestBody, index_RegService as RegService, type index_TxComplete as TxComplete, type index_TxCompleteRequestBody as TxCompleteRequestBody, type index_TxInit as TxInit, type index_TxInitRequestBody as TxInitRequestBody, index_TxService as TxService, type index_User as User, type index_UserLogin as UserLogin };
912
889
  }
913
890
 
914
891
  type Complete<T> = {
@@ -1062,6 +1039,14 @@ interface AuthResult {
1062
1039
  * A short-lived authorization token is returned, allowing access to protected resources for the given user such as listing, renaming or deleting passkeys.
1063
1040
  */
1064
1041
  token: string;
1042
+ /**
1043
+ * The unique identifier of the authenticated user.
1044
+ */
1045
+ userId: string;
1046
+ /**
1047
+ * The identifier for the passkey used in authentication, if applicable.
1048
+ */
1049
+ passkeyId?: string;
1065
1050
  /**
1066
1051
  * An identifier for the device used in the authentication process. This property helps determine if supported authentications can be proceeded,
1067
1052
  * allowing future authentications to identify the device correctly.
@@ -1112,6 +1097,40 @@ interface VerifyConfigResult {
1112
1097
  */
1113
1098
  code?: string;
1114
1099
  }
1100
+ /**
1101
+ * Represents the claims included in a TrustID token.
1102
+ */
1103
+ interface TrustIDClaims {
1104
+ /**
1105
+ * Unique identifier for the Trust ID.
1106
+ */
1107
+ id: string;
1108
+ /**
1109
+ * Username associated with the token owner.
1110
+ */
1111
+ username: string;
1112
+ /**
1113
+ * Audience for which the token is intended. This is the app ID.
1114
+ */
1115
+ aud: string;
1116
+ }
1117
+ /**
1118
+ * Represents a stored Trust ID record in the trust store database.
1119
+ */
1120
+ interface TrustIDRecord {
1121
+ /**
1122
+ * Unique identifier for the Trust ID, derived from the TrustID token.
1123
+ */
1124
+ id: string;
1125
+ /**
1126
+ * Username associated with the Trust ID.
1127
+ */
1128
+ username: string;
1129
+ /**
1130
+ * Cryptographic key pair used for signing and verification.
1131
+ */
1132
+ keyPair: CryptoKeyPair;
1133
+ }
1115
1134
 
1116
1135
  declare class SessionManager {
1117
1136
  /**
@@ -1904,21 +1923,5 @@ declare function isPlatformAuthenticatorAvailable(): Promise<boolean>;
1904
1923
  * Checks if conditional UI is available
1905
1924
  * */
1906
1925
  declare function isConditionalUIAvailable(): Promise<boolean>;
1907
- interface DoesDeviceSupportPasskeysResponse {
1908
- solution: string;
1909
- deviceSupported: boolean;
1910
- }
1911
- /**
1912
- * Attempts to provide a solution for missing platform authenticator
1913
- */
1914
- declare function doesDeviceSupportPasskeys(): Promise<DoesDeviceSupportPasskeysResponse>;
1915
- /**
1916
- * Determines whether a passkey can be created on the current device.
1917
- *
1918
- * @returns {Promise<boolean>} A promise that resolves to a boolean indicating whether a passkey can be created.
1919
- * - `true`: The device supports passkeys and a platform authenticator is available.
1920
- * - `false`: Either the device does not support passkeys or a platform authenticator is not available.
1921
- */
1922
- declare function canCreatePasskey(): Promise<boolean>;
1923
1926
 
1924
- export { AbortError, type AllOptions, ApiError, type AuthResult, type AuthenticateWithPasskeyAutofillOptions, type AuthenticateWithPasskeysOptions, type Callbacks, type Complete, type ConfirmTransactionOptions, type CreatePasskeyOptions, type DeletePasskeyOptions, type DeviceInfoRequestBody, type DoesDeviceSupportPasskeysResponse, type FallbackCallback, type FallbackOptions, type ListPasskeysOptions, index as LoginIDAPI, type LoginIDConfig, LoginIDWebSDK, type Message, type Otp, type Passkey, type PasskeyCollection, PasskeyError, type PasskeyManagementOptions, type PasskeyOptions, type RenamePasskeyOptions, type RequestAndSendOtpOptions, type RequestOtpOptions, type SessionInfo, type SuccessCallback, type Transports, type UsernameType, type ValidateOtpOptions, type VerifyConfigResult, WebAuthnHelper, canCreatePasskey, createPasskeyCredential, LoginIDWebSDK as default, doesDeviceSupportPasskeys, getPasskeyCredential, isConditionalUIAvailable, isPlatformAuthenticatorAvailable };
1927
+ export { AbortError, type AllOptions, ApiError, type AuthResult, type AuthenticateWithPasskeyAutofillOptions, type AuthenticateWithPasskeysOptions, type Callbacks, type Complete, type ConfirmTransactionOptions, type CreatePasskeyOptions, type DeletePasskeyOptions, type DeviceInfoRequestBody, type FallbackCallback, type FallbackOptions, type ListPasskeysOptions, index as LoginIDAPI, type LoginIDConfig, LoginIDWebSDK, type Message, type Otp, type Passkey, type PasskeyCollection, PasskeyError, type PasskeyManagementOptions, type PasskeyOptions, type RenamePasskeyOptions, type RequestAndSendOtpOptions, type RequestOtpOptions, type SessionInfo, type SuccessCallback, type Transports, type TrustIDClaims, type TrustIDRecord, type UsernameType, type ValidateOtpOptions, type VerifyConfigResult, WebAuthnHelper, createPasskeyCredential, LoginIDWebSDK as default, getPasskeyCredential, isConditionalUIAvailable, isPlatformAuthenticatorAvailable };
@@ -1,2 +1,2 @@
1
- "use strict";var LoginID=(()=>{var _t=Object.create;var ye=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var Lt=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty;var Ht=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ut=(t,e)=>{for(var o in e)ye(t,o,{get:e[o],enumerable:!0})},pt=(t,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lt(e))!Mt.call(t,r)&&r!==o&&ye(t,r,{get:()=>e[r],enumerable:!(s=Ft(e,r))||s.enumerable});return t};var Kt=(t,e,o)=>(o=t!=null?_t(zt(t)):{},pt(e||!t||!t.__esModule?ye(o,"default",{value:t,enumerable:!0}):o,t)),jt=t=>pt(ye({},"__esModule",{value:!0}),t);var wt=Ht((re,we)=>{"use strict";(function(t,e){"use strict";var o="1.0.37",s="",r="?",a="function",c="undefined",d="object",g="string",R="major",i="model",u="name",n="type",l="vendor",p="version",O="architecture",Y="console",h="mobile",f="tablet",x="smarttv",U="wearable",ve="embedded",ke=500,ie="Amazon",X="Apple",Xe="ASUS",Ze="BlackBerry",D="Browser",ne="Chrome",Bt="Edge",ae="Firefox",le="Google",Qe="Huawei",xe="LG",Pe="Microsoft",et="Motorola",ue="Opera",pe="Samsung",tt="Sharp",ce="Sony",Oe="Xiaomi",Te="Zebra",ot="Facebook",rt="Chromium OS",st="Mac OS",Dt=function(b,C){var y={};for(var A in b)C[A]&&C[A].length%2===0?y[A]=C[A].concat(b[A]):y[A]=b[A];return y},de=function(b){for(var C={},y=0;y<b.length;y++)C[b[y].toUpperCase()]=b[y];return C},it=function(b,C){return typeof b===g?Z(C).indexOf(Z(b))!==-1:!1},Z=function(b){return b.toLowerCase()},Nt=function(b){return typeof b===g?b.replace(/[^\d\.]/g,s).split(".")[0]:e},qe=function(b,C){if(typeof b===g)return b=b.replace(/^\s\s*/,s),typeof C===c?b:b.substring(0,ke)},Q=function(b,C){for(var y=0,A,B,q,w,m,I;y<C.length&&!m;){var Ee=C[y],lt=C[y+1];for(A=B=0;A<Ee.length&&!m&&Ee[A];)if(m=Ee[A++].exec(b),m)for(q=0;q<lt.length;q++)I=m[++B],w=lt[q],typeof w===d&&w.length>0?w.length===2?typeof w[1]==a?this[w[0]]=w[1].call(this,I):this[w[0]]=w[1]:w.length===3?typeof w[1]===a&&!(w[1].exec&&w[1].test)?this[w[0]]=I?w[1].call(this,I,w[2]):e:this[w[0]]=I?I.replace(w[1],w[2]):e:w.length===4&&(this[w[0]]=I?w[3].call(this,I.replace(w[1],w[2])):e):this[w]=I||e;y+=2}},Ie=function(b,C){for(var y in C)if(typeof C[y]===d&&C[y].length>0){for(var A=0;A<C[y].length;A++)if(it(C[y][A],b))return y===r?e:y}else if(it(C[y],b))return y===r?e:y;return b},Ut={"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},nt={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2","8.1":"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},at={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[u,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[u,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[u,p],[/opios[\/ ]+([\w\.]+)/i],[p,[u,ue+" Mini"]],[/\bopr\/([\w\.]+)/i],[p,[u,ue]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[p,[u,"Baidu"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim)\s?(?:browser)?[\/ ]?([\w\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[u,p],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[u,"UC"+D]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[p,[u,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[u,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[u,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[p,[u,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[p,[u,"Smart Lenovo "+D]],[/(avast|avg)\/([\w\.]+)/i],[[u,/(.+)/,"$1 Secure "+D],p],[/\bfocus\/([\w\.]+)/i],[p,[u,ae+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[u,ue+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[u,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[u,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[u,ue+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[u,"MIUI "+D]],[/fxios\/([-\w\.]+)/i],[p,[u,ae]],[/\bqihu|(qi?ho?o?|360)browser/i],[[u,"360 "+D]],[/(oculus|sailfish|huawei|vivo)browser\/([\w\.]+)/i],[[u,/(.+)/,"$1 "+D],p],[/samsungbrowser\/([\w\.]+)/i],[p,[u,pe+" Internet"]],[/(comodo_dragon)\/([\w\.]+)/i],[[u,/_/g," "],p],[/metasr[\/ ]?([\d\.]+)/i],[p,[u,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[u,"Sogou Mobile"],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345Explorer)[\/ ]?([\w\.]+)/i],[u,p],[/(lbbrowser)/i,/\[(linkedin)app\]/i],[u],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[u,ot],p],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[u,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[u,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[p,[u,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[u,ne+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[u,ne+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[u,"Android "+D]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[u,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[u,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,u],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[u,[p,Ie,Ut]],[/(webkit|khtml)\/([\w\.]+)/i],[u,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[u,"Netscape"],p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[u,ae+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[u,p],[/(cobalt)\/([\w\.]+)/i],[u,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[O,"amd64"]],[/(ia32(?=;))/i],[[O,Z]],[/((?:i[346]|x)86)[;\)]/i],[[O,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[O,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[O,"armhf"]],[/windows (ce|mobile); ppc;/i],[[O,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[O,/ower/,s,Z]],[/(sun4\w)[;\)]/i],[[O,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[O,Z]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[i,[l,pe],[n,f]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[i,[l,pe],[n,h]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[i,[l,X],[n,h]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[i,[l,X],[n,f]],[/(macintosh);/i],[i,[l,X]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[i,[l,tt],[n,h]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[i,[l,Qe],[n,f]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[i,[l,Qe],[n,h]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[i,/_/g," "],[l,Oe],[n,h]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[i,/_/g," "],[l,Oe],[n,f]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[i,[l,"OPPO"],[n,h]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[i,[l,"Vivo"],[n,h]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[i,[l,"Realme"],[n,h]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[i,[l,et],[n,h]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[i,[l,et],[n,f]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[i,[l,xe],[n,f]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[i,[l,xe],[n,h]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[i,[l,"Lenovo"],[n,f]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[i,/_/g," "],[l,"Nokia"],[n,h]],[/(pixel c)\b/i],[i,[l,le],[n,f]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[i,[l,le],[n,h]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[i,[l,ce],[n,h]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[i,"Xperia Tablet"],[l,ce],[n,f]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[i,[l,"OnePlus"],[n,h]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[i,[l,ie],[n,f]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[i,/(.+)/g,"Fire Phone $1"],[l,ie],[n,h]],[/(playbook);[-\w\),; ]+(rim)/i],[i,l,[n,f]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[i,[l,Ze],[n,h]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[i,[l,Xe],[n,f]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[i,[l,Xe],[n,h]],[/(nexus 9)/i],[i,[l,"HTC"],[n,f]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[l,[i,/_/g," "],[n,h]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[i,[l,"Acer"],[n,f]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[i,[l,"Meizu"],[n,h]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[i,[l,"Ulefone"],[n,h]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[l,i,[n,h]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[l,i,[n,f]],[/(surface duo)/i],[i,[l,Pe],[n,f]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[i,[l,"Fairphone"],[n,h]],[/(u304aa)/i],[i,[l,"AT&T"],[n,h]],[/\bsie-(\w*)/i],[i,[l,"Siemens"],[n,h]],[/\b(rct\w+) b/i],[i,[l,"RCA"],[n,f]],[/\b(venue[\d ]{2,7}) b/i],[i,[l,"Dell"],[n,f]],[/\b(q(?:mv|ta)\w+) b/i],[i,[l,"Verizon"],[n,f]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[i,[l,"Barnes & Noble"],[n,f]],[/\b(tm\d{3}\w+) b/i],[i,[l,"NuVision"],[n,f]],[/\b(k88) b/i],[i,[l,"ZTE"],[n,f]],[/\b(nx\d{3}j) b/i],[i,[l,"ZTE"],[n,h]],[/\b(gen\d{3}) b.+49h/i],[i,[l,"Swiss"],[n,h]],[/\b(zur\d{3}) b/i],[i,[l,"Swiss"],[n,f]],[/\b((zeki)?tb.*\b) b/i],[i,[l,"Zeki"],[n,f]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[l,"Dragon Touch"],i,[n,f]],[/\b(ns-?\w{0,9}) b/i],[i,[l,"Insignia"],[n,f]],[/\b((nxa|next)-?\w{0,9}) b/i],[i,[l,"NextBook"],[n,f]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[l,"Voice"],i,[n,h]],[/\b(lvtel\-)?(v1[12]) b/i],[[l,"LvTel"],i,[n,h]],[/\b(ph-1) /i],[i,[l,"Essential"],[n,h]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[i,[l,"Envizen"],[n,f]],[/\b(trio[-\w\. ]+) b/i],[i,[l,"MachSpeed"],[n,f]],[/\btu_(1491) b/i],[i,[l,"Rotor"],[n,f]],[/(shield[\w ]+) b/i],[i,[l,"Nvidia"],[n,f]],[/(sprint) (\w+)/i],[l,i,[n,h]],[/(kin\.[onetw]{3})/i],[[i,/\./g," "],[l,Pe],[n,h]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[i,[l,Te],[n,f]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[i,[l,Te],[n,h]],[/smart-tv.+(samsung)/i],[l,[n,x]],[/hbbtv.+maple;(\d+)/i],[[i,/^/,"SmartTV"],[l,pe],[n,x]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[l,xe],[n,x]],[/(apple) ?tv/i],[l,[i,X+" TV"],[n,x]],[/crkey/i],[[i,ne+"cast"],[l,le],[n,x]],[/droid.+aft(\w+)( bui|\))/i],[i,[l,ie],[n,x]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[i,[l,tt],[n,x]],[/(bravia[\w ]+)( bui|\))/i],[i,[l,ce],[n,x]],[/(mitv-\w{5}) bui/i],[i,[l,Oe],[n,x]],[/Hbbtv.*(technisat) (.*);/i],[l,i,[n,x]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[l,qe],[i,qe],[n,x]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[n,x]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[l,i,[n,Y]],[/droid.+; (shield) bui/i],[i,[l,"Nvidia"],[n,Y]],[/(playstation [345portablevi]+)/i],[i,[l,ce],[n,Y]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[i,[l,Pe],[n,Y]],[/((pebble))app/i],[l,i,[n,U]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[i,[l,X],[n,U]],[/droid.+; (glass) \d/i],[i,[l,le],[n,U]],[/droid.+; (wt63?0{2,3})\)/i],[i,[l,Te],[n,U]],[/(quest( 2| pro)?)/i],[i,[l,ot],[n,U]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[l,[n,ve]],[/(aeobc)\b/i],[i,[l,ie],[n,ve]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[i,[n,h]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[i,[n,f]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[n,f]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[n,h]],[/(android[-\w\. ]{0,9});.+buil/i],[i,[l,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[u,Bt+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[u,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[u,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,u]],os:[[/microsoft (windows) (vista|xp)/i],[u,p],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[u,[p,Ie,nt]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[p,Ie,nt],[u,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[u,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[u,st],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,u],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[u,p],[/\(bb(10);/i],[p,[u,Ze]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[u,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[u,ae+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[u,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[u,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[u,ne+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[u,rt],p],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[u,p],[/(sunos) ?([\w\.\d]*)/i],[[u,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[u,p]]},P=function(b,C){if(typeof b===d&&(C=b,b=e),!(this instanceof P))return new P(b,C).getResult();var y=typeof t!==c&&t.navigator?t.navigator:e,A=b||(y&&y.userAgent?y.userAgent:s),B=y&&y.userAgentData?y.userAgentData:e,q=C?Dt(at,C):at,w=y&&y.userAgent==A;return this.getBrowser=function(){var m={};return m[u]=e,m[p]=e,Q.call(m,A,q.browser),m[R]=Nt(m[p]),w&&y&&y.brave&&typeof y.brave.isBrave==a&&(m[u]="Brave"),m},this.getCPU=function(){var m={};return m[O]=e,Q.call(m,A,q.cpu),m},this.getDevice=function(){var m={};return m[l]=e,m[i]=e,m[n]=e,Q.call(m,A,q.device),w&&!m[n]&&B&&B.mobile&&(m[n]=h),w&&m[i]=="Macintosh"&&y&&typeof y.standalone!==c&&y.maxTouchPoints&&y.maxTouchPoints>2&&(m[i]="iPad",m[n]=f),m},this.getEngine=function(){var m={};return m[u]=e,m[p]=e,Q.call(m,A,q.engine),m},this.getOS=function(){var m={};return m[u]=e,m[p]=e,Q.call(m,A,q.os),w&&!m[u]&&B&&B.platform!="Unknown"&&(m[u]=B.platform.replace(/chrome os/i,rt).replace(/macos/i,st)),m},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return A},this.setUA=function(m){return A=typeof m===g&&m.length>ke?qe(m,ke):m,this},this.setUA(A),this};P.VERSION=o,P.BROWSER=de([u,p,R]),P.CPU=de([O]),P.DEVICE=de([i,l,n,Y,h,x,f,U,ve]),P.ENGINE=P.OS=de([u,p]),typeof re!==c?(typeof we!==c&&we.exports&&(re=we.exports=P),re.UAParser=P):typeof define===a&&define.amd?define(function(){return P}):typeof t!==c&&(t.UAParser=P);var _=typeof t!==c&&(t.jQuery||t.Zepto);if(_&&!_.ua){var me=new P;_.ua=me.getResult(),_.ua.get=function(){return me.getUA()},_.ua.set=function(b){me.setUA(b);var C=me.getResult();for(var y in C)_.ua[y]=C[y]}}})(typeof window=="object"?window:re)});var no={};ut(no,{AbortError:()=>ge,ApiError:()=>T,LoginIDAPI:()=>Ke,LoginIDWebSDK:()=>Ye,PasskeyError:()=>k,WebAuthnHelper:()=>Ae,canCreatePasskey:()=>vt,createPasskeyCredential:()=>$,default:()=>io,doesDeviceSupportPasskeys:()=>He,getPasskeyCredential:()=>G,isConditionalUIAvailable:()=>At,isPlatformAuthenticatorAvailable:()=>Me});var Se=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,o=this.config.baseUrl.match(e);if(o)return o[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},he=Se;var Wt=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Vt=t=>{if(!t)return t;let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",o=[],s=0;for(;s<t.length;){let c=t.charCodeAt(s++),d=t.charCodeAt(s++),g=t.charCodeAt(s++),R=c<<16|d<<8|g;o.push(e[R>>18&63]+e[R>>12&63]+e[R>>6&63]+e[R&63])}let r=o.join(""),a=t.length%3;return a?r.slice(0,a-3)+"===".slice(a||3):r},Jt=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",o={},s=String.fromCharCode;for(let d=0;d<64;d++)o[e.charAt(d)]=d;let r=0,a=0,c="";for(let d of t){let g=o[d];if(g!==void 0)for(r=(r<<6)+g,a+=6;a>=8;)c+=s(r>>(a-=8)&255)}return c},v=t=>{let e="",o=new Uint8Array(t);for(let r=0;r<o.byteLength;r++)e+=String.fromCharCode(o[r]);let s=Vt(e);return Wt(s)},F=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=Jt(t),o=new Uint8Array(e.length);for(let s=0;s<e.length;s++)o[s]=e.charCodeAt(s);return o.buffer},ct=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),dt=(t,e)=>{e.forEach(o=>{Object.getOwnPropertyNames(o.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(o.prototype,s)||Object.create(null))})})},ee=t=>{try{let o=t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(window.atob(o).split("").map(r=>"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(s)}catch(e){console.error(e)}},mt=t=>{let o=`; ${document.cookie}`.split(`; ${t}=`);if(o&&o.length===2)return o.pop().split(";").shift()},yt=t=>{document.cookie=t},ht=t=>{document.cookie=`${t}=; expires=${new Date}`};var Be=class{config;constructor(e){this.config=new he(e)}getToken(e){if(e.authzToken)return e.authzToken;{let o=this.getJwtCookie();return o||""}}getSessionInfo(){if(!this.isLoggedIn())return null;let e=ee(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let o=ee(e),s=new Date(o.exp*1e3).toUTCString(),r=`${this.getJwtCookieName()}=${e}; expires=${s}`;yt(r)}getJwtCookie(){return mt(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}logout(){ht(this.getJwtCookieName())}},ft=Be;var L=class{constructor(e){this.config=e}};var T=class extends Error{url;status;statusText;body;request;constructor(e,o,s){super(s),this.name="ApiError",this.url=o.url,this.status=o.status,this.statusText=o.statusText,this.body=o.body,this.request=e}};var te=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},z=class{#t;#o;#e;#r;#i;#n;#s;constructor(e){this.#t=!1,this.#o=!1,this.#e=!1,this.#r=[],this.#i=new Promise((o,s)=>{this.#n=o,this.#s=s;let r=d=>{this.#t||this.#o||this.#e||(this.#t=!0,this.#n&&this.#n(d))},a=d=>{this.#t||this.#o||this.#e||(this.#o=!0,this.#s&&this.#s(d))},c=d=>{this.#t||this.#o||this.#e||this.#r.push(d)};return Object.defineProperty(c,"isResolved",{get:()=>this.#t}),Object.defineProperty(c,"isRejected",{get:()=>this.#o}),Object.defineProperty(c,"isCancelled",{get:()=>this.#e}),e(r,a,c)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,o){return this.#i.then(e,o)}catch(e){return this.#i.catch(e)}finally(e){return this.#i.finally(e)}cancel(){if(!(this.#t||this.#o||this.#e)){if(this.#e=!0,this.#r.length)try{for(let e of this.#r)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#r.length=0,this.#s&&this.#s(new te("Request aborted"))}}get isCancelled(){return this.#e}};var Ne=t=>t!=null,oe=t=>typeof t=="string",De=t=>oe(t)&&t!=="",Ue=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),bt=t=>t instanceof FormData,$t=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Gt=t=>{let e=[],o=(r,a)=>{e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(a))}`)},s=(r,a)=>{Ne(a)&&(Array.isArray(a)?a.forEach(c=>{s(r,c)}):typeof a=="object"?Object.entries(a).forEach(([c,d])=>{s(`${r}[${c}]`,d)}):o(r,a))};return Object.entries(t).forEach(([r,a])=>{s(r,a)}),e.length>0?`?${e.join("&")}`:""},Yt=(t,e)=>{let o=t.ENCODE_PATH||encodeURI,s=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(a,c)=>e.path?.hasOwnProperty(c)?o(String(e.path[c])):a),r=`${t.BASE}${s}`;return e.query?`${r}${Gt(e.query)}`:r},Xt=t=>{if(t.formData){let e=new FormData,o=(s,r)=>{oe(r)||Ue(r)?e.append(s,r):e.append(s,JSON.stringify(r))};return Object.entries(t.formData).filter(([s,r])=>Ne(r)).forEach(([s,r])=>{Array.isArray(r)?r.forEach(a=>o(s,a)):o(s,r)}),e}},fe=async(t,e)=>typeof e=="function"?e(t):e,Zt=async(t,e)=>{let[o,s,r,a]=await Promise.all([fe(e,t.TOKEN),fe(e,t.USERNAME),fe(e,t.PASSWORD),fe(e,t.HEADERS)]),c=Object.entries({Accept:"application/json",...a,...e.headers}).filter(([d,g])=>Ne(g)).reduce((d,[g,R])=>({...d,[g]:String(R)}),{});if(De(o)&&(c.Authorization=`Bearer ${o}`),De(s)&&De(r)){let d=$t(`${s}:${r}`);c.Authorization=`Basic ${d}`}return e.body&&(e.mediaType?c["Content-Type"]=e.mediaType:Ue(e.body)?c["Content-Type"]=e.body.type||"application/octet-stream":oe(e.body)?c["Content-Type"]="text/plain":bt(e.body)||(c["Content-Type"]="application/json")),new Headers(c)},Qt=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):oe(t.body)||Ue(t.body)||bt(t.body)?t.body:JSON.stringify(t.body)},eo=async(t,e,o,s,r,a,c)=>{let d=new AbortController,g={headers:a,body:s??r,method:e.method,signal:d.signal};return t.WITH_CREDENTIALS&&(g.credentials=t.CREDENTIALS),c(()=>d.abort()),await fetch(o,g)},to=(t,e)=>{if(e){let o=t.headers.get(e);if(oe(o))return o}},oo=async t=>{if(t.status!==204)try{let e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(r=>e.toLowerCase().startsWith(r))?await t.json():await t.text()}catch(e){console.error(e)}},ro=(t,e)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(s)throw new T(t,e,s);if(!e.ok){let r=e.status??"unknown",a=e.statusText??"unknown",c=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})();throw new T(t,e,`Generic Error: status: ${r}; status text: ${a}; body: ${c}`)}},gt=(t,e)=>new z(async(o,s,r)=>{try{let a=Yt(t,e),c=Xt(e),d=Qt(e),g=await Zt(t,e);if(!r.isCancelled){let R=await eo(t,e,a,d,c,g,r),i=await oo(R),u=to(R,e.responseHeader),n={url:a,ok:R.ok,status:R.status,statusText:R.statusText,body:u??i};ro(e,n),o(n.body)}}catch(a){s(a)}});var be=class extends L{constructor(e){super(e)}request(e){return gt(this.config,e)}};var M=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:o}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":o},body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var H=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:o}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:o},errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:o,authorization:s}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:s},body:o,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:o}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:o},errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var K=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:o,authorization:s}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":o,Authorization:s},body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}};var j=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var W=class{auth;passkeys;reg;tx;request;constructor(e,o=be){this.request=new o({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new M(this.request),this.passkeys=new H(this.request),this.reg=new K(this.request),this.tx=new j(this.request)}};var _e=class{config;service;session;constructor(e){this.config=new he(e),this.service=new W({BASE:e.baseUrl}),this.session=new ft(e)}},E=_e;var Fe=class extends Error{constructor(e){super(e),this.name="AbortError"}},ge=Fe;var Le=class t{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let e=new ge("Cancelling current WebAuthn request");t.abortController.abort(e)};static renewWebAuthnAbortController=()=>{t.abortWebAuthnRequest();let e=new AbortController;t.abortController=e};static assignWebAuthnAbortController=e=>{t.abortWebAuthnRequest(),t.abortController=e}},N=Le;var S=(t,e,o)=>({...o,authzToken:e||o.authzToken||"",usernameType:o.usernameType||"other",displayName:o.displayName||t,callbacks:o.callbacks||{}}),Rt=(t,e)=>({...S(t,"",e),txType:e.txType||"raw",nonce:e.nonce||ct()}),V=(t,e=!0,o=!1)=>({token:t,isAuthenticated:e,isFallback:o});var ze=class extends E{constructor(e){super(e)}async validateOtp(e,o,s={}){let r=S(e,"",s),a={authCode:o,user:{username:e,usernameType:r.usernameType}},c=await this.service.auth.authAuthCodeVerify({requestBody:a}),d=V(c.jwtAccess);return N.renewWebAuthnAbortController(),this.session.setJwtCookie(d.token),d}async requestAndSendOtp(e,o="email",s={}){let r=S(e,"",s),a={user:{username:e,usernameType:r.usernameType}};switch(o){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:a});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:a});break;default:throw new Error("Invalid message method")}}},Re=ze;var Ct=Kt(wt(),1),se=t=>{let e={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return t&&(e.deviceId=t),e},so=(t,e)=>{let o=t.split(".").map(Number),s=e.split(".").map(Number),r=Math.max(o.length,s.length);for(let a=0;a<r;a++){let c=a<o.length?o[a]:0,d=a<s.length?s[a]:0;if(c<d)return-1;if(c>d)return 1}return 0};async function Me(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function At(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function He(){let t=new Ct.UAParser(window.navigator.userAgent).getResult(),e={solution:"",deviceSupported:!1};if(!window.PublicKeyCredential)return e.solution="Your browser seems to be outdated. Please upgrade to the latest version.",e;if(!await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable())switch(t.os.name){case"Mac OS":{let s=t.browser.version||"";return t.browser.name==="Firefox"&&so(s,"122.0")<0?(e.solution="Please update your Firefox browser to the latest version.",e):(e.solution="Enable Touch ID on your device.",e)}case"iOS":return e.solution="Enable Face ID or Touch ID on your device.",e;case"Windows":return e.solution="Enable Windows Hello on your device. See here: https://support.microsoft.com/en-us/windows/learn-about-windows-hello-and-set-it-up-dae28983-8242-bb2a-d3d1-87c9d265a5f0.",e;case"Android":return t.browser.name==="Firefox"?(e.solution="Passkeys may not be supported on your Firefox browser. Please switch to a Chromium browser.",e):(e.solution="Enable device unlock via fingerprint, PIN, or facial recognition on your device.",e);default:return e.solution="Enable device unlock features such as fingerprint, PIN, or facial recognition.",e}return e.deviceSupported=!0,e}async function vt(){let t=await Me(),e=await He();return t&&e.deviceSupported}var Ke={};ut(Ke,{ApiError:()=>T,AuthService:()=>M,BaseHttpRequest:()=>L,CancelError:()=>te,CancelablePromise:()=>z,LoginIDService:()=>W,OpenAPI:()=>kt,PasskeysService:()=>H,RegService:()=>K,TxService:()=>j});var kt={BASE:"https://api.loginid.io/fido2/v2",VERSION:"2.0",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};var je=class extends E{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let o=S("","",{}),s={app:{id:this.config.getAppId()},deviceInfo:se(),user:{username:"",usernameType:o.usernameType}};await this.service.auth.authAuthInit({requestBody:s})}catch(o){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",o instanceof T&&(e.code=o.body.msgCode||"unknown_error",e.message=o.body.msg||o.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){this.session.logout()}},xt=je;var Pt=t=>`LoginID_${t}_device-id`,J=class{static persistDeviceId(e,o){o&&localStorage.setItem(Pt(e),o)}static getDeviceId(e){return localStorage.getItem(Pt(e))||""}};var Ot=t=>[...t.crossAuthMethods,...t.fallbackMethods];var We=class extends Error{code;constructor(e,o,s){super(e),this.code=o,this.cause=s}},k=We;var Ve=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},Je=Ve;var Tt=(t,e)=>{let o=t.name,{publicKey:s}=e;if(o==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new k("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new k("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(o==="InvalidStateError")return new k("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(o==="NotAllowedError")return new k("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(o==="NotSupportedError")return new k("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",t);if(o==="SecurityError"){let r=s?.rp?.id;if(r!==window.location.hostname)return new k(`The domain of the relying party (${r}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return o==="UnknownError"?new k("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},qt=(t,e)=>{let o=t.name,{publicKey:s}=e;if(o==="AbortError"&&e.signal instanceof AbortSignal)return new k("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(o==="NotAllowedError")return new k("Passkey authentication has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(o==="SecurityError"){let r=s?.rpId;if(r!==window.location.hostname)return new k(`The domain of the relying party (${r}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return o==="UnknownError"?new k("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},hr=new Je("User needs to be logged in to perform this operation."),It=new Je("No login options available.");var $=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let r of t.excludeCredentials){let a={id:F(r.id),transports:r.transports,type:r.type};e.push(a)}}let o=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:F(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:o,rp:t.rp,timeout:t.timeout,user:{...t.user,id:F(t.user.id)}}};try{let r=await navigator.credentials.create(s);if(r===null)throw new Error("Failed to create the passkey credential.");return r}catch(r){throw r instanceof Error?Tt(r,s):r}},G=async(t,e={})=>{let o;if(t.allowCredentials!==void 0){o=[];for(let r of t.allowCredentials){let a={id:F(r.id),transports:r.transports,type:r.type};o.push(a)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortController&&{signal:e.abortController.signal},publicKey:{allowCredentials:o,challenge:F(t.challenge),extensions:t.extensions,rpId:t.rpId,timeout:t.timeout,userVerification:t.userVerification}};try{let r=await navigator.credentials.get(s);if(r===null)throw new Error("Failed to create the passkey credential.");return r}catch(r){throw r instanceof Error?qt(r,s):r}};var $e=class extends Re{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:o,session:s}=e;N.renewWebAuthnAbortController();let r=await $(o),a=r.response,c=a.getPublicKey&&a.getPublicKey(),d=a.getPublicKeyAlgorithm&&a.getPublicKeyAlgorithm(),g=a.getAuthenticatorData&&a.getAuthenticatorData(),R=a.getTransports&&a.getTransports();return{creationResult:{attestationObject:v(a.attestationObject),clientDataJSON:v(a.clientDataJSON),credentialId:r.id,...c&&{publicKey:v(c)},...d&&{publicKeyAlgorithm:d},...g&&{authenticatorData:v(g)},...R&&{transports:R}},session:s}}async createPasskey(e,o="",s={}){let r=this.config.getAppId(),a=J.getDeviceId(r),c=se(a),d=S(e,o,s);d.authzToken=this.session.getToken(d),d.authzToken&&ee(d.authzToken).username!==e&&(d.authzToken="");let g={app:{id:r},deviceInfo:c,user:{username:e,usernameType:d.usernameType,displayName:d.displayName}},R=await this.service.reg.regRegInit({requestBody:g,...d.authzToken&&{authorization:d.authzToken}}),i=await this.createNavigatorCredential(R),u=await this.service.reg.regRegComplete({requestBody:i}),n=V(u.jwtAccess);return this.session.setJwtCookie(u.jwtAccess),J.persistDeviceId(r,a||u.deviceId),n}async getNavigatorCredential(e,o={}){let{assertionOptions:s,session:r}=e;o.abortController?N.assignWebAuthnAbortController(o.abortController):(N.renewWebAuthnAbortController(),o.abortController=N.abortController);let a=await G(s,o),c=a.response;return{assertionResult:{authenticatorData:v(c.authenticatorData),clientDataJSON:v(c.clientDataJSON),credentialId:a.id,signature:v(c.signature),...c.userHandle&&{userHandle:v(c.userHandle)}},session:r}}async authenticateWithPasskey(e="",o={}){let s=this.config.getAppId(),r=se(J.getDeviceId(s)),a=S(e,"",o),c={app:{id:s},deviceInfo:r,user:{username:e,usernameType:a.usernameType}},d=await this.service.auth.authAuthInit({requestBody:c});switch(d.action){case"proceed":{let g=await this.getNavigatorCredential(d,o),R=await this.service.auth.authAuthComplete({requestBody:g}),i=V(R.jwtAccess);return this.session.setJwtCookie(i.token),a?.callbacks?.onSuccess&&await a.callbacks.onSuccess(i),i}case"crossAuth":case"fallback":{if(a?.callbacks?.onFallback){let g=Ot(d);await a.callbacks.onFallback(e,g)}return V("",!1,!0)}default:throw It}}async authenticateWithPasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async requestOtp(e,o={}){if(o.authzToken=this.session.getToken(o),!o.authzToken){let r=await this.authenticateWithPasskey(e,o);o.authzToken=r.token}return await this.service.auth.authAuthCodeRequest({authorization:o.authzToken})}async confirmTransaction(e,o,s={}){let r=Rt(e,s),a={username:e,txPayload:o,nonce:r.nonce,txType:r.txType},{assertionOptions:c,session:d}=await this.service.tx.txTxInit({requestBody:a}),g={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:c,session:d},{assertionResult:R}=await this.getNavigatorCredential(g),i={authenticatorData:R.authenticatorData,clientData:R.clientDataJSON,keyHandle:R.credentialId,session:d,signature:R.signature};return await this.service.tx.txTxComplete({requestBody:i})}},Et=$e;var Ge=class extends E{constructor(e){super(e)}async listPasskeys(e={}){let o=this.session.getToken(e);return await this.service.passkeys.passkeysPasskeysList({authorization:o})}async renamePasskey(e,o,s={}){let r=this.session.getToken(s),a={name:o};await this.service.passkeys.passkeysPasskeyRename({authorization:r,id:e,requestBody:a})}async deletePasskey(e,o={}){let s=this.session.getToken(o);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e})}},St=Ge;var Ce=class extends E{constructor(e){super(e)}};dt(Ce,[E,Et,Re,St,xt]);var Ye=Ce;var Ae=class{static async getNavigatorCredential(e,o={}){let{assertionOptions:s,session:r}=e,a=await G(s,o),c=a.response;return{assertionResult:{authenticatorData:v(c.authenticatorData),clientDataJSON:v(c.clientDataJSON),credentialId:a.id,signature:v(c.signature),...c.userHandle&&{userHandle:v(c.userHandle)}},session:r}}static async createNavigatorCredential(e){let{registrationRequestOptions:o,session:s}=e,r=await $(o),a=r.response,c=a.getPublicKey&&a.getPublicKey(),d=a.getPublicKeyAlgorithm&&a.getPublicKeyAlgorithm(),g=a.getAuthenticatorData&&a.getAuthenticatorData(),R=a.getTransports&&a.getTransports();return{creationResult:{attestationObject:v(a.attestationObject),clientDataJSON:v(a.clientDataJSON),credentialId:r.id,...c&&{publicKey:v(c)},...d&&{publicKeyAlgorithm:d},...g&&{authenticatorData:v(g)},...R&&{transports:R}},session:s}}};var io=Ye;return jt(no);})();
1
+ "use strict";var LoginID=(()=>{var M=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var ze=Object.prototype.hasOwnProperty;var fe=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})},Ve=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Je(e))!ze.call(t,o)&&o!==r&&M(t,o,{get:()=>e[o],enumerable:!(s=je(e,o))||s.enumerable});return t};var Me=t=>Ve(M({},"__esModule",{value:!0}),t);var ct={};fe(ct,{AbortError:()=>H,ApiError:()=>y,LoginIDAPI:()=>se,LoginIDWebSDK:()=>he,PasskeyError:()=>d,WebAuthnHelper:()=>z,createPasskeyCredential:()=>S,default:()=>lt,getPasskeyCredential:()=>w,isConditionalUIAvailable:()=>Se,isPlatformAuthenticatorAvailable:()=>Ee});var $=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,r=this.config.baseUrl.match(e);if(r)return r[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},K=$;var U=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),L=t=>{if(!t)return t;let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<t.length;){let i=t.charCodeAt(s++),a=t.charCodeAt(s++),u=t.charCodeAt(s++),p=i<<16|a<<8|u;r.push(e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63])}let o=r.join(""),n=t.length%3;return n?o.slice(0,n-3)+"===".slice(n||3):o},$e=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let a=0;a<64;a++)r[e.charAt(a)]=a;let o=0,n=0,i="";for(let a of t){let u=r[a];if(u!==void 0)for(o=(o<<6)+u,n+=6;n>=8;)i+=s(o>>(n-=8)&255)}return i},l=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=L(e);return U(s)},A=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=$e(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},ge=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),Re=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},B=t=>{try{let r=t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(window.atob(r).split("").map(o=>"%"+("00"+o.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(s)}catch(e){console.error(e)}},be=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},Ce=t=>{document.cookie=t},Ae=t=>{document.cookie=`${t}=; expires=${new Date}`},Pe=(t=25)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<t;s++)r+=e.charAt(Math.floor(Math.random()*e.length));return r},Ie=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),G=async t=>await window.crypto.subtle.exportKey("jwk",t.publicKey),Te=async(t,e)=>{let s=new TextEncoder().encode(e),o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,s);return l(o)};var Y=class{config;constructor(e){this.config=new K(e)}getToken(e){if(e.authzToken)return e.authzToken;{let r=this.getJwtCookie();return r||""}}getSessionInfo(){if(!this.isLoggedIn())return null;let e=B(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=B(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;Ce(o)}getJwtCookie(){return be(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}logout(){Ae(this.getJwtCookieName())}},Oe=Y;var P=class{constructor(e){this.config=e}};var y=class extends Error{url;status;statusText;body;request;constructor(e,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=e}};var v=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},I=class{#t;#r;#e;#o;#n;#i;#s;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#o=[],this.#n=new Promise((r,s)=>{this.#i=r,this.#s=s;let o=a=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(a))},n=a=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#s&&this.#s(a))},i=a=>{this.#t||this.#r||this.#e||this.#o.push(a)};return Object.defineProperty(i,"isResolved",{get:()=>this.#t}),Object.defineProperty(i,"isRejected",{get:()=>this.#r}),Object.defineProperty(i,"isCancelled",{get:()=>this.#e}),e(o,n,i)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,r){return this.#n.then(e,r)}catch(e){return this.#n.catch(e)}finally(e){return this.#n.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#o.length)try{for(let e of this.#o)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#o.length=0,this.#s&&this.#s(new v("Request aborted"))}}get isCancelled(){return this.#e}};var X=t=>t!=null,D=t=>typeof t=="string",Q=t=>D(t)&&t!=="",Z=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),qe=t=>t instanceof FormData,Ge=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Ye=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{X(n)&&(Array.isArray(n)?n.forEach(i=>{s(o,i)}):typeof n=="object"?Object.entries(n).forEach(([i,a])=>{s(`${o}[${i}]`,a)}):r(o,n))};return Object.entries(t).forEach(([o,n])=>{s(o,n)}),e.length>0?`?${e.join("&")}`:""},Qe=(t,e)=>{let r=t.ENCODE_PATH||encodeURI,s=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(n,i)=>e.path?.hasOwnProperty(i)?r(String(e.path[i])):n),o=`${t.BASE}${s}`;return e.query?`${o}${Ye(e.query)}`:o},Xe=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{D(o)||Z(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>X(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},W=async(t,e)=>typeof e=="function"?e(t):e,Ze=async(t,e)=>{let[r,s,o,n]=await Promise.all([W(e,t.TOKEN),W(e,t.USERNAME),W(e,t.PASSWORD),W(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>X(u)).reduce((a,[u,p])=>({...a,[u]:String(p)}),{});if(Q(r)&&(i.Authorization=`Bearer ${r}`),Q(s)&&Q(o)){let a=Ge(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:Z(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":D(e.body)?i["Content-Type"]="text/plain":qe(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},et=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):D(t.body)||Z(t.body)||qe(t.body)?t.body:JSON.stringify(t.body)},tt=async(t,e,r,s,o,n,i)=>{let a=new AbortController,u={headers:n,body:s??o,method:e.method,signal:a.signal};return t.WITH_CREDENTIALS&&(u.credentials=t.CREDENTIALS),i(()=>a.abort()),await fetch(r,u)},rt=(t,e)=>{if(e){let r=t.headers.get(e);if(D(r))return r}},ot=async t=>{if(t.status!==204)try{let e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(o=>e.toLowerCase().startsWith(o))?await t.json():await t.text()}catch(e){console.error(e)}},st=(t,e)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(s)throw new y(t,e,s);if(!e.ok){let o=e.status??"unknown",n=e.statusText??"unknown",i=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})();throw new y(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},xe=(t,e)=>new I(async(r,s,o)=>{try{let n=Qe(t,e),i=Xe(e),a=et(e),u=await Ze(t,e);if(!o.isCancelled){let p=await tt(t,e,n,a,i,u,o),c=await ot(p),m=rt(p,e.responseHeader),g={url:n,ok:p.ok,status:p.status,statusText:p.statusText,body:m??c};st(e,g),r(g.body)}}catch(n){s(n)}});var F=class extends P{constructor(e){super(e)}request(e){return xe(this.config,e)}};var T=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}};var O=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:r}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:r,authorization:s}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:s},body:r,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:r}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:r},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}};var q=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:r,authorization:s}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":r,Authorization:s},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}};var x=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}};var k=class{auth;passkeys;reg;tx;request;constructor(e,r=F){this.request=new r({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new T(this.request),this.passkeys=new O(this.request),this.reg=new q(this.request),this.tx=new x(this.request)}};var ee=class{config;service;session;constructor(e){this.config=new K(e),this.service=new k({BASE:e.baseUrl}),this.session=new Oe(e)}},h=ee;var te=class extends Error{constructor(e){super(e),this.name="AbortError"}},H=te;var re=class t{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let e=new H("Cancelling current WebAuthn request");t.abortController.abort(e)};static renewWebAuthnAbortController=()=>{t.abortWebAuthnRequest();let e=new AbortController;t.abortController=e};static assignWebAuthnAbortController=e=>{t.abortWebAuthnRequest(),t.abortController=e}},b=re;var f=(t,e,r)=>({...r,authzToken:e||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||t,callbacks:r.callbacks||{}}),ke=(t,e)=>({...f(t,"",e),txType:e.txType||"raw",nonce:e.nonce||ge()}),E=(t,e=!0,r=!1)=>({userId:t.userId,token:t.jwtAccess,passkeyId:t.passkeyId,isAuthenticated:e,isFallback:r});var oe=class extends h{constructor(e){super(e)}async validateOtp(e,r,s={}){let o=f(e,"",s),n={authCode:r,user:{username:e,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:n}),a=E(i);return b.renewWebAuthnAbortController(),this.session.setJwtCookie(a.token),a}async requestAndSendOtp(e,r="email",s={}){let o=f(e,"",s),n={user:{username:e,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:n});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:n});break;default:throw new Error("Invalid message method")}}},j=oe;var _=t=>{let e={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return t&&(e.deviceId=t),e};async function Ee(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Se(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}var se={};fe(se,{ApiError:()=>y,AuthService:()=>T,BaseHttpRequest:()=>P,CancelError:()=>v,CancelablePromise:()=>I,LoginIDService:()=>k,OpenAPI:()=>we,PasskeysService:()=>O,RegService:()=>q,TxService:()=>x});var we={BASE:"https://api.loginid.io/fido2/v2",VERSION:"2.0",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};var ne=class extends h{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let r=f("","",{}),s={app:{id:this.config.getAppId()},deviceInfo:_(),user:{username:"",usernameType:r.usernameType}};await this.service.auth.authAuthInit({requestBody:s})}catch(r){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",r instanceof y&&(e.code=r.body.msgCode||"unknown_error",e.message=r.body.msg||r.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){this.session.logout()}},Be=ne;var ve=t=>[...t.crossAuthMethods,...t.fallbackMethods];var ie=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=ie;var ae=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},ue=ae;var De=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new d("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new d("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new d("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new d("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new d("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",t);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new d(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new d("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},_e=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new d("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new d("Passkey authentication has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new d(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new d("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},br=new ue("User needs to be logged in to perform this operation."),Ne=new ue("No login options available.");var Ke=t=>`LoginID_${t}_device-id`,C=class{static persistDeviceId(e,r){r&&localStorage.setItem(Ke(e),r)}static getDeviceId(e){return localStorage.getItem(Ke(e))||""}};var S=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:A(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:A(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:A(t.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?De(o,s):o}},w=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:A(o.id),transports:o.transports,type:o.type};r.push(n)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortController&&{signal:e.abortController.signal},publicKey:{allowCredentials:r,challenge:A(t.challenge),extensions:t.extensions,rpId:t.rpId,timeout:t.timeout,userVerification:t.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?_e(o,s):o}};var pe=class extends Error{code;constructor(e,r){super(e),this.name="StorageError",this.code=r}},R=pe;var le=class{dbName;dbVersion;storeKey;indexes;constructor(e,r,s,o=[]){this.dbName=e,this.dbVersion=r,this.storeKey=s,this.indexes=o}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let r=e.result;if(!r.objectStoreNames.contains(this.storeKey)){let s=r.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:o,keyPath:n,options:i})=>s.createIndex(o,n,i))}},e}async getByIndex(e,r){return new Promise((s,o)=>{let n=this.openDb();n.onsuccess=()=>{let c=n.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(r);c.onsuccess=()=>{let m=c.result;m?s(m):o(new R(`No record found for ${r} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},c.onerror=()=>o(new R(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},n.onerror=()=>o(new R("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let u=o.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);u.onsuccess=()=>r(),u.onerror=()=>s(new R("Failed to save record.","ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new R("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},Ue=le;var ce=(t,e,r)=>(r||(r=Pe()),{id:r,username:e,aud:t}),de=async(t,e,r)=>{let o=U(L(JSON.stringify({alg:"ES256",jwk:e}))),n=U(L(JSON.stringify(t))),i=`${o}.${n}`,a=await Te(r,i);return`${i}.${a}`};var nt=1,it="app_id_idx",at="username_idx",ut="loginid-trust-store",pt="LoginID_trust-id",Le="app_id_username_idx",N=class extends Ue{appId;constructor(e){super(ut,nt,pt,[{name:at,keyPath:["username"]},{name:it,keyPath:["appId"]},{name:Le,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let r=await Ie(),s=await G(r),o=ce(this.appId,e),n=await de(o,s,r.privateKey);return await this.putRecord({id:o.id,appId:this.appId,username:e,keyPair:r}),n}async signWithTrustId(e){let r=await this.getByIndex(Le,[this.appId,e]),s=await G(r.keyPair),o=ce(this.appId,e,r.id);return await de(o,s,r.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(r){return r instanceof R&&r.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+r),"")}}};var me=class extends j{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;b.renewWebAuthnAbortController();let o=await S(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}async createPasskey(e,r="",s={}){let o=this.config.getAppId(),n=C.getDeviceId(o),i=_(n),a=new N(o),u=f(e,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&B(u.authzToken).username!==e&&(u.authzToken="");let p=await a.setOrSignWithTrustId(e),c={app:{id:o},deviceInfo:i,user:{username:e,usernameType:u.usernameType,displayName:u.displayName},...p&&{trustInfo:p}},m=await this.service.reg.regRegInit({requestBody:c,...u.authzToken&&{authorization:u.authzToken}}),g=await this.createNavigatorCredential(m),V=await this.service.reg.regRegComplete({requestBody:g}),He=E(V);return this.session.setJwtCookie(V.jwtAccess),C.persistDeviceId(o,n||V.deviceId),He}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortController?b.assignWebAuthnAbortController(r.abortController):(b.renewWebAuthnAbortController(),r.abortController=b.abortController);let n=await w(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=this.config.getAppId(),o=_(C.getDeviceId(s)),n=new N(s),i=f(e,"",r),a=await n.setOrSignWithTrustId(r.autoFill?"":e),u={app:{id:s},deviceInfo:o,user:{username:e,usernameType:i.usernameType},...a&&{trustInfo:a}},p=await this.service.auth.authAuthInit({requestBody:u});switch(p.action){case"proceed":{let c=await this.getNavigatorCredential(p,r),m=await this.service.auth.authAuthComplete({requestBody:c}),g=E(m);return this.session.setJwtCookie(g.token),C.persistDeviceId(s,m.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g}case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let m=ve(p);await i.callbacks.onFallback(e,m)}return E({userId:"",jwtAccess:""},!1,!0)}default:throw Ne}}async authenticateWithPasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async requestOtp(e,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(e,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(e,r,s={}){let o=ke(e,s),n={username:e,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:a}=await this.service.tx.txTxInit({requestBody:n}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:a},{assertionResult:p}=await this.getNavigatorCredential(u),c={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:a,signature:p.signature};return await this.service.tx.txTxComplete({requestBody:c})}},We=me;var ye=class extends h{constructor(e){super(e)}async listPasskeys(e={}){let r=this.session.getToken(e);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(e,r,s={}){let o=this.session.getToken(s),n={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:e,requestBody:n})}async deletePasskey(e,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e})}},Fe=ye;var J=class extends h{constructor(e){super(e)}};Re(J,[h,We,j,Fe,Be]);var he=J;var z=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await w(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await S(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}};var lt=he;return Me(ct);})();
2
2
  //# sourceMappingURL=index.global.js.map
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ie=Object.defineProperty;var Te=(t,e)=>{for(var r in e)Ie(t,r,{get:e[r],enumerable:!0})};var H=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,r=this.config.baseUrl.match(e);if(r)return r[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},N=H;var xe=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),ke=t=>{if(!t)return t;let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<t.length;){let i=t.charCodeAt(s++),a=t.charCodeAt(s++),u=t.charCodeAt(s++),p=i<<16|a<<8|u;r.push(e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63])}let o=r.join(""),n=t.length%3;return n?o.slice(0,n-3)+"===".slice(n||3):o},Ee=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let a=0;a<64;a++)r[e.charAt(a)]=a;let o=0,n=0,i="";for(let a of t){let u=r[a];if(u!==void 0)for(o=(o<<6)+u,n+=6;n>=8;)i+=s(o>>(n-=8)&255)}return i},l=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=ke(e);return xe(s)},R=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=Ee(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},oe=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),se=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},k=t=>{try{let r=t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(window.atob(r).split("").map(o=>"%"+("00"+o.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(s)}catch(e){console.error(e)}},ne=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},ie=t=>{document.cookie=t},ae=t=>{document.cookie=`${t}=; expires=${new Date}`};var _=class{config;constructor(e){this.config=new N(e)}getToken(e){if(e.authzToken)return e.authzToken;{let r=this.getJwtCookie();return r||""}}getSessionInfo(){if(!this.isLoggedIn())return null;let e=k(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=k(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;ie(o)}getJwtCookie(){return ne(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}logout(){ae(this.getJwtCookieName())}},ue=_;var b=class{constructor(e){this.config=e}};var m=class extends Error{url;status;statusText;body;request;constructor(e,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=e}};var E=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},C=class{#t;#r;#e;#o;#n;#i;#s;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#o=[],this.#n=new Promise((r,s)=>{this.#i=r,this.#s=s;let o=a=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(a))},n=a=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#s&&this.#s(a))},i=a=>{this.#t||this.#r||this.#e||this.#o.push(a)};return Object.defineProperty(i,"isResolved",{get:()=>this.#t}),Object.defineProperty(i,"isRejected",{get:()=>this.#r}),Object.defineProperty(i,"isCancelled",{get:()=>this.#e}),e(o,n,i)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,r){return this.#n.then(e,r)}catch(e){return this.#n.catch(e)}finally(e){return this.#n.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#o.length)try{for(let e of this.#o)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#o.length=0,this.#s&&this.#s(new E("Request aborted"))}}get isCancelled(){return this.#e}};var z=t=>t!=null,S=t=>typeof t=="string",W=t=>S(t)&&t!=="",j=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),pe=t=>t instanceof FormData,Se=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},ve=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{z(n)&&(Array.isArray(n)?n.forEach(i=>{s(o,i)}):typeof n=="object"?Object.entries(n).forEach(([i,a])=>{s(`${o}[${i}]`,a)}):r(o,n))};return Object.entries(t).forEach(([o,n])=>{s(o,n)}),e.length>0?`?${e.join("&")}`:""},we=(t,e)=>{let r=t.ENCODE_PATH||encodeURI,s=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(n,i)=>e.path?.hasOwnProperty(i)?r(String(e.path[i])):n),o=`${t.BASE}${s}`;return e.query?`${o}${ve(e.query)}`:o},Be=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{S(o)||j(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>z(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},U=async(t,e)=>typeof e=="function"?e(t):e,De=async(t,e)=>{let[r,s,o,n]=await Promise.all([U(e,t.TOKEN),U(e,t.USERNAME),U(e,t.PASSWORD),U(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>z(u)).reduce((a,[u,p])=>({...a,[u]:String(p)}),{});if(W(r)&&(i.Authorization=`Bearer ${r}`),W(s)&&W(o)){let a=Se(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:j(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":S(e.body)?i["Content-Type"]="text/plain":pe(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},Ne=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):S(t.body)||j(t.body)||pe(t.body)?t.body:JSON.stringify(t.body)},Ue=async(t,e,r,s,o,n,i)=>{let a=new AbortController,u={headers:n,body:s??o,method:e.method,signal:a.signal};return t.WITH_CREDENTIALS&&(u.credentials=t.CREDENTIALS),i(()=>a.abort()),await fetch(r,u)},Fe=(t,e)=>{if(e){let r=t.headers.get(e);if(S(r))return r}},Le=async t=>{if(t.status!==204)try{let e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(o=>e.toLowerCase().startsWith(o))?await t.json():await t.text()}catch(e){console.error(e)}},Ke=(t,e)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(s)throw new m(t,e,s);if(!e.ok){let o=e.status??"unknown",n=e.statusText??"unknown",i=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})();throw new m(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},le=(t,e)=>new C(async(r,s,o)=>{try{let n=we(t,e),i=Be(e),a=Ne(e),u=await De(t,e);if(!o.isCancelled){let p=await Ue(t,e,n,a,i,u,o),d=await Le(p),g=Fe(p,e.responseHeader),D={url:n,ok:p.ok,status:p.status,statusText:p.statusText,body:g??d};Ke(e,D),r(D.body)}}catch(n){s(n)}});var F=class extends b{constructor(e){super(e)}request(e){return le(this.config,e)}};var A=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":r},body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var P=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:r}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:r,authorization:s}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:s},body:r,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:r}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:r},errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var q=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:r,authorization:s}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":r,Authorization:s},body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}};var O=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var I=class{auth;passkeys;reg;tx;request;constructor(e,r=F){this.request=new r({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new A(this.request),this.passkeys=new P(this.request),this.reg=new q(this.request),this.tx=new O(this.request)}};var V=class{config;service;session;constructor(e){this.config=new N(e),this.service=new I({BASE:e.baseUrl}),this.session=new ue(e)}},y=V;var M=class extends Error{constructor(e){super(e),this.name="AbortError"}},J=M;var $=class t{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let e=new J("Cancelling current WebAuthn request");t.abortController.abort(e)};static renewWebAuthnAbortController=()=>{t.abortWebAuthnRequest();let e=new AbortController;t.abortController=e};static assignWebAuthnAbortController=e=>{t.abortWebAuthnRequest(),t.abortController=e}},h=$;var f=(t,e,r)=>({...r,authzToken:e||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||t,callbacks:r.callbacks||{}}),ce=(t,e)=>({...f(t,"",e),txType:e.txType||"raw",nonce:e.nonce||oe()}),T=(t,e=!0,r=!1)=>({token:t,isAuthenticated:e,isFallback:r});var G=class extends y{constructor(e){super(e)}async validateOtp(e,r,s={}){let o=f(e,"",s),n={authCode:r,user:{username:e,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:n}),a=T(i.jwtAccess);return h.renewWebAuthnAbortController(),this.session.setJwtCookie(a.token),a}async requestAndSendOtp(e,r="email",s={}){let o=f(e,"",s),n={user:{username:e,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:n});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:n});break;default:throw new Error("Invalid message method")}}},L=G;import{UAParser as He}from"ua-parser-js";var v=t=>{let e={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return t&&(e.deviceId=t),e},_e=(t,e)=>{let r=t.split(".").map(Number),s=e.split(".").map(Number),o=Math.max(r.length,s.length);for(let n=0;n<o;n++){let i=n<r.length?r[n]:0,a=n<s.length?s[n]:0;if(i<a)return-1;if(i>a)return 1}return 0};async function de(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function We(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function me(){let t=new He(window.navigator.userAgent).getResult(),e={solution:"",deviceSupported:!1};if(!window.PublicKeyCredential)return e.solution="Your browser seems to be outdated. Please upgrade to the latest version.",e;if(!await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable())switch(t.os.name){case"Mac OS":{let s=t.browser.version||"";return t.browser.name==="Firefox"&&_e(s,"122.0")<0?(e.solution="Please update your Firefox browser to the latest version.",e):(e.solution="Enable Touch ID on your device.",e)}case"iOS":return e.solution="Enable Face ID or Touch ID on your device.",e;case"Windows":return e.solution="Enable Windows Hello on your device. See here: https://support.microsoft.com/en-us/windows/learn-about-windows-hello-and-set-it-up-dae28983-8242-bb2a-d3d1-87c9d265a5f0.",e;case"Android":return t.browser.name==="Firefox"?(e.solution="Passkeys may not be supported on your Firefox browser. Please switch to a Chromium browser.",e):(e.solution="Enable device unlock via fingerprint, PIN, or facial recognition on your device.",e);default:return e.solution="Enable device unlock features such as fingerprint, PIN, or facial recognition.",e}return e.deviceSupported=!0,e}async function ze(){let t=await de(),e=await me();return t&&e.deviceSupported}var fe={};Te(fe,{ApiError:()=>m,AuthService:()=>A,BaseHttpRequest:()=>b,CancelError:()=>E,CancelablePromise:()=>C,LoginIDService:()=>I,OpenAPI:()=>ye,PasskeysService:()=>P,RegService:()=>q,TxService:()=>O});var ye={BASE:"https://api.loginid.io/fido2/v2",VERSION:"2.0",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};var Y=class extends y{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let r=f("","",{}),s={app:{id:this.config.getAppId()},deviceInfo:v(),user:{username:"",usernameType:r.usernameType}};await this.service.auth.authAuthInit({requestBody:s})}catch(r){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",r instanceof m&&(e.code=r.body.msgCode||"unknown_error",e.message=r.body.msg||r.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){this.session.logout()}},he=Y;var ge=t=>`LoginID_${t}_device-id`,x=class{static persistDeviceId(e,r){r&&localStorage.setItem(ge(e),r)}static getDeviceId(e){return localStorage.getItem(ge(e))||""}};var Re=t=>[...t.crossAuthMethods,...t.fallbackMethods];var Q=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},c=Q;var X=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},Z=X;var be=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new c("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new c("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new c("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new c("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new c("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",t);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new c(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new c("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},Ce=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new c("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new c("Passkey authentication has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new c(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new c("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},Zt=new Z("User needs to be logged in to perform this operation."),Ae=new Z("No login options available.");var w=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:R(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:R(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:R(t.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?be(o,s):o}},B=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:R(o.id),transports:o.transports,type:o.type};r.push(n)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortController&&{signal:e.abortController.signal},publicKey:{allowCredentials:r,challenge:R(t.challenge),extensions:t.extensions,rpId:t.rpId,timeout:t.timeout,userVerification:t.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Ce(o,s):o}};var ee=class extends L{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;h.renewWebAuthnAbortController();let o=await w(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}async createPasskey(e,r="",s={}){let o=this.config.getAppId(),n=x.getDeviceId(o),i=v(n),a=f(e,r,s);a.authzToken=this.session.getToken(a),a.authzToken&&k(a.authzToken).username!==e&&(a.authzToken="");let u={app:{id:o},deviceInfo:i,user:{username:e,usernameType:a.usernameType,displayName:a.displayName}},p=await this.service.reg.regRegInit({requestBody:u,...a.authzToken&&{authorization:a.authzToken}}),d=await this.createNavigatorCredential(p),g=await this.service.reg.regRegComplete({requestBody:d}),D=T(g.jwtAccess);return this.session.setJwtCookie(g.jwtAccess),x.persistDeviceId(o,n||g.deviceId),D}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortController?h.assignWebAuthnAbortController(r.abortController):(h.renewWebAuthnAbortController(),r.abortController=h.abortController);let n=await B(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=this.config.getAppId(),o=v(x.getDeviceId(s)),n=f(e,"",r),i={app:{id:s},deviceInfo:o,user:{username:e,usernameType:n.usernameType}},a=await this.service.auth.authAuthInit({requestBody:i});switch(a.action){case"proceed":{let u=await this.getNavigatorCredential(a,r),p=await this.service.auth.authAuthComplete({requestBody:u}),d=T(p.jwtAccess);return this.session.setJwtCookie(d.token),n?.callbacks?.onSuccess&&await n.callbacks.onSuccess(d),d}case"crossAuth":case"fallback":{if(n?.callbacks?.onFallback){let u=Re(a);await n.callbacks.onFallback(e,u)}return T("",!1,!0)}default:throw Ae}}async authenticateWithPasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async requestOtp(e,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(e,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(e,r,s={}){let o=ce(e,s),n={username:e,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:a}=await this.service.tx.txTxInit({requestBody:n}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:a},{assertionResult:p}=await this.getNavigatorCredential(u),d={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:a,signature:p.signature};return await this.service.tx.txTxComplete({requestBody:d})}},Pe=ee;var te=class extends y{constructor(e){super(e)}async listPasskeys(e={}){let r=this.session.getToken(e);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(e,r,s={}){let o=this.session.getToken(s),n={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:e,requestBody:n})}async deletePasskey(e,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e})}},qe=te;var K=class extends y{constructor(e){super(e)}};se(K,[y,Pe,L,qe,he]);var Oe=K;var re=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await B(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await w(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}};var Lr=Oe;export{J as AbortError,m as ApiError,fe as LoginIDAPI,Oe as LoginIDWebSDK,c as PasskeyError,re as WebAuthnHelper,ze as canCreatePasskey,w as createPasskeyCredential,Lr as default,me as doesDeviceSupportPasskeys,B as getPasskeyCredential,We as isConditionalUIAvailable,de as isPlatformAuthenticatorAvailable};
1
+ var Le=Object.defineProperty;var We=(t,e)=>{for(var r in e)Le(t,r,{get:e[r],enumerable:!0})};var z=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,r=this.config.baseUrl.match(e);if(r)return r[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},K=z;var U=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),L=t=>{if(!t)return t;let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<t.length;){let i=t.charCodeAt(s++),a=t.charCodeAt(s++),u=t.charCodeAt(s++),p=i<<16|a<<8|u;r.push(e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63])}let o=r.join(""),n=t.length%3;return n?o.slice(0,n-3)+"===".slice(n||3):o},Fe=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let a=0;a<64;a++)r[e.charAt(a)]=a;let o=0,n=0,i="";for(let a of t){let u=r[a];if(u!==void 0)for(o=(o<<6)+u,n+=6;n>=8;)i+=s(o>>(n-=8)&255)}return i},l=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=L(e);return U(s)},A=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=Fe(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},me=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),ye=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},S=t=>{try{let r=t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(window.atob(r).split("").map(o=>"%"+("00"+o.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(s)}catch(e){console.error(e)}},he=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},fe=t=>{document.cookie=t},ge=t=>{document.cookie=`${t}=; expires=${new Date}`},Re=(t=25)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<t;s++)r+=e.charAt(Math.floor(Math.random()*e.length));return r},be=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),V=async t=>await window.crypto.subtle.exportKey("jwk",t.publicKey),Ce=async(t,e)=>{let s=new TextEncoder().encode(e),o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,s);return l(o)};var M=class{config;constructor(e){this.config=new K(e)}getToken(e){if(e.authzToken)return e.authzToken;{let r=this.getJwtCookie();return r||""}}getSessionInfo(){if(!this.isLoggedIn())return null;let e=S(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=S(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;fe(o)}getJwtCookie(){return he(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}logout(){ge(this.getJwtCookieName())}},Ae=M;var P=class{constructor(e){this.config=e}};var y=class extends Error{url;status;statusText;body;request;constructor(e,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=e}};var w=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},I=class{#t;#r;#e;#o;#n;#i;#s;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#o=[],this.#n=new Promise((r,s)=>{this.#i=r,this.#s=s;let o=a=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(a))},n=a=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#s&&this.#s(a))},i=a=>{this.#t||this.#r||this.#e||this.#o.push(a)};return Object.defineProperty(i,"isResolved",{get:()=>this.#t}),Object.defineProperty(i,"isRejected",{get:()=>this.#r}),Object.defineProperty(i,"isCancelled",{get:()=>this.#e}),e(o,n,i)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,r){return this.#n.then(e,r)}catch(e){return this.#n.catch(e)}finally(e){return this.#n.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#o.length)try{for(let e of this.#o)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#o.length=0,this.#s&&this.#s(new w("Request aborted"))}}get isCancelled(){return this.#e}};var G=t=>t!=null,B=t=>typeof t=="string",$=t=>B(t)&&t!=="",Y=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),Pe=t=>t instanceof FormData,He=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},je=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{G(n)&&(Array.isArray(n)?n.forEach(i=>{s(o,i)}):typeof n=="object"?Object.entries(n).forEach(([i,a])=>{s(`${o}[${i}]`,a)}):r(o,n))};return Object.entries(t).forEach(([o,n])=>{s(o,n)}),e.length>0?`?${e.join("&")}`:""},Je=(t,e)=>{let r=t.ENCODE_PATH||encodeURI,s=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(n,i)=>e.path?.hasOwnProperty(i)?r(String(e.path[i])):n),o=`${t.BASE}${s}`;return e.query?`${o}${je(e.query)}`:o},ze=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{B(o)||Y(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>G(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},W=async(t,e)=>typeof e=="function"?e(t):e,Ve=async(t,e)=>{let[r,s,o,n]=await Promise.all([W(e,t.TOKEN),W(e,t.USERNAME),W(e,t.PASSWORD),W(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>G(u)).reduce((a,[u,p])=>({...a,[u]:String(p)}),{});if($(r)&&(i.Authorization=`Bearer ${r}`),$(s)&&$(o)){let a=He(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:Y(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":B(e.body)?i["Content-Type"]="text/plain":Pe(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},Me=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):B(t.body)||Y(t.body)||Pe(t.body)?t.body:JSON.stringify(t.body)},$e=async(t,e,r,s,o,n,i)=>{let a=new AbortController,u={headers:n,body:s??o,method:e.method,signal:a.signal};return t.WITH_CREDENTIALS&&(u.credentials=t.CREDENTIALS),i(()=>a.abort()),await fetch(r,u)},Ge=(t,e)=>{if(e){let r=t.headers.get(e);if(B(r))return r}},Ye=async t=>{if(t.status!==204)try{let e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(o=>e.toLowerCase().startsWith(o))?await t.json():await t.text()}catch(e){console.error(e)}},Qe=(t,e)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(s)throw new y(t,e,s);if(!e.ok){let o=e.status??"unknown",n=e.statusText??"unknown",i=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})();throw new y(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},Ie=(t,e)=>new I(async(r,s,o)=>{try{let n=Je(t,e),i=ze(e),a=Me(e),u=await Ve(t,e);if(!o.isCancelled){let p=await $e(t,e,n,a,i,u,o),c=await Ye(p),m=Ge(p,e.responseHeader),g={url:n,ok:p.ok,status:p.status,statusText:p.statusText,body:m??c};Qe(e,g),r(g.body)}}catch(n){s(n)}});var F=class extends P{constructor(e){super(e)}request(e){return Ie(this.config,e)}};var T=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}};var O=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:r}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:r,authorization:s}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:s},body:r,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:r}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:r},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}};var q=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:r,authorization:s}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":r,Authorization:s},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}};var x=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}};var k=class{auth;passkeys;reg;tx;request;constructor(e,r=F){this.request=new r({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new T(this.request),this.passkeys=new O(this.request),this.reg=new q(this.request),this.tx=new x(this.request)}};var Q=class{config;service;session;constructor(e){this.config=new K(e),this.service=new k({BASE:e.baseUrl}),this.session=new Ae(e)}},h=Q;var X=class extends Error{constructor(e){super(e),this.name="AbortError"}},Z=X;var ee=class t{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let e=new Z("Cancelling current WebAuthn request");t.abortController.abort(e)};static renewWebAuthnAbortController=()=>{t.abortWebAuthnRequest();let e=new AbortController;t.abortController=e};static assignWebAuthnAbortController=e=>{t.abortWebAuthnRequest(),t.abortController=e}},b=ee;var f=(t,e,r)=>({...r,authzToken:e||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||t,callbacks:r.callbacks||{}}),Te=(t,e)=>({...f(t,"",e),txType:e.txType||"raw",nonce:e.nonce||me()}),E=(t,e=!0,r=!1)=>({userId:t.userId,token:t.jwtAccess,passkeyId:t.passkeyId,isAuthenticated:e,isFallback:r});var te=class extends h{constructor(e){super(e)}async validateOtp(e,r,s={}){let o=f(e,"",s),n={authCode:r,user:{username:e,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:n}),a=E(i);return b.renewWebAuthnAbortController(),this.session.setJwtCookie(a.token),a}async requestAndSendOtp(e,r="email",s={}){let o=f(e,"",s),n={user:{username:e,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:n});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:n});break;default:throw new Error("Invalid message method")}}},H=te;var v=t=>{let e={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return t&&(e.deviceId=t),e};async function Xe(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Ze(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}var qe={};We(qe,{ApiError:()=>y,AuthService:()=>T,BaseHttpRequest:()=>P,CancelError:()=>w,CancelablePromise:()=>I,LoginIDService:()=>k,OpenAPI:()=>Oe,PasskeysService:()=>O,RegService:()=>q,TxService:()=>x});var Oe={BASE:"https://api.loginid.io/fido2/v2",VERSION:"2.0",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};var re=class extends h{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let r=f("","",{}),s={app:{id:this.config.getAppId()},deviceInfo:v(),user:{username:"",usernameType:r.usernameType}};await this.service.auth.authAuthInit({requestBody:s})}catch(r){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",r instanceof y&&(e.code=r.body.msgCode||"unknown_error",e.message=r.body.msg||r.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){this.session.logout()}},xe=re;var ke=t=>[...t.crossAuthMethods,...t.fallbackMethods];var oe=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=oe;var se=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},ne=se;var Ee=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new d("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new d("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new d("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new d("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new d("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",t);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new d(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new d("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},Se=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new d("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new d("Passkey authentication has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new d(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new d("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},dr=new ne("User needs to be logged in to perform this operation."),we=new ne("No login options available.");var Be=t=>`LoginID_${t}_device-id`,C=class{static persistDeviceId(e,r){r&&localStorage.setItem(Be(e),r)}static getDeviceId(e){return localStorage.getItem(Be(e))||""}};var D=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:A(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:A(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:A(t.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Ee(o,s):o}},_=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:A(o.id),transports:o.transports,type:o.type};r.push(n)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortController&&{signal:e.abortController.signal},publicKey:{allowCredentials:r,challenge:A(t.challenge),extensions:t.extensions,rpId:t.rpId,timeout:t.timeout,userVerification:t.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Se(o,s):o}};var ie=class extends Error{code;constructor(e,r){super(e),this.name="StorageError",this.code=r}},R=ie;var ae=class{dbName;dbVersion;storeKey;indexes;constructor(e,r,s,o=[]){this.dbName=e,this.dbVersion=r,this.storeKey=s,this.indexes=o}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let r=e.result;if(!r.objectStoreNames.contains(this.storeKey)){let s=r.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:o,keyPath:n,options:i})=>s.createIndex(o,n,i))}},e}async getByIndex(e,r){return new Promise((s,o)=>{let n=this.openDb();n.onsuccess=()=>{let c=n.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(r);c.onsuccess=()=>{let m=c.result;m?s(m):o(new R(`No record found for ${r} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},c.onerror=()=>o(new R(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},n.onerror=()=>o(new R("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let u=o.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);u.onsuccess=()=>r(),u.onerror=()=>s(new R("Failed to save record.","ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new R("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ve=ae;var ue=(t,e,r)=>(r||(r=Re()),{id:r,username:e,aud:t}),pe=async(t,e,r)=>{let o=U(L(JSON.stringify({alg:"ES256",jwk:e}))),n=U(L(JSON.stringify(t))),i=`${o}.${n}`,a=await Ce(r,i);return`${i}.${a}`};var et=1,tt="app_id_idx",rt="username_idx",ot="loginid-trust-store",st="LoginID_trust-id",De="app_id_username_idx",N=class extends ve{appId;constructor(e){super(ot,et,st,[{name:rt,keyPath:["username"]},{name:tt,keyPath:["appId"]},{name:De,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let r=await be(),s=await V(r),o=ue(this.appId,e),n=await pe(o,s,r.privateKey);return await this.putRecord({id:o.id,appId:this.appId,username:e,keyPair:r}),n}async signWithTrustId(e){let r=await this.getByIndex(De,[this.appId,e]),s=await V(r.keyPair),o=ue(this.appId,e,r.id);return await pe(o,s,r.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(r){return r instanceof R&&r.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+r),"")}}};var le=class extends H{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;b.renewWebAuthnAbortController();let o=await D(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}async createPasskey(e,r="",s={}){let o=this.config.getAppId(),n=C.getDeviceId(o),i=v(n),a=new N(o),u=f(e,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&S(u.authzToken).username!==e&&(u.authzToken="");let p=await a.setOrSignWithTrustId(e),c={app:{id:o},deviceInfo:i,user:{username:e,usernameType:u.usernameType,displayName:u.displayName},...p&&{trustInfo:p}},m=await this.service.reg.regRegInit({requestBody:c,...u.authzToken&&{authorization:u.authzToken}}),g=await this.createNavigatorCredential(m),J=await this.service.reg.regRegComplete({requestBody:g}),Ue=E(J);return this.session.setJwtCookie(J.jwtAccess),C.persistDeviceId(o,n||J.deviceId),Ue}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortController?b.assignWebAuthnAbortController(r.abortController):(b.renewWebAuthnAbortController(),r.abortController=b.abortController);let n=await _(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=this.config.getAppId(),o=v(C.getDeviceId(s)),n=new N(s),i=f(e,"",r),a=await n.setOrSignWithTrustId(r.autoFill?"":e),u={app:{id:s},deviceInfo:o,user:{username:e,usernameType:i.usernameType},...a&&{trustInfo:a}},p=await this.service.auth.authAuthInit({requestBody:u});switch(p.action){case"proceed":{let c=await this.getNavigatorCredential(p,r),m=await this.service.auth.authAuthComplete({requestBody:c}),g=E(m);return this.session.setJwtCookie(g.token),C.persistDeviceId(s,m.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g}case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let m=ke(p);await i.callbacks.onFallback(e,m)}return E({userId:"",jwtAccess:""},!1,!0)}default:throw we}}async authenticateWithPasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async requestOtp(e,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(e,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(e,r,s={}){let o=Te(e,s),n={username:e,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:a}=await this.service.tx.txTxInit({requestBody:n}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:a},{assertionResult:p}=await this.getNavigatorCredential(u),c={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:a,signature:p.signature};return await this.service.tx.txTxComplete({requestBody:c})}},_e=le;var ce=class extends h{constructor(e){super(e)}async listPasskeys(e={}){let r=this.session.getToken(e);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(e,r,s={}){let o=this.session.getToken(s),n={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:e,requestBody:n})}async deletePasskey(e,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e})}},Ne=ce;var j=class extends h{constructor(e){super(e)}};ye(j,[h,_e,H,Ne,xe]);var Ke=j;var de=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await _(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await D(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}};var po=Ke;export{Z as AbortError,y as ApiError,qe as LoginIDAPI,Ke as LoginIDWebSDK,d as PasskeyError,de as WebAuthnHelper,D as createPasskeyCredential,po as default,_ as getPasskeyCredential,Ze as isConditionalUIAvailable,Xe as isPlatformAuthenticatorAvailable};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loginid/websdk3",
3
- "version": "3.0.8-next.1",
3
+ "version": "3.1.0",
4
4
  "description": "",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -74,9 +74,6 @@
74
74
  "webauthn",
75
75
  "passwordless"
76
76
  ],
77
- "dependencies": {
78
- "ua-parser-js": "^1.0.37"
79
- },
80
77
  "config": {
81
78
  "commitizen": {
82
79
  "path": "./node_modules/cz-conventional-changelog"